1var app=function(){"use strict";function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}function t(){}function i(e){return e()}function r(){return Object.create(null)}function n(e){e.forEach(i)}function s(e){return"function"==typeof e}function o(e,t){return e!=e?t==t:e!==t||e&&"object"==typeof e||"function"==typeof e}function a(e,i,r){e.$$.on_destroy.push(function(e,...i){if(null==e)return t;const r=e.subscribe(...i);return r.unsubscribe?()=>r.unsubscribe():r}(i,r))}function c(e,t){e.appendChild(t)}function l(e,t,i){e.insertBefore(t,i||null)}function d(e){e.parentNode.removeChild(e)}function u(e){return document.createElement(e)}function h(e){return document.createTextNode(e)}function p(){return h(" ")}function m(){return h("")}function v(e,t,i,r){return e.addEventListener(t,i,r),()=>e.removeEventListener(t,i,r)}function g(e){return function(t){return t.preventDefault(),e.call(this,t)}}function f(e,t,i){null==i?e.removeAttribute(t):e.getAttribute(t)!==i&&e.setAttribute(t,i)}function y(e,t){t=""+t,e.wholeText!==t&&(e.data=t)}function T(e,t){e.value=null==t?"":t}function E(e,t){for(let i=0;i<e.options.length;i+=1){const r=e.options[i];if(r.__value===t)return void(r.selected=!0)}e.selectedIndex=-1}function k(e,t,i){e.classList[i?"add":"remove"](t)}let S;function b(e){S=e}function R(){if(!S)throw new Error("Function called outside component initialization");return S}function C(e){R().$$.on_mount.push(e)}const P=[],w=[],A=[],I=[],_=Promise.resolve();let D=!1;function O(e){A.push(e)}const M=new Set;let L=0;function N(){const e=S;do{for(;L<P.length;){const e=P[L];L++,b(e),x(e.$$)}for(b(null),P.length=0,L=0;w.length;)w.pop()();for(let e=0;e<A.length;e+=1){const t=A[e];M.has(t)||(M.add(t),t())}A.length=0}while(P.length);for(;I.length;)I.pop()();D=!1,M.clear(),b(e)}function x(e){if(null!==e.fragment){e.update(),n(e.before_update);const t=e.dirty;e.dirty=[-1],e.fragment&&e.fragment.p(e.ctx,t),e.after_update.forEach(O)}}const U=new Set;let G;function F(){G={r:0,c:[],p:G}}function j(){G.r||n(G.c),G=G.p}function V(e,t){e&&e.i&&(U.delete(e),e.i(t))}function B(e,t,i,r){if(e&&e.o){if(U.has(e))return;U.add(e),G.c.push((()=>{U.delete(e),r&&(i&&e.d(1),r())})),e.o(t)}}function $(e,t){B(e,1,1,(()=>{t.delete(e.key)}))}function K(e){e&&e.c()}function H(e,t,r,o){const{fragment:a,on_mount:c,on_destroy:l,after_update:d}=e.$$;a&&a.m(t,r),o||O((()=>{const t=c.map(i).filter(s);l?l.push(...t):n(t),e.$$.on_mount=[]})),d.forEach(O)}function q(e,t){const i=e.$$;null!==i.fragment&&(n(i.on_destroy),i.fragment&&i.fragment.d(t),i.on_destroy=i.fragment=null,i.ctx=[])}function W(e,t){-1===e.$$.dirty[0]&&(P.push(e),D||(D=!0,_.then(N)),e.$$.dirty.fill(0)),e.$$.dirty[t/31|0]|=1<<t%31}function z(e,i,s,o,a,c,l,u=[-1]){const h=S;b(e);const p=e.$$={fragment:null,ctx:null,props:c,update:t,not_equal:a,bound:r(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(i.context||(h?h.$$.context:[])),callbacks:r(),dirty:u,skip_bound:!1,root:i.target||h.$$.root};l&&l(p.root);let m=!1;if(p.ctx=s?s(e,i.props||{},((t,i,...r)=>{const n=r.length?r[0]:i;return p.ctx&&a(p.ctx[t],p.ctx[t]=n)&&(!p.skip_bound&&p.bound[t]&&p.bound[t](n),m&&W(e,t)),i})):[],p.update(),m=!0,n(p.before_update),p.fragment=!!o&&o(p.ctx),i.target){if(i.hydrate){const e=function(e){return Array.from(e.childNodes)}(i.target);p.fragment&&p.fragment.l(e),e.forEach(d)}else p.fragment&&p.fragment.c();i.intro&&V(e.$$.fragment),H(e,i.target,i.anchor,i.customElement),N()}b(h)}class J{$destroy(){q(this,1),this.$destroy=t}$on(e,t){const i=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return i.push(t),()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}$set(e){var t;this.$$set&&(t=e,0!==Object.keys(t).length)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}var Y="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Q(e){var t={exports:{}};return e(t,t.exports),t.exports}var Z=Q((function(e,t){e.exports=function(){var e=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)},t=y,i=a,r=c,n=l,s=f,o=new RegExp(["(\\\\.)","([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^()])+)\\))?|\\(((?:\\\\.|[^()])+)\\))([+*?])?|(\\*))"].join("|"),"g");function a(e){for(var t,i=[],r=0,n=0,s="";null!=(t=o.exec(e));){var a=t[0],c=t[1],l=t.index;if(s+=e.slice(n,l),n=l+a.length,c)s+=c[1];else{s&&(i.push(s),s="");var d=t[2],h=t[3],p=t[4],m=t[5],v=t[6],g=t[7],f="+"===v||"*"===v,y="?"===v||"*"===v,T=d||"/",E=p||m||(g?".*":"[^"+T+"]+?");i.push({name:h||r++,prefix:d||"",delimiter:T,optional:y,repeat:f,pattern:u(E)})}}return n<e.length&&(s+=e.substr(n)),s&&i.push(s),i}function c(e){return l(a(e))}function l(t){for(var i=new Array(t.length),r=0;r<t.length;r++)"object"==typeof t[r]&&(i[r]=new RegExp("^"+t[r].pattern+"$"));return function(r){for(var n="",s=r||{},o=0;o<t.length;o++){var a=t[o];if("string"!=typeof a){var c,l=s[a.name];if(null==l){if(a.optional)continue;throw new TypeError('Expected "'+a.name+'" to be defined')}if(e(l)){if(!a.repeat)throw new TypeError('Expected "'+a.name+'" to not repeat, but received "'+l+'"');if(0===l.length){if(a.optional)continue;throw new TypeError('Expected "'+a.name+'" to not be empty')}for(var d=0;d<l.length;d++){if(c=encodeURIComponent(l[d]),!i[o].test(c))throw new TypeError('Expected all "'+a.name+'" to match "'+a.pattern+'", but received "'+c+'"');n+=(0===d?a.prefix:a.delimiter)+c}}else{if(c=encodeURIComponent(l),!i[o].test(c))throw new TypeError('Expected "'+a.name+'" to match "'+a.pattern+'", but received "'+c+'"');n+=a.prefix+c}}else n+=a}return n}}function d(e){return e.replace(/([.+*?=^!:${}()[\]|\/])/g,"\\$1")}function u(e){return e.replace(/([=!:$\/()])/g,"\\$1")}function h(e,t){return e.keys=t,e}function p(e){return e.sensitive?"":"i"}function m(e,t){var i=e.source.match(/\((?!\?)/g);if(i)for(var r=0;r<i.length;r++)t.push({name:r,prefix:null,delimiter:null,optional:!1,repeat:!1,pattern:null});return h(e,t)}function v(e,t,i){for(var r=[],n=0;n<e.length;n++)r.push(y(e[n],t,i).source);return h(new RegExp("(?:"+r.join("|")+")",p(i)),t)}function g(e,t,i){for(var r=a(e),n=f(r,i),s=0;s<r.length;s++)"string"!=typeof r[s]&&t.push(r[s]);return h(n,t)}function f(e,t){for(var i=(t=t||{}).strict,r=!1!==t.end,n="",s=e[e.length-1],o="string"==typeof s&&/\/$/.test(s),a=0;a<e.length;a++){var c=e[a];if("string"==typeof c)n+=d(c);else{var l=d(c.prefix),u=c.pattern;c.repeat&&(u+="(?:"+l+u+")*"),n+=u=c.optional?l?"(?:"+l+"("+u+"))?":"("+u+")?":l+"("+u+")"}}
1return i||(n=(o?n.slice(0,-2):n)+"(?:\\/(?=$))?"),n+=r?"$":i&&o?"":"(?=\\/|$)",new RegExp("^"+n,p(t))}function y(t,i,r){return e(i=i||[])?r||(r={}):(r=i,i=[]),t instanceof RegExp?m(t,i):e(t)?v(t,i,r):g(t,i,r)}t.parse=i,t.compile=r,t.tokensToFunction=n,t.tokensToRegExp=s;var T,E="undefined"!=typeof document,k="undefined"!=typeof window,S="undefined"!=typeof history,b="undefined"!=typeof process,R=E&&document.ontouchstart?"touchstart":"click",C=k&&!(!window.history.location&&!window.location);function P(){this.callbacks=[],this.exits=[],this.current="",this.len=0,this._decodeURLComponents=!0,this._base="",this._strict=!1,this._running=!1,this._hashbang=!1,this.clickHandler=this.clickHandler.bind(this),this._onpopstate=this._onpopstate.bind(this)}function w(){var e=new P;function t(){return A.apply(e,arguments)}return t.callbacks=e.callbacks,t.exits=e.exits,t.base=e.base.bind(e),t.strict=e.strict.bind(e),t.start=e.start.bind(e),t.stop=e.stop.bind(e),t.show=e.show.bind(e),t.back=e.back.bind(e),t.redirect=e.redirect.bind(e),t.replace=e.replace.bind(e),t.dispatch=e.dispatch.bind(e),t.exit=e.exit.bind(e),t.configure=e.configure.bind(e),t.sameOrigin=e.sameOrigin.bind(e),t.clickHandler=e.clickHandler.bind(e),t.create=w,Object.defineProperty(t,"len",{get:function(){return e.len},set:function(t){e.len=t}}),Object.defineProperty(t,"current",{get:function(){return e.current},set:function(t){e.current=t}}),t.Context=D,t.Route=O,t}function A(e,t){if("function"==typeof e)return A.call(this,"*",e);if("function"==typeof t)for(var i=new O(e,null,this),r=1;r<arguments.length;++r)this.callbacks.push(i.middleware(arguments[r]));else"string"==typeof e?this["string"==typeof t?"redirect":"show"](e,t):this.start(e)}function I(e){if(!e.handled){var t=this,i=t._window;(t._hashbang?C&&this._getBase()+i.location.hash.replace("#!",""):C&&i.location.pathname+i.location.search)!==e.canonicalPath&&(t.stop(),e.handled=!1,C&&(i.location.href=e.canonicalPath))}}function _(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function D(e,t,i){var r=this.page=i||A,n=r._window,s=r._hashbang,o=r._getBase();"/"===e[0]&&0!==e.indexOf(o)&&(e=o+(s?"#!":"")+e);var a=e.indexOf("?");this.canonicalPath=e;var c=new RegExp("^"+_(o));if(this.path=e.replace(c,"")||"/",s&&(this.path=this.path.replace("#!","")||"/"),this.title=E&&n.document.title,this.state=t||{},this.state.path=e,this.querystring=~a?r._decodeURLEncodedURIComponent(e.slice(a+1)):"",this.pathname=r._decodeURLEncodedURIComponent(~a?e.slice(0,a):e),this.params={},this.hash="",!s){if(!~this.path.indexOf("#"))return;var l=this.path.split("#");this.path=this.pathname=l[0],this.hash=r._decodeURLEncodedURIComponent(l[1])||"",this.querystring=this.querystring.split("#")[0]}}function O(e,i,r){var n=this.page=r||M,s=i||{};s.strict=s.strict||n._strict,this.path="*"===e?"(.*)":e,this.method="GET",this.regexp=t(this.path,this.keys=[],s)}P.prototype.configure=function(e){var t=e||{};this._window=t.window||k&&window,this._decodeURLComponents=!1!==t.decode
1URLComponents,this._popstate=!1!==t.popstate&&k,this._click=!1!==t.click&&E,this._hashbang=!!t.hashbang;var i=this._window;this._popstate?i.addEventListener("popstate",this._onpopstate,!1):k&&i.removeEventListener("popstate",this._onpopstate,!1),this._click?i.document.addEventListener(R,this.clickHandler,!1):E&&i.document.removeEventListener(R,this.clickHandler,!1),this._hashbang&&k&&!S?i.addEventListener("hashchange",this._onpopstate,!1):k&&i.removeEventListener("hashchange",this._onpopstate,!1)},P.prototype.base=function(e){if(0===arguments.length)return this._base;this._base=e},P.prototype._getBase=function(){var e=this._base;if(e)return e;var t=k&&this._window&&this._window.location;return k&&this._hashbang&&t&&"file:"===t.protocol&&(e=t.pathname),e},P.prototype.strict=function(e){if(0===arguments.length)return this._strict;this._strict=e},P.prototype.start=function(e){var t=e||{};if(this.configure(t),!1!==t.dispatch){var i;if(this._running=!0,C){var r=this._window.location;i=this._hashbang&&~r.hash.indexOf("#!")?r.hash.substr(2)+r.search:this._hashbang?r.search+r.hash:r.pathname+r.search+r.hash}this.replace(i,null,!0,t.dispatch)}},P.prototype.stop=function(){if(this._running){this.current="",this.len=0,this._running=!1;var e=this._window;this._click&&e.document.removeEventListener(R,this.clickHandler,!1),k&&e.removeEventListener("popstate",this._onpopstate,!1),k&&e.removeEventListener("hashchange",this._onpopstate,!1)}},P.prototype.show=function(e,t,i,r){var n=new D(e,t,this),s=this.prevContext;return this.prevContext=n,this.current=n.path,!1!==i&&this.dispatch(n,s),!1!==n.handled&&!1!==r&&n.pushState(),n},P.prototype.back=function(e,t){var i=this;if(this.len>0){var r=this._window;S&&r.history.back(),this.len--}else e?setTimeout((function(){i.show(e,t)})):setTimeout((function(){i.show(i._getBase(),t)}))},P.prototype.redirect=function(e,t){var i=this;"string"==typeof e&&"string"==typeof t&&A.call(this,e,(function(e){setTimeout((function(){i.replace(t)}),0)})),"string"==typeof e&&void 0===t&&setTimeout((function(){i.replace(e)}),0)},P.prototype.replace=function(e,t,i,r){var n=new D(e,t,this),s=this.prevContext;return this.prevContext=n,this.current=n.path,n.init=i,n.save(),!1!==r&&this.dispatch(n,s),n},P.prototype.dispatch=function(e,t){var i=0,r=0,n=this;function s(){var e=n.exits[r++];if(!e)return o();e(t,s)}function o(){var t=n.callbacks[i++];if(e.path===n.current)return t?void t(e,o):I.call(n,e);e.handled=!1}t?s():o()},P.prototype.exit=function(e,t){if("function"==typeof e)return this.exit("*",e);for(var i=new O(e,null,this),r=1;r<arguments.length;++r)this.exits.push(i.middleware(arguments[r]))},P.prototype.clickHandler=function(e){if(1===this._which(e)&&!(e.metaKey||e.ctrlKey||e.shiftKey||e.defaultPrevented)){var t=e.target,i=e.path||(e.composedPath?e.composedPath():null);if(i)for(var r=0;r<i.length;r++)if(i[r].nodeName&&"A"===i[r].nodeName.toUpperCase()&&i[r].href){t=i[r];break}for(;t&&"A"!==t.nodeName.toUpperCase();)t=t.parentNode;if(t&&"A"===t.nodeName.toUpperCase()){var n="object"==typeof t.href&&"SVGAnimatedString"===t.href.constructor.name;if(!t.hasAttribute("download")&&"external"!==t.getAttribute("rel")){var s=t.getAttribute("href");if((this._hashbang||!this._samePath(t)||!t.hash&&"#"!==s)&&!(s&&s.indexOf("mailto:")>-1)&&!(n?t.target.baseVal:t.target)&&(n||this.sameOrigin(t.href))){var o=n?t.href.baseVal:t.pathname+t.search+(t.hash||"");o="/"!==o[0]?"/"+o:o,b&&o.match(/^\/[a-zA-Z]:\//)&&(o=o.replace(/^\/[a-zA-Z]:\//,"/"));var a=o,c=this._getBase();0===o.indexOf(c)&&(o=o.substr(c.length)),this._hashbang&&(o=o.replace("#!","")),(!c||a!==o||C&&"file:"===this._window.location.protocol)&&(e.preventDefault(),this.show(a))}}}}},P.prototype._onpopstate=(T=!1,k?(E&&"complete"===document.readyState?T=!0:window.addEventListener("load",(function(){setTimeout((function(){T=!0}),0)})),function(e){if(T){var t=this;if(e.state){var i=e.state.path;t.replace(i,e.state)}else if(C){var r=t._window.location;t.show(r.pathname+r.search+r.hash,void 0,void 0,!1)}}}):function(){}),P.prototype._which=function(e){return null==(e=e||k&&this._window.event).which?e.button:e.which},P.prototype._toURL=function(e){var t=this._window;if("function"==typeof URL&&C)return new URL(e,t.location.toString());if(E){var i=t.document.createElement("a");return i.href=e,i}},P.prototype.sameOrigin=function(e){if(!e||!C)return!1;var t=this._toURL(e),i=this._window.location;return i.protocol===t.protocol&&i.hostname===t.hostname&&(i.port===t.port||""===i.port&&(80==t.port||443==t.port))},P.prototype._samePath=function(e){if(!C)return!1;var t=this._window.location;return e.pathname===t.pathname&&e.search===t.search},P.prototype._decodeURLEncodedURIComponent=function(e){return"string"!=typeof e?e:this._decodeURLComponents?decodeURIComponent(e.replace(/\+/g," ")):e},D.prototype.pushState=function(){var e=this.page,t=e._window,i=e._hashbang;e.len++,S&&t.history.pushState(this.state,this.title,i&&"/"!==this.path?"#!"+this.path:this.canonicalPath)},D.prototype.save=function(){var e=this.page;S&&e._window.history.replaceState(this.state,this.title,e._hashbang&&"/"!==this.path?"#!"+this.path:this.canonicalPath)},O.prototype.middleware=function(e){var t=this;return function(i,r){if(t.match(i.path,i.params))return i.routePath=t.path,e(i,r);r()}},O.prototype.match=function(e,t){var i=this.keys,r=e.indexOf("?"),n=~r?e.slice(0,r):e,s=this.regexp.exec(decodeURIComponent(n));if(!s)return!1;delete t[0];for(var o=1,a=s.length;o<a;++o){var c=i[o-1],l=this.page._decodeURLEncodedURIComponent(s[o]);void 0===l&&hasOwnProperty.call(t,c.name)||(t[c.name]=l)}return!0};var M=w(),L=M,N=M;return L.default=N,L}()}));function X(e){for(var t=arguments.length,i=Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];throw Error("[Immer] minified error nr: "+e+(i.length?" "+i.map((function(e){return"'"+e+"'"})).join(","):"")+". Find the full error at: https://bit.ly/3cXEKWf")}function ee(e){return!!e&&!!e[Fe]}function te(e){return!!e&&(function(e){if(!e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var i=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return i===Object||"function"==typeof i&&Function.toString.call(i)===je}(e)||Array.isArray(e)||!!e[Ge]||!!e.constructor[Ge]||oe(e)||ae(e))}function ie(e,t,i){void 0===i&&(i=!1),0===re(e)?(i?Object.keys:Ve)(e).forEach((function(r){i&&"symbol"==typeof r||t(r,e[r],e)})):e.forEach((function(i,r){return t(r,i,e)}))}function re(e){var t=e[Fe];return t?t.i>3?t.i-4:t.i:Array.isArray(e)?1:oe(e)?2:ae(e)?3:0}function ne(e,t){return 2===re(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function se(e,t,i){var r=re(e);2===r?e.set(t,i):3===r?(e.delete(t),e.add(i)):e[t]=i}function oe(e){return Le&&e instanceof Map}function ae(e){return Ne&&e instanceof Set}function ce(e){return e.o||e.t}function le(e){if(Array.isArray(e))return Array.prototype.slice.call(e);var t=Be(e);delete t[Fe];for(var i=Ve(t),r=0;r<i.length;r++){var n=i[r],s=t[n];
vendor: 5,452 bytes, line 1
1!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(t[n]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[n]})}return Object.create(Object.getPrototypeOf(e),t)}function de(e,t){return void 0===t&&(t=!1),he(e)||ee(e)||!te(e)||(re(e)>1&&(e.set=e.add=e.clear=e.delete=ue),Object.freeze(e),t&&ie(e,(function(e,t){return de(t,!0)}),!0)),e}function ue(){X(2)}function he(e){return null==e||"object"!=typeof e||Object.isFrozen(e)}function pe(e){var t=$e[e];return t||X(18,e),t}function me(){return Oe}function ve(e,t){t&&(pe("Patches"),e.u=[],e.s=[],e.v=t)}function ge(e){fe(e),e.p.forEach(Te),e.p=null}function fe(e){e===Oe&&(Oe=e.l)}function ye(e){return Oe={p:[],l:Oe,h:e,m:!0,_:0}}function Te(e){var t=e[Fe];0===t.i||1===t.i?t.j():t.O=!0}function Ee(e,t){t._=t.p.length;var i=t.p[0],r=void 0!==e&&e!==i;return t.h.g||pe("ES5").S(t,e,r),r?(i[Fe].P&&(ge(t),X(4)),te(e)&&(e=ke(t,e),t.l||be(t,e)),t.u&&pe("Patches").M(i[Fe].t,e,t.u,t.s)):e=ke(t,i,[]),ge(t),t.u&&t.v(t.u,t.s),e!==Ue?e:void 0}function ke(e,t,i){if(he(t))return t;var r=t[Fe];if(!r)return ie(t,(function(n,s){return Se(e,r,t,n,s,i)}),!0),t;if(r.A!==e)return t;if(!r.P)return be(e,r.t,!0),r.t;if(!r.I){r.I=!0,r.A._--;var n=4===r.i||5===r.i?r.o=le(r.k):r.o;ie(3===r.i?new Set(n):n,(function(t,s){return Se(e,r,n,t,s,i)})),be(e,n,!1),i&&e.u&&pe("Patches").R(r,i,e.u,e.s)}return r.o}function Se(e,t,i,r,n,s){if(ee(n)){var o=ke(e,n,s&&t&&3!==t.i&&!ne(t.D,r)?s.concat(r):void 0);if(se(i,r,o),!ee(o))return;e.m=!1}if(te(n)&&!he(n)){if(!e.h.F&&e._<1)return;ke(e,n),t&&t.A.l||be(e,n)}}function be(e,t,i){void 0===i&&(i=!1),e.h.F&&e.m&&de(t,i)}function Re(e,t){var i=e[Fe];return(i?ce(i):e)[t]}function Ce(e,t){if(t in e)for(var i=Object.getPrototypeOf(e);i;){var r=Object.getOwnPropertyDescriptor(i,t);if(r)return r;i=Object.getPrototypeOf(i)}}function Pe(e){e.P||(e.P=!0,e.l&&Pe(e.l))}function we(e){e.o||(e.o=le(e.t))}function Ae(e,t,i){var r=oe(t)?pe("MapSet").N(t,i):ae(t)?pe("MapSet").T(t,i):e.g?function(e,t){var i=Array.isArray(e),r={i:i?1:0,A:t?t.A:me(),P:!1,I:!1,D:{},l:t,t:e,k:null,o:null,j:null,C:!1},n=r,s=Ke;i&&(n=[r],s=He);var o=Proxy.revocable(n,s),a=o.revoke,c=o.proxy;return r.k=c,r.j=a,c}(t,i):pe("ES5").J(t,i);return(i?i.A:me()).p.push(r),r}function Ie(e){return ee(e)||X(22,e),function e(t){if(!te(t))return t;var i,r=t[Fe],n=re(t);if(r){if(!r.P&&(r.i<4||!pe("ES5").K(r)))return r.t;r.I=!0,i=_e(t,n),r.I=!1}else i=_e(t,n);return ie(i,(function(t,n){r&&function(e,t){return 2===re(e)?e.get(t):e[t]}(r.t,t)===n||se(i,t,e(n))})),3===n?new Set(i):i}(e)}function _e(e,t){switch(t){case 2:return new Map(e);case 3:return Array.from(e)}return le(e)}var De,Oe,Me="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),Le="undefined"!=typeof Map,Ne="undefined"!=typeof Set,xe="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,Ue=Me?Symbol.for("immer-nothing"):((De={})["immer-nothing"]=!0,De),Ge=Me?Symbol.for("immer-draftable"):"__$immer_draftable",Fe=Me?Symbol.for("immer-state"):"__$immer_state",je=""+Object.prototype.constructor,Ve="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,Be=Object.getOwnPropertyDescriptors||function(e){var t={};return Ve(e).forEach((function(i){t[i]=Object.getOwnPropertyDescriptor(e,i)})),t},$e={},Ke={get:function(e,t){if(t===Fe)return e;var i=ce(e);if(!ne(i,t))return function(e,t,i){var r,n=Ce(t,i);return n?"value"in n?n.value:null===(r=n.get)||void 0===r?void 0:r.call(e.k):void 0}(e,i,t);var r=i[t];return e.I||!te(r)?r:r===Re(e.t,t)?(we(e),e.o[t]=Ae(e.A.h,r,e)):r},has:function(e,t){return t in ce(e)},ownKeys:function(e){return Reflect.ownKeys(ce(e))},set:function(e,t,i){var r=Ce(ce(e),t);if(null==r?void 0:r.set)return r.set.call(e.k,i),!0;if(!e.P){var n=Re(ce(e),t),s=null==n?void 0:n[Fe];if(s&&s.t===i)return e.o[t]=i,e.D[t]=!1,!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(i,n)&&(void 0!==i||ne(e.t,t)))return!0;we(e),Pe(e)}return e.o[t]===i&&"number"!=typeof i&&(void 0!==i||t in e.o)||(e.o[t]=i,e.D[t]=!0,!0)},deleteProperty:function(e,t){return void 0!==Re(e.t,t)||t in e.t?(e.D[t]=!1,we(e),Pe(e)):delete e.D[t],e.o&&delete e.o[t],!0},getOwnPropertyDescriptor:function(e,t){var i=ce(e),r=Reflect.getOwnPropertyDescriptor(i,t);return r?{writable:!0,configurable:1!==e.i||"length"!==t,enumerable:r.enumerable,value:i[t]}:r},defineProperty:function(){X(11)},getPrototypeOf:function(e){return Object.getPrototypeOf(e.t)},setPrototypeOf:function(){X(12)}},He={};ie(Ke,(function(e,t){He[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),He.deleteProperty=function(e,t){return He.set.call(this,e,t,void 0)},He.set=function(e,t,i){return Ke.set.call(this,e[0],t,i,e[0])};var qe=function(){function e(e){var t=this;this.g=xe,this.F=!0,this.produce=function(e,i,r){if("function"==typeof e&&"function"!=typeof i){var n=i;i=e;var s=t;return function(e){var t=this;void 0===e&&(e=n);for(var r=arguments.length,o=Array(r>1?r-1:0),a=1;a<r;a++)o[a-1]=arguments[a];return s.produce(e,(function(e){var r;return(r=i).call.apply(r,[t,e].concat(o))}))}}var o;if("function"!=typeof i&&X(6),void 0!==r&&"function"!=typeof r&&X(7),te(e)){var a=ye(t),c=Ae(t,e,void 0),l=!0;try{o=i(c),l=!1}finally{l?ge(a):fe(a)}return"undefined"!=typeof Promise&&o instanceof Promise?o.then((function(e){return ve(
1a,r),Ee(e,a)}),(function(e){throw ge(a),e})):(ve(a,r),Ee(o,a))}if(!e||"object"!=typeof e){if(void 0===(o=i(e))&&(o=e),o===Ue&&(o=void 0),t.F&&de(o,!0),r){var d=[],u=[];pe("Patches").M(e,o,d,u),r(d,u)}return o}X(21,e)},this.produceWithPatches=function(e,i){if("function"==typeof e)return function(i){for(var r=arguments.length,n=Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return t.produceWithPatches(i,(function(t){return e.apply(void 0,[t].concat(n))}))};var r,n,s=t.produce(e,i,(function(e,t){r=e,n=t}));return"undefined"!=typeof Promise&&s instanceof Promise?s.then((function(e){return[e,r,n]})):[s,r,n]},"boolean"==typeof(null==e?void 0:e.useProxies)&&this.setUseProxies(e.useProxies),"boolean"==typeof(null==e?void 0:e.autoFreeze)&&this.setAutoFreeze(e.autoFreeze)}var t=e.prototype;return t.createDraft=function(e){te(e)||X(8),ee(e)&&(e=Ie(e));var t=ye(this),i=Ae(this,e,void 0);return i[Fe].C=!0,fe(t),i},t.finishDraft=function(e,t){var i=(e&&e[Fe]).A;return ve(i,t),Ee(void 0,i)},t.setAutoFreeze=function(e){this.F=e},t.setUseProxies=function(e){e&&!xe&&X(20),this.g=e},t.applyPatches=function(e,t){var i;for(i=t.length-1;i>=0;i--){var r=t[i];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}i>-1&&(t=t.slice(i+1));var n=pe("Patches").$;return ee(e)?n(e,t):this.produce(e,(function(e){return n(e,t)}))},e}(),We=new qe,ze=We.produce;We.produceWithPatches.bind(We),We.setAutoFreeze.bind(We),We.setUseProxies.bind(We),We.applyPatches.bind(We),We.createDraft.bind(We),We.finishDraft.bind(We);var Je=ze;function Ye(e){let t;const i=new Set,r=(e,r)=>{const n="function"==typeof e?e(t):e;if(n!==t){const e=t;t=r?n:Object.assign({},t,n),i.forEach((i=>i(t,e)))}},n=()=>t,s={setState:r,getState:n,subscribe:(e,r,s)=>r||s?((e,r=n,s=Object.is)=>{let o=r(t);function a(){const i=r(t);if(!s(o,i)){const t=o;e(o=i,t)}}return i.add(a),()=>i.delete(a)})(e,r,s):(i.add(e),()=>i.delete(e)),destroy:()=>i.clear()};return t=e(r,n,s),s}function Qe(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(let r=0;r<i.length;r++)if(!Object.prototype.hasOwnProperty.call(t,i[r])||!Object.is(e[i[r]],t[i[r]]))return!1;return!0}let Ze=!0,Xe=!0;function et(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function tt(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,s),n.apply(this,[e,s])};const s=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function it(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ze=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function rt(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xe=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function nt(){if("object"==typeof window){if(Ze)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function st(e,t){Xe&&console.warn(e+" is deprecated, please use "+t+" instead.")}function ot(e){return"[object Object]"===Object.prototype.toString.call(e)}function at(e){return ot(e)?Object.keys(e).reduce((function(t,i){const r=ot(e[i]),n=r?at(e[i]):e[i],s=r&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[i]:n})}),{}):e}function ct(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?ct(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{ct(e,e.get(t),i)}))})))}function lt(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}
vendor: 8,635 bytes, line 1
1)),s.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&ct(e,i,n)}))})),n}const dt=nt;function ut(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let o=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),dt("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return dt("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function ht(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function pt(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const n=new Event("track");n.track=i.track,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const n=new Event("track");n.track=i,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else tt(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function mt(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function vt(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(s(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(n(t)))},i])})).then(i,r)}}function gt(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>lt(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),tt(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>lt(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;
vendor: 4,614 bytes, line 1
1return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ft(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function yt(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ft(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}
vendor: 11,521 bytes, line 1
1return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=o(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Tt(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function Et(e,t){tt(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var kt=Object.freeze({__proto__:null,shimMediaStream:ht,shimOnTrack:pt,shimGetSendersWithDtmf:mt,shimGetStats:vt,shimSenderReceiverGetStats:gt,shimAddTrackRemoveTrackWithNative:ft,shimAddTrackRemoveTrack:yt,shimPeerConnection:Tt,fixNegotiationNeeded:Et,shimGetUserMedia:ut,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function St(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){st("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function bt(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Rt(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,s)}}function Ct(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Pt(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),tt(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function wt(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){st("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function At(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function It(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],i=e&&"sendEncodings"in e;i&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function _t(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Dt(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Ot(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Mt=Object.freeze({__proto__:null,shimOnTrack:bt,shimPeerConnection:Rt,shimSenderGetStats:Ct,shimReceiverGetStats:Pt,shimRemoveStream:wt,shimRTCDataChannel:At,shimAddTransceiver:It,shimGetParameters:_t,shimCreateOffer:Dt,shimCreateAnswer:Ot,shimGetUserMedia:St,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function Lt(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Nt(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>
vendor: 5,573 bytes, line 1
1{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function xt(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function Ut(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Gt(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function Gt(e){return e&&void 0!==e.video?Object.assign({},e,{video:at(e.video)}):e}function Ft(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];!r.hasOwnProperty("urls")&&r.hasOwnProperty("url")?(st("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function jt(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Vt(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Bt(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var $t=Object.freeze({__proto__:null,shimLocalStreamsAPI:Lt,shimRemoteStreamsAPI:Nt,shimCallbacksAPI:xt,shimGetUserMedia:Ut,shimConstraints:Gt,shimRTCIceServerUrls:Ft,shimTrackEventTransceiver:jt,shimCreateOfferLegacy:Vt,shimAudioContext:Bt}),Kt=Q((function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.pu
vendor: 4,629 bytes, line 1
1sh(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){let t=e.substr(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substr(e.indexOf(" ")+1).split(";");for(let e=0;e<r.length;e++)i=r[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substr(t+1,r-t-1),i.value=e.substr(r+1)):i.attribute=e.substr(t+1),i},t.parseSsrcGroup=function(e){const t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substr(6)},t.parseFingerprint=function(e){const t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");for(let n=3;n<r.length;n++){const s=r[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const r=t.parseRtpMap(o),n=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(r.parameters=n.length?t.parseFmtp(n[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))})),i},t.writeRtpDescription=function(e,i){let r="";
vendor: 5,130 bytes, line 1
1r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" UDP/TLS/RTP/SAVPF ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substr(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substr(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let n;r.length>0&&(n=parseInt(r[0].substr(19),10)),isNaN(n)&&(n=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:i.fmt,maxMessageSize:n};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substr(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,i,r){let n;const s=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[e].substr(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substr(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t})),Ht=e({__proto__:null,default:Kt},[Kt]);function qt(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),r=Kt.parseCandidate(e.candidate),n=Object.assign(i,r);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,tt(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Wt(e,t){if(!e.RTCPeerConnection)return;
vendor: 5,667 bytes, line 1
1"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=Kt.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Kt.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},r=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},n=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},s=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=Kt.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=r(arguments[0]),t=n(e),i=s(arguments[0],e);let o;o=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function zt(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const r=arguments[0],n=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},tt(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Jt(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function Yt(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Qt(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Zt(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);const t="offer"===e.type?this.createOffer:this.createAnswer;return t.apply(this).then((e=>i.apply(this,[e])))})}var Xt=Object.freeze({__proto__:null,shimRTCIceCandidate:qt,shimMaxMessageSize:Wt,shimSendThrowTypeError:zt,shimConnectionState:Jt,removeExtmapAllowMixed:Yt,shimAddIceCandidateNullOrEmpty:Qt,shimParameterlessSetLocalDescription:Zt});const ei=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=nt,r=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=et(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=et(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);
vendor: 5,723 bytes, line 1
1else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=et(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:Xt,extractVersion:et,disableLog:it,disableWarnings:rt,sdp:Ht};switch(r.browser){case"chrome":if(!kt||!Tt||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=kt,Qt(e,r),Zt(e),ut(e,r),ht(e),Tt(e,r),pt(e),yt(e,r),mt(e),vt(e),gt(e),Et(e,r),qt(e),Jt(e),Wt(e,r),zt(e),Yt(e,r);break;case"firefox":if(!Mt||!Rt||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=Mt,Qt(e,r),Zt(e),St(e,r),Rt(e,r),bt(e),wt(e),Ct(e),Pt(e),At(e),It(e),_t(e),Dt(e),Ot(e),qt(e),Jt(e),Wt(e,r),zt(e);break;case"safari":if(!$t||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=$t,Qt(e,r),Zt(e),Ft(e),Vt(e),xt(e),Lt(e),Nt(e),jt(e),Ut(e),Bt(e),qt(e),Wt(e,r),zt(e),Yt(e,r);break;default:i("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});var ti=Q((function(e){var t=e.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"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(e){return null!=e.subtype?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(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","max
1MessageSize"],format:function(e){return null!=e.maxMessageSize?"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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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(t).forEach((function(e){t[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),ii=Q((function(e,t){var i=function(e){return String(Number(e))===e?Number(e):e},r=function(e,t,r){var n=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:n&&!t[e.name]&&(t[e.name]={});var s=e.push?{}:n?t[e.name]:t;!function(e,t,r,n){if(n&&!r)t[n]=i(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(t[r[s]]=i(e[s+1]))}(r.match(e.reg),s,e.names,e.name),e.push&&t[e.push].push(s)},n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(e){var t={},i=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(i.push({rtp:[],fmtp:[]}),s=i[i.length-1]);for(var o=0;o<(ti[t]||[]).length;o+=1){var a=ti[t][o];if(a.reg.test(n))return r(a,s,n)}})),t.media=i,t};var s=function(e,t){var r=t.split(/=(.+)/,2);return 2===r.length?e[r[0]]=i(r[1]):1===r.length&&t.length>1&&(e[r[0]]=void 0),e};t.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(e){return e.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(e){for(var t=[],r=e.split(" ").map(i),n=0;n<r.length;n+=3)t.push({component:r[n],ip:r[n+1],port:r[n+2]});return t},t.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},t.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var t,r=!1;return"~"!==e[0]?t=i(e):(t=i(e.substring(1,e.length)),r=!0),{scid:t,paused:r}}))}))}})),ri=/%[sdv%]/g,ni=function(e){var t=1,i=arguments,r=i.length;return e.replace(ri,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},si=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?r.push(i[t.name][s]):r.push(i[t.names[n]])}else r.push(i[t.name]);return ni.apply(null,r)},oi=["v","o","s","i","u","e","p","c","b","t","r","z","a"],ai=["i","c","b","a"],ci=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEac
vendor: 4,482 bytes, line 1
1h((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||oi,r=t.innerOrder||ai,n=[];return i.forEach((function(t){ti[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(si(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(si(t,i,e))}))}))})),e.media.forEach((function(e){n.push(si("m",ti.m[0],e)),r.forEach((function(t){ti[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(si(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(si(t,i,e))}))}))}))})),n.join("\r\n")+"\r\n"},li=ii.parse;ii.parseParams,ii.parseFmtpConfig,ii.parsePayloads,ii.parseRemoteCandidates,ii.parseImageAttributes,ii.parseSimulcastStreamList;var di,ui=Q((function(e,t){!function(i,r){var n="function",s="undefined",o="object",a="string",c="model",l="name",d="type",u="vendor",h="version",p="architecture",m="console",v="mobile",g="tablet",f="smarttv",y="wearable",T="embedded",E="Amazon",k="Apple",S="ASUS",b="BlackBerry",R="Firefox",C="Google",P="Huawei",w="LG",A="Microsoft",I="Motorola",_="Opera",D="Samsung",O="Sony",M="Xiaomi",L="Zebra",N="Facebook",x=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},U=function(e,t){return typeof e===a&&-1!==G(t).indexOf(G(e))},G=function(e){return e.toLowerCase()},F=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,"").replace(/\s\s*$/,""),typeof t===s?e:e.substring(0,255)},j=function(e,t){for(var i,s,a,c,l,d,u=0;u<t.length&&!l;){var h=t[u],p=t[u+1];for(i=s=0;i<h.length&&!l;)if(l=h[i++].exec(e))for(a=0;a<p.length;a++)d=l[++s],typeof(c=p[a])===o&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,d):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=d?d.replace(c[1],c[2]):r:this[c[0]]=d?c[1].call(this,d,c[2]):r:4===c.length&&(this[c[0]]=d?c[3].call(this,d.replace(c[1],c[2])):r):this[c]=d||r;u+=2}},V=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var n=0;n<t[i].length;n++)if(U(t[i][n],e))return"?"===i?r:i}else if(U(t[i],e))return"?"===i?r:i;return e},B={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},$={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,h],[/opios[\/ ]+([\w\.]+)/i],[h,[l,"Opera Mini"]],[/\bopr\/([\w\.]+)/i],[h,[l,_]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale|qqbrowserlite|qq)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,h],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[l,"UCBrowser"]],[/\bqbcore\/([\w\.]+)/i],[h,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[h,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[h,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure Browser"],h],[/\bfocus\/([\w\.]+)/i],[h,[l,"Firefox Focus"]],[/\bopt\/([\w\.]+)/i],[h,[l,"Opera Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[l,"Opera Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[l,"MIUI Browser"]],[/fxios\/([-\w\.]+)/i],[h,[l,R]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 Browser"]],[/(oculus|samsung|sailfish)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 Browser"],h],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,h],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,N],h],[/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[l,"Chrome Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,"Chrome WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[l,"Android Browser"]],[/(chrome|omniweb|arora|[t
vendor: 4,662 bytes, line 1
1izenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,h],[/version\/([\w\.]+) .*mobile\/\w+ (safari)/i],[h,[l,"Mobile Safari"]],[/version\/([\w\.]+) .*(mobile ?safari|safari)/i],[h,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[h,V,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[l,"Firefox Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,h]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[p,"amd64"]],[/(ia32(?=;))/i],[[p,G]],[/((?:i[346]|x)86)[;\)]/i],[[p,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/windows (ce|mobile); ppc;/i],[[p,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[p,/ower/,"",G]],[/(sun4\w)[;\)]/i],[[p,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[p,G]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[pt]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[c,[u,D],[d,g]],[/\b((?:s[cgp]h|gt|sm)-\w+|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[c,[u,D],[d,v]],[/\((ip(?:hone|od)[\w ]*);/i],[c,[u,k],[d,v]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[c,[u,k],[d,g]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[c,[u,P],[d,g]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}-[atu]?[ln][01259x][012359][an]?)\b(?!.+d\/s)/i],[c,[u,P],[d,v]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[c,/_/g," "],[u,M],[d,v]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[c,/_/g," "],[u,M],[d,g]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[c,[u,"OPPO"],[d,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[c,[u,"Vivo"],[d,v]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[c,[u,"Realme"],[d,v]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[c,[u,I],[d,v]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[c,[u,I],[d,g]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[c,[u,w],[d,g]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[c,[u,w],[d,v]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[c,[u,"Lenovo"],[d,g]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[c,/_/g," "],[u,"Nokia"],[d,v]],[/(pixel c)\b/i],[c,[u,C],[d,g]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[c,[u,C],[d,v]],[/droid.+ ([c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[c,[u,O],[d,v]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[c,"Xperia Tablet"],[u,O],[d,g]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[c,[u,"OnePlus"],[d,v]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[c,[u,E],[d,g]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[c,/(.+)/g,"Fire Phone $1"],[u,E],[d,v]],[/(playbook);[-\w\),; ]+(rim)/i],[c,u,[d,g]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[c,[u,b],[d,v]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[c,[u,S],[d,g]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[c,[u,S],[d,v]],[/(nexus 9)/i],[c,[u,"HTC"],[d,g]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic|sony)[-_ ]?([-\w]*)/i],[u,[c,/_/g," "],[d,v]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[c,[u,"Acer"],[d,g]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[c,[u,"Meizu"],[d,v]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[c,[u,"Sharp"],[d,v]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asu
vendor: 6,593 bytes, line 1
1s)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[u,c,[d,v]],[/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[u,c,[d,g]],[/(surface duo)/i],[c,[u,A],[d,g]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[c,[u,"Fairphone"],[d,v]],[/(u304aa)/i],[c,[u,"AT&T"],[d,v]],[/\bsie-(\w*)/i],[c,[u,"Siemens"],[d,v]],[/\b(rct\w+) b/i],[c,[u,"RCA"],[d,g]],[/\b(venue[\d ]{2,7}) b/i],[c,[u,"Dell"],[d,g]],[/\b(q(?:mv|ta)\w+) b/i],[c,[u,"Verizon"],[d,g]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[c,[u,"Barnes & Noble"],[d,g]],[/\b(tm\d{3}\w+) b/i],[c,[u,"NuVision"],[d,g]],[/\b(k88) b/i],[c,[u,"ZTE"],[d,g]],[/\b(nx\d{3}j) b/i],[c,[u,"ZTE"],[d,v]],[/\b(gen\d{3}) b.+49h/i],[c,[u,"Swiss"],[d,v]],[/\b(zur\d{3}) b/i],[c,[u,"Swiss"],[d,g]],[/\b((zeki)?tb.*\b) b/i],[c,[u,"Zeki"],[d,g]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[u,"Dragon Touch"],c,[d,g]],[/\b(ns-?\w{0,9}) b/i],[c,[u,"Insignia"],[d,g]],[/\b((nxa|next)-?\w{0,9}) b/i],[c,[u,"NextBook"],[d,g]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[u,"Voice"],c,[d,v]],[/\b(lvtel\-)?(v1[12]) b/i],[[u,"LvTel"],c,[d,v]],[/\b(ph-1) /i],[c,[u,"Essential"],[d,v]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[c,[u,"Envizen"],[d,g]],[/\b(trio[-\w\. ]+) b/i],[c,[u,"MachSpeed"],[d,g]],[/\btu_(1491) b/i],[c,[u,"Rotor"],[d,g]],[/(shield[\w ]+) b/i],[c,[u,"Nvidia"],[d,g]],[/(sprint) (\w+)/i],[u,c,[d,v]],[/(kin\.[onetw]{3})/i],[[c,/\./g," "],[u,A],[d,v]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[c,[u,L],[d,g]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[c,[u,L],[d,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[u,c,[d,m]],[/droid.+; (shield) bui/i],[c,[u,"Nvidia"],[d,m]],[/(playstation [345portablevi]+)/i],[c,[u,O],[d,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[c,[u,A],[d,m]],[/smart-tv.+(samsung)/i],[u,[d,f]],[/hbbtv.+maple;(\d+)/i],[[c,/^/,"SmartTV"],[u,D],[d,f]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[u,w],[d,f]],[/(apple) ?tv/i],[u,[c,"Apple TV"],[d,f]],[/crkey/i],[[c,"Chromecast"],[u,C],[d,f]],[/droid.+aft(\w)( bui|\))/i],[c,[u,E],[d,f]],[/\(dtv[\);].+(aquos)/i],[c,[u,"Sharp"],[d,f]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w ]*; *(\w[^;]*);([^;]*)/i],[[u,F],[c,F],[d,f]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,f]],[/((pebble))app/i],[u,c,[d,y]],[/droid.+; (glass) \d/i],[c,[u,C],[d,y]],[/droid.+; (wt63?0{2,3})\)/i],[c,[u,L],[d,y]],[/(quest( 2)?)/i],[c,[u,N],[d,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[u,[d,T]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[c,[d,v]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[c,[d,g]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,g]],[/(phone|mobile(?:[;\/]| safari)|pda(?=.+windows ce))/i],[[d,v]],[/(android[-\w\. ]{0,9});.+buil/i],[c,[u,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,h],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[h,V,B]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[h,V,B]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,"Mac OS"],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86)/i],[h,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,h],[/\(bb(10);/i],[h,[l,b]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[l,"Firefox OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[l,"webOS"]],[/crkey\/([\d\.]+)/i],[h,[l,"Chromecast"]],[/(cros) [\w]+ ([\w\.]+\w)/i],[[l,"Chromium OS"],h],[/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,h],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,h]]},K=function(e,t){if(typeof e===o&&(t=e,e=r),!(this instanceof K))return new K(e,t).getResult();var n=e||(typeof i!==s&&i.navigator&&i.navigator.userAgent?i.navigator.userAgent:""),c=t?function(e,t){var i={};for(var r in e)t[r]&&t[r].length%2==0?i[r]=t[r].concat(e[r]):i[r]=e[r];return i}($,t):$;return this.getBrowser=function(){var e,t={};return t.name=r,t.version=r,j.call(t,n,c.browser),t.major=typeof(e=t.version)===a?e.replace(/[^\d\.]/g,"").split(".")[0]:r,t},this.getCPU=function(){var e={};return e.architecture=r,j.call(e,n,c.cpu),e},this.getDevice=function(){var e={};return e.vendor=r,e.model=r,e.type=r,j.call(e,n,c.device),e},this.getEngine=function(){var e={};return e.name=r,e.version=r,j.call(e,n,c.engine),e},this.getOS=function(){var e={};return e.name=r,e.version=r,j.call(e,n,c.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return n},this.setUA=function(e){return n=typeof e===a&&e.length>255?F(e,255):e,this},this.setUA(n),this};K.VERSION="1.0.2",K.BROWSER=x([l,h,"major"]),K.CPU=x([p]),K.DEVICE=x([c,u,d,m,v,f,g,y,T]),K.ENGINE=K.OS=x([l,h]),e.exports&&(t=e.exports=K),t.UAParser=K;var H=typeof i!==s&&(i.jQuery||i.Zepto);
1if(H&&!H.ua){var q=new K;H.ua=q.getResult(),H.ua.get=function(){return q.getUA()},H.ua.set=function(e){q.setUA(e);var t=q.getResult();for(var i in t)H.ua[i]=t[i]}}}("object"==typeof window?window:Y)})),hi=new Uint8Array(16);function pi(){if(!di&&!(di="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return di(hi)}var mi=/^(?:[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 vi(e){return"string"==typeof e&&mi.test(e)}for(var gi=[],fi=0;fi<256;++fi)gi.push((fi+256).toString(16).substr(1));function yi(e,t,i){var r=(e=e||{}).random||(e.rng||pi)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){i=i||0;for(var n=0;n<16;++n)t[i+n]=r[n];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(gi[e[t+0]]+gi[e[t+1]]+gi[e[t+2]]+gi[e[t+3]]+"-"+gi[e[t+4]]+gi[e[t+5]]+"-"+gi[e[t+6]]+gi[e[t+7]]+"-"+gi[e[t+8]]+gi[e[t+9]]+"-"+gi[e[t+10]]+gi[e[t+11]]+gi[e[t+12]]+gi[e[t+13]]+gi[e[t+14]]+gi[e[t+15]]).toLowerCase();if(!vi(i))throw TypeError("Stringified UUID is invalid");return i}(r)} 2/*! 3 * EventEmitter2 4 * https://github.com/hij1nx/EventEmitter2 5 * 6 * Copyright (c) 2013 hij1nx 7 * Licensed under the MIT license. 8 */var Ti,Ei=Q((function(e,t){!function(t){var i=Object.hasOwnProperty,r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},n="object"==typeof process&&"function"==typeof process.nextTick,s="function"==typeof Symbol,o="object"==typeof Reflect,a="function"==typeof setImmediate?setImmediate:setTimeout,c=s?o&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys;function l(){this._events={},this._conf&&d.call(this,this._conf)}function d(e){e&&(this._conf=e,e.delimiter&&(this.delimiter=e.delimiter),e.maxListeners!==t&&(this._maxListeners=e.maxListeners),e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this._newListener=e.newListener),e.removeListener&&(this._removeListener=e.removeListener),e.verboseMemoryLeak&&(this.verboseMemoryLeak=e.verboseMemoryLeak),e.ignoreErrors&&(this.ignoreErrors=e.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function u(e,t){var i="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";if(this.verboseMemoryLeak&&(i+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning){var r=new Error(i);r.name="MaxListenersExceededWarning",r.emitter=this,r.count=e,process.emitWarning(r)}else console.error(i),console.trace&&console.trace()}var h=function(e,t,i){var r=arguments.length;switch(r){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,i];default:for(var n=new Array(r);r--;)n[r]=arguments[r];return n}};function p(e,i){for(var r={},n=e.length,s=i?value.length:0,o=0;o<n;o++)r[e[o]]=o<s?i[o]:t;return r}function m(e,t,i){var r,n;if(this._emitter=e,this._target=t,this._listeners={},this._listenersCount=0,(i.on||i.off)&&(r=i.on,n=i.off),t.addEventListener?(r=t.addEventListener,n=t.removeEventListener):t.addListener?(r=t.addListener,n=t.removeListener):t.on&&(r=t.on,n=t.off),!r&&!n)throw Error("target does not implement any known event API");if("function"!=typeof r)throw TypeError("on method must be a function");if("function"!=typeof n)throw TypeError("off method must be a function");this._on=r,this._off=n;var s=e._observers;s?s.push(this):e._observers=[this]}function v(e,r,n,s){var o=Object.assign({},r);if(!e)return o;if("object"!=typeof e)throw TypeError("options must be an object");var a,c,l,d=Object.keys(e),u=d.length;function h(e){throw Error('Invalid "'+a+'" option value'+(e?". Reason: "+e:""))}for(var p=0;p<u;p++){if(a=d[p],!s&&!i.call(r,a))throw Error('Unknown "'+a+'" option');(c=e[a])!==t&&(l=n[a],o[a]=l?l(c,h):c)}return o}function g(e,t){return"function"==typeof e&&e.hasOwnProperty("prototype")||t("value must be a constructor"),e}function f(e){var t="value must be type of "+e.join("|"),i=e.length,r=e[0],n=e[1];return 1===i?function(e,i){if(typeof e===r)return e;i(t)}:2===i?function(e,i){var s=typeof e;if(s===r||s===n)return e;i(t)}:function(r,n){for(var s=typeof r,o=i;o-- >0;)if(s===e[o])return r;n(t)}}Object.assign(m.prototype,{subscribe:function(e,t,i){var r=this,n=this._target,s=this._emitter,o=this._listeners,a=function(){var r=h.apply(null,arguments),o={data:r,name:t,original:e};if(i){var a=i.call(n,o);!1!==a&&s.emit.apply(s,[o.name].concat(r))}else s.emit.apply(s,[t].concat(r))};if(o[e])throw Error("Event '"+e+"' is already listening");this._listenersCount++,s._newListener&&s._removeListener&&!r._onNewListener?(this._onNewListener=function(i){i===t&&null===o[e]&&(o[e]=a,r._on.call(n,e,a))},s.on("newListener",this._onNewListener),this._onRemoveListener=function(i){i===t&&!s.hasListeners(i)&&o[e]&&(o[e]=null,r._off.call(n,e,a))},o[e]=null,s.on("removeListener",this._onRemoveListener)):(o[e]=a,r._on.call(n,e,a))},unsubscribe:function(e){var t,i,r,n=this,s=this._listeners,o=this._emitter,a=this._off,l=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function d(){n._onNewListener&&(o.off("newListener",n._onNewListener),o.off("removeListener",n._onRemoveListener),n._onNewListener=null,n._onRemoveListener=null);var e=k.call(o,n);o._observers.splice(e,1)}if(e){if(!(t=s[e]))return;a.call(l,e,t),delete s[e],--this._listenersCount||d()}else{for(r=(i=c(s)).length;r-- >0;)e=i[r],a.call(l,e,s[e]);this._listeners={},this._listenersCount=0,d()}}});var y=f(["function"]),T=f(["object","function"]);function E(e,t,i){var r,n,s,o=0,a=new e((function(c,l,d){function u(){n&&(n=null),o&&(clearTimeout(o),o=0)}i=v(i,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),r=!i.overload&&"function"==typeof e.prototype.cancel&&"function"==typeof d;var h=function(e){u(),c(e)},p=function(e){u(),l(e)};r?t(h,p,d):(n=[function(e){p(e||Error("canceled"))}],t(h,p,(function(e){if(s)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");n.push(e)})),s=!0),i.timeout>0&&(o=setTimeout((function(){var e=Error("timeout");e.code="ETIMEDOUT",o=0,a.cancel(e),l(e)}),i.timeout))}));return r||(a.cancel=function(e){if(n){for(var t=n.length,i=1;i<t;i++)n[i](e);n[0](e),n=null}}),a}function k(e){var t=this._observers;if(!t)return-1;for(var i=t.length,r=0;r<i;r++)if(t[r]._target===e)return r;return-1}function S(e,t,i,r,n){if(!i)return null;if(0===r){var s=typeof t;if("string"===s){var o,a,l=0,d=0,u=this.delimiter,h=u.length;if(-1!==(a=t.indexOf(u))){o=new Array(5);do{o[l++]=t.slice(d,a),d=a+h}while(-1!==(a=t.indexOf(u,d)));o[l++]=t.slice(d),t=o,n=l}else t=[t],n=1}
8else"object"===s?n=t.length:(t=[t],n=1)}var p,m,v,g,f,y,T,E=null,k=t[r],b=t[r+1];if(r===n)i._listeners&&("function"==typeof i._listeners?(e&&e.push(i._listeners),E=[i]):(e&&e.push.apply(e,i._listeners),E=[i]));else{if("*"===k){for(a=(y=c(i)).length;a-- >0;)"_listeners"!==(p=y[a])&&(T=S(e,t,i[p],r+1,n))&&(E?E.push.apply(E,T):E=T);return E}if("**"===k){for((f=r+1===n||r+2===n&&"*"===b)&&i._listeners&&(E=S(e,t,i,n,n)),a=(y=c(i)).length;a-- >0;)"_listeners"!==(p=y[a])&&("*"===p||"**"===p?(i[p]._listeners&&!f&&(T=S(e,t,i[p],n,n))&&(E?E.push.apply(E,T):E=T),T=S(e,t,i[p],r,n)):T=S(e,t,i[p],p===b?r+2:r,n),T&&(E?E.push.apply(E,T):E=T));return E}i[k]&&(E=S(e,t,i[k],r+1,n))}if((m=i["*"])&&S(e,t,m,r+1,n),v=i["**"])if(r<n)for(v._listeners&&S(e,t,v,n,n),a=(y=c(v)).length;a-- >0;)"_listeners"!==(p=y[a])&&(p===b?S(e,t,v[p],r+2,n):p===k?S(e,t,v[p],r+1,n):((g={})[p]=v[p],S(e,t,{"**":g},r+1,n)));else v._listeners?S(e,t,v,n,n):v["*"]&&v["*"]._listeners&&S(e,t,v["*"],n,n);return E}function b(e,t,i){var r,n,s=0,o=0,a=this.delimiter,c=a.length;if("string"==typeof e)if(-1!==(r=e.indexOf(a))){n=new Array(5);do{n[s++]=e.slice(o,r),o=r+c}while(-1!==(r=e.indexOf(a,o)));n[s++]=e.slice(o)}else n=[e],s=1;else n=e,s=e.length;if(s>1)for(r=0;r+1<s;r++)if("**"===n[r]&&"**"===n[r+1])return;var l,d=this.listenerTree;for(r=0;r<s;r++)if(d=d[l=n[r]]||(d[l]={}),r===s-1)return d._listeners?("function"==typeof d._listeners&&(d._listeners=[d._listeners]),i?d._listeners.unshift(t):d._listeners.push(t),!d._listeners.warned&&this._maxListeners>0&&d._listeners.length>this._maxListeners&&(d._listeners.warned=!0,u.call(this,d._listeners.length,l))):d._listeners=t,!0;return!0}function R(e,t,i,r){for(var n,s,o,a,l=c(e),d=l.length,u=e._listeners;d-- >0;)n=e[s=l[d]],o="_listeners"===s?i:i?i.concat(s):[s],a=r||"symbol"==typeof s,u&&t.push(a?o:o.join(this.delimiter)),"object"==typeof n&&R.call(this,n,t,o,a);return t}function C(e){for(var t,i,r,n=c(e),s=n.length;s-- >0;)(t=e[i=n[s]])&&(r=!0,"_listeners"===i||C(t)||delete e[i]);return r}function P(e,t,i){this.emitter=e,this.event=t,this.listener=i}function w(e,i,r){if(!0===r)o=!0;else if(!1===r)s=!0;else{if(!r||"object"!=typeof r)throw TypeError("options should be an object or true");var s=r.async,o=r.promisify,c=r.nextTick,l=r.objectify}if(s||c||o){var d=i,u=i._origin||i;if(c&&!n)throw Error("process.nextTick is not supported");o===t&&(o="AsyncFunction"===i.constructor.name),i=function(){var e=arguments,t=this,i=this.event;return o?c?Promise.resolve():new Promise((function(e){a(e)})).then((function(){return t.event=i,d.apply(t,e)})):(c?process.nextTick:a)((function(){t.event=i,d.apply(t,e)}))},i._async=!0,i._origin=u}return[i,l?new P(this,e,i):this]}function A(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,d.call(this,e)}P.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},A.EventEmitter2=A,A.prototype.listenTo=function(e,i,n){if("object"!=typeof e)throw TypeError("target musts be an object");var s=this;function o(t){if("object"!=typeof t)throw TypeError("events must be an object");var i,r=n.reducers,o=k.call(s,e);i=-1===o?new m(s,e,n):s._observers[o];for(var a,l=c(t),d=l.length,u="function"==typeof r,h=0;h<d;h++)a=l[h],i.subscribe(a,t[a]||a,u?r:r&&r[a])}return n=v(n,{on:t,off:t,reducers:t},{on:y,off:y,reducers:T}),r(i)?o(p(i)):o("string"==typeof i?p(i.split(/\s+/)):i),this},A.prototype.stopListeningTo=function(e,t){var i=this._observers;if(!i)return!1;var r,n=i.length,s=!1;if(e&&"object"!=typeof e)throw TypeError("target should be an object");for(;n-- >0;)r=i[n],e&&r._target!==e||(r.unsubscribe(t),s=!0);return s},A.prototype.delimiter=".",A.prototype.setMaxListeners=function(e){e!==t&&(this._maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e)},A.prototype.getMaxListeners=function(){return this._maxListeners},A.prototype.event="",A.prototype.once=function(e,t,i){return this._once(e,t,!1,i)},A.prototype.prependOnceListener=function(e,t,i){return this._once(e,t,!0,i)},A.prototype._once=function(e,t,i,r){return this._many(e,1,t,i,r)},A.prototype.many=function(e,t,i,r){return this._many(e,t,i,!1,r)}
8,A.prototype.prependMany=function(e,t,i,r){return this._many(e,t,i,!0,r)},A.prototype._many=function(e,t,i,r,n){var s=this;if("function"!=typeof i)throw new Error("many only accepts instances of Function");function o(){return 0==--t&&s.off(e,o),i.apply(this,arguments)}return o._origin=i,this._on(e,o,r,n)},A.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||l.call(this);var e,t,i,r,n,o,a=arguments[0],c=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return!1;if(c&&(e=a,"newListener"!==a&&"removeListener"!==a&&"object"==typeof a)){if(i=a.length,s)for(r=0;r<i;r++)if("symbol"==typeof a[r]){o=!0;break}o||(a=a.join(this.delimiter))}var d,u=arguments.length;if(this._all&&this._all.length)for(r=0,i=(d=this._all.slice()).length;r<i;r++)switch(this.event=a,u){case 1:d[r].call(this,a);break;case 2:d[r].call(this,a,arguments[1]);break;case 3:d[r].call(this,a,arguments[1],arguments[2]);break;default:d[r].apply(this,arguments)}if(c)d=[],S.call(this,d,e,this.listenerTree,0,i);else{if("function"==typeof(d=this._events[a])){switch(this.event=a,u){case 1:d.call(this);break;case 2:d.call(this,arguments[1]);break;case 3:d.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(u-1),n=1;n<u;n++)t[n-1]=arguments[n];d.apply(this,t)}return!0}d&&(d=d.slice())}if(d&&d.length){if(u>3)for(t=new Array(u-1),n=1;n<u;n++)t[n-1]=arguments[n];for(r=0,i=d.length;r<i;r++)switch(this.event=a,u){case 1:d[r].call(this);break;case 2:d[r].call(this,arguments[1]);break;case 3:d[r].call(this,arguments[1],arguments[2]);break;default:d[r].apply(this,t)}return!0}if(!this.ignoreErrors&&!this._all&&"error"===a)throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");return!!this._all},A.prototype.emitAsync=function(){if(!this._events&&!this._all)return!1;this._events||l.call(this);var e,t,i,r,n,o,a=arguments[0],c=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);if(c&&(e=a,"newListener"!==a&&"removeListener"!==a&&"object"==typeof a)){if(r=a.length,s)for(n=0;n<r;n++)if("symbol"==typeof a[n]){t=!0;break}t||(a=a.join(this.delimiter))}var d,u=[],h=arguments.length;if(this._all)for(n=0,r=this._all.length;n<r;n++)switch(this.event=a,h){case 1:u.push(this._all[n].call(this,a));break;case 2:u.push(this._all[n].call(this,a,arguments[1]));break;case 3:u.push(this._all[n].call(this,a,arguments[1],arguments[2]));break;default:u.push(this._all[n].apply(this,arguments))}if(c?(d=[],S.call(this,d,e,this.listenerTree,0)):d=this._events[a],"function"==typeof d)switch(this.event=a,h){case 1:u.push(d.call(this));break;case 2:u.push(d.call(this,arguments[1]));break;case 3:u.push(d.call(this,arguments[1],arguments[2]));break;default:for(i=new Array(h-1),o=1;o<h;o++)i[o-1]=arguments[o];u.push(d.apply(this,i))}else if(d&&d.length){if(d=d.slice(),h>3)for(i=new Array(h-1),o=1;o<h;o++)i[o-1]=arguments[o];for(n=0,r=d.length;n<r;n++)switch(this.event=a,h){case 1:u.push(d[n].call(this));break;case 2:u.push(d[n].call(this,arguments[1]));break;case 3:u.push(d[n].call(this,arguments[1],arguments[2]));break;default:u.push(d[n].apply(this,i))}}else if(!this.ignoreErrors&&!this._all&&"error"===a)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(u)},A.prototype.on=function(e,t,i){return this._on(e,t,!1,i)},A.prototype.prependListener=function(e,t,i){return this._on(e,t,!0,i)},A.prototype.onAny=function(e){return this._onAny(e,!1)},A.prototype.prependAny=function(e){return this._onAny(e,!0)},A.prototype.addListener=A.prototype.on,A.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},A.prototype._on=function(e,i,r,n){if("function"==typeof e)return this._onAny(e,i),this;if("function"!=typeof i)throw new Error("on only accepts instances of Function");this._events||l.call(this);var s,o=this;return n!==t&&(i=(s=w.call(this,e,i,n))[0],o=s[1]),this._newListener&&this.emit
8("newListener",e,i),this.wildcard?(b.call(this,e,i,r),o):(this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),r?this._events[e].unshift(i):this._events[e].push(i),!this._events[e].warned&&this._maxListeners>0&&this._events[e].length>this._maxListeners&&(this._events[e].warned=!0,u.call(this,this._events[e].length,e))):this._events[e]=i,o)},A.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var i,n=[];if(this.wildcard){var s="string"==typeof e?e.split(this.delimiter):e.slice();if(!(n=S.call(this,null,s,this.listenerTree,0)))return this}else{if(!this._events[e])return this;i=this._events[e],n.push({_listeners:i})}for(var o=0;o<n.length;o++){var a=n[o];if(i=a._listeners,r(i)){for(var c=-1,l=0,d=i.length;l<d;l++)if(i[l]===t||i[l].listener&&i[l].listener===t||i[l]._origin&&i[l]._origin===t){c=l;break}if(c<0)continue;return this.wildcard?a._listeners.splice(c,1):this._events[e].splice(c,1),0===i.length&&(this.wildcard?delete a._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(i===t||i.listener&&i.listener===t||i._origin&&i._origin===t)&&(this.wildcard?delete a._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return this.listenerTree&&C(this.listenerTree),this},A.prototype.offAny=function(e){var t,i=0,r=0;if(e&&this._all&&this._all.length>0){for(i=0,r=(t=this._all).length;i<r;i++)if(e===t[i])return t.splice(i,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(i=0,r=t.length;i<r;i++)this.emit("removeListenerAny",t[i]);this._all=[]}return this},A.prototype.removeListener=A.prototype.off,A.prototype.removeAllListeners=function(e){if(e===t)return!this._events||l.call(this),this;if(this.wildcard){var i,r=S.call(this,null,e,this.listenerTree,0);if(!r)return this;for(i=0;i<r.length;i++)r[i]._listeners=null;this.listenerTree&&C(this.listenerTree)}else this._events&&(this._events[e]=null);return this},A.prototype.listeners=function(e){var i,r,n,s,o,a=this._events;if(e===t){if(this.wildcard)throw Error("event name required for wildcard emitter");if(!a)return[];for(s=(i=c(a)).length,n=[];s-- >0;)"function"==typeof(r=a[i[s]])?n.push(r):n.push.apply(n,r);return n}if(this.wildcard){if(!(o=this.listenerTree))return[];var l=[],d="string"==typeof e?e.split(this.delimiter):e.slice();return S.call(this,l,d,o,0),l}return a&&(r=a[e])?"function"==typeof r?[r]:r:[]},A.prototype.eventNames=function(e){var t=this._events;return this.wildcard?R.call(this,this.listenerTree,[],null,e):t?c(t):[]},A.prototype.listenerCount=function(e){return this.listeners(e).length},A.prototype.hasListeners=function(e){if(this.wildcard){var i=[],r="string"==typeof e?e.split(this.delimiter):e.slice();return S.call(this,i,r,this.listenerTree,0),i.length>0}var n=this._events,s=this._all;return!!(s&&s.length||n&&(e===t?c(n).length:n[e]))},A.prototype.listenersAny=function(){return this._all?this._all:[]},A.prototype.waitFor=function(e,i){var r=this,n=typeof i;return"number"===n?i={timeout:i}:"function"===n&&(i={filter:i}),E((i=v(i,{timeout:0,filter:t,handleError:!1,Promise:Promise,overload:!1},{filter:y,Promise:g})).Promise,(function(t,n,s){function o(){var s=i.filter;if(!s||s.apply(r,arguments))if(r.off(e,o),i.handleError){var a=arguments[0];a?n(a):t(h.apply(null,arguments).slice(1))}else t(h.apply(null,arguments))}s((function(){r.off(e,o)})),r._on(e,o,!1)}),{timeout:i.timeout,overload:i.overload})};var I=A.prototype;Object.defineProperties(A,{defaultMaxListeners:{get:function(){return I._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");I._maxListeners=e},enumerable:!0},once:{value:function(e,t,i){return E((i=v(i,{Promise:Promise,timeout:0,overload:!1},{Promise:g})).Promise,(function(i,r,n){var s;if("function"==typeof e.addEventListener)return s=function(){i(h.apply(null,arguments))},n((function(){e.removeEventListener(t,s)})),void e.addEventListener(t,s,{once:!0});var o,a=function(){o&&e.removeListener("error",o),i(h.apply(null,arguments))};"error"!==t&&(o=function(i){e.removeListener(t,a),r(i)},e.once("error",o)),n((function(){o&&e.removeListener("error",o),e.removeListener(t,a)})),e.once(t,a)}),{timeout:i.timeout,overload:i.overload})},writable:!0,configurable:!0}}),Object.defineProperties(I,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),e.exports=A}()})),ki=Object.defineProperty,Si=Object.defineProperties,bi=Object.getOwnPropertyDescriptors,Ri=Object.getOwnPropertySymbols,Ci=Object.prototype.hasOwnProperty,Pi=Object.prototype.propertyIsEnumerable,wi=(e,t,i)=>t in e?ki(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Ai=(e,t)=>{for(var i in t||(t={}))Ci.call(t,i)&&wi(e,i,t[i]);if(Ri)for(var i of Ri(t))Pi.call(t,i)&&wi(e,i,t[i]);return e},Ii=(e,t)=>Si(e,bi(t)),_i=(e,t,i)=>new Promise(((r,n)=>{var s=e=>{try{a(i.next(e))}catch(e){n(e)}},o=e=>{try{a(i.throw(e))}catch(e){n(e)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);a((i=i.apply(e,t)).next())}));!function(e){e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.TIME=4]="TIME",e[e.TIMEEND=5]="TIMEEND",e[e.ERROR=6]="ERROR",e[e.NONE=7]="NONE"}(Ti||(Ti={}));var Di,Oi="undefined"!=typeof window&&void 0!==window.expect,Mi=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanUp(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:console.log(t,...i);break;case 1:console.debug(t,...i);break;case 2:console.info(t,...i);break;case 3:console.warn(t,...i);break;case 6:console.error(t,...i);break;case 4:performance.mark(i[0]);break;case 5:{let e=i[0];try{let i=performance.measure(e,e);this.log(1,t,e,null==i?void 0:i.duration),performance.clearMarks(e),performance.clearMeasures(e)}catch(i){this.log(1,t,e,i)}break}}}};Mi.level=Oi?7:0,function(e){e[e.Publish=0]="Publish",e[e.Subscribe=1]="Subscribe"}(Di||(Di={}));var Li,Ni={WebSocketConnectionErrors:{GENERIC_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003},InitAPIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3008,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}}
8,xi=class extends Error{constructor(e,t,i,r,n,s=!1){super(r),this.code=e,this.name=t,this.message=r,this.description=n,this.isTerminal=s,Object.setPrototypeOf(this,xi.prototype),this.action=i.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(e){this.nativeError=e}};!function(e){e.NONE="NONE",e.TRACK="TRACK",e.INIT="INIT",e.PUBLISH="PUBLISH",e.UNPUBLISH="UNPUBLISH",e.JOIN="JOIN",e.SUBSCRIBE="SUBSCRIBE",e.DATA_CHANNEL_SEND="DATA_CHANNEL_SEND",e.RESTART_ICE="RESTART_ICE",e.VIDEO_PLUGINS="VIDEO_PLUGINS",e.AUDIO_PLUGINS="AUDIO_PLUGINS",e.AUTOPLAY="AUTOPLAY",e.RECONNECT_SIGNAL="RECONNECT_SIGNAL",e.VALIDATION="VALIDATION",e.PLAYLIST="PLAYLIST",e.PREVIEW="PREVIEW"}(Li||(Li={}));var Ui={WebSocketConnectionErrors:{GenericConnect:(e,t="")=>new xi(Ni.WebSocketConnectionErrors.GENERIC_CONNECT,"WebsocketConnection",e,`[WS]: ${t}`,`[WS]: ${t}`),WebSocketConnectionLost:(e,t="")=>new xi(Ni.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,"WebSocketConnectionLost",e,"Network connection lost ",t)},InitAPIErrors:{ServerErrors:(e,t,i="")=>new xi(e,"ServerErrors",t,"[INIT]: Server error",i),EndpointUnreachable:(e,t="")=>new xi(Ni.InitAPIErrors.ENDPOINT_UNREACHABLE,"EndpointUnreachable",e,"Endpoint is not reachable.",t),InvalidTokenFormat:(e,t="")=>new xi(Ni.InitAPIErrors.INVALID_TOKEN_FORMAT,"InvalidTokenFormat",e,`Token is not in proper JWT format - ${t}`,t),InitConfigNotAvailable:(e,t="")=>new xi(Ni.InitAPIErrors.INIT_CONFIG_NOT_AVAILABLE,"InitError",e,`[INIT]: ${t}`,`[INIT]: ${t}`)},TracksErrors:{GenericTrack:(e,t="")=>new xi(Ni.TracksErrors.GENERIC_TRACK,"GenericTrack",e,`[TRACK]: ${t}`,`[TRACK]: ${t}`),CantAccessCaptureDevice:(e,t,i="")=>new xi(Ni.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,"CantAccessCaptureDevice",e,`[TRACK]: No permission to access capture device - ${t}`,i),DeviceNotAvailable:(e,t,i="")=>new xi(Ni.TracksErrors.DEVICE_NOT_AVAILABLE,"DeviceNotAvailable",e,`[TRACK]: Capture device is no longer available - ${t}`,i),DeviceInUse:(e,t,i="")=>new xi(Ni.TracksErrors.DEVICE_IN_USE,"DeviceInUse",e,`[TRACK]: Capture device is in use by another application - ${t}`,i),DeviceLostMidway:(e,t,i="")=>new xi(Ni.TracksErrors.DEVICE_LOST_MIDWAY,"DeviceLostMidway",e,`Lost access to capture device midway - ${t}`,i),NothingToReturn:(e,t="")=>new xi(Ni.TracksErrors.NOTHING_TO_RETURN,"NothingToReturn",e,"There is no media to return. Please select either video or audio or both.",t),InvalidVideoSettings:(e,t="")=>new xi(Ni.TracksErrors.INVALID_VIDEO_SETTINGS,"InvalidVideoSettings",e,"Cannot enable simulcast when no video settings are provided",t),AutoplayBlocked:(e,t="")=>new xi(Ni.TracksErrors.AUTOPLAY_ERROR,"AutoplayBlocked",e,"Autoplay blocked because the user didn't interact with the document first",t),CodecChangeNotPermitted:(e,t="")=>new xi(Ni.TracksErrors.CODEC_CHANGE_NOT_PERMITTED,"CodecChangeNotPermitted",e,"Codec can't be changed mid call.",t),OverConstrained:(e,t,i="")=>new xi(Ni.TracksErrors.OVER_CONSTRAINED,"OverConstrained",e,`[TRACK]: Requested constraints cannot be satisfied with the device hardware - ${t}`,i),NoAudioDetected:(e,t="Please check the mic or use another audio input")=>new xi(Ni.TracksErrors.NO_AUDIO_DETECTED,"NoAudioDetected",e,"No audio input detected from microphone",t)},WebrtcErrors:{CreateOfferFailed:(e,t="")=>new xi(Ni.WebrtcErrors.CREATE_OFFER_FAILED,"CreateOfferFailed",e,`[${e.toString()}]: Failed to create offer. `,t),CreateAnswerFailed:(e,t="")=>new xi(Ni.WebrtcErrors.CREATE_ANSWER_FAILED,"CreateAnswerFailed",e,`[${e.toString()}]: Failed to create answer. `,t),SetLocalDescriptionFailed:(e,t="")=>new xi(Ni.WebrtcErrors.SET_LOCAL_DESCRIPTION_FAILED,"SetLocalDescriptionFailed",e,`[${e.toString()}]: Failed to set offer. `,t),SetRemoteDescriptionFailed:(e,t="")=>new xi(Ni.WebrtcErrors.SET_REMOTE_DESCRIPTION_FAILED,"SetRemoteDescriptionFailed",e,`[${e.toString()}]: Failed to set answer. `,t),ICEFailure:(e,t="")=>new xi(Ni.WebrtcErrors.ICE_FAILURE,"ICEFailure",e,`[${e.toString()}]: Ice connection state FAILED`,t)},WebsocketMethodErrors:{ServerErrors:(e,t,i)=>new xi(e,"ServerErrors",t,i,i,!0),AlreadyJoined:(e,t="")=>new xi(Ni.WebsocketMethodErrors.ALREADY_JOINED,"AlreadyJoined",e,"[JOIN]: You have already joined this room.",t),CannotJoinPreviewInProgress:(e,t="")=>new xi(Ni.WebsocketMethodErrors.CANNOT_JOIN_PREVIEW_IN_PROGRESS,"CannotJoinPreviewInProgress",e,"[JOIN]: Cannot join if preview is in progress",t)},GenericErrors:{NotConnected:(e,t="")=>new xi(Ni.GenericErrors.NOT_CONNECTED,"NotConnected",e,"Client is not connected",t),Signalling:(e,t)=>
8new xi(Ni.GenericErrors.SIGNALLING,"Signalling",e,`Unknown signalling error: ${e.toString()} ${t} `,t),Unknown:(e,t)=>new xi(Ni.GenericErrors.UNKNOWN,"Unknown",e,`Unknown exception: ${t}`,t),NotReady:(e,t="")=>new xi(Ni.GenericErrors.NOT_READY,"NotReady",e,t,t),JsonParsingFailed:(e,t,i="")=>new xi(Ni.GenericErrors.JSON_PARSING_FAILED,"JsonParsingFailed",e,`Failed to parse JSON message - ${t}`,i),TrackMetadataMissing:(e,t="")=>new xi(Ni.GenericErrors.TRACK_METADATA_MISSING,"TrackMetadataMissing",e,"Track Metadata Missing",t),RTCTrackMissing:(e,t="")=>new xi(Ni.GenericErrors.RTC_TRACK_MISSING,"RTCTrackMissing",e,"RTC Track missing",t),PeerMetadataMissing:(e,t="")=>new xi(Ni.GenericErrors.PEER_METADATA_MISSING,"PeerMetadataMissing",e,"Peer Metadata Missing",t),ValidationFailed:(e,t)=>new xi(Ni.GenericErrors.INVALID_ROLE,"ValidationFailed",Li.VALIDATION,e,t?JSON.stringify(t):""),InvalidRole:(e,t)=>new xi(Ni.GenericErrors.INVALID_ROLE,"InvalidRole",e,"Invalid role. Join with valid role",t,!0),PreviewAlreadyInProgress:(e,t="")=>new xi(Ni.GenericErrors.PREVIEW_IN_PROGRESS,"PreviewAlreadyInProgress",e,"[Preview]: Cannot join if preview is in progress",t),MissingMediaDevices:()=>new xi(Ni.GenericErrors.MISSING_MEDIADEVICES,"MissingMediaDevices",Li.JOIN,"navigator.mediaDevices is undefined. 100ms SDK won't work on this website as WebRTC is not supported on HTTP endpoints(missing navigator.mediaDevices). Please ensure you're using the SDK either on localhost or a valid HTTPS endpoint.","",!0),MissingRTCPeerConnection:()=>new xi(Ni.GenericErrors.MISSING_RTCPEERCONNECTION,"MissingRTCPeerConnection",Li.JOIN,"RTCPeerConnection which is a core requirement for WebRTC call was not found, this could be due to an unsupported browser or browser extensions blocking WebRTC","",!0)},MediaPluginErrors:{PlatformNotSupported:(e,t="")=>new xi(7001,"PlatformNotSupported",e,"Check HMS Docs to see the list of supported platforms",t),InitFailed:(e,t="")=>new xi(7002,"InitFailed",e,"Plugin init failed",t),ProcessingFailed:(e,t="")=>new xi(7003,"ProcessingFailed",e,"Plugin processing failed",t),AddAlreadyInProgress:(e,t="")=>new xi(7004,"AddAlreadyInProgress",e,"Plugin add already in progress",t)},PlaylistErrors:{NoEntryToPlay:(e,t)=>new xi(Ni.PlaylistErrors.NO_ENTRY_TO_PLAY,"NoEntryToPlay",e,"Reached end of playlist",t),NoEntryPlaying:(e,t)=>new xi(Ni.PlaylistErrors.NO_ENTRY_IS_PLAYING,"NoEntryIsPlaying",e,"No entry is playing at this time",t)}},Gi="VALIDATIONS";function Fi(e){return null!=e}var ji=()=>{if(!Fi(RTCPeerConnection)){let e=Ui.GenericErrors.MissingRTCPeerConnection();throw Mi.e(Gi,e),e}},Vi=()=>{if(!Fi(navigator.mediaDevices)){let e=Ui.GenericErrors.MissingMediaDevices();throw Mi.e(Gi,e),e}};var Bi,$i,Ki,Hi,qi,Wi,zi="HMSConnection",Ji=class{constructor(e,t){this.candidates=new Array,this.role=e,this.signal=t}get iceConnectionState(){return this.nativeConnection.iceConnectionState}get connectionState(){return this.nativeConnection.connectionState}get action(){return this.role===Di.Publish?Li.PUBLISH:Li.SUBSCRIBE}addTransceiver(e,t){return this.nativeConnection.addTransceiver(e,t)}createOffer(e,t){return _i(this,null,(function*(){try{let i=yield this.nativeConnection.createOffer(e);return Mi.d(zi,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),function(e){return e.sdp.includes("usedtx=1")?e:{type:e.type,sdp:e.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}(function(e,t){var i;let r=li(e.sdp);if(!(null==(i=r.origin)?void 0:i.username.startsWith("mozilla")))return e;let n=Array.from(t.values());return r.media.forEach((e=>{var t,i,r;let s=null==(t=e.msid)?void 0:t.split(" ")[0],o=null==(i=n.find((t=>t.type===e.type&&t.stream_id===s)))?void 0:i.track_id;o&&(e.msid=null==(r=e.msid)?void 0:r.replace(/\s(.+)/,` ${o}`))})),{type:e.type,sdp:ci(r)}}(i,t))}catch(e){throw Ui.WebrtcErrors.CreateOfferFailed(this.action,e.message)}}))}createAnswer(e){return _i(this,null,(function*(){try{let t=yield this.nativeConnection.createAnswer(e);return Mi.d(zi,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(e){throw Ui.WebrtcErrors.CreateAnswerFailed(this.action,e.message)}}))}setLocalDescription(e){return _i(this,null,(function*(){try{Mi.d(zi,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(e){throw Ui.WebrtcErrors.SetLocalDescriptionFailed(this.action,e.message)}}))}setRemoteDescription(e){return _i(this,null,(function*(){try{Mi.d(zi,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(e){throw Ui.WebrtcErrors.SetRemoteDescriptionFailed(this.action,e.message)}}))}addIceCandidate(e){return _i(this,null,(function*(){Mi.d(zi,`[role=${this.role}] addIceCandidate candidate=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.addIceCandidate(e)}))}get remoteDescription(){return this.nativeConnection.remoteDescription}getSenders(){return this.nativeConnection.getSenders()}removeTrack(e){this.nativeConnection.removeTrack(e)}setMaxBitrate(e,t){return _i(this,null,(function*(){let i=this.getSenders().find((e=>{var i;return(null==(i=null==e?void 0:e.track)?void 0:i.id)===t.getTrackIDBeingSent()}
8));if(i){let t=i.getParameters();t.encodings.length>0&&(t.encodings[0].maxBitrate=1e3*e),yield i.setParameters(t)}else Mi.w(zi,`no sender found to setMaxBitrate for track - ${t.trackId}, sentTrackId - ${t.getTrackIDBeingSent()}`)}))}getStats(){return _i(this,null,(function*(){return yield this.nativeConnection.getStats()}))}close(){return _i(this,null,(function*(){this.nativeConnection.close()}))}},Yi="renegotiation-callback-id",Qi="ion-sfu",Zi="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID",Xi="device-change",er="local-audio-enabled",tr="local-video-enabled",ir="stats-update",rr="track-degraded",nr="track-restored",sr="track-audio-level-update",or="local-audio-silence",ar=class extends Ji{constructor(e,t,i,r){super(Di.Publish,e),this.observer=i,this.transport=r,this.nativeConnection=new RTCPeerConnection(t),this.nativeConnection.createDataChannel(Qi,{protocol:"SCTP"}),this.nativeConnection.onicecandidate=({candidate:t})=>{t&&e.trickle(this.role,t)},this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState)}}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>_i(this,null,(function*(){Mi.d("HMSPublishConnection","onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()}))}trackUpdate(e){this.transport.trackUpdate(e)}},cr=class{constructor(e){this.tracks=new Array,this.nativeStream=e,this.id=e.id}};!function(e){e[e.PEER_ADDED=0]="PEER_ADDED",e[e.PEER_REMOVED=1]="PEER_REMOVED",e[e.PEER_KNOCKED=2]="PEER_KNOCKED",e[e.ROOM_TYPE_CHANGED=3]="ROOM_TYPE_CHANGED",e[e.METADATA_UPDATED=4]="METADATA_UPDATED",e[e.SCREENSHARE_STARTED=5]="SCREENSHARE_STARTED",e[e.SCREENSHARE_STOPPED=6]="SCREENSHARE_STOPPED",e[e.DEFAULT_UPDATE=7]="DEFAULT_UPDATE",e[e.RECORDING_STATE_UPDATED=8]="RECORDING_STATE_UPDATED",e[e.BROWSER_RECORDING_STATE_UPDATED=9]="BROWSER_RECORDING_STATE_UPDATED",e[e.SERVER_RECORDING_STATE_UPDATED=10]="SERVER_RECORDING_STATE_UPDATED",e[e.RTMP_STREAMING_STATE_UPDATED=11]="RTMP_STREAMING_STATE_UPDATED",e[e.HLS_STREAMING_STATE_UPDATED=12]="HLS_STREAMING_STATE_UPDATED",e[e.ROOM_STATE=13]="ROOM_STATE"}(Bi||(Bi={})),function(e){e[e.PEER_JOINED=0]="PEER_JOINED",e[e.PEER_LEFT=1]="PEER_LEFT",e[e.AUDIO_TOGGLED=2]="AUDIO_TOGGLED",e[e.VIDEO_TOGGLED=3]="VIDEO_TOGGLED",e[e.BECAME_DOMINANT_SPEAKER=4]="BECAME_DOMINANT_SPEAKER",e[e.RESIGNED_DOMINANT_SPEAKER=5]="RESIGNED_DOMINANT_SPEAKER",e[e.STARTED_SPEAKING=6]="STARTED_SPEAKING",e[e.STOPPED_SPEAKING=7]="STOPPED_SPEAKING",e[e.ROLE_UPDATED=8]="ROLE_UPDATED",e[e.PEER_LIST=9]="PEER_LIST",e[e.NAME_UPDATED=10]="NAME_UPDATED",e[e.METADATA_UPDATED=11]="METADATA_UPDATED"}($i||($i={})),function(e){e[e.TRACK_ADDED=0]="TRACK_ADDED",e[e.TRACK_REMOVED=1]="TRACK_REMOVED",e[e.TRACK_MUTED=2]="TRACK_MUTED",e[e.TRACK_UNMUTED=3]="TRACK_UNMUTED",e[e.TRACK_DESCRIPTION_CHANGED=4]="TRACK_DESCRIPTION_CHANGED",e[e.TRACK_DEGRADED=5]="TRACK_DEGRADED",e[e.TRACK_RESTORED=6]="TRACK_RESTORED"}(Ki||(Ki={})),(qi=Hi||(Hi={}))[qi.DEFAULT=0]="DEFAULT",function(e){e.NONE="none",e.LOW="low",e.MEDIUM="medium",e.HIGH="high"}(Wi||(Wi={}));var lr,dr,ur,hr={f:Wi.HIGH,h:Wi.MEDIUM,q:Wi.LOW};!function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264"}(lr||(lr={})),function(e){e.OPUS="opus"}(dr||(dr={})),function(e){e.audio="audio",e.video="video"}(ur||(ur={}));var pr,mr=class extends cr{constructor(e,t){super(e),this.audio=!0,this.video=Wi.NONE,this.frameRate=Wi.HIGH,this.connection=t}setAudio(e){this.audio!==e&&(this.audio=e,this.syncWithApiChannel())}setVideoLayer(e){this.video=e,Mi.d(`[Remote stream] ${this.id}`,`Switching to ${e} layer`)}setVideo(e){this.video!==e?(this.setVideoLayer(e),this.syncWithApiChannel()):Mi.d(`[Remote stream] ${this.id}`,`Already on ${e} layer`)}getSimulcastLayer(){return this.video}isAudioSubscribed(){return this.audio}isServerHandlingDegradation(){return this.connection.isServerHandlingDegradation}syncWithApiChannel(){let e={streamId:this.id,video:this.video,audio:this.audio,framerate:this.frameRate};
8this.connection.sendOverApiDataChannel(JSON.stringify(e))}},vr=class{get enabled(){return this.nativeTrack.enabled}get trackId(){return this.firstTrackId||this.sdpTrackId||this.nativeTrack.id}getMediaTrackSettings(){return this.nativeTrack.getSettings()}setEnabled(e){return _i(this,null,(function*(){this.nativeTrack.enabled=e}))}constructor(e,t,i){this.stream=e,this.nativeTrack=t,this.source=i}setSdpTrackId(e){this.sdpTrackId=e}setFirstTrackId(e){this.firstTrackId=e}cleanup(){var e;null==(e=this.nativeTrack)||e.stop()}};!function(e){e.AUDIO="audio",e.VIDEO="video"}(pr||(pr={}));var gr,fr=class extends vr{constructor(e,t,i){if(super(e,t,i),this.type=pr.AUDIO,this.audioElement=null,"audio"!==t.kind)throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?100*this.audioElement.volume:null}setVolume(e){if(e<0||e>100)throw Error("Please pass a valid number between 0-100");this.subscribeToAudio(0!==e&&this.enabled),this.audioElement&&(this.audioElement.volume=e/100)}setAudioElement(e){this.audioElement=e}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(e){return _i(this,null,(function*(){var t;if(this.audioElement)try{"function"==typeof this.audioElement.setSinkId&&(yield null==(t=this.audioElement)?void 0:t.setSinkId(e.deviceId),this.outputDevice=e)}catch(e){Mi.d("audio-track",e)}else Mi.d("audio-track","no audio element to set output")}))}removeSink(){var e;this.audioElement&&(null==(e=window.HMS)?void 0:e.AUDIO_SINK)&&(this.audioElement.srcObject=null,this.subscribeToAudio(!1))}addSink(){var e,t;if(!this.nativeTrack||!this.audioElement||!(null==(e=window.HMS)?void 0:e.AUDIO_SINK))return;let i=this.audioElement.srcObject;null!==i&&i instanceof MediaStream&&(null==(t=i.getAudioTracks()[0])?void 0:t.id)===this.nativeTrack.id||(this.audioElement.srcObject=new MediaStream([this.nativeTrack]),this.subscribeToAudio(!0))}subscribeToAudio(e){this.stream instanceof mr&&this.stream.setAudio(e)}},yr=class extends fr{setEnabled(e){var t=e=>super[e];return _i(this,null,(function*(){e!==this.enabled&&(yield t("setEnabled").call(this,e),this.subscribeToAudio(e))}))}},Tr=class extends vr{constructor(e,t,i){if(super(e,t,i),this.type=pr.VIDEO,this.sinkCount=0,"video"!==t.kind)throw new Error("Expected 'track' kind = 'video'")}hasSinks(){return this.sinkCount>0}addSink(e){this.addSinkInternal(e,this.nativeTrack)}removeSink(e){e.srcObject=null,this.sinkCount>0&&this.sinkCount--}addSinkInternal(e,t){var i;let r=e.srcObject;null!==r&&r instanceof MediaStream&&(null==(i=r.getVideoTracks()[0])?void 0:i.id)===t.id||(e.srcObject=new MediaStream([t]),this.sinkCount++)}},Er=class extends Tr{constructor(){super(...arguments),this._degraded=!1,this._degradedAt=null,this._layerDefinitions=[]}get degraded(){return this._degraded}get degradedAt(){return this._degradedAt}setEnabled(e){var t=e=>super[e];return _i(this,null,(function*(){e!==this.enabled&&(this._degraded&&!e&&(this._degraded=!1),yield t("setEnabled").call(this,e))}))}preferLayer(e){this.stream.setVideo(e)}getSimulcastLayer(){return this.stream.getSimulcastLayer()}addSink(e){super.addSink(e),this.updateLayer()}removeSink(e){super.removeSink(e),this.updateLayer()}getSimulcastDefinitions(){return[...this._layerDefinitions]}setSimulcastDefinitons(e){this._layerDefinitions=e}setDegraded(e){if(this._degraded=e,e&&(this._degradedAt=new Date),this.stream instanceof mr&&this.stream.isServerHandlingDegradation()){let t=e?Wi.NONE:Wi.HIGH;this.stream.setVideoLayer(t)}else this.updateLayer()}updateLayer(){let e=this.hasSinks()?Wi.HIGH:Wi.NONE;this.degraded&&(e=Wi.NONE),this.stream.setVideo(e)}},kr=class extends Ji{constructor(e,t,i,r){super(Di.Subscribe,e),this.TAG="[HMSSubscribeConnection]",this.remoteStreams=new Map,this.pendingMessageQueue=[],this.handlePendingApiMessages=()=>{this.pendingMessageQueue.length>0&&(Mi.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach((e=>
8this.sendOverApiDataChannel(e))),this.pendingMessageQueue.length=0)},this.observer=i,this.isServerHandlingDegradation=r,this.nativeConnection=new RTCPeerConnection(t),this.initNativeConnectionCallbacks()}initNativeConnectionCallbacks(){this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState)},this.nativeConnection.ondatachannel=e=>{e.channel.label===Qi&&(this.apiChannel=new class{constructor(e,t,i=""){this.TAG="HMSDataChannel",this.nativeChannel=e,this.observer=t,this.metadata=i,e.onmessage=e=>{this.observer.onMessage(e.data)}}get id(){return this.nativeChannel.id}get label(){return this.nativeChannel.label}get readyState(){return this.nativeChannel.readyState}send(e){Mi.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}}(e.channel,{onMessage:e=>{this.observer.onApiChannelMessage(e)}},`role=${this.role}`),e.channel.onopen=this.handlePendingApiMessages)},this.nativeConnection.onicecandidate=e=>{null!==e.candidate&&this.signal.trickle(this.role,e.candidate)},this.nativeConnection.ontrack=e=>{var t;let i=e.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let e=new mr(i,this);this.remoteStreams.set(r,e),i.onremovetrack=t=>{let i=e.tracks.findIndex((e=>e.nativeTrack.id===t.track.id));if(i>=0){let t=e.tracks[i];this.observer.onTrackRemove(t),e.tracks.splice(i,1),0===e.tracks.length&&this.remoteStreams.delete(r)}}}let n=this.remoteStreams.get(r),s=new("audio"===e.track.kind?yr:Er)(n,e.track),o=function(e,t){var i;if(!(null==e?void 0:e.sdp)||!t)return;let r=li(e.sdp).media.find((e=>Fi(e.mid)&&parseInt(e.mid)===parseInt(t)));return null==(i=null==r?void 0:r.msid)?void 0:i.split(" ")[1]}(this.remoteDescription,null==(t=e.transceiver)?void 0:t.mid);o&&s.setSdpTrackId(o),n.tracks.push(s),this.observer.onTrackAdd(s)}}sendOverApiDataChannel(e){this.apiChannel&&"open"===this.apiChannel.readyState?this.apiChannel.send(e):(Mi.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,e),this.pendingMessageQueue.push(e))}close(){var e=e=>super[e];return _i(this,null,(function*(){var t;yield e("close").call(this),null==(t=this.apiChannel)||t.close()}))}},Sr=new ui.UAParser,br="undefined"==typeof window&&!(null==(gr=Sr.getBrowser().name)?void 0:gr.toLowerCase().includes("electron")),Rr="undefined"!=typeof window;var Cr,Pr=function(){if(br)return"hmsclient/0.1.44";let e=Sr.getDevice(),t=Sr.getBrowser(),i=Sr.getOS();return e.type?`hmsclient/0.1.44 ${i.name}/${i.version} (${e.vendor}_${e.type}_/_${t.name}_${t.version})`:`hmsclient/0.1.44 ${i.name}/${i.version} (${t.name}_${t.version})`}(),wr="InitService";!function(e){e.JOIN="join",e.OFFER="offer",e.ANSWER="answer",e.TRICKLE="trickle",e.TRACK_UPDATE="track-update",e.BROADCAST="broadcast",e.ANALYTICS="analytics",e.SERVER_ERROR="on-error",e.SERVER_WARNING="on-warning",e.SDK_NOTIFICATION="sdk-notification",e.LEAVE="leave",e.END_ROOM="end-room",e.PING="ping",e.ROLE_CHANGE_REQUEST="role-change-request",e.ROLE_CHANGE="role-change",e.TRACK_UPDATE_REQUEST="track-update-request",e.PEER_LEAVE_REQUEST="peer-leave-request",e.CHANGE_TRACK_MUTE_STATE_REQUEST="change-track-mute-state-request",e.START_RTMP_OR_RECORDING_REQUEST="rtmp-start",e.STOP_RTMP_AND_RECORDING_REQUEST="rtmp-stop",e.UPDATE_PEER_METADATA="peer-update",e.START_HLS_STREAMING="hls-start",e.STOP_HLS_STREAMING="hls-stop"}(Cr||(Cr={}));var Ar,Ir=class{constructor(){this._volume=1,this._codec=dr.OPUS,this._maxBitrate=32,this._deviceId="default",this._advanced=[{googEchoCancellation:{exact:!0}},{googExperimentalEchoCancellation:{exact:!0}},{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{googHighpassFilter:{exact:!0}},{googAudioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}build(){return new _r(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced)}}
8,_r=class{constructor(e,t,i,r,n){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=n}toConstraints(){return{deviceId:this.deviceId,advanced:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}},Dr=class{constructor(){this._width=320,this._height=180,this._codec=lr.VP8,this._maxFramerate=30,this._maxBitrate=150,this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if("number"==typeof e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}build(){return new Or(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate)}},Or=class{constructor(e,t,i,r,n,s,o){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=o,this.deviceId=n,this.advanced=s}toConstraints(){return{width:this.width,height:this.height,frameRate:this.maxFramerate,deviceId:this.deviceId}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec}}},Mr=class{constructor(){this._video=(new Dr).build(),this._audio=(new Ir).build(),this._screen=(new Dr).build(),this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(null===this._audio&&null===this._video)throw Ui.TracksErrors.NothingToReturn(Li.TRACK);if(null===this._video&&this._simulcast)throw Ui.TracksErrors.InvalidVideoSettings(Li.TRACK,"Cannot enable simulcast when no video settings are provided");return new Lr(this._video,this._audio,this._simulcast,this._screen||void 0)}},Lr=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:null!==this.audio,video_enabled:null!==this.video};return this.audio&&(e=Ai(Ai({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=Ai(Ai({},this.video.toAnalyticsProperties()),e)),e}};!function(e){e.ROOM_STATE="room-state",e.PEER_JOIN="on-peer-join",e.PEER_LEAVE="on-peer-leave",e.PEER_LIST="peer-list",e.TRACK_METADATA_ADD="on-track-add",e.TRACK_UPDATE="on-track-update",e.CHANGE_TRACK_MUTE_STATE_UPDATE="on-change-track-mute-state-request",e.ACTIVE_SPEAKERS="active-speakers",e.SFU_STATS="sfu-stats",e.ON_SFU_TRACK_LAYER_UPDATE="on-track-layer-update",e.BROADCAST="on-broadcast",e.ROLE_CHANGE="on-role-change",e.POLICY_CHANGE="on-policy-change",e.ROLE_CHANGE_REQUEST="on-role-change-request",e.TRACK_UPDATE_REQUEST="on-track-update-request",e.PEER_UPDATE="on-peer-update",e.PEER_LEAVE_REQUEST="on-peer-leave-request",e.UNSUPPORTED="unsupported",e.RTMP_START="on-rtmp-start",e.RTMP_STOP="on-rtmp-stop",e.RECORDING_START="on-record-start",e.RECORDING_STOP="on-record-stop",e.HLS_START="on-hls-start",e.HLS_STOP="on-hls-stop"}(Ar||(Ar={}));var Nr=class{constructor({sender:e,message:t,type:i="chat",recipientPeer:r,recipientRoles:n,time:s}){this.sender=e,this.message=t,this.type=i,this.recipientPeer=r,this.recipientRoles=n,this.time=s}toSignalParams(){var e,t;let i=null==(e=this.recipientRoles)?void 0:e.map((e=>e.name)),r=null==(t=this.recipientPeer)?void 0:t.peerId,n={info:{sender:this.sender.peerId,message:this.message,type:this.type}};return(null==i?void 0:i.length)&&(n.roles=i),r&&(n.peer_id=r),n}},xr=class{constructor({peerId:e,name:t,isLocal:i,customerUserId:r,metadata:n,role:s}){this.customerUserId="",this.metadata="",this.auxiliaryTracks=[],this.name=t,this.peerId=e,this.isLocal=i,this.customerUserId=r,this.metadata=n,s&&(this.role=s)}updateRole(e){this.role=e}updateName(e){this.name=e}updateMetadata(e){this.metadata=e}},Ur=class{};Ur.makePeerId=()=>yi();var Gr,Fr=class extends xr{constructor(e){super(Ii(Ai({},e),{peerId:Ur.makePeerId(),isLocal:!0})),this.isLocal=!0,this.auxiliaryTracks=[]}},jr=class extends xr{constructor(e){super(Ii(Ai({},e),{isLocal:!1})),this.isLocal=!1,this.auxiliaryTracks=[]}};function Vr(e,t){let i=function(e,t){let i=e.message.toLowerCase();if("screen"===t&&"chrome"===ei.browserDetails.browser&&"NotAllowedError"===e.name&&e.message.includes("denied by system"))return Ui.TracksErrors.DeviceNotAvailable(Li.TRACK,t,e.message);switch(e.name){case"OverconstrainedError":return Ui.TracksErrors.OverConstrained(Li.TRACK,t,e.constraint);case"NotAllowedError":return Ui.TracksErrors.CantAccessCaptureDevice(Li.TRACK,t,e.message);case"NotFoundError":return Ui.TracksErrors.DeviceNotAvailable(Li.TRACK,t,e.message);case"NotReadableError":return Ui.TracksErrors.DeviceInUse(Li.TRACK,t,e.message);case"TypeError":return Ui.TracksErrors.NothingToReturn(Li.TRACK,e.message);default:return i.includes("device not found")?Ui.TracksErrors.DeviceNotAvailable(Li.TRACK,t,e.message):i.includes("permission denied")?Ui.TracksErrors.CantAccessCaptureDevice(Li.TRACK,t,e.message):Ui.TracksErrors.GenericTrack(Li.TRACK,e.message)}}(e,t);return i.addNativeError(e),i}function Br(e){return"canvas"in e||"MediaStreamAudioDestinationNode"===e.label||""===e.label}!function(e){e.AUDIO="audio",e.VIDEO="video",e.AV="audio, video",e.SCREEN="screen"}(Gr||(Gr={}));var $r=class{constructor(e=1/0){this.capacity=e,this.storage=[]}size(){return this.storage.length}enqueue(e){this.size()===this.capacity&&this.dequeue(),this.storage.push(e)}dequeue(){return this.storage.shift()}aggregate(e){return e(this.storage)}};function Kr(e){if(e<0)throw Error("`ms` should be a positive integer");return new Promise((t=>setTimeout(t,e)))}var Hr,qr;!function(e){e.TRANSFORM="TRANSFORM",e.ANALYZE="ANALYZE"}(Hr||(Hr={})),function(e){e.CUSTOM="CUSTOM",e.LOCAL="LOCAL",e.HMS="HMS"}(qr||(qr={}));var Wr,zr,Jr=function(){if(Rr&&window){let e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e?qr.LOCAL:e.includes("app.100ms.live")?qr.HMS:qr.CUSTOM}return qr.CUSTOM}(),Yr=class{constructor({name:e,level:t,properties:i,includesPII:r,timestamp:n}){this.name=e,this.level=t,this.includesPII=r||!1,this.properties=i||{},this.timestamp=n||(new Date).getTime()}toSignalParams(){return{name:this.name,info:Ii(Ai({},this.properties),{timestamp:this.timestamp,domain:Jr}),timestamp:(new Date).getTime()}}};!function(e){e[e.VERBOSE=0]="VERBOSE",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.OFF=3]="OFF"}(Wr||(Wr={})),function(e){e[e.VERBOSE=0]="VERBOSE",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.OFF=3]="OFF"}(zr||(zr={}));var Qr=class{static failure(e,t){let i=zr.ERROR,r=Ai({plugin_name:e},t.toAnalyticsProperties());return new Yr({name:"mediaPlugin.failed",level:i,properties:r})}static audioPluginStats({pluginName:e,duration:t,loadTime:i}){let r=zr.INFO;return new Yr({name:"mediaPlugin.stats",level:r,properties:{plugin_name:e,duration:t,load_time:i}})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:n,inputFrameRate:s,pluginFrameRate:o}){let a=zr.INFO;return new Yr({name:"mediaPlugin.stats",level:a,properties:{plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:n,input_frame_rate:s,plugin_frame_rate:o}})}},Zr="AnalyticsEventsService",Xr=new class{constructor(){this.bufferSize=100,this.transports=[],this.pendingEvents=[],this.level=Wr.INFO}addTransport(e){this.transports.push(e)}removeTransport(e){this.transports.splice(this.transports.indexOf(e),1)}queue(e){if(e.level>=this.level&&(this.pendingEvents.push(e),this.pendingEvents.length>this.bufferSize)){let e=this.pendingEvents.shift();
8Mi.d(Zr,"Max buffer size reached","Removed event to accommodate new events",e)}return this}flush(){if(0!==this.transports.length)try{for(;this.pendingEvents.length>0;){let e=this.pendingEvents.shift();e&&this.transports.forEach((t=>t.sendEvent(e)))}}catch(e){Mi.w(Zr,"Flush Failed",e)}else Mi.w(Zr,"No valid signalling API found to flush analytics")}},en=Xr,tn="AudioPluginsAnalytics",rn="AudioPluginsManager",nn=class{constructor(e){this.key=e,this.storage=null}getStorage(){return Rr&&(this.storage=window.localStorage),this.storage}get(){var e;let t=null==(e=this.getStorage())?void 0:e.getItem(this.key);return t?JSON.parse(t):void 0}set(e){var t;let i=JSON.stringify(e);null==(t=this.getStorage())||t.setItem(this.key,i)}clear(){var e;null==(e=this.getStorage())||e.removeItem(this.key)}},sn=new class{constructor(){this.storage=new nn("hms-device-selection"),this.remember=!1,this.TAG="HMSDeviceStorage"}setDevices(e){this.devices=e}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find((e=>this.isSame({deviceId:t,groupId:i},e)));if(!r)return void Mi.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);let n=this.storage.get()||{};n[e]=r,this.storage.set(n)}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}};function on(e,t){return function(i){return i in e&&e[i]!==t[i]}}var an,cn=class extends fr{constructor(e,t,i,r,n=(new Ir).build()){super(e,t,i),this.eventBus=r,this.handleSettingsChange=e=>_i(this,null,(function*(){let t=this.stream,i=on(e,this.settings);i("maxBitrate")&&e.maxBitrate&&(yield t.setMaxBitrate(e.maxBitrate,this)),i("advanced")&&(yield this.nativeTrack.applyConstraints(e.toConstraints()))})),this.handleDeviceChange=(e,t=!1)=>_i(this,null,(function*(){on(e,this.settings)("deviceId")&&(yield this.replaceTrackWith(e),t||sn.updateSelection("audioInput",{deviceId:e.deviceId,groupId:this.nativeTrack.getSettings().groupId}))})),e.tracks.push(this),this.settings=n,"default"===n.deviceId&&!Br(t)&&(this.settings=this.buildNewSettings({deviceId:t.getSettings().deviceId})),this.pluginsManager=new class{constructor(e){this.pluginAddInProgress=!1,this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new class{constructor(){this.initTime={},this.addedTimestamps={},this.pluginAdded={}}added(e){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e]};en.queue(Qr.audioPluginStats(t)).flush(),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(en.queue(Qr.failure(e,t)).flush(),this.clean(e))}initWithTime(e,t){return _i(this,null,(function*(){if(this.initTime[e])return void Mi.i(tn,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);let i;try{i=yield this.timeInMs(t),Mi.i(tn,`Time taken for Plugin ${e} initialization : ${i}`)}catch(t){let i=Ui.MediaPluginErrors.InitFailed(Li.AUDIO_PLUGINS,`failed during initialization of plugin${t.message||t}`);throw Mi.e(tn,i),this.failure(e,i),i}i&&(this.initTime[e]=i)}))}timeInMs(e){return _i(this,null,(function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)}))}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.pluginAdded[e]}}}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return _i(this,null,(function*(){var t;let i=null==(t=e.getName)?void 0:t.call(e);if(i){if(this.pluginAddInProgress){let e=Ui.MediaPluginErrors.AddAlreadyInProgress(Li.AUDIO_PLUGINS,"Add Plugin is already in Progress");throw this.analytics.failure(i,e),Mi.w("can't add another plugin when previous add is in progress"),e}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}}else Mi.w("no name provided by the plugin")}))}addPluginInternal(e){return _i(this,null,(function*(){var t;let i=null==(t=e.getName)?void 0:t.call(e);
8if(this.pluginsMap.get(i))Mi.w(rn,`plugin - ${i} already added.`);else{if(!e.isSupported()){let t=Ui.MediaPluginErrors.PlatformNotSupported(Li.AUDIO_PLUGINS,"platform not supported ");return this.analytics.failure(i,t),void Mi.i(rn,`Platform is not supported for plugin - ${e.getName()}`)}try{0===this.pluginsMap.size?yield this.initContextAndAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(i),yield this.analytics.initWithTime(i,(()=>_i(this,null,(function*(){return e.init()})))),this.pluginsMap.set(i,e),yield this.processPlugin(e),yield this.connectToDestination()}catch(e){throw Mi.e(rn,"failed to add plugin",e),e}}}))}removePlugin(e){return _i(this,null,(function*(){yield this.removePluginInternal(e),0===this.pluginsMap.size?(yield this.cleanup(),Mi.i(rn,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()}))}cleanup(){return _i(this,null,(function*(){var e,t,i,r;for(let e of this.pluginsMap.values())yield this.removePluginInternal(e);yield this.hmsTrack.setProcessedTrack(void 0),null==(e=this.audioContext)||e.close(),null==(t=this.sourceNode)||t.disconnect(),null==(i=this.prevAudioNode)||i.disconnect(),null==(r=this.outputTrack)||r.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.audioContext=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0}))}reprocessPlugins(){return _i(this,null,(function*(){if(0===this.pluginsMap.size||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initContextAndAudioNodes();for(let t of e)yield this.addPlugin(t)}))}initContextAndAudioNodes(){return _i(this,null,(function*(){if(this.audioContext||(this.audioContext=new AudioContext),!this.sourceNode){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e)}if(!this.destinationNode){this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0];try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw Mi.e(rn,"error in setting processed track",e),e}}}))}processPlugin(e){return _i(this,null,(function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();Mi.e(rn,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}}))}connectToDestination(){return _i(this,null,(function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){Mi.e(rn,"error in connecting to destination node",e)}}))}removePluginInternal(e){return _i(this,null,(function*(){var t;let i=null==(t=e.getName)?void 0:t.call(e);this.pluginsMap.get(i)?(Mi.i(rn,`removing plugin ${i}`),this.pluginsMap.delete(i),e.stop(),this.analytics.removed(i)):Mi.w(rn,`plugin - ${i} not found to remove.`)}))}}(this),this.setFirstTrackId(t.id)}replaceTrackWith(e){return _i(this,null,(function*(){let t=this.nativeTrack,i=this.enabled,r=Boolean(this.audioLevelMonitor);null==t||t.stop();let n=yield function(e){return _i(this,null,(function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:!!e&&e.toConstraints()})).getAudioTracks()[0]}catch(e){throw Vr(e,Gr.AUDIO)}}))}(e);n.enabled=i;let s=this.stream;yield s.replaceSenderTrack(t,this.processedTrack||n),yield s.replaceStreamTrack(t,n),this.nativeTrack=n,r&&this.initAudioLevelMonitor(),yield this.pluginsManager.reprocessPlugins()}))}setEnabled(e){var t=e=>super[e];return _i(this,null,(function*(){e!==this.enabled&&(e&&Br(this.nativeTrack)&&(yield this.replaceTrackWith(this.settings)),yield t("setEnabled").call(this,e),this.eventBus.localAudioEnabled.publish(e),this.stream.trackUpdate(this))}))}isPublishedTrackId(e){return this.publishedTrackId===e}setSettings(e,t=!1){return _i(this,null,(function*(){let i=this.buildNewSettings(e);yield this.handleDeviceChange(i,t),Br(this.nativeTrack)||(yield this.handleSettingsChange(i)),this.settings=i}))}getPlugins(){return this.pluginsManager.getPlugins()}
8addPlugin(e){return _i(this,null,(function*(){return this.pluginsManager.addPlugin(e)}))}removePlugin(e){return _i(this,null,(function*(){return this.pluginsManager.removePlugin(e)}))}setProcessedTrack(e){return _i(this,null,(function*(){if(!e)return this.processedTrack&&(yield this.stream.replaceSenderTrack(this.processedTrack,this.nativeTrack)),void(this.processedTrack=void 0);e!==this.processedTrack&&(this.processedTrack?yield this.stream.replaceSenderTrack(this.processedTrack,e):yield this.stream.replaceSenderTrack(this.nativeTrack,e),this.processedTrack=e)}))}initAudioLevelMonitor(){this.audioLevelMonitor&&this.destroyAudioLevelMonitor(),Mi.d("HMSLocalAudioTrack","Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new class{constructor(e,t,i){this.track=e,this.audioLevelEvent=t,this.silenceEvent=i,this.TAG="[TrackAudioLevelMonitor]",this.audioLevel=0,this.isMonitored=!1,this.interval=100,this.historyInterval=700,this.history=new $r(this.historyInterval/this.interval),this.detectSilence=()=>_i(this,null,(function*(){let e=0;for(;this.isMonitored;){if(this.track.enabled){if(!this.isSilentThisInstant())break;if(e++,e>10){this.silenceEvent.publish({track:this.track});break}}yield Kr(30)}}));try{let e=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(e)}catch(e){Mi.w(this.TAG,"Unable to initialize AudioContext",e)}}start(){this.stop(),this.isMonitored=!0,Mi.d(this.TAG,"Starting track Monitor",this.track),this.loop().then((()=>Mi.d(this.TAG,"Stopping track Monitor",this.track)))}stop(){this.analyserNode?(this.sendAudioLevel(0),this.isMonitored=!1):Mi.d(this.TAG,"AudioContext not initialized")}loop(){return _i(this,null,(function*(){for(;this.isMonitored;)this.sendAudioLevel(this.getMaxAudioLevelOverPeriod()),yield Kr(this.interval)}))}sendAudioLevel(e=0){if(e=e>35?e:0,Math.abs(this.audioLevel-e)>5){this.audioLevel=e;let t={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(t)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode)return void Mi.d(this.TAG,"AudioContext not initialized");let e=this.calculateAudioLevel();return void 0!==e&&this.history.enqueue(e),this.history.aggregate((e=>Math.max(...e)))}calculateAudioLevel(){if(!this.analyserNode)return void Mi.d(this.TAG,"AudioContext not initialized");let e=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(e);let t=.009,i=t;for(let t of e)i=Math.max(i,(t-128)/128);let r=(Math.log(t)-Math.log(i))/Math.log(t);return Math.ceil(Math.min(Math.max(100*r,0),100))}isSilentThisInstant(){if(!this.analyserNode)return void Mi.d(this.TAG,"AudioContext not initialized");let e=new Uint8Array(this.analyserNode.fftSize);return this.analyserNode.getByteTimeDomainData(e),!e.some((e=>128!==e&&0!==e))}createAnalyserNodeForStream(e){let t=new AudioContext,i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i}}(this,this.eventBus.trackAudioLevelUpdate,this.eventBus.localAudioSilence),this.audioLevelMonitor.start(),this.audioLevelMonitor.detectSilence()}destroyAudioLevelMonitor(){var e;null==(e=this.audioLevelMonitor)||e.stop(),this.audioLevelMonitor=void 0}cleanup(){var e=e=>super[e];return _i(this,null,(function*(){var t;e("cleanup").call(this),yield this.pluginsManager.cleanup(),null==(t=this.processedTrack)||t.stop(),this.destroyAudioLevelMonitor()}))}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}buildNewSettings(e){let{volume:t,codec:i,maxBitrate:r,deviceId:n,advanced:s}=Ai(Ai({},this.settings),e);return new _r(t,i,r,n,s)}};!function(e){e.TRANSFORM="TRANSFORM",e.ANALYZE="ANALYZE"}(an||(an={}));var ln=class{constructor(){this.total=0,this.count=0}add(e){this.count++,this.total+=e}getAvg(){return Math.floor(this.total/this.count)}reset(){this.total=0,this.count=0}},dn="VideoPluginsAnalytics",un=320,hn=240,pn="VideoPluginsManager",mn="HMSLocalStream",vn=class extends cr{constructor(){super(...arguments),this.connection=null}setConnection(e){this.connection=e}addTransceiver(e,t){let i=[];if(e instanceof bn)if(t.length>0)Mi.v(mn,"Simulcast enabled with layers",t),i.push(...t);else{let t={active:this.nativeStream.active};e.settings.maxBitrate&&!br&&(t.maxBitrate=e.settings.maxBitrate),i.push(t)}let r=this.connection.addTransceiver(e.nativeTrack,{streams:[this.nativeStream],direction:"sendonly",sendEncodings:i});return this.setPreferredCodec(r,e.nativeTrack.kind),r}setMaxBitrate(e,t){return _i(this,null,(function*(){var i;yield null==(i=this.connection)?void 0:i.setMaxBitrate(e,t)}))}setPreferredCodec(e,t){}replaceTrack(e,t){return _i(this,null,(function*(){yield this.replaceSenderTrack(e,t),e.stop(),this.replaceStreamTrack(e,t)}))}replaceStreamTrack(e,t){this.nativeStream.addTrack(t),this.nativeStream.removeTrack(e)}replaceSenderTrack(e,t){return _i(this,null,(function*(){var i;let r=null==(i=this.connection)?void 0:i.getSenders().find((t=>t.track&&t.track.id===e.id));void 0!==r?yield r.replaceTrack(t):Mi.w(mn,`No sender found for trackId=${e.id}`)}))}removeSender(e){let t=0;
8this.connection.getSenders().forEach((i=>{var r,n;if((null==(r=i.track)?void 0:r.id)===e.trackId||(null==(n=i.track)?void 0:n.id)===e.getTrackIDBeingSent()){this.connection.removeTrack(i),t+=1;let r=this.tracks.indexOf(e);-1!==r?this.tracks.splice(r,1):Mi.e(mn,`Cannot find ${e.trackId} in locally stored tracks`)}})),1!==t&&Mi.e(mn,`Removed ${t} sender's, expected to remove 1`)}trackUpdate(e){var t;null==(t=this.connection)||t.trackUpdate(e)}},gn=class{static connect(e,t=new Date,i=new Date,r){let n=this.eventNameFor("connect",void 0===e),s=e?zr.ERROR:zr.INFO,o=this.getPropertiesWithError({[this.KEY_REQUESTED_AT]:null==t?void 0:t.getTime(),[this.KEY_RESPONDED_AT]:null==i?void 0:i.getTime(),endpoint:r},e);return new Yr({name:n,level:s,properties:o})}static disconnect(e){let t=e?zr.ERROR:zr.INFO,i=this.getPropertiesWithError({},e);return new Yr({name:"disconnected",level:t,properties:i})}static join(e,t,i){let r=this.eventNameFor("join",void 0===i),n=i?zr.ERROR:zr.INFO,s=this.getPropertiesWithError({[this.KEY_REQUESTED_AT]:e.getTime(),[this.KEY_RESPONDED_AT]:t.getTime()},i);return new Yr({name:r,level:n,properties:s})}static publish({devices:e,settings:t,error:i}){let r=this.eventNameFor("publish",void 0===i),n=i?zr.ERROR:zr.INFO,s=this.getPropertiesWithError({devices:e,audio:null==t?void 0:t.audio,video:null==t?void 0:t.video},i);return new Yr({name:r,level:n,properties:s})}static subscribeFail(e){let t=this.eventNameFor("subscribe",!1),i=zr.ERROR,r=e.toAnalyticsProperties();return new Yr({name:t,level:i,properties:r})}static leave(){return new Yr({name:"leave",level:zr.INFO})}static autoplayError(){return new Yr({name:"autoplayError",level:zr.ERROR})}static deviceChange({selection:e,type:t,devices:i,error:r}){let n=this.eventNameFor(r?"publish":`device.${t}`,void 0===r),s=r?zr.ERROR:zr.INFO,o=this.getPropertiesWithError({selection:e,devices:i},r);return new Yr({name:n,level:s,properties:o})}static performance(e){let t=zr.INFO,i=e.toAnalyticsProperties();return new Yr({name:"perf.stats",level:t,properties:i})}static rtcStats(e){let t=zr.INFO,i=e.toAnalyticsProperties();return new Yr({name:"rtc.stats",level:t,properties:i})}static degradationStats(e,t){let i=zr.INFO,r={degradedAt:e.degradedAt,trackId:e.trackId};if(!t&&e.degradedAt instanceof Date){let t=new Date,i=t.valueOf()-e.degradedAt.valueOf();r=Ii(Ai({},r),{duration:i,restoredAt:t})}return new Yr({name:"video.degradation.stats",level:i,properties:r})}static audioDetectionFail(e,t){let i=this.getPropertiesWithError({device:t},e),r=zr.ERROR;return new Yr({name:"audiopresence.failed",level:r,properties:i})}static eventNameFor(e,t){return`${e}.${t?"success":"failed"}`}static getPropertiesWithError(e,t){return t&&(e=Ai(Ai({},t.toAnalyticsProperties()),e)),e}};gn.KEY_REQUESTED_AT="requested_at",gn.KEY_RESPONDED_AT="responded_at";var fn,yn="default",Tn="default",En=class{constructor(e,t,i,r){this.store=e,this.observer=t,this.deviceManager=i,this.eventBus=r,this.TAG="[LocalTrackManager]"}getTracksToPublish(e){return _i(this,null,(function*(){let t=this.store.getPublishParams();if(!t)return[];let{allowed:i}=t,r=Boolean(i&&i.includes("audio")),n=Boolean(i&&i.includes("video"));if(!r&&!n)return[];let s=[],o=this.getTrackSettings(e,t);if(!o)return[];let a=this.store.getLocalPeerTracks(),c=a.find((e=>e.type===pr.VIDEO&&"regular"===e.source)),l=a.find((e=>e.type===pr.AUDIO&&"regular"===e.source)),d=a.find((e=>e.type===pr.VIDEO&&"screen"===e.source)),u=Boolean(c&&this.store.getTrackById(c.trackId)),h=Boolean(l&&this.store.getTrackById(l.trackId));if(c&&o.video&&(yield c.setSettings(o.video)),l&&o.audio&&(yield l.setSettings(o.audio)),d&&o.screen&&d.setSettings(o.screen),u&&h)return[];let p={audio:r&&!l&&(!e.isAudioMuted||"empty"),video:n&&!c&&(!e.isVideoMuted||"empty")};try{Mi.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:p}),s=yield this.getLocalTracks(p,o)}catch(e){s=yield this.retryGetLocalTracks(e,o,p)}return c&&n&&!u&&s.push(c),l&&r&&!h&&s.push(l),s}))}getLocalTracks(){return _i(this,arguments,(function*(e={audio:!0,video:!0},t){try{let i=yield this.getNativeLocalTracks(e,t),r=i.find((e=>"video"===e.kind)),n=i.find((e=>"audio"===e.kind)),s=new vn(new MediaStream(i)),o=[];if(n&&(null==t?void 0:t.audio)){let e=new cn(s,n,"regular",this.eventBus,t.audio);o.push(e)}if(r&&(null==t?void 0:t.video)){let e=new bn(s,r,"regular",this.eventBus,t.video);o.push(e)}return o}catch(e){throw e instanceof xi&&en.queue(gn.publish({devices:this.deviceManager.getDevices(),error:e,settings:t})).flush(),e}}))}getNativeLocalTracks(){return _i(this,arguments,(function*(e={audio:!1,video:!1},t){let i=new Lr(!0===e.video?t.video:null,!0===e.audio?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),"empty"===e.audio&&r.push(En.getEmptyAudioTrack()),"empty"===e.video&&r.push(En.getEmptyVideoTrack()),r}))}getLocalScreen(e,t){return _i(this,null,(function*(){let i=t.toConstraints();delete i.advanced;let r,n={video:e.toConstraints(),audio:Ii(Ai({},i),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})};try{r=yield navigator.mediaDevices.getDisplayMedia(n)}catch(e){throw Vr(e,Gr.SCREEN)}let s=[],o=new vn(r),a=r.getVideoTracks()[0],c=new bn(o,a,"screen",this.eventBus,e);s.push(c);let l=r.getAudioTracks()[0];if(l){let e=new cn(o,l,"screen",this.eventBus,t);s.push(e)}return Mi.v(this.TAG,"getLocalScreen",s),s}))}requestPermissions(){return _i(this,null,(function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0}
8)).getTracks().forEach((e=>e.stop()))}catch(e){Mi.e(this.TAG,e)}}))}static getEmptyVideoTrack(e){var t,i,r;let n=(null==(t=null==e?void 0:e.getSettings())?void 0:t.width)||320,s=(null==(i=null==e?void 0:e.getSettings())?void 0:i.height)||240;fn||(null==(r=(fn=Object.assign(document.createElement("canvas"),{width:n,height:s})).getContext("2d"))||r.fillRect(0,0,n,s));let o=fn.captureStream(10).getVideoTracks()[0],a=setInterval((()=>{if("ended"===o.readyState)return void clearInterval(a);let e=fn.getContext("2d");if(e){let t=0===e.getImageData(0,0,1,1).data[0]?1:0;e.fillStyle=`rgb(${t}, 0, 0)`,e.fillRect(0,0,1,1)}}),100);return o.onended=()=>{clearInterval(a)},o.enabled=!1,o}static getEmptyAudioTrack(){let e=new AudioContext,t=e.createOscillator(),i=t.connect(e.createMediaStreamDestination());t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}getAVTracks(e){return _i(this,null,(function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:!!e.audio&&e.audio.toConstraints(),video:!!e.video&&e.video.toConstraints()});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){let i=!1,r=!1;throw yield this.deviceManager.init(),!this.deviceManager.hasWebcamPermission&&e.video&&(i=!0),!this.deviceManager.hasMicrophonePermission&&e.audio&&(r=!0),Vr(t,i&&r?Gr.AV:i?Gr.VIDEO:Gr.AUDIO)}}))}getTrackSettings(e,t){let{audio:i,video:r,screen:n,allowed:s}=t,o=Boolean(s&&s.includes("audio")),a=Boolean(s&&s.includes("video")),c=Boolean(s&&s.includes("screen"));if(!o&&!a)return null;let l=this.store.getLocalPeer(),d=null==l?void 0:l.videoTrack,u=null==l?void 0:l.audioTrack,h=(null==u?void 0:u.settings.deviceId)||e.audioInputDeviceId,p=(null==d?void 0:d.settings.deviceId)||e.videoDeviceId,m=null,v=null,g=null;if(o&&(m=(new Ir).codec(i.codec).maxBitrate(i.bitRate).deviceId(h||yn).build()),a){let e=this.store.getSimulcastDimensions("regular");v=(new Dr).codec(r.codec).maxBitrate(r.bitRate).maxFramerate(r.frameRate).setWidth((null==e?void 0:e.width)||r.width).setHeight((null==e?void 0:e.height)||r.height).deviceId(p||Tn).build()}if(c){let e=this.store.getSimulcastDimensions("screen");g=(new Dr).maxBitrate(n.bitRate,!1).codec(n.codec).maxFramerate(n.frameRate).setWidth((null==e?void 0:e.width)||n.width).setHeight((null==e?void 0:e.height)||n.height).build()}return(new Mr).video(v).audio(m).screen(g).build()}retryGetLocalTracks(e,t,i){return _i(this,null,(function*(){if(!(e instanceof xi&&e.action===Li.TRACK))return Mi.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(Ui.TracksErrors.GenericTrack(Li.TRACK,e.message)),[];{this.observer.onFailure(e);let r=e.code===Ni.TracksErrors.OVER_CONSTRAINED,n=e.message.includes("audio"),s=e.message.includes("video");if(r){let r=(new Mr).video(new Or).audio(new _r).build();Mi.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,r)}catch(e){let r=e instanceof xi?e.nativeError:e,n=e;if("OverconstrainedError"===(null==r?void 0:r.name)){let e=Ui.TracksErrors.GenericTrack(Li.TRACK,"Overconstrained error after dropping all constraints");e.addNativeError(r),n=e}return yield this.retryGetLocalTracks(n,t,i)}}i.audio=n?"empty":i.audio,i.video=s?"empty":i.video,Mi.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t)}catch(e){return Mi.w(this.TAG,"Fetch empty tacks failed",e),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(Ui.TracksErrors.GenericTrack(Li.TRACK,e.message)),yield this.getLocalTracks(i,t)}}}))}};function kn(e,t){return function(i){return i in e&&e[i]!==t[i]}}var Sn,bn=class extends Tr{constructor(e,t,i,r,n=(new Dr).build()){super(e,t,i),this.eventBus=r,this.buildNewSettings=e=>{let{width:t,height:i,codec:r,maxFramerate:n,maxBitrate:s,deviceId:o,advanced:a}=Ai(Ai({},this.settings),e);return new Or(t,i,r,n,o,a,s)},this.handleSettingsChange=e=>_i(this,null,(function*(){let t=this.stream,i=kn(e,this.settings);i("maxBitrate")&&e.maxBitrate&&(yield t.setMaxBitrate(e.maxBitrate,this)),(i("width")||i("height")||i("advanced"))&&(yield this.nativeTrack.applyConstraints(e.toConstraints()))})),this.handleDeviceChange=(e,t=!1)=>_i(this,null,(function*(){if(kn(e,this.settings)("deviceId")&&"regular"===this.source){if(this.enabled){let t=yield this.replaceTrackWith(e);yield this.replaceSender(t,this.enabled),this.nativeTrack=t}t||sn.updateSelection("videoInput",{deviceId:e.deviceId,groupId:this.nativeTrack.getSettings().groupId})}})),e.tracks.push(this),this.settings=n,"default"===n.deviceId&&t.enabled&&(this.settings=this.buildNewSettings({deviceId:t.getSettings().deviceId})),this.pluginsManager=new class{constructor(e){this.pluginsLoopRunning=!1,this.pluginsLoopState="paused",this.pluginAddInProgress=!1,this.hmsTrack=e,this.plugins=[],this.pluginsMap={},this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new class{constructor(){this.initTime={}
8,this.preProcessingAvgs=new ln,this.addedTimestamps={},this.processingAvgs={},this.pluginAdded={},this.pluginInputFrameRate={},this.pluginFrameRate={}}added(e,t,i){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.processingAvgs[e]=new ln,this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t}removed(e){var t;if(this.pluginAdded[e]){let i={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],avgPreProcessingTime:this.preProcessingAvgs.getAvg(),avgProcessingTime:null==(t=this.processingAvgs[e])?void 0:t.getAvg(),inputFrameRate:this.pluginInputFrameRate[e],pluginFrameRate:this.pluginFrameRate[e]};en.queue(Qr.stats(i)).flush(),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(en.queue(Qr.failure(e,t)).flush(),this.clean(e))}initWithTime(e,t){return _i(this,null,(function*(){if(this.initTime[e])return void Mi.i(dn,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);let i;try{i=yield this.timeInMs(t),Mi.i(dn,`Time taken for Plugin ${e} initialization : ${i}`)}catch(t){let i=Ui.MediaPluginErrors.InitFailed(Li.VIDEO_PLUGINS,`failed during initialization of plugin${t.message||t}`);throw Mi.e(dn,i),this.failure(e,i),i}i&&(this.initTime[e]=i)}))}preProcessWithTime(e){return _i(this,null,(function*(){let t=yield this.timeInMs(e);this.preProcessingAvgs.add(t)}))}processWithTime(e,t){return _i(this,null,(function*(){var i;let r;try{r=yield this.timeInMs(t)}catch(t){let i=Ui.MediaPluginErrors.ProcessingFailed(Li.VIDEO_PLUGINS,`Failed during processing of plugin${t.message||t}`);throw Mi.e(dn,i),this.failure(e,i),i}r&&(null==(i=this.processingAvgs[e])||i.add(r))}))}timeInMs(e){return _i(this,null,(function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)}))}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.processingAvgs[e],delete this.pluginAdded[e],delete this.pluginInputFrameRate[e],delete this.pluginFrameRate[e]}},this.canvases=new Array}getPlugins(){return[...this.plugins]}addPlugin(e,t){return _i(this,null,(function*(){var i;if(this.pluginAddInProgress){let t=null==(i=e.getName)?void 0:i.call(e);if(!t||""===t)return void Mi.w("no name provided by the plugin");let r=Ui.MediaPluginErrors.AddAlreadyInProgress(Li.VIDEO_PLUGINS,"Add Plugin is already in Progress");throw this.analytics.failure(t,r),Mi.w("can't add another plugin when previous add is in progress"),r}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e,t)}finally{this.pluginAddInProgress=!1}}))}addPluginInternal(e,t){return _i(this,null,(function*(){var i;let r=null==(i=e.getName)?void 0:i.call(e);if(!r||""===r)return void Mi.w("no name provided by the plugin");if(this.pluginsMap[r])return void Mi.w(pn,`plugin - ${e.getName()} already added.`);let n=this.hmsTrack.getMediaTrackSettings().frameRate||24,s=0;if(t&&t>0?(Mi.i(pn,`adding plugin ${e.getName()} with framerate ${t}`),t<n&&(s=Math.ceil(n/t)-1),this.analytics.added(r,n,t)):(Mi.i(pn,`adding plugin ${e.getName()}`),this.analytics.added(r,n)),Mi.i(pn,"numFrames to skip processing",s),this.pluginNumFramesToSkip[r]=s,this.pluginNumFramesSkipped[r]=s,!e.isSupported()){let t=Ui.MediaPluginErrors.PlatformNotSupported(Li.VIDEO_PLUGINS,"platform not supported ");return this.analytics.failure(r,t),void Mi.i(pn,`Platform is not supported for plugin - ${e.getName()}`)}try{if(yield this.analytics.initWithTime(r,(()=>_i(this,null,(function*(){return yield e.init()})))),this.plugins.push(r),this.pluginsMap[r]=e,this.plugins.length+1>this.canvases.length)for(let e=this.canvases.length;e<=this.plugins.length;e++)this.canvases[e]=document.createElement("canvas");yield this.startPluginsLoop()}catch(t){throw Mi.e(pn,"failed to add plugin",t),yield this.removePlugin(e),t}}))}removePlugin(e){return _i(this,null,(function*(){let t=e.getName();this.pluginsMap[t]?(Mi.i(pn,`removing plugin ${t}`),this.removePluginEntry(t),0===this.plugins.length&&(Mi.i(pn,"No plugins left, stopping plugins loop"),yield this.stopPluginsLoop()),e.stop(),this.analytics.removed(t)):Mi.w(pn,`plugin - ${t} not found to remove.`)}))}removePluginEntry(e){let t=this.plugins.indexOf(e);-1!==t&&this.plugins.splice(t,1),this.pluginsMap[e]&&delete this.pluginsMap[e],this.pluginNumFramesToSkip[e]&&delete this.pluginNumFramesToSkip[e],this.pluginNumFramesSkipped[e]&&delete this.pluginNumFramesSkipped[e]}waitForRestart(){return _i(this,null,(function*(){if(this.pluginsLoopRunning&&"running"!==this.pluginsLoopState)for(;"paused"===this.pluginsLoopState;)yield Kr(100)}))}cleanup(){return _i(this,null,(function*(){var e;
8for(let e of this.plugins)yield this.removePlugin(this.pluginsMap[e]);null==(e=this.outputTrack)||e.stop()}))}initElementsAndStream(){this.inputCanvas||(this.inputCanvas=document.createElement("canvas")),this.outputCanvas=document.createElement("canvas"),this.inputVideo||(this.inputVideo=document.createElement("video")),this.inputCanvas.getContext("2d"),this.outputCanvas.getContext("2d");let e=this.outputCanvas.captureStream();this.outputTrack=e.getVideoTracks()[0]}startPluginsLoop(){return _i(this,null,(function*(){if(!this.pluginsLoopRunning){this.initElementsAndStream(),this.pluginsLoopRunning=!0;try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw this.pluginsLoopRunning=!1,Mi.e(pn,"error in setting processed track",e),e}this.pluginsLoop().then((()=>{Mi.d(pn,"processLoop stopped")}))}}))}stopPluginsLoop(){return _i(this,null,(function*(){var e;this.pluginsLoopRunning=!1,yield this.hmsTrack.setProcessedTrack(void 0),this.resetCanvases(),null==(e=this.outputTrack)||e.stop(),this.inputVideo&&(this.inputVideo.srcObject=null,this.inputVideo=void 0)}))}pluginsLoop(){return _i(this,null,(function*(){for(;this.pluginsLoopRunning;){let e=this.hmsTrack.getMediaTrackSettings().frameRate||24,t=Math.floor(1e3/e);if(!this.hmsTrack.enabled||"ended"===this.hmsTrack.nativeTrack.readyState){"running"===this.pluginsLoopState&&this.resetCanvases(),this.pluginsLoopState="paused",yield Kr(t);continue}let i=0;try{yield this.analytics.preProcessWithTime((()=>_i(this,null,(function*(){return yield this.doPreProcessing()}))));let e=Date.now();yield this.processFramesThroughPlugins(),i=Math.floor(Date.now()-e),i>t&&(i=t)}catch(e){Mi.e(pn,"error in plugins loop",e)}this.pluginsLoopState="running",yield Kr(t-i)}}))}doPreProcessing(){return _i(this,null,(function*(){yield this.addTrackToVideo(),yield this.updateInputCanvas()}))}processFramesThroughPlugins(){return _i(this,null,(function*(){this.canvases[0]=this.inputCanvas;for(let e=0;e<this.plugins.length;e++){let t=this.plugins[e],i=this.pluginsMap[t];if(i)try{let r=this.checkIfSkipRequired(t);if(i.getPluginType()===an.TRANSFORM){let n=(e,n)=>_i(this,null,(function*(){try{yield i.processVideoFrame(e,n,r)}catch(e){Mi.e(pn,`error in processing plugin ${t}`,e)}}));r?e==this.plugins.length-1?yield n(this.canvases[e],this.outputCanvas):yield n(this.canvases[e],this.canvases[e+1]):e==this.plugins.length-1?yield this.analytics.processWithTime(t,(()=>_i(this,null,(function*(){return n(this.canvases[e],this.outputCanvas)})))):yield this.analytics.processWithTime(t,(()=>_i(this,null,(function*(){return n(this.canvases[e],this.canvases[e+1])}))))}else i.getPluginType()===an.ANALYZE&&!r&&(yield this.analytics.processWithTime(t,(()=>_i(this,null,(function*(){return yield i.processVideoFrame(this.inputCanvas)})))))}catch(e){Mi.e(pn,`error in processing plugin ${t}`,e),yield this.removePlugin(i)}}}))}addTrackToVideo(){return _i(this,null,(function*(){var e;if(!this.inputVideo)return;let t=this.inputVideo.srcObject;null!==t&&t instanceof MediaStream&&(null==(e=t.getVideoTracks()[0])?void 0:e.id)===this.hmsTrack.nativeTrack.id||(this.inputVideo.pause(),this.inputVideo.srcObject=new MediaStream([this.hmsTrack.nativeTrack]),this.inputVideo.muted=!0,this.inputVideo.playsInline=!0,this.inputVideo&&(this.inputVideo.oncanplaythrough=()=>{var e;null==(e=this.inputVideo)||e.play()}))}))}updateInputCanvas(){return _i(this,null,(function*(){if(!this.inputCanvas||!this.inputVideo)return;let{width:e=un,height:t=hn}=this.hmsTrack.getMediaTrackSettings();this.inputCanvas.height!==t&&(this.inputCanvas.height=t),this.inputCanvas.width!==e&&(this.inputCanvas.width=e),this.inputCanvas.getContext("2d").drawImage(this.inputVideo,0,0,e,t)}))}resetCanvases(){if(!this.outputCanvas||!this.inputCanvas)return;let e=this.outputCanvas.getContext("2d");e&&(e.fillStyle="rgb(0, 0, 0)",e.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height));let t=this.inputCanvas.getContext("2d");t&&(t.fillStyle="rgb(0, 0, 0)",t.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height)),this.canvases=[]}checkIfSkipRequired(e){let t=!1;return this.pluginNumFramesSkipped[e]<this.pluginNumFramesToSkip[e]?(this.pluginNumFramesSkipped[e]++,t=!0):(t=!1,this.pluginNumFramesSkipped[e]=0),t}}(this),this.setFirstTrackId(this.trackId)}setEnabled(e){var t=e=>super[e];return _i(this,null,(function*(){if(e!==this.enabled){if("regular"===this.source){let t;t=e?yield this.replaceTrackWith(this.settings):yield this.replaceTrackWithBlank(),yield this.replaceSender(t,e),this.nativeTrack=t,e&&(yield this.pluginsManager.waitForRestart())}yield t("setEnabled").call(this,e),this.eventBus.localVideoEnabled.publish(e),this.stream.trackUpdate(this)}}))}isPublishedTrackId(e){return this.publishedTrackId===e}addSink(e){this.addSinkInternal(e,this.processedTrack||this.nativeTrack)}setSettings(e,t=!1){return _i(this,null,(function*(){let i=this.buildNewSettings(e);yield this.handleDeviceChange(i,t),this.enabled?(yield this.handleSettingsChange(i),this.settings=i):this.settings=i}))}getPlugins(){return this.pluginsManager.getPlugins()}
8addPlugin(e,t){return _i(this,null,(function*(){return this.pluginsManager.addPlugin(e,t)}))}removePlugin(e){return _i(this,null,(function*(){return this.pluginsManager.removePlugin(e)}))}cleanup(){var e=e=>super[e];return _i(this,null,(function*(){var t;e("cleanup").call(this),yield this.pluginsManager.cleanup(),null==(t=this.processedTrack)||t.stop()}))}setProcessedTrack(e){return _i(this,null,(function*(){if(this.nativeTrack.enabled)return e?void(e!==this.processedTrack&&(this.processedTrack?yield this.stream.replaceSenderTrack(this.processedTrack,e):yield this.stream.replaceSenderTrack(this.nativeTrack,e),this.processedTrack=e)):(this.processedTrack&&(yield this.stream.replaceSenderTrack(this.processedTrack,this.nativeTrack)),void(this.processedTrack=void 0));this.processedTrack=e}))}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}replaceTrackWith(e){return _i(this,null,(function*(){let t=this.nativeTrack;null==t||t.stop();let i=yield function(e){return _i(this,null,(function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:!!e&&e.toConstraints()})).getVideoTracks()[0]}catch(e){throw Vr(e,Gr.VIDEO)}}))}(e);return"default"===this.settings.deviceId&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),i}))}replaceTrackWithBlank(){return _i(this,null,(function*(){let e=this.nativeTrack;return null==e||e.stop(),En.getEmptyVideoTrack(e)}))}replaceSender(e,t){return _i(this,null,(function*(){let i=this.stream;t?yield i.replaceSenderTrack(this.nativeTrack,this.processedTrack||e):yield i.replaceSenderTrack(this.processedTrack||this.nativeTrack,e),yield i.replaceStreamTrack(this.nativeTrack,e)}))}},Rn=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof vr?(this.mute=!e.enabled,this.track_id=e.publishedTrackId,this.stream_id=e.stream.id):(this.mute=e.mute,this.track_id=e.track_id,this.stream_id=e.stream_id)}};!function(e){e[e.Disconnected=0]="Disconnected",e[e.Connecting=1]="Connecting",e[e.Joined=2]="Joined",e[e.Failed=3]="Failed",e[e.Reconnecting=4]="Reconnecting",e[e.Leaving=5]="Leaving"}(Sn||(Sn={}));var Cn;!function(e){e[e.ConnectFailed=0]="ConnectFailed",e[e.SignalDisconnect=1]="SignalDisconnect",e[e.PublishIceConnectionFailed=2]="PublishIceConnectionFailed",e[e.SubscribeIceConnectionFailed=3]="SubscribeIceConnectionFailed"}(Cn||(Cn={}));var Pn={0:[],1:[],2:[1],3:[1]},wn="[RetryScheduler]",An=class extends $r{constructor(){super(100),this.localStorage=new nn("hms-analytics"),this.localStorage.clear(),this.initLocalStorageQueue()}enqueue(e){super.enqueue(e),this.localStorage.set(this.storage)}dequeue(){let e=super.dequeue();return this.localStorage.set(this.storage),e}initLocalStorageQueue(){var e;null==(e=this.localStorage.get())||e.forEach((e=>{let t=new Yr(e);super.enqueue(t)}))}},In=(e,t,i,r)=>_i(void 0,null,(function*(){var n;let s,o=t instanceof cn||t instanceof bn,a=o?"publish":"subscribe",c=o?t.getTrackBeingSent():t.nativeTrack;try{s=yield null==(n=e[a])?void 0:n.call(e,c)}catch(e){Mi.e("[HMSWebrtcStats]","Error in getting track stats",t,c,e)}let l=_n(s),d=Mn("publish"===a?"bytesSent":"bytesReceived",l,r),u=Ln("packetsLost",l,r);return(null==l?void 0:l.remote)&&Object.assign(l.remote,{packetsLostRate:Ln("packetsLost",l.remote,null==r?void 0:r.remote)}),l&&Object.assign(l,{bitrate:d,packetsLostRate:u,peerId:t.peerId,peerName:i})})),_n=e=>{let t,i;return null==e||e.forEach((e=>
8{switch(e.type){case"inbound-rtp":case"outbound-rtp":t=e;break;case"remote-inbound-rtp":i=e}})),t&&Object.assign(t,{remote:i})},Dn=(e,t,i)=>{let r=On(t),n=Mn("publish"===e?"bytesSent":"bytesReceived",r,i&&i[e]);return r&&Object.assign(r,{bitrate:n})},On=e=>{let t;return e.forEach((i=>{"transport"===i.type&&(t=e.get(i.selectedCandidatePairId))})),t||e.forEach((e=>{"candidate-pair"===e.type&&e.selected&&(t=e)})),t},Mn=(e,t,i)=>8*Ln(e,t,i),Ln=(e,t,i)=>{let r=t&&t[e],n=i?i[e]:null;return t&&i&&Fi(r)&&Fi(n)?1e3*Nn(r,n,t.timestamp,i.timestamp):0},Nn=(e,t,i,r)=>Fi(e)&&Fi(t)&&i&&r?(e-t)/(i-r):0,xn="[HMSTransport]:";function Un(e){if(0===e.length)throw Ui.InitAPIErrors.InvalidTokenFormat(Li.INIT,"Token cannot be an empty string");let t=e.split(".");if(3!==t.length)throw Ui.InitAPIErrors.InvalidTokenFormat(Li.INIT,"Expected 3 '.' separate fields - header, payload and signature respectively");let i=atob(t[1]);try{let e=JSON.parse(i);return{roomId:e.room_id,userId:e.user_id,role:e.role}}catch(e){throw Ui.InitAPIErrors.InvalidTokenFormat(Li.INIT,`couldn't parse to json - ${e.message}`)}}var Gn="autoplay-error",Fn={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},jn=class extends Ei.EventEmitter2{on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,t){return super.emit(e,t)}listeners(e){return super.listeners(e)}},Vn=class{constructor(e){this.audioContext=new AudioContext,this.source=this.audioContext.createMediaElementSource(e),this.source.connect(this.audioContext.destination)}resumeContext(){"suspended"===this.audioContext.state&&(Mi.d(this.TAG,"AudioContext is resumed"),this.audioContext.resume())}getAudioTrack(){return this.destinationNode&&this.source.disconnect(this.destinationNode),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.source.connect(this.destinationNode),this.destinationNode.stream.getAudioTracks()[0]}cleanup(){"closed"!==this.audioContext.state&&this.audioContext.close()}get TAG(){return"AudioContextManager"}},Bn=class extends jn{constructor(){super(),this.seeked=!1,this.audioElement=this.getAudioElement()}play(e){return _i(this,null,(function*(){return new Promise(((t,i)=>{this.audioElement=this.getAudioElement(),this.audioElement.src=e,this.seeked=!1,this.audioElement.onerror=()=>{let t=`Error loading ${e}`;Mi.e(this.TAG,t),this.stop(),i(t)},this.audioElement.oncanplaythrough=()=>_i(this,null,(function*(){try{if(!this.audioElement)return;if(this.audioContextManager.resumeContext(),this.track)this.seeked?this.seeked=!1:(yield this.audioElement.play(),t([this.track]));else{yield this.audioElement.play();let e=this.audioContextManager.getAudioTrack();this.track=e,t([e])}}catch(t){Mi.e(this.TAG,"Error playing audio",e,t.message),i(t)}})),this.audioElement.onseeked=()=>{this.seeked=!0}}))}))}getTracks(){return this.track?[this.track.id]:[]}getElement(){return this.audioElement}stop(){var e,t;null==(e=this.audioElement)||e.pause(),null==(t=this.audioElement)||t.removeAttribute("src"),this.audioElement=null,this.audioContextManager.cleanup(),this.track=void 0}getAudioElement(){if(this.audioElement)return this.audioElement;let e=document.createElement("audio");return e.crossOrigin="anonymous",e.addEventListener("timeupdate",(e=>this.emit("progress",e))),e.addEventListener("ended",(()=>{this.emit("ended",null)})),this.audioContextManager=new Vn(e),e}get TAG(){return"PlaylistAudioManager"}},$n=class extends jn{constructor(){super(),this.tracks=[],this.DEFAUL_FPS=24,this.seeked=!1,this.drawImage=()=>{var e,t,i;this.videoElement&&!this.videoElement.paused&&!this.videoElement.ended&&(null==(i=this.canvasContext)||i.drawImage(this.videoElement,0,0,null==(e=this.canvas)?void 0:e.width,null==(t=this.canvas)?void 0:t.height),this.timer=setTimeout((()=>{this.drawImage()}),1e3/this.DEFAUL_FPS))},this.videoElement=this.getVideoElement(),this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d")}play(e){return new Promise(((t,i)=>{this.videoElement=this.getVideoElement(),this.videoElement.src=e,this.seeked=!1,this.videoElement.onerror=()=>{let t=`Error loading ${e}`;Mi.e(this.TAG,t),this.stop(),i(t)},this.videoElement.oncanplaythrough=()=>_i(this,null,(function*(){var r,n,s;try{if(!this.videoElement)return;if(this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,0===this.tracks.length){this.clearCanvasAndTracks();let e=this.canvas.captureStream();if(!e)return void Mi.e(this.TAG,"Browser does not support captureStream");this.videoElement.onplay=this.drawImage,this.audioContextManager.resumeContext(),yield this.videoElement.play();let i=this.audioContextManager.getAudioTrack();
8e.addTrack(i),e.getTracks().forEach((e=>{this.tracks.push(e)})),t(this.tracks)}else this.seeked?(this.seeked=!1,null==(s=this.canvasContext)||s.drawImage(this.videoElement,0,0,null==(r=this.canvas)?void 0:r.width,null==(n=this.canvas)?void 0:n.height)):(yield this.videoElement.play(),t(this.tracks))}catch(t){Mi.e(this.TAG,"Error playing video",e,t.message),i(t)}})),this.videoElement.onseeked=()=>{this.seeked=!0}}))}getTracks(){return this.tracks.map((e=>e.id))}getElement(){return this.videoElement}stop(){var e,t;null==(e=this.videoElement)||e.pause(),null==(t=this.videoElement)||t.removeAttribute("src"),this.videoElement=null,this.clearCanvasAndTracks()}clearCanvasAndTracks(){var e;this.tracks=[],null==(e=this.canvasContext)||e.clearRect(0,0,this.canvas.width,this.canvas.height),clearTimeout(this.timer)}getVideoElement(){if(this.videoElement)return this.videoElement;let e=document.createElement("video");return e.crossOrigin="anonymous",e.addEventListener("timeupdate",(e=>this.emit("progress",e))),e.addEventListener("ended",(()=>{this.emit("ended",null)})),this.audioContextManager=new Vn(e),e}get TAG(){return"PlaylistVideoManager"}},Kn={list:[],currentIndex:-1,isAutoplayOn:!0},Hn={list:[],currentIndex:-1,isAutoplayOn:!0},qn=class extends jn{constructor(e){super(),this.sdk=e,this.state={audio:Ai({},Kn),video:Ai({},Hn)},this.addTrack=(e,t)=>_i(this,null,(function*(){yield this.sdk.addTrack(e,t),Mi.d(this.TAG,"Playlist track added",e)})),this.removeTrack=e=>_i(this,null,(function*(){yield this.sdk.removeTrack(e),Mi.d(this.TAG,"Playlist track removed",e)})),this.audioManager=new Bn,this.videoManager=new $n,this.addListeners()}getList(e=ur.audio){return this.state[e].list}setList(e){e&&0!==e.length?e.forEach((e=>{this.state[e.type].list.push(e)})):Mi.w(this.TAG,"Please pass in a list of HMSPlaylistItem's")}removeItem(e){let t=this.state[e.type].list,i=t.findIndex((t=>e.id===t.id));i>-1&&t.splice(i,1)}seek(e,t=ur.audio){let{currentIndex:i}=this.state[t];if(-1===i)throw Ui.PlaylistErrors.NoEntryToPlay(Li.PLAYLIST,"No item is currently playing");let r=this.getElement(t);if(r){let t=Math.max(r.currentTime+e,0);r.currentTime=Math.min(t,r.duration)}}seekTo(e,t=ur.audio){let{currentIndex:i}=this.state[t];if(-1===i)throw Ui.PlaylistErrors.NoEntryToPlay(Li.PLAYLIST,"No item is currently playing");if(e<0)throw Error("value cannot be negative");let r=this.getElement(t);r&&(r.currentTime=Math.min(e,r.duration))}setVolume(e,t=ur.audio){if(e<0||e>100)throw Error("Please pass a valid number between 0-100");let i=this.getElement(t);i&&(i.volume=.01*e)}getVolume(e=ur.audio){let t=this.getElement(e);return t?100*t.volume:0}getCurrentTime(e=ur.audio){let t=this.getElement(e);return(null==t?void 0:t.currentTime)||0}getCurrentIndex(e=ur.audio){return this.state[e].currentIndex}getCurrentProgress(e=ur.audio){var t;let{list:i,currentIndex:r}=this.state[e],n=null==(t=i[r])?void 0:t.url,s=this.getElement(e);return n&&s?Math.floor(s.currentTime/s.duration*100):0}getCurrentSelection(e=ur.audio){let{list:t,currentIndex:i}=this.state[e];if(-1!==i)return t[i]}isPlaying(e=ur.audio){let t=this.getElement(e);return!!t&&!t.paused}setIsAutoplayOn(e=ur.audio,t){this.state[e].isAutoplayOn=t}getPlaybackRate(e=ur.audio){let t=this.getElement(e);return t?t.playbackRate:1}setPlaybackRate(e=ur.audio,t){if(t<.25||t>2)throw Error("Please pass a value between 0.25 and 2.0");let i=this.getElement(e);i&&(i.playbackRate=t)}setEnabled(e,t){return _i(this,arguments,(function*(e,{id:t,type:i=ur.audio}){let r=this.state[i].list.findIndex((e=>e.id===t));if(!t||-1===r)return void Mi.w(this.TAG,"Pass a valid id");let n=this.state[i].list[r].url;e?yield this.play(n,i):yield this.pause(n,i),this.state[i].currentIndex=r,this.setDuration(i)}))}playNext(){return _i(this,arguments,(function*(e=ur.audio){let{list:t,currentIndex:i}=this.state[e];if(i>=t.length-1)throw Ui.PlaylistErrors.NoEntryToPlay(Li.PLAYLIST,"Reached end of playlist");yield this.play(t[i+1].url,e),this.state[e].currentIndex=i+1,this.setDuration(e)}))}playPrevious(){return _i(this,arguments,(function*(e=ur.audio){let{list:t,currentIndex:i}=this.state[e];if(i<=0)throw Ui.PlaylistErrors.NoEntryToPlay(Li.PLAYLIST,"Reached start of playlist");yield this.play(t[i-1].url,e),this.state[e].currentIndex=i-1,this.setDuration(e)}))}stop(){return _i(this,arguments,(function*(e=ur.audio){var t;let i=e===ur.audio?this.audioManager:this.videoManager;null==(t=i.getElement())||t.pause(),yield this.removeTracks(e),i.stop(),this.state[e].currentIndex=-1}))}cleanup(){this.state={audio:Ai({},Kn),video:Ai({},Hn)},this.audioManager.stop(),this.videoManager.stop()}onProgress(e){this.videoManager.on("progress",(()=>{try{e({type:ur.video,progress:this.getCurrentProgress(ur.video)})}catch(e){Mi.e(this.TAG,"Error in onProgress callback")}})),this.audioManager.on("progress",(()=>{try{e({type:ur.audio,progress:this.getCurrentProgress(ur.audio)})}catch(e){Mi.e(this.TAG,"Error in onProgress callback")}}))}onNewTrackStart(e){this.on("newTrackStart",e)}onPlaylistEnded(e){this.on("playlistEnded",e)}onCurrentTrackEnded(e){this.on("currentTrackEnded",e)}getElement(e=ur.audio){return e===ur.audio?this.audioManager.getElement():this.videoManager.getElement()}removeTracks(){return _i(this,arguments,(function*(e=ur.audio){let t=(e===ur.audio?this.audioManager:this.videoManager).getTracks();for(let e of t)yield this.removeTrack(e)}))}play(e){return _i(this,arguments,(function*(e,t=ur.audio){let i=t===ur.audio?this.audioManager:this.videoManager,r=i.getElement();if(this.isItemCurrentlyPlaying(e,t))Mi.w(this.TAG,`The ${t} is currently playing`);else if(null==r?void 0:r.src.includes(e))yield r.play();else{null==r||r.pause();let n=yield i.play(e);for(let e of n)yield this.addTrack(e,t===ur.audio?"audioplaylist":"videoplaylist")}}))}isItemCurrentlyPlaying(e,t){let i=this.getElement(t);return!(!i||i.paused||!i.src.includes(e))}setDuration(e=ur.audio){let t=this.getElement(e),{list:i,currentIndex:r}=this.state[e];
8i[r]&&(i[r].duration=(null==t?void 0:t.duration)||0),this.emit("newTrackStart",i[r])}pause(e){return _i(this,arguments,(function*(e,t=ur.audio){let i=this.getElement(t);i&&!i.paused&&i.src.includes(e)?(i.pause(),Mi.d(this.TAG,"paused url",e)):Mi.w(this.TAG,"The passed in url is not currently playing")}))}addListeners(){this.audioManager.on("ended",(()=>this.handleEnded(ur.audio))),this.videoManager.on("ended",(()=>this.handleEnded(ur.video)))}handleEnded(){return _i(this,arguments,(function*(e=ur.audio){let{list:t,currentIndex:i,isAutoplayOn:r}=this.state[e];i===t.length-1?(yield this.stop(e),this.emit("playlistEnded",e)):r?this.playNext(e):yield this.pause(t[i].url,e),this.emit("currentTrackEnded",t[i])}))}get TAG(){return"PlaylistManager"}},Wn=class{constructor(e,t){this.eventName=e,this.eventEmitter=t,this.publish=e=>{this.eventEmitter.emit(this.eventName,e)},this.subscribe=e=>{this.eventEmitter.on(this.eventName,e)},this.subscribeOnce=e=>{this.eventEmitter.once(this.eventName,e)},this.unsubscribe=e=>{this.eventEmitter.off(this.eventName,e)},this.removeAllListeners=()=>{this.eventEmitter.removeAllListeners(this.eventName)}}},zn={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default"},Jn={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,deviceManagersInitialised:!1};function Yn(e,t){return e===t}function Qn(e,t,i){if(null===t||null===i||t.length!==i.length)return!1;for(var r=t.length,n=0;n<r;n++)if(!e(t[n],i[n]))return!1;return!0}function Zn(e){var t=Array.isArray(e[0])?e[0]:e;if(!t.every((function(e){return"function"==typeof e}))){var i=t.map((function(e){return typeof e})).join(", ");throw new Error("Selector creators expect all input-selectors to be functions, instead received the following types: ["+i+"]")}return t}Mi.i("adapter",`${ei.browserDetails.browser} v${ei.browserDetails.version}`);var Xn,es=function(e){for(var t=arguments.length,i=Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return function(){for(var t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];var s=0,o=r.pop(),a=Zn(r),c=e.apply(void 0,[function(){return s++,o.apply(null,arguments)}].concat(i)),l=e((function(){for(var e=[],t=a.length,i=0;i<t;i++)e.push(a[i].apply(null,arguments));return c.apply(null,e)}));return l.resultFunc=o,l.dependencies=a,l.recomputations=function(){return s},l.resetRecomputations=function(){return s=0},l}}((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Yn,i=null,r=null;return function(){return Qn(t,i,arguments)||(r=e.apply(null,arguments)),i=arguments,r}})),ts=Object.defineProperty,is=Object.defineProperties,rs=Object.getOwnPropertyDescriptors,ns=Object.getOwnPropertySymbols,ss=Object.prototype.hasOwnProperty,os=Object.prototype.propertyIsEnumerable,as=(e,t,i)=>t in e?ts(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,cs=(e,t)=>{for(var i in t||(t={}))ss.call(t,i)&&as(e,i,t[i]);if(ns)for(var i of ns(t))os.call(t,i)&&as(e,i,t[i]);return e},ls=(e,t)=>is(e,rs(t)),ds=(e,t,i)=>new Promise(((r,n)=>{var s=e=>{try{a(i.next(e))}catch(e){n(e)}},o=e=>{try{a(i.throw(e))}catch(e){n(e)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);a((i=i.apply(e,t)).next())}));!function(e){e.Disconnected="Disconnected",e.Preview="Preview",e.Connecting="Connecting",e.Connected="Connected",e.Reconnecting="Reconnecting",e.Disconnecting="Disconnecting",e.Failed="Failed"}(Xn||(Xn={}));var us,hs,ps,ms,vs=()=>({room:{id:"",isConnected:!1,name:"",peers:[],shareableLink:"",localPeer:"",hasWaitingRoom:!1,roomState:Xn.Disconnected,recording:{browser:{running:!1},server:{running:!1},hls:{running:!1}},rtmp:{running:!1},hls:{running:!1,variants:[]},sessionId:""},peers:{},tracks:{},playlist:{audio:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1},video:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1}},messages:{byID:{},allIDs:[]},speakers:{},settings:{audioInputDeviceId:"",audioOutputDeviceId:"",videoInputDeviceId:""}
8,devices:{audioInput:[],audioOutput:[],videoInput:[]},roles:{},roleChangeRequests:[],errors:[]}),gs=()=>({peerStats:{},trackStats:{},localPeer:{id:""}});!function(e){e.CHAT="chat"}(us||(us={})),function(e){e.INFO="info",e.ERROR="error",e.CRITICAL="critical"}(hs||(hs={})),function(e){e.PEER_JOINED="PEER_JOINED",e.PEER_LEFT="PEER_LEFT",e.PEER_LIST="PEER_LIST",e.NEW_MESSAGE="NEW_MESSAGE",e.ERROR="ERROR",e.RECONNECTING="RECONNECTING",e.RECONNECTED="RECONNECTED",e.TRACK_ADDED="TRACK_ADDED",e.TRACK_REMOVED="TRACK_REMOVED",e.TRACK_MUTED="TRACK_MUTED",e.TRACK_UNMUTED="TRACK_UNMUTED",e.TRACK_DEGRADED="TRACK_DEGRADED",e.TRACK_RESTORED="TRACK_RESTORED",e.ROLE_CHANGE_REQUEST="ROLE_CHANGE_REQUEST",e.ROLE_UPDATED="ROLE_UPDATED",e.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",e.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",e.ROOM_ENDED="ROOM_ENDED",e.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",e.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",e.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",e.NAME_UPDATED="NAME_UPDATED",e.METADATA_UPDATED="METADATA_UPDATED"}(ps||(ps={})),function(e){e.audio="audio",e.video="video"}(ms||(ms={}));var fs=(e,t)=>{let i=bs(Object.keys(e),Object.keys(t));for(let r of i){let i=e[r],n=t[r];Ts(i,n)?Object.assign(i,n):Es(i,n)?delete e[r]:ks(i,n)&&(e[r]=n)}},ys=(e,t)=>{e.plugins&&Ss(e.plugins,t.plugins)&&(t.plugins=e.plugins),e.layerDefinitions&&Ss(e.layerDefinitions,t.layerDefinitions)&&(t.layerDefinitions=e.layerDefinitions)},Ts=(e,t)=>e&&t,Es=(e,t)=>e&&!t,ks=(e,t)=>!e&&t,Ss=(e,t)=>{if(e===t||0===e.length&&0===(null==t?void 0:t.length))return!0;if(!e||!t||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},bs=(e,t)=>{let i=new Set;for(let t of e)i.add(t);for(let e of t)i.add(e);return Array.from(i)},Rs=class{static convertPeer(e){var t,i,r;return{id:e.peerId,name:e.name,roleName:null==(t=e.role)?void 0:t.name,isLocal:e.isLocal,videoTrack:null==(i=e.videoTrack)?void 0:i.trackId,audioTrack:null==(r=e.audioTrack)?void 0:r.trackId,auxiliaryTracks:e.auxiliaryTracks.map((e=>e.trackId)),customerUserId:e.customerUserId,customerDescription:e.metadata,metadata:e.metadata}}static convertTrack(e,t){let i={id:e.trackId,source:e.source,type:e.type,enabled:e.enabled,displayEnabled:e.enabled,peerId:e.peerId||t};return this.enrichTrack(i,e),i}static enrichTrack(e,t){let i=t.getMediaTrackSettings();
8"screen"===e.source&&"video"===e.type&&(e.displaySurface=i.displaySurface),e.height=i.height,e.width=i.width,t instanceof yr&&(e.volume=t.getVolume()||0),Rs.updateDeviceID(e,t),Rs.enrichVideoTrack(e,t),Rs.enrichPluginsDetails(e,t)}static updateDeviceID(e,t){var i;e.deviceID=t instanceof bn||t instanceof cn?t.settings.deviceId:null==(i=t.getMediaTrackSettings())?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof Er&&(e.layer=t.getSimulcastLayer(),e.degraded=t.degraded,Ss(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichPluginsDetails(e,t){(t instanceof bn||t instanceof cn)&&(Ss(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e){var t,i;let{recording:r,rtmp:n,hls:s}=Rs.convertRecordingStreamingState(null==e?void 0:e.recording,null==e?void 0:e.rtmp,null==e?void 0:e.hls);return{id:e.id,name:e.name,localPeer:null!=(i=null==(t=e.localPeer)?void 0:t.peerId)?i:"",hasWaitingRoom:e.hasWaitingRoom,shareableLink:e.shareableLink,recording:r,rtmp:n,hls:s,sessionId:e.sessionId,startedAt:e.startedAt,joinedAt:e.joinedAt,peerCount:e.peerCount}}static convertMessage(e){var t,i,r;return{sender:e.sender.peerId,senderName:e.sender.name,senderRole:null==(t=e.sender.role)?void 0:t.name,senderUserId:e.sender.customerUserId,recipientPeer:null==(i=e.recipientPeer)?void 0:i.peerId,recipientRoles:null==(r=e.recipientRoles)?void 0:r.map((e=>e.name)),time:e.time,type:e.type,message:e.message}}static convertRoles(e){let t={};return e&&e.forEach((e=>{t[e.name]=e})),t}static convertRoleChangeRequest(e){var t;return{requestedBy:null==(t=e.requestedBy)?void 0:t.peerId,roleName:e.role.name,token:e.token}}static convertException(e){return{code:e.code,action:e.action,name:e.name,message:e.message,description:e.description,isTerminal:e.isTerminal,nativeError:e.nativeError,timestamp:new Date}}static convertDeviceChangeUpdate(e){let t={devices:e.devices,selection:e.selection,type:e.type};return e.error&&(t.error=this.convertException(e.error)),t}static convertPlaylist(e){return{audio:this.getConvertedPlaylistType(e,ms.audio),video:this.getConvertedPlaylistType(e,ms.video)}}static convertPlaylistItem(e,t){let i=t.type,r=e.getCurrentSelection(i),n=e.isPlaying(i),s=t.url===(null==r?void 0:r.url);return ls(cs({},t),{type:t.type,selected:s,playing:s&&n})}static getConvertedPlaylistType(e,t){let i={},r=e.getCurrentSelection(t),n=e.getCurrentProgress(t),s=e.getVolume(t),o=e.getList(t),a=e.getCurrentIndex(t);return e.getList(t).forEach((t=>{i[t.id]=Rs.convertPlaylistItem(e,t)})),{list:i,selection:{id:null==r?void 0:r.id,hasPrevious:a>0,hasNext:a<o.length-1},progress:n,volume:s,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i){var r;return{recording:{browser:cs({running:!1},null==e?void 0:e.browser),server:cs({running:!1},null==e?void 0:e.server),hls:cs({running:!1},null==e?void 0:e.hls)},rtmp:cs({running:!1},t),hls:{variants:(null==(r=null==i?void 0:i.variants)?void 0:r.map((e=>e)))||[],running:!!(null==i?void 0:i.running),error:null==i?void 0:i.error}}}};function Cs(e,t,i=As){let r,n;if(t)for(let s of t.auxiliaryTracks){let t=e[s];i(t)&&(n=Ps(t)?t:n,r=ws(t)?t:r)}return{video:r,audio:n}}function Ps(e){return e&&"audio"===e.type}function ws(e){return e&&"video"===e.type}function As(e){return e&&"screen"===e.source}function Is(e){return e&&"audioplaylist"===e.source}function _s(e){return e&&"videoplaylist"===e.source}function Ds(e){return Boolean(null==e?void 0:e.degraded)}function Os(e,t){return!(!t||!e.tracks[t])&&e.tracks[t].enabled}var Ms=e=>e.room;es(Ms,(e=>e.id));var Ls=e=>e.peers,Ns=e=>e.messages.byID,xs=e=>e.messages.allIDs,Us=e=>e.tracks,Gs=e=>e.settings,Fs=es([Ms],(e=>e&&e.isConnected));es([Fs,Ms],((e,t)=>e?t.peerCount||t.peers.length:Math.max(t.peerCount||t.peers.length-1,0)));var js=es([Ms,Ls],((e,t)=>e.peers.map((e=>t[e])))),Vs=es(Us,(e=>Object.values(e))),Bs=es(Ms,Ls,((e,t)=>t[e.localPeer])),$s=es(Ms,(e=>e.localPeer)),Ks=es(Bs,(e=>null==e?void 0:e.audioTrack)),Hs=es(Bs,(e=>null==e?void 0:e.videoTrack)),qs=es(Bs,(e=>null==e?void 0:e.auxiliaryTracks)),Ws=es([Ks,Hs,qs],((e,t,i)=>{let r=[...i];return e&&r.unshift(e),t&&r.unshift(t),r}));es(js,(e=>e.filter((e=>!e.isLocal)))),es(Ls,(e=>e.speakers),((e,t)=>{let i=Object.entries(t).sort(((e,t)=>{var i,r;let n=(null==(i=e[1])?void 0:i.audioLevel)||0;return((null==(r=t[1])?void 0:r.audioLevel)||0)>n?1:-1}));if(i.length>0&&i[0][1].audioLevel&&i[0][1].audioLevel>0){let t=i[0][1].peerID;if(t in e)return e[t]}return null}));var zs=e=>{let t=Bs(e);return Os(e,null==t?void 0:t.audioTrack)},Js=e=>{let t=Bs(e);return Os(e,null==t?void 0:t.videoTrack)},Ys=e=>{let t=Bs(e);return function(e,t){return!(!t||!e.tracks[t])&&e.tracks[t].displayEnabled}(e,null==t?void 0:t.videoTrack)},Qs=es(Bs,Us,((e,t)=>{let{video:i,audio:r}=Cs(t,e);return!(!i&&!r)})),Zs=es(Ls,Us,((e,t)=>{let i;for(let r in e){let n=e[r],{video:s,audio:o}=Cs(t,n);if(s)return n;o&&!i&&(i=n)}return i}));es(Zs,(e=>!!e)),es(Ls,Us,((e,t)=>{for(let i in e){let r=e[i],{audio:n,video:s}=Cs(t,r);if(!s&&n)return r}})),es(Ls,Us,((e,t)=>{let i=[],r=[];for(let n in e){let s=e[n],{video:o,audio:a}=Cs(t,s);o?i.push(s):a&&r.push(s)}return i.concat(r)})),es(Ls,Us,((e,t)=>{for(let i in t){let r=t[i];if(_s(r)&&ws(r)&&r.peerId)return e[r.peerId]}})),es(Ls,Us,((e,t)=>{for(let i in t){let r=t[i];if(Is(r)&&r.peerId)return e[r.peerId]}})),es(Vs,(e=>e.filter(Ds)));var Xs=es(xs,(e=>e.length));es(Ns,(e=>Object.values(e).filter((e=>!e.read)).length));var eo=es(xs,Ns,((e,t)=>{let i=[];return e.forEach((e=>{i.push(t[e])})),i})),to=es([Ms],(e=>e&&e.roomState));es(to,(e=>e===Xn.Preview));var io=es(Ms,(e=>e.roomState!==Xn.Disconnected)),ro=e=>e.roles;es([ro],(e=>Object.keys(e)));var no=es([Bs,ro],((e,t)=>(null==e?void 0:e.roleName)?t[e.roleName]:null));es([no],(e=>{var t;return!!(null==(t=null==e?void 0:e.subscribeParams)?void 0:t.subscribeToRoles)&&e.subscribeParams.subscribeToRoles.length>0}));var so=es(no,(e=>null==e?void 0:e.permissions));es(Ms,(e=>e.recording)),es(Ms,(e=>e.rtmp)),es(Ms,(e=>e.hls)),es(Ms,(e=>e.sessionId)),es(Ms,(e=>e.startedAt));var oo=(e=ms.audio)=>t=>t.playlist[e].list,ao=(e=ms.audio)=>t=>t.playlist[e].selection,co=(e=ms.audio)=>t=>t.playlist[e].progress,lo=(e=ms.audio)=>t=>t.playlist[e].currentTime,uo=(e=ms.audio)=>t=>t.playlist[e].playbackRate,ho=(e=ms.audio)=>t=>t.playlist[e].volume,po=(e=ms.audio)=>es(oo(e),(e=>Object.values(e))),mo=(e=ms.audio)=>es(oo(e),ao(e),((e,t)=>{if(t.id)return e[t.id]})),vo={selection:ao(ms.audio),progress:co(ms.audio),currentTime:lo(ms.audio),playbackRate:uo(ms.audio),volume:ho(ms.audio),list:po(ms.audio),selectedItem:mo(ms.audio)},go={selection:ao(ms.video),progress:co(ms.video),currentTime:lo(ms.video),playbackRate:uo(ms.video),volume:ho(ms.video),list:po(ms.video),selectedItem:mo(ms.video)};function fo(e){return t=>i=>e(i,t)}var yo="HMS-Store:",To=class{static v(e,...t){this.log(Ti.VERBOSE,e,...t)}static d(...e){this.log(Ti.DEBUG,...e)}static i(...e){this.log(Ti.INFO,...e)}static w(...e){this.log(Ti.WARN,...e)}static e(...e){this.log(Ti.ERROR,...e)}static time(e){this.log(Ti.TIME,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(Ti.TIMEEND,"[HMSPerformanceTiming]",e,e)}static cleanUp(){performance.clearMarks(),performance.clearMeasures()}static log(e,...t){if(!(this.level.valueOf()>e.valueOf()))switch(e){case Ti.VERBOSE:console.log(yo,...t);break;case Ti.DEBUG:console.debug(yo,...t);break;case Ti.INFO:console.info(yo,...t);break;case Ti.WARN:console.warn(yo,...t);break;case Ti.ERROR:console.error(yo,...t);break;case Ti.TIME:performance.mark(t[1]);break;case Ti.TIMEEND:{let e=t[0],i=t[1];try{let t=performance.measure(i,i);
8this.log(Ti.DEBUG,e,i,null==t?void 0:t.duration),performance.clearMarks(i),performance.clearMeasures(i)}catch(t){this.log(Ti.DEBUG,e,i,t)}break}}}};To.level=Ti.VERBOSE;var Eo=(e,t)=>t,ko=(e,t)=>t,So=es([Ls,Eo],((e,t)=>t?e[t]:null)),bo=es([Us,(e,t)=>t],((e,t)=>t?e[t]:null)),Ro=fo(So);fo(es(So,(e=>null==e?void 0:e.name)));var Co=fo(bo),Po=fo(((e,t)=>{let i=So(e,t);if(i&&i.audioTrack&&""!==i.audioTrack)return e.tracks[i.audioTrack]})),wo=(e,t)=>t?e.speakers[t]:null;fo(es(wo,(e=>(null==e?void 0:e.audioLevel)||0)));var Ao=fo(es(((e,t)=>{let i=Po(t)(e);return wo(e,null==i?void 0:i.id)}),(e=>(null==e?void 0:e.audioLevel)||0)));fo(es(Us,So,((e,t)=>{let i=null==t?void 0:t.auxiliaryTracks.find((t=>{let i=e[t];return _s(i)&&ws(i)}));return i?e[i]:void 0}))),fo(es(Us,So,((e,t)=>{let i=null==t?void 0:t.auxiliaryTracks.find((t=>{let i=e[t];return _s(i)&&Ps(i)}));return i?e[i]:void 0}))),fo(es(Us,So,((e,t)=>{let i=null==t?void 0:t.auxiliaryTracks.find((t=>{let i=e[t];return Is(i)&&Ps(i)}));return i?e[i]:void 0}))),fo(es(Us,So,((e,t)=>Cs(e,t))));var Io=fo(((e,t)=>{let i=So(e,t);return Os(e,null==i?void 0:i.audioTrack)})),_o=es([eo,$s,Eo],((e,t,i)=>{if(i)return e.filter((e=>{var r;return!(!e.recipientPeer&&!(null==(r=e.recipientRoles)?void 0:r.length)||![t,i].includes(e.sender))&&[t,i].includes(e.recipientPeer)}))})),Do=es([eo,ko],((e,t)=>{if(t)return e.filter((e=>{var i,r;return!!(null==(i=e.recipientRoles)?void 0:i.length)&&(null==(r=e.recipientRoles)?void 0:r.includes(t))}))})),Oo=es(eo,(e=>e.filter((e=>{var t;return!e.recipientPeer&&!(null==(t=e.recipientRoles)?void 0:t.length)}))));es([Do,ko],(e=>e?e.filter((e=>!e.read)).length:0)),es([_o,Eo],(e=>e?e.filter((e=>!e.read)).length:0)),es(Oo,(e=>e.filter((e=>!e.read)).length)),es([Ls,Us],((e,t)=>Object.values(e).map((e=>{var i;return{peer:e,isAudioEnabled:!!e.audioTrack&&(null==(i=t[e.audioTrack])?void 0:i.enabled)}}))));es([e=>e.roleChangeRequests[0]||null,Ls,ro],((e,t,i)=>e?{requestedBy:e.requestedBy?t[e.requestedBy]:void 0,role:i[e.roleName],token:e.token}:null)),es([no],(e=>{var t;let i=!1,r=!1,n=!1;return(null==(t=null==e?void 0:e.publishParams)?void 0:t.allowed)&&(i=e.publishParams.allowed.includes("video"),r=e.publishParams.allowed.includes("audio"),n=e.publishParams.allowed.includes("screen")),{video:i,audio:r,screen:n}})),es([Hs,Us],((e,t)=>{let i=null;return e&&(i=t[e]),(null==i?void 0:i.plugins)||[]})),es([Ks,Us],((e,t)=>{let i=null;return e&&(i=t[e]),(null==i?void 0:i.plugins)||[]}));var Mo=class{constructor(e,t,i,r){this.playlistManager=e,this.syncPlaylistState=i,this.store=r,this.type=t}play(e){return ds(this,null,(function*(){e?yield this.playlistManager.setEnabled(!0,{id:e,type:this.type}):To.w("Please pass id to play")}))}pause(){return ds(this,null,(function*(){let e=this.type===ms.audio?vo:go,t=this.store.getState(e.selection);t.id?yield this.playlistManager.setEnabled(!1,{id:t.id,type:this.t
8ype}):To.w("No item is currently playing to pause")}))}playNext(){return ds(this,null,(function*(){yield this.playlistManager.playNext(this.type)}))}playPrevious(){return ds(this,null,(function*(){yield this.playlistManager.playPrevious(this.type)}))}seek(e){this.playlistManager.seek(e,this.type),this.syncPlaylistState(`seekOn${this.type}Playlist`)}seekTo(e){this.playlistManager.seekTo(e,this.type),this.syncPlaylistState(`seekToOn${this.type}Playlist`)}setVolume(e){this.playlistManager.setVolume(e,this.type),this.syncPlaylistState(`setVolumeOn${this.type}Playlist`)}setList(e){this.playlistManager.setList(e),this.syncPlaylistState(`setListOn${this.type}Playlist`)}stop(){return ds(this,null,(function*(){yield this.playlistManager.stop(this.type),this.syncPlaylistState(`stop${this.type}Playlist`)}))}setIsAutoplayOn(e){this.playlistManager.setIsAutoplayOn(this.type,e)}setPlaybackRate(e){this.playlistManager.setPlaybackRate(this.type,e),this.syncPlaylistState(`set${this.type}PlaybackRate`)}},Lo={[$i.PEER_JOINED]:ps.PEER_JOINED,[$i.PEER_LEFT]:ps.PEER_LEFT,[$i.ROLE_UPDATED]:ps.ROLE_UPDATED,[$i.AUDIO_TOGGLED]:"PEER_AUDIO_UPDATED",[$i.VIDEO_TOGGLED]:"PEER_VIDEO_UPDATED",[$i.NAME_UPDATED]:ps.NAME_UPDATED,[$i.METADATA_UPDATED]:ps.METADATA_UPDATED},No={[Ki.TRACK_ADDED]:ps.TRACK_ADDED,[Ki.TRACK_REMOVED]:ps.TRACK_REMOVED,[Ki.TRACK_MUTED]:ps.TRACK_MUTED,[Ki.TRACK_UNMUTED]:ps.TRACK_UNMUTED,[Ki.TRACK_DEGRADED]:ps.TRACK_DEGRADED,[Ki.TRACK_RESTORED]:ps.TRACK_RESTORED},xo={[$i.PEER_JOINED]:"peerJoined",[$i.PEER_LEFT]:"peerLeft",[$i.NAME_UPDATED]:"peerNameUpdated",[$i.METADATA_UPDATED]:"peerMetadataUpdated"},Uo="hmsNotification",Go=e=>Rr?`${e} ${document.title}`:e,Fo=(e,t,i)=>{var r;let n=jo(i,t),s=null==(r=e.getWebrtcInternals())?void 0:r.onStatsChange((e=>Vo(t,e,i)));return()=>{n(),s&&s()}},jo=(e,t)=>{let i,r,n;return e.getState($s)?t.namedSetState((t=>{t.localPeer.id=e.getState($s)}),"localpeer-id"):i=e.subscribe((e=>{e&&t.namedSetState((t=>{t.localPeer.id=e}),"localpeer-id")}),$s),e.getState(Hs)?t.namedSetState((t=>{t.localPeer.videoTrack=e.getState(Hs)}),"localpeer-videotrack-id"):r=e.subscribe((e=>{e&&t.namedSetState((t=>{t.localPeer.videoTrack=e}),"localpeer-videotrack-id")}),Hs),e.getState(Ks)?t.namedSetState((t=>{t.localPeer.videoTrack=e.getState(Ks)}),"localpeer-audiotrack-id"):n=e.subscribe((e=>{e&&t.namedSetState((t=>{t.localPeer.videoTrack=e}),"localpeer-audiotrack-id")}),Ks),()=>{null==i||i(),null==r||r(),null==n||n()}},Vo=(e,t,i)=>{let r=i.getState(Us);e.namedSetState((e=>{let n={},s=Object.keys(r);for(let e of s){let i=t.getTrackStats(e);i&&(n[e]=i)}fs(e.trackStats,n);let o={[i.getState($s)]:t.getLocalPeerStats()};fs(e.peerStats,o)}),"webrtc-stats")},Bo=(e,t="resetState")=>{e.namedSetState((e=>{Object.assign(e,{peerStats:{},trackStats:{},localPeer:{id:""}})}),t)},$o=e=>e.trackStats,Ko=e=>e.peerStats,Ho=es([Ko,e=>e.localPeer.id],((e,t)=>e[t]));es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.subscribe)?void 0:t.packetsLost})),es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.subscribe)?void 0:t.jitter})),es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.publish)?void 0:t.bitrate})),es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.subscribe)?void 0:t.bitrate})),es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.publish)?void 0:t.availableOutgoingBitrate})),es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.subscribe)?void 0:t.availableIncomingBitrate})),es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.publish)?void 0:t.bytesSent})),es(Ho,(e=>{var t;return null==(t=null==e?void 0:e.subscribe)?void 0:t.bytesReceived})),es([Ko,(e,t)=>t],((e,t)=>t?e[t]:void 0));var qo=es([$o,(e,t)=>t],((e,t)=>t?e[t]:void 0));fo(es(qo,(e=>null==e?void 0:e.bitrate))),fo(es(qo,(e=>null==e?void 0:e.bytesReceived))),fo(es(qo,(e=>null==e?void 0:e.framesPerSecond))),fo(es(qo,(e=>null==e?void 0:e.jitter))),fo(es(qo,(e=>null==e?void 0:e.packetsLost)));var Wo=es([$o,e=>e.localPeer.audioTrack],((e,t)=>t?e[t]:void 0)),zo=es([$o,e=>e.localPeer.videoTrack],((e,t)=>t?e[t]:void 0));es(Wo,(e=>null==e?void 0:e.bitrate)),es(zo,(e=>null==e?void 0:e.bitrate)),es(Wo,(e=>null==e?void 0:e.bytesSent)),es(zo,(e=>null==e?void 0:e.bytesSent)),es(zo,(e=>null==e?void 0:e.framesPerSecond)),es(zo,(e=>null==e?void 0:e.qualityLimitationReason));
8var Jo=class{constructor(e,t,i){this.getStats=()=>(this.stats||(this.stats=new class{constructor(e,t){this.hmsStore=e,this.sdk=t,this.store=Jo.createNewHMSStore(Go("HMSStatsStore"),gs),this.getState=this.store.getState,this.subscribe=this.store.subscribe,this.getPublishPeerConnection=()=>new Promise((e=>{var t,i;"Connected"===this.hmsStore.getState(to)?e(null==(i=null==(t=this.sdk)?void 0:t.getWebrtcInternals())?void 0:i.getPublishPeerConnection()):this.hmsStore.subscribe((t=>{var i,r;"Connected"===t&&e(null==(r=null==(i=this.sdk)?void 0:i.getWebrtcInternals())?void 0:r.getPublishPeerConnection())}),to)})),this.getSubscribePeerConnection=()=>new Promise((e=>{var t,i;"Connected"===this.hmsStore.getState(to)?e(null==(i=null==(t=this.sdk)?void 0:t.getWebrtcInternals())?void 0:i.getSubscribePeerConnection()):this.hmsStore.subscribe((t=>{var i,r;"Connected"===t&&e(null==(r=null==(i=this.sdk)?void 0:i.getWebrtcInternals())?void 0:r.getSubscribePeerConnection())}),to)})),this.sdk&&((e,t,i)=>{let r;i.getState(to)===Xn.Connected&&(r=Fo(e,t,i)),i.subscribe((n=>{[Xn.Connected,Xn.Reconnecting].includes(n)?r||(r=Fo(e,t,i)):r&&(Bo(t),r())}),to)})(this.sdk,this.store,this.hmsStore)}}(this.store,this.sdk)),this.stats),this.store=e||Jo.createNewHMSStore(Go("HMSStore"),vs),this.notifications=i||new class{constructor(e){this.id=0,this.onNotification=e=>(this.eventEmitter.addListener(Uo,e),()=>{this.eventEmitter.removeListener(Uo,e)}),this.store=e,this.eventEmitter=new Ei.EventEmitter2}sendPlaylistTrackEnded(e){let t=this.createNotification(ps.PLAYLIST_TRACK_ENDED,e,hs.INFO);this.emitEvent(t)}sendDeviceChange(e){var t;let i=this.createNotification(ps.DEVICE_CHANGE_UPDATE,e,e.error?hs.ERROR:hs.INFO,`Selected ${e.type} device - ${null==(t=e.selection)?void 0:t.label}`);this.emitEvent(i)}sendLeaveRoom(e){var t;let i=null==(t=e.requestedBy)?void 0:t.name,r=this.createNotification(e.roomEnded||!i?ps.ROOM_ENDED:ps.REMOVED_FROM_ROOM,e,hs.INFO,`${e.roomEnded?"Room ended":"Removed from room"} ${i?`by ${i}`:""}`);this.emitEvent(r)}sendPeerList(e){let t=this.createNotification(ps.PEER_LIST,e,hs.INFO);this.emitEvent(t)}sendPeerUpdate(e,t){let i=this.store.getState(Ro(null==t?void 0:t.id))||t,r=Lo[e];if(r){let e=this.createNotification(r,i,hs.INFO);this.emitEvent(e)}}sendTrackUpdate(e,t){let i=this.store.getState(Co(t)),r=No[e];if(r){let e=this.createNotification(r,i,hs.INFO);this.emitEvent(e)}}sendMessageReceived(e){let t=this.createNotification(ps.NEW_MESSAGE,e,hs.INFO);this.emitEvent(t)}sendError(e){let t=this.createNotification(ps.ERROR,e,hs.ERROR);this.emitEvent(t)}sendReconnecting(e){let t=this.createNotification(ps.RECONNECTING,e,hs.ERROR);this.emitEvent(t)}sendReconnected(){let e=this.createNotification(ps.RECONNECTED,null,hs.INFO);this.emitEvent(e)}sendChangeTrackStateRequest(e){let t=this.createNotification(ps.CHANGE_TRACK_STATE_REQUEST,e,hs.INFO);this.emitEvent(t)}sendChangeMultiTrackStateRequest(e){let t=this.createNotification(ps.CHANGE_MULTI_TRACK_STATE_REQUEST,e,hs.INFO);this.emitEvent(t)}emitEvent(e){this.eventEmitter.emit(Uo,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}}(this.store),t?this.actions=t:(this.sdk=new class{constructor(){this.TAG="[HMSSdk]:",this.transportState=Sn.Disconnected,this.sdkState=Ai({},Jn),this.handleAutoplayError=e=>{var t,i;null==(i=null==(t=this.errorListener)?void 0:t.onError)||i.call(t,e.error)},this.observer={onNotification:e=>{e.method!==Ar.PEER_LEAVE_REQUEST?this.notificationManager.handleNotification(e,this.sdkState.isReconnecting):this.handlePeerLeaveRequest(e.params)},onTrackAdd:e=>{this.notificationManager.handleTrackAdd(e)},onTrackRemove:e=>{this.notificationManager.handleTrackRemove(e)},onTrackDegrade:e=>{var t,i;Mi.d(this.TAG,"Sending Track Update Track Degraded",e),null==(i=this.listener)||i.onTrackUpdate(Ki.TRACK_DEGRADED,e,null==(t=this.store)?void 0:t.getPeerByTrackId(e.trackId))},onTrackRestore:e=>{var t,i;Mi.d(this.TAG,"Sending Track Update Track Restored",e),null==(i=this.listener)||i.onTrackUpdate(Ki.TRACK_RESTORED,e,null==(t=this.store)?void 0:t.getPeerByTrackId(e.trackId))},onFailure:e=>{var t;null==(t=this.errorListener)||t.onError(e)},onStateChange:(e,t)=>
8_i(this,null,(function*(){var i,r,n,s;switch(e){case Sn.Joined:this.transportState===Sn.Reconnecting&&(null==(i=this.listener)||i.onReconnected());break;case Sn.Failed:yield this.leave(),null==(n=null==(r=this.errorListener)?void 0:r.onError)||n.call(r,t),this.sdkState.isReconnecting=!1;break;case Sn.Reconnecting:this.sdkState.isReconnecting=!0,null==(s=this.listener)||s.onReconnecting(t)}this.transportState=e}))},this.handlePeerLeaveRequest=e=>{var t;let i=this.store.getPeerById(e.requested_by),r={roomEnded:e.room_end,reason:e.reason,requestedBy:i};null==(t=this.listener)||t.onRemovedFromRoom(r),this.leave()},this.handleDeviceChange=e=>{var t,i,r,n,s,o;if(Mi.d(this.TAG,"Device Change event",e),null==(i=null==(t=this.deviceChangeListener)?void 0:t.onDeviceChange)||i.call(t,e),e.error&&e.type){let t=e.type.includes("audio")?null==(r=this.localPeer)?void 0:r.audioTrack:null==(n=this.localPeer)?void 0:n.videoTrack;null==(s=this.errorListener)||s.onError(e.error),[Ni.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,Ni.TracksErrors.DEVICE_IN_USE,Ni.TracksErrors.DEVICE_NOT_AVAILABLE].includes(e.error.code)&&t&&(t.setEnabled(!1),null==(o=this.listener)||o.onTrackUpdate(Ki.TRACK_MUTED,t,this.localPeer))}},this.sendAudioPresenceFailed=()=>{let e=Ui.TracksErrors.NoAudioDetected(Li.PREVIEW);en.queue(gn.audioDetectionFail(e,this.deviceManager.getCurrentSelection().audioInput)).flush()}}initStoreAndManagers(){if(this.sdkState.isInitialised)return this.notificationManager.setListener(this.listener),void this.audioSinkManager.setListener(this.listener);this.sdkState.isInitialised=!0,this.store=new class{constructor(){this.comparator=new class{constructor(e){this.store=e,this.primitiveComparator=(e,t)=>e===t?0:Number(e)-Number(t),this.stringComparator=(e,t)=>e===t?0:e<t?-1:1}getPeerComparators(){return{videoEnabled:(e,t)=>{var i,r;return this.primitiveComparator(Boolean(null==(i=e.videoTrack)?void 0:i.enabled),Boolean(null==(r=t.videoTrack)?void 0:r.enabled))},audioEnabled:(e,t)=>{var i,r;return this.primitiveComparator(Boolean(null==(i=e.audioTrack)?void 0:i.enabled),Boolean(null==(r=t.audioTrack)?void 0:r.enabled))},screenShare:(e,t)=>this.primitiveComparator(e.auxiliaryTracks.some((e=>"screen"===e.source)),t.auxiliaryTracks.some((e=>"screen"===e.source))),audioLevel:(e,t)=>{var i,r;return this.primitiveComparator((null==(i=this.store.getSpeakers().find((t=>t.peer&&t.peer.peerId===(null==e?void 0:e.peerId))))?void 0:i.audioLevel)||-1,(null==(r=this.store.getSpeakers().find((e=>e.peer&&e.peer.peerId===(null==t?void 0:t.peerId))))?void 0:r.audioLevel)||-1)},rolePriority:(e,t)=>{var i,r;return this.primitiveComparator((null==(i=e.role)?void 0:i.priority)||0,(null==(r=t.role)?void 0:r.priority)||0)}}}getTrackComparators(){return{video:(e,t)=>this.primitiveComparator(e.type===pr.VIDEO,t.type===pr.VIDEO),audio:(e,t)=>this.primitiveComparator(e.type===pr.AUDIO,t.type===pr.AUDIO),enabled:(e,t)=>this.primitiveComparator(Boolean(e.enabled),Boolean(t.enabled)),peerAudioLevel:(e,t)=>{let i=this.store.getPeerByTrackId(e.trackId),r=this.store.getPeerByTrackId(t.trackId);return this.getPeerComparators().audioLevel(i,r)},audioLevel:(e,t)=>{var i,r;return this.primitiveComparator((null==(i=this.store.getSpeakers().find((t=>t.track.trackId===e.trackId)))?void 0:i.audioLevel)||0,(null==(r=this.store.getSpeakers().find((e=>e.track.trackId===t.trackId)))?void 0:r.audioLevel)||0)},screenShare:(e,t)=>this.primitiveComparator("screen"===e.source,"screen"===t.source),rolePriority:(e,t)=>{var i,r,n,s;return this.primitiveComparator((null==(r=null==(i=this.store.getPeerByTrackId(e.trackId))?void 0:i.role)?void 0:r.priority)||0,(null==(s=null==(n=this.store.getPeerByTrackId(t.trackId))?void 0:n.role)?void 0:s.priority)||0)}}}}(this),this.knownRoles={},this.peers={},this.tracks={},this.peerTrackStates={},this.speakers=[],this.videoLayers=null,this.screenshareLayers=null,this.roleDetailsArrived=!1}getConfig(){return this.config}getPublishParams(){return this.publishParams}getComparator(){return this.comparator}getRoom(){return this.room}getPolicyForRole(e){return this.knownRoles[e]}getKnownRoles(){return this.knownRoles}getLocalPeer(){if(this.localPeerId&&this.peers[this.localPeerId])return this.peers[this.localPeerId]}getRemotePeers(){return Object.values(this.peers).filter((e=>!e.isLocal))}getPeers(){return Object.values(this.peers)}getPeerById(e){if(this.peers[e])return this.peers[e]}getTracksMap(){return this.tracks}getTracks(){return Object.values(this.tracks)}getVideoTracks(){return this.getTracks().filter((e=>e.type===pr.VIDEO))}getRemoteVideoTracks(){return this.getTracks().filter((e=>e instanceof Er))}getAudioTracks(){return this.getTracks().filter((e=>e.type===pr.AUDIO))}getPeerTracks(e){let t=e?this.peers[e]:void 0,i=[];return(null==t?void 0:t.videoTrack)&&i.push(t.videoTrack),(null==t?void 0:t.audioTrack)&&i.push(t.audioTrack),i.concat((null==t?void 0:t.auxiliaryTracks)||[])}getLocalPeerTracks(){return this.getPeerTracks(this.localPeerId)}getTrackById(e){var t,i;let r=this.tracks[e];if(r)return r;let n=this.getLocalPeer();if(n){if(null==(t=n.audioTrack)?void 0:t.isPublishedTrackId(e))return n.audioTrack;if(null==(i=n.videoTrack)?void 0:i.isPublishedTrackId(e))return n.videoTrack}}getPeerByTrackId(e){let t=this.tracks[e];return t.peerId?this.peers[t.peerId]:void 0}getSpeakers(){return this.speakers}getSpeakerPeers(){return this.speakers.map((e=>e.peer))}setRoom(e){this.room=e}setKnownRoles(e){this.knownRoles=e,this.roleDetailsArrived=!0,this.updatePeersPolicy()}hasRoleDetailsArrived(){return this.roleDetailsArrived}setConfig(e){var t,i,r;if(sn.rememberDevices(Boolean(e.rememberDeviceSelection)),e.rememberDeviceSelection){let n=sn.get
8Selection();n&&(e.settings||(e.settings={}),(null==(t=n.audioInput)?void 0:t.deviceId)&&(e.settings.audioInputDeviceId=e.settings.audioInputDeviceId||n.audioInput.deviceId),(null==(i=n.audioOutput)?void 0:i.deviceId)&&(e.settings.audioOutputDeviceId=e.settings.audioOutputDeviceId||n.audioOutput.deviceId),(null==(r=n.videoInput)?void 0:r.deviceId)&&(e.settings.videoDeviceId=e.settings.videoDeviceId||n.videoInput.deviceId))}this.config=e}setPublishParams(e){this.publishParams=e}addPeer(e){this.peers[e.peerId]=e,e.isLocal&&(this.localPeerId=e.peerId)}addTrack(e){this.tracks[e.trackId]=e}getTrackState(e){return this.peerTrackStates[e]}setTrackState(e){this.peerTrackStates[e.trackInfo.track_id]=e}removePeer(e){this.localPeerId===e&&(this.localPeerId=void 0),delete this.peers[e]}removeTrack(e){delete this.tracks[e]}updateSpeakers(e){this.speakers=e}updateAudioOutputVolume(e){this.getAudioTracks().forEach((t=>t.setVolume(e)))}updateAudioOutputDevice(e){this.getAudioTracks().forEach((t=>{t.setOutputDevice(e)}))}getSubscribeDegradationParams(){var e,t;let i=null==(t=null==(e=this.getLocalPeer())?void 0:e.role)?void 0:t.subscribeParams.subscribeDegradation;if(i&&Object.keys(i).length>0)return i}getSimulcastLayers(e){var t,i;return"screen"===e?(null==(t=this.screenshareLayers)?void 0:t.layers)||[]:(null==(i=this.videoLayers)?void 0:i.layers)||[]}getSimulcastDimensions(e){let t="screen"===e?this.screenshareLayers:this.videoLayers;return{width:null==t?void 0:t.width,height:null==t?void 0:t.height}}convertSimulcastLayers(e){return Ii(Ai({},e),{layers:(e.layers||[]).map((e=>Ii(Ai({},e),{maxBitrate:1e3*e.maxBitrate})))})}setVideoSimulcastLayers(e){this.videoLayers=this.convertSimulcastLayers(e)}setScreenshareSimulcastLayers(e){this.screenshareLayers=this.convertSimulcastLayers(e)}getSimulcastDefinitionsForPeer(e,t){if(!e.role)return[];let i,r=this.getPolicyForRole(e.role.name).publishParams;if("regular"===t?i=r.videoSimulcastLayers:"screen"===t&&(i=r.screenSimulcastLayers),!i||!i.layers||0===i.layers.length)return[];let n=i.width,s=i.height;return i.layers.map((e=>({layer:hr[e.rid],resolution:{width:n&&e.scaleResolutionDownBy?n/e.scaleResolutionDownBy:void 0,height:s&&e.scaleResolutionDownBy?s/e.scaleResolutionDownBy:void 0}})))}cleanUp(){let e=this.getTracks();for(let t of e)t.cleanup();this.config=void 0,this.localPeerId=void 0,this.roleDetailsArrived=!1}setErrorListener(e){this.errorListener=e}updatePeersPolicy(){this.getPeers().forEach((e=>{var t;e.role?e.role=this.getPolicyForRole(e.role.name):null==(t=this.errorListener)||t.onError(Ui.GenericErrors.InvalidRole(Li.VALIDATION,""))}))}},this.eventBus=new class{constructor(){this.eventEmitter=new Ei.EventEmitter2,this.deviceChange=new Wn(Xi,this.eventEmitter),this.localAudioEnabled=new Wn(er,this.eventEmitter),this.localVideoEnabled=new Wn(tr,this.eventEmitter),this.statsUpdate=new Wn(ir,this.eventEmitter),this.trackDegraded=new Wn(rr,this.eventEmitter),this.trackRestored=new Wn(nr,this.eventEmitter),this.trackAudioLevelUpdate=new Wn(sr,this.eventEmitter),this.localAudioSilence=new Wn(or,this.eventEmitter)}},this.playlistManager=new qn(this),this.notificationManager=new class{constructor(e,t,i){this.store=e,this.listener=t,this.audioListener=i,this.TAG="[HMSNotificationManager]",this.eventEmitter=new Ei.EventEmitter2,this.hasConsistentRoomStateArrived=!1,this.ignoreNotification=e=>{if(e===Ar.PEER_LIST)this.hasConsistentRoomStateArrived=!0;else if(e===Ar.ROOM_STATE)return this.hasConsistentRoomStateArrived;return!1},this.handleTrackAdd=e=>{this.trackManager.handleTrackAdd(e)},this.handleTrackRemove=e=>{this.trackManager.handleTrackRemove(e)},this.updateLocalPeer=({name:e,metadata:t})=>{let i=this.store.getLocalPeer();this.peerManager.handlePeerInfoUpdate({peer:i,name:e,data:t})},this.trackManager=new class{constructor(e,t,i){this.store=e,this.eventEmitter=t,this.listener=i,this.tracksToProcess=new Map,this.handleTrackAdd=e=>{Mi.d(this.TAG,"ONTRACKADD",e,e.nativeTrack),this.store.addTrack(e),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()},this.handleTrackRemove=e=>{var t;Mi.d(this.TAG,"ONTRACKREMOVE",e,e.nativeTrack);let i=this.store.getTrackState(e.trackId);if(!i)return;e.type===pr.AUDIO&&this.eventEmitter.emit("track-removed",{detail:e});let r=this.store.getPeerById(i.peerId);if(!r)return;let n=()=>{let t=r.auxiliaryTracks.indexOf(e);t>-1&&r.auxiliaryTracks.splice(t,1)};switch(e.type){case pr.AUDIO:"regular"!==e.source?n():r.audioTrack=void 0;break;case pr.VIDEO:"regular"!==e.source?n():r.videoTrack=void 0}this.store.removeTrack(e.trackId),null==(t=this.listener)||t.onTrackUpdate(Ki.TRACK_REMOVED,e,r)},this.handleTrackLayerUpdate=e=>{var t,i;for(let r in e.tracks){let n=e.tracks[r],s=this.store.getTrackById(r);if(!s)continue;let o=this.store.getPeerByTrackId(r);if(o&&s instanceof Er){let e=this.isTrackDegraded(n.expected_layer,n.current_layer);s.setDegraded(e),e?null==(t=this.listener)||t.onTrackUpdate(Ki.TRACK_DEGRADED,s,o):null==(i=this.listener)||i.onTrackUpdate(Ki.TRACK_RESTORED,s,o)}}},this.handleTrackUpdate=e=>{var t,i,r,n;Mi.d(this.TAG,"TRACK_UPDATE",e);let s=this.store.getPeerById(e.peer.peer_id);if(s)for(let o in e.tracks){let a=Object.assign({},null==(t=this.store.getTrackState(o))?void 0:t.trackInfo),c=e.tracks[o],l=this.store.getTrackById(o);this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:Ai(Ai({},a),c)}),!l||this.tracksToProcess.has(o)?this.processPendingTracks():(l.setEnabled(!c.mute),a.mute!==c.mute?(c.mute?null==(i=this.listener)||i.onTrackUpdate(Ki.TRACK_MUTED,l,s):null==(r=this.listener)||r.onTrackUpdate(Ki.TRACK_UNMUTED,l,s),l.type===pr.AUDIO&&this.eventEmitter.emit("track-updated",{detail:{track:l,enabled:!c.mute}})):a.description!==c.description&&(null==(n=this.listener)||n.onTrackUpdate(Ki.TRACK_DESCRIPTION_CHANGED,l,s)))}}}get TAG(){return`[${this.constructor.name}]`}isTrackDegraded(e,t){let i=e=>{switch(e){case Wi.HIGH:return 3;case Wi.MEDIUM:return 2;case Wi.LOW:return 1;case Wi.NONE:return 0}};return i(t)<i(e)}handleTrackMetadataAdd(e){Mi.d(this.TAG,"TRACK_METADATA_ADD",e);for(let t in e.tracks)this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:e.tracks[t]});this.processPendingTracks()}
8processPendingTracks(){new Map(this.tracksToProcess).forEach((e=>{var t;let i=this.store.getTrackState(e.trackId);if(!i)return;let r=this.store.getPeerById(i.peerId);if(r){switch(e.source=i.trackInfo.source,e.peerId=r.peerId,e.setEnabled(!i.trackInfo.mute),e.type){case pr.AUDIO:r.audioTrack||"regular"!==e.source?r.auxiliaryTracks.push(e):r.audioTrack=e;break;case pr.VIDEO:{let t=e,i=this.store.getSimulcastDefinitionsForPeer(r,t.source);t.setSimulcastDefinitons(i),r.videoTrack||"regular"!==e.source?r.auxiliaryTracks.push(t):r.videoTrack=t}}e.type===pr.AUDIO?this.eventEmitter.emit("track-added",{detail:{track:e,peer:r}}):null==(t=this.listener)||t.onTrackUpdate(Ki.TRACK_ADDED,e,r),this.tracksToProcess.delete(e.trackId)}}))}}(this.store,this.eventEmitter,this.listener),this.peerManager=new class{constructor(e,t,i){this.store=e,this.trackManager=t,this.listener=i,this.handlePeerList=e=>{var t;if(0===e.length)return;let i=[];for(let t of e)i.push(this.makePeer(t));null==(t=this.listener)||t.onPeerUpdate($i.PEER_LIST,i),this.trackManager.processPendingTracks()},this.handlePeerJoin=e=>{var t;let i=this.makePeer(e);null==(t=this.listener)||t.onPeerUpdate($i.PEER_JOINED,i),this.trackManager.processPendingTracks()},this.handlePeerLeave=e=>{var t,i,r,n;let s=this.store.getPeerById(e.peer_id);this.store.removePeer(e.peer_id),Mi.d(this.TAG,"PEER_LEAVE event",e,this.store.getPeers()),s&&(s.audioTrack&&(null==(t=this.listener)||t.onTrackUpdate(Ki.TRACK_REMOVED,s.audioTrack,s)),s.videoTrack&&(null==(i=this.listener)||i.onTrackUpdate(Ki.TRACK_REMOVED,s.videoTrack,s)),null==(r=s.auxiliaryTracks)||r.forEach((e=>{var t;null==(t=this.listener)||t.onTrackUpdate(Ki.TRACK_REMOVED,e,s)})),null==(n=this.listener)||n.onPeerUpdate($i.PEER_LEFT,s))}}get TAG(){return`[${this.constructor.name}]`}handleNotification(e,t){switch(e){case Ar.PEER_JOIN:{let e=t;this.handlePeerJoin(e);break}case Ar.PEER_LEAVE:{let e=t;this.handlePeerLeave(e);break}case Ar.PEER_UPDATE:this.handlePeerUpdate(t)}}handlePeerUpdate(e){var t;let i=this.store.getPeerById(e.peer_id);if(i){if(i.role&&i.role.name!==e.role){let r=this.store.getPolicyForRole(e.role);i.updateRole(r),null==(t=this.listener)||t.onPeerUpdate($i.ROLE_UPDATED,i)}this.handlePeerInfoUpdate(Ai({peer:i},e.info))}}handlePeerInfoUpdate({peer:e,name:t,data:i}){var r,n;!e||(t&&e.name!==t&&(e.updateName(t),null==(r=this.listener)||r.onPeerUpdate($i.NAME_UPDATED,e)),i&&e.metadata!==i&&(e.updateMetadata(i),null==(n=this.listener)||n.onPeerUpdate($i.METADATA_UPDATED,e)))}makePeer(e){let t=new jr({peerId:e.peer_id,name:e.info.name,customerUserId:e.info.user_id,metadata:e.info.data,role:this.store.getPolicyForRole(e.role)});this.store.addPeer(t),Mi.d(this.TAG,"adding to the peerList",t);for(let t in e.tracks)this.store.setTrackState({peerId:e.peer_id,trackInfo:e.tracks[t]});return t}}(this.store,this.trackManager,this.listener),this.peerListManager=new class{constructor(e,t,i,r){this.store=e,this.peerManager=t,this.trackManager=i,this.listener=r,this.handleInitialPeerList=e=>{let t=Object.values(e.peers);this.peerManager.handlePeerList(t)},this.handleReconnectPeerList=e=>{this.handleRepeatedPeerList(e.peers)},this.handlePreviewRoomState=e=>{if(!this.store.hasRoleDetailsArrived())return;let t=e.peers||{};Object.keys(t).forEach((e=>{t[e].tracks={}})),this.handleRepeatedPeerList(t)},this.handleRepeatedPeerList=e=>{let t=this.store.getRemotePeers(),i=Object.values(e),r=t.filter((t=>!e[t.peerId]));Mi.d(this.TAG,{peersToRemove:r}),r.forEach((e=>{var t;let i={peer_id:e.peerId,role:(null==(t=e.role)?void 0:t.name)||"",info:{name:e.name,data:e.metadata||"",user_id:e.customerUserId||""},tracks:{}};this.peerManager.handlePeerLeave(i)})),i.forEach((e=>{let t=this.store.getPeerById(e.peer_id),i=Object.values(e.tracks);t?(this.store.getPeerTracks(t.peerId).forEach((i=>{var r;e.tracks[i.trackId]||(this.removePeerTrack(t,i.trackId),null==(r=this.listener)||r.onTrackUpdate(Ki.TRACK_REMOVED,i,t))})),i.forEach((e=>{this.store.getTrackById(e.track_id)||this.store.setTrackState({peerId:t.peerId,trackInfo:e})})),this.trackManager.handleTrackUpdate({peer:{info:e.info,peer_id:e.peer_id},tracks:e.tracks}),this.peerManager.handlePeerUpdate(e)):this.peerManager.handlePeerJoin(e)}))}}get TAG(){return`[${this.constructor.name}]`}handleNotification(e,t,i){if(e===Ar.PEER_LIST){let e=t;i?(Mi.d(this.TAG,"RECONNECT_PEER_LIST event",e),this.handleReconnectPeerList(e)):(Mi.d(this.TAG,"PEER_LIST event",e),this.handleInitialPeerList(e))}else if(e===Ar.ROOM_STATE){let e=t;this.handlePreviewRoomState(e)}}removePeerTrack(e,t){var i,r;if((null==(i=e.audioTrack)?void 0:i.trackId)===t)e.audioTrack=void 0;else if((null==(r=e.videoTrack)?void 0:r.trackId)===t)e.videoTrack=void 0;else{let i=e.auxiliaryTracks.findIndex((e=>e.trackId===t));i>=0&&e.auxiliaryTracks.splice(i,1)}}}(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new class{constructor(e,t){this.store=e,this.listener=t}get TAG(){return`[${this.constructor.name}]`}handleNotification(e,t){e===Ar.BROADCAST&&this.handleBroadcast(t)}handleBroadcast(e){var t;let i=e.peer,r=e.info,n=e.roles,s=this.store.getPeerById(i.peer_id);s||(s=new xr({peerId:i.peer_id,name:i.info.name,isLocal:!1,customerUserId:i.info.user_id,metadata:i.info.data}));let o=e.private?this.store.getLocalPeer():void 0,a=[];if(null==n?void 0:n.length){let e=this.store.getKnownRoles();for(let t of n)e[t]&&a.push(e[t])}let c=new Nr(Ii(Ai({},r),{sender:s,recipientRoles:a,recipientPeer:o,time:new Date(e.timestamp)}));Mi.d(this.TAG,"Received Message:: ",c),null==(t=this.listener)||t.onMessageReceived(c)}}(this.store,this.listener),this.policyChangeManager=new class{constructor(e,t){this.store=e,this.eventEmitter=t}handlePolicyChange(e){var t,i;let r=this.store.getLocalPeer();if(r&&!r.role){let t=e.known_roles[e.name];r.updateRole(t)}this.store.setKnownRoles(e.known_roles);let n=null==(t=e.known_roles[e.name])?void 0:t.publishParams;if(this.store.setPublishParams(n),this.setSimulcastLayers(n),this.handleStreamingRecordingPermissions(null==(i=e.known_roles[e.name])?void 0:i.permissions),(null==r?void 0:r.role)&&r.role.name!==e.name){let t=this.store.getPolicyForRole(e.name),i=r.role;r.updateRole(t),this.eventEmitter.emit("local-peer-role-update",{detail:{oldRole:i,newRole:t}})}this.eventEmitter.emit("policy-change",{detail:{params:e}})}setSimulcastLayers(e){if(e&&Object.keys(e).length>0){let{videoSimulcastLayers:t,screenSimulcastLayers:i}=e;this.store.setVideoSimulcastLayers(t),this.store.setScreenshareSimulcastLayers(i)}}handleStreamingRecordingPermissions(e){e&&(void 0===e.recording&&(e.recording=!0),void 0===e.streaming&&(e.streaming=!0))}}(this.store,this.eventEmitter),this.requestManager=new class{constructor(e,t){this.store=e,this.listener=t}handleNotification(e,t){switch(e){case Ar.ROLE_CHANGE_REQUEST:this.handleRoleChangeRequest(t);break;case Ar.TRACK_UPDATE_REQUEST:this.handleTrackUpdateRequest(t);break;case Ar.CHANGE_TRACK_MUTE_STATE_UPDATE:this.handleChangeTrackStateRequest(t);break;default:return}}handleRoleChangeRequest(e){var t;let i={requestedBy:this.store.getPeerById(e.requested_by),role:this.store.getPolicyForRole(e.role),token:e.token};null==(t=this.listener)||t.onRoleChangeRequest(i)}handleTrackUpdateRequest(e){let{requested_by:t,track_id:i,mute:r}=e,n=this.store.getPeerById(t),s=this.store.getLocalPeerTracks().find((e=>e.publishedTrackId===i));if(!n||n.isLocal||!s)return;let o=()=>{var e;null==(e=this.listener)||e.onChangeTrackStateRequest({requestedBy:n,track:s,enabled:!r})};if(r){if(s.enabled===!r)return;s.setEnabled(!r).then(o)}else o()}handleChangeTrackStateRequest(e){var t;let{type:i,source:r,value:n,requested_by:s}=e,o=this.store.getPeerById(s);if(!o)return;let a=!n,c=this.getTracksToBeUpdated({type:i,source:r,enabled:a});if(0!==c.length)if(a)null==(t=this.listener)||t.onChangeMultiTrackStateRequest({requestedBy:o,tracks:c,type:i,source:r,enabled:!0});else{let e=[];for(let t of c)e.push(t.setEnabled(!1));Promise.all(e).then((()=>{var e;null==(e=this.listener)||e.onChangeMultiTrackStateRequest({requestedBy:o,tracks:c,enabled:!1})}))}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let r=this.store.getLocalPeerTracks();return e&&(r=r.filter((t=>t.type===e))),t&&(r=r.filter((e=>e.source===t))),r.filter((e=>e.enabled!==i))}}(this.store,this.listener),this.activeSpeakerManager=new class{constructor(e,t,i){this.store=e,this.listener=t,this.audioListener=i}handleActiveSpeakers(e){var t,i,r;let n=e["speaker-list"],s=n.map((e=>({audioLevel:e.level,peer:this.store.getPeerById(e.peer_id),track:this.store.getTrackById(e.track_id)})));null==(t=this.audioListener)||t.onAudioLevelUpdate(s),this.store.updateSpeakers(s);let o=n[0];if(o){let e=this.store.getPeerById(o.peer_id);null==(i=this.listener)||i.onPeerUpdate($i.BECAME_DOMINANT_SPEAKER,e)}else null==(r=this.listener)||r.onPeerUpdate($i.RESIGNED_DOMINANT_SPEAKER,null)}}(this.store,this.listener,this.audioListener),this.roomUpdateManager=new class{constructor(e,t){this.store=e,this.listener=t}handleNotification(e,t){switch(e){case Ar.PEER_LIST:this.onRoomState(t.room);break;case Ar.RTMP_START:this.onRTMPStart(t);break;case Ar.RTMP_STOP:this.onRTMPStop(t);break;case Ar.RECORDING_START:this.onRecordingStart(t);break;case Ar.RECORDING_STOP:this.onRecordingStop(t);break;case Ar.ROOM_STATE:this.handlePreviewRoomState(t);break;default:this.onHLS(e,t)}}handlePreviewRoomState(e){let{room:t}=e;this.onRoomState(t,e.peer_count)}onRoomState(e,t){var i,r,n;let{recording:s,streaming:o,session_id:a,started_at:c,name:l}=e,d=this.store.getRoom();d.peerCount=t,d.name=l,d.recording.server.running=!!(null==s?void 0:s.sfu.enabled),d.recording.browser.running=!!(null==s?void 0:s.browser.enabled),d.rtmp.running=!!(null==(i=null==o?void 0:o.rtmp)?void 0:i.enabled),d.rtmp.startedAt=this.getAsDate(null==(r=null==o?void 0:o.rtmp)?void 0:r.started_at),d.recording.server.startedAt=this.getAsDate(null==s?void 0:s.sfu.started_at),d.recording.browser.startedAt=this.getAsDate(null==s?void 0:s.browser.started_at),d.recording.hls=this.getHLSRecording(null==o?void 0:o.hls),d.hls=this.convertHls(null==o?void 0:o.hls),d.sessionId=a,d.startedAt=this.getAsDate(c),null==(n=this.listener)||n.onRoomUpdate(Bi.RECORDING_STATE_UPDATED,d)}getAsDate(e){return e?new Date(e):void 0}onRTMPStart(e){var t;this.setRTMPStatus(!(null==(t=e.error)?void 0:t.code),e)}onRTMPStop(e){this.setRTMPStatus(!1,e)}onRecordingStart(e){var t;this.setRecordingStatus(!(null==(t=e.error)?void 0:t.code),e)}onRecordingStop(e){this.setRecordingStatus(!1,e)}onHLS(e,t){var i,r;if(![Ar.HLS_START,Ar.HLS_STOP].includes(e))return;let n=this.store.getRoom();t.enabled=e===Ar.HLS_START&&!(null==(i=t.error)?void 0:i.code),n.hls=this.convertHls(t),n.recording.hls=this.getHLSRecording(t),null==(r=this.listener)||r.onRoomUpdate(Bi.HLS_STREAMING_STATE_UPDATED,n)}convertHls(e){var t,i;let r={running:!!(null==e?void 0:e.enabled),variants:[],error:(null==(t=null==e?void 0:e.error)?void 0:t.code)?e.error:void 0};
8return null==(i=null==e?void 0:e.variants)||i.forEach((e=>{r.variants.push({meetingURL:e.meeting_url,url:e.url,metadata:e.metadata,startedAt:this.getAsDate(e.started_at)})})),r}getHLSRecording(e){var t,i,r,n;let s={running:!1};return(null==e?void 0:e.hls_recording)&&(s={running:!!(null==e?void 0:e.enabled),singleFilePerLayer:!!(null==(t=e.hls_recording)?void 0:t.single_file_per_layer),hlsVod:!!(null==(i=e.hls_recording)?void 0:i.hls_vod),startedAt:this.getAsDate(null==(r=null==e?void 0:e.variants)?void 0:r[0].started_at),error:(null==(n=null==e?void 0:e.error)?void 0:n.code)?e.error:void 0}),s}setRecordingStatus(e,t){var i,r,n;let s,o=this.store.getRoom();"sfu"===t.type?(o.recording.server={running:e,startedAt:e?this.getAsDate(t.started_at):void 0,error:(null==(i=t.error)?void 0:i.code)?t.error:void 0},s=Bi.SERVER_RECORDING_STATE_UPDATED):(o.recording.browser={running:e,startedAt:e?this.getAsDate(t.started_at):void 0,error:(null==(r=t.error)?void 0:r.code)?t.error:void 0},s=Bi.BROWSER_RECORDING_STATE_UPDATED),null==(n=this.listener)||n.onRoomUpdate(s,o)}setRTMPStatus(e,t){var i,r;let n=this.store.getRoom();n.rtmp={running:e,startedAt:e?this.getAsDate(t.started_at):void 0,error:(null==(i=t.error)?void 0:i.code)?t.error:void 0},null==(r=this.listener)||r.onRoomUpdate(Bi.RTMP_STREAMING_STATE_UPDATED,n)}}(this.store,this.listener)}setListener(e){this.listener=e,this.trackManager.listener=e,this.peerManager.listener=e,this.peerListManager.listener=e,this.broadcastManager.listener=e,this.requestManager.listener=e,this.activeSpeakerManager.listener=e,this.roomUpdateManager.listener=e}setAudioListener(e){this.audioListener=e,this.activeSpeakerManager.audioListener=e}addEventListener(e,t){this.eventEmitter.addListener(e,t)}removeEventListener(e,t){this.eventEmitter.removeListener(e,t)}once(e,t){this.eventEmitter.once(e,t)}handleNotification(e,t=!1){var i,r;let n=e.method,s=e.params;if([Ar.ACTIVE_SPEAKERS,Ar.SFU_STATS].includes(n)||Mi.d(this.TAG,"Received notification",{method:n,notification:s}),n===Ar.SFU_STATS&&(null==(i=window.HMS)?void 0:i.ON_SFU_STATS)&&"function"==typeof(null==(r=window.HMS)?void 0:r.ON_SFU_STATS)&&window.HMS.ON_SFU_STATS(e.params),!this.ignoreNotification(n))switch(this.roomUpdateManager.handleNotification(n,s),this.peerManager.handleNotification(n,s),this.requestManager.handleNotification(n,s),this.peerListManager.handleNotification(n,s,t),this.broadcastManager.handleNotification(n,s),n){case Ar.TRACK_METADATA_ADD:this.trackManager.handleTrackMetadataAdd(s);break;case Ar.TRACK_UPDATE:this.trackManager.handleTrackUpdate(s);break;case Ar.ON_SFU_TRACK_LAYER_UPDATE:this.trackManager.handleTrackLayerUpdate(s);break;case Ar.ACTIVE_SPEAKERS:this.activeSpeakerManager.handleActiveSpeakers(s);break;case Ar.POLICY_CHANGE:this.policyChangeManager.handlePolicyChange(s)}}}(this.store,this.listener,this.audioListener),this.deviceManager=new class{constructor(e,t){this.store=e,this.eventBus=t,this.audioInput=[],this.audioOutput=[],this.videoInput=[],this.hasWebcamPermission=!1,this.hasMicrophonePermission=!1,this.TAG="[Device Manager]:",this.initialized=!1,this.videoInputChanged=!1,this.audioInputChanged=!1,this.updateOutputDevice=e=>{let t=this.audioOutput.find((t=>t.deviceId===e));return t&&(this.outputDevice=t,this.store.updateAudioOutputDevice(t),sn.updateSelection("audioOutput",{deviceId:t.deviceId,groupId:t.groupId})),t},this.getCurrentSelection=()=>{var e,t;let i=this.store.getLocalPeer(),r=this.createIdentifier(null==(e=null==i?void 0:i.audioTrack)?void 0:e.getMediaTrackSettings()),n=this.createIdentifier(null==(t=null==i?void 0:i.videoTrack)?void 0:t.getMediaTrackSettings()),s=this.audioInput.find((e=>this.createIdentifier(e)===r)),o=this.videoInput.find((e=>this.createIdentifier(e)===n));return{audioInput:s,videoInput:o,audioOutput:this.outputDevice}},this.computeChange=(e,t)=>
8e.length!==t.length||t.some((t=>!e.includes(this.createIdentifier(t)))),this.enumerateDevices=()=>_i(this,null,(function*(){try{let e=yield navigator.mediaDevices.enumerateDevices(),t=this.videoInput.map(this.createIdentifier),i=this.audioInput.map(this.createIdentifier);this.audioInput=[],this.audioOutput=[],this.videoInput=[],e.forEach((e=>{"audioinput"===e.kind&&e.label?(this.hasMicrophonePermission=!0,this.audioInput.push(e)):"audiooutput"===e.kind?this.audioOutput.push(e):"videoinput"===e.kind&&e.label&&(this.hasWebcamPermission=!0,this.videoInput.push(e))})),this.videoInputChanged=this.computeChange(t,this.videoInput),this.audioInputChanged=this.computeChange(i,this.audioInput),sn.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){Mi.e(this.TAG,"Failed enumerating devices",e)}})),this.handleDeviceChange=function(e,t=300){let i;return function(...r){clearTimeout(i),i=void 0;let n=this;i=setTimeout((()=>{e.apply(n,r)}),t)}}((()=>_i(this,null,(function*(){yield this.enumerateDevices(),en.queue(gn.deviceChange({selection:this.getCurrentSelection(),type:"list",devices:this.getDevices()})).flush(),this.logDevices("After Device Change");let e=this.store.getLocalPeer();this.setOutputDevice(!0),yield this.handleAudioInputDeviceChange(null==e?void 0:e.audioTrack),yield this.handleVideoInputDeviceChange(null==e?void 0:e.videoTrack)}))),500).bind(this),this.handleAudioInputDeviceChange=e=>_i(this,null,(function*(){if(!e)return void Mi.d(this.TAG,"No Audio track on local peer");if(!this.audioInputChanged)return void Mi.d(this.TAG,"No Change in AudioInput Device");let t=this.getNewAudioInputDevice();if(!t||!t.deviceId)return void Mi.w(this.TAG,"Audio device not found");let{settings:i}=e,r=(new Ir).codec(i.codec).maxBitrate(i.maxBitrate).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"audioInput"}),this.logDevices("Audio Device Change Success")}catch(e){Mi.e(this.TAG,"[Audio Device Change]",e),en.queue(gn.deviceChange({selection:{audioInput:t},devices:this.getDevices(),error:e})).flush(),this.eventBus.deviceChange.publish({error:e,selection:t,type:"audioInput",devices:this.getDevices()})}})),this.handleVideoInputDeviceChange=e=>_i(this,null,(function*(){if(!e)return void Mi.d(this.TAG,"No video track on local peer");if(!this.videoInputChanged)return void Mi.d(this.TAG,"No Change in VideoInput Device");let t=this.videoInput[0];if(!t||!t.deviceId)return void Mi.w(this.TAG,"Video device not found");let{settings:i}=e,r=(new Dr).codec(i.codec).maxBitrate(i.maxBitrate).maxFramerate(i.maxFramerate).setWidth(i.width).setHeight(i.height).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"video"}),this.logDevices("Video Device Change Success")}catch(e){Mi.e(this.TAG,"[Video Device Change]",e),en.queue(gn.deviceChange({selection:{videoInput:t},devices:this.getDevices(),error:e})).flush(),this.eventBus.deviceChange.publish({error:e,type:"video",selection:t,devices:this.getDevices()})}}))}init(){return _i(this,null,(function*(){this.initialized||(this.initialized=!0,navigator.mediaDevices.addEventListener("devicechange",this.handleDeviceChange),yield this.enumerateDevices(),this.logDevices("Init"),this.setOutputDevice(),this.eventBus.deviceChange.publish({devices:this.getDevices()}),this.eventBus.localVideoEnabled.subscribeOnce((e=>_i(this,null,(function*(){!e||(yield this.enumerateDevices(),this.videoInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()}))})))),this.eventBus.localAudioEnabled.subscribeOnce((e=>_i(this,null,(function*(){!e||(yield this.enumerateDevices(),this.audioInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()}))})))),en.queue(gn.deviceChange({selection:this.getCurrentSelection(),type:"list",devices:this.getDevices()})).flush())}))}getDevices(){return{audioInput:this.audioInput,audioOutput:this.audioOutput,videoInput:this.videoInput}}cleanUp(){this.initialized=!1,this.audioInput=[],this.audioOutput=[],this.videoInput=[],this.outputDevice=void 0,navigator.mediaDevices.removeEventListener("devicechange",this.handleDeviceChange)}createIdentifier(e){return e?`${e.deviceId}${e.groupId}`:""}getNewAudioInputDevice(){let e=this.audioInput.find((e=>"default"===e.deviceId));return e?this.audioInput.find((t=>t.label!==e.label&&e.label.includes(t.label))):this.audioInput[0]}setOutputDevice(e=!1){let t=this.getNewAudioInputDevice(),i=this.createIdentifier(this.outputDevice);this.outputDevice=void 0,(null==t?void 0:t.groupId)&&(this.outputDevice=this.audioOutput.find((e=>"default"!==t.deviceId&&e.label===t.label))),this.outputDevice||(this.outputDevice=this.audioOutput.find((e=>"default"===e.deviceId))||this.audioOutput[0]),this.store.updateAudioOutputDevice(this.outputDevice),e&&i!==this.createIdentifier(this.outputDevice)&&this.eventBus.deviceChange.publish({selection:this.outputDevice,type:"audioOutput",devices:this.getDevices()})}logDevices(e=""){Mi.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}}(this.store,this.eventBus),this.audioSinkManager=new class{constructor(e,t,i,r){this.store=e,this.notificationManager=t,this.deviceManager=i,this.eventBus=r,this.autoPausedTracks=new Set,this.TAG="[AudioSinkManager]:",this.volume=100,this.eventEmitter=new Ei.EventEmitter2,this.state=Ai({},Fn),this.audioContextList=new Map,this.handleAudioPaused=e=>{var t;let i=null==(t=e.target.srcObject)?void 0:t.getAudioTracks()[0];if(!(null==i?void 0:i.enabled))return;Mi.d(this.TAG,"Audio Paused",e.target.id);let r=this.store.getTrackById(e.target.id);r&&("mobile"===Sr.getDevice().type?setTimeout((()=>_i(this,null,(function*(){r&&(yield this.playAudioFor(r))}))),500):this.autoPausedTracks.add(r))},this.handleTrackUpdate=e=>{var t;if(null==(t=window.HMS)?void 0:t.AUDIO_SINK){let{track:t,enabled:i}=e.detail;i?(t.addSink(),this.playAudioFor(t)):t.removeSink()}},this.handleTrackAdd=e=>{this.handleTrackAddAsync(e)},this.handleTrackAddAsync=e=>_i(this,null,(function*(){var t,i,r,n;let{track:s,peer:o}=e.detail,a=document.createElement("audio");if(a.style.display="none",a.id=s.trackId,a.addEventListener("pause",this.handleAudioPaused),s.setAudioElement(a),s.setVolume(this.volume),this.connectAudioContext(a,s.trackId),Mi.d(this.TAG,"Audio track added",s.trackId),null==(t=this.audioSink)||t.append(a),this.outputDevice&&(yield s.setOutputDevice(this.outputDevice)),null==(i=window.HMS)?void 0:i.AUDIO_SINK){if(!s.enabled)return s.removeSink(),void(null==(r=this.listener)||r.onTrackUpdate(Ki.TRACK_ADDED,s,o));s.addSink()}
8else a.srcObject=new MediaStream([s.nativeTrack]);null==(n=this.listener)||n.onTrackUpdate(Ki.TRACK_ADDED,s,o),void 0===this.state.autoplayFailed&&(this.state.autoplayCheckPromise||(this.state.autoplayCheckPromise=new Promise((e=>{this.playAudioFor(s).then(e)}))),yield this.state.autoplayCheckPromise),this.state.autoplayFailed?this.autoPausedTracks.add(s):yield this.playAudioFor(s)})),this.handleAudioDeviceChange=e=>{e.error||!e.selection||"video"===e.type||this.unpauseAudioTracks()},this.handleTrackRemove=e=>{let t=e.detail;this.autoPausedTracks.delete(t);let i=document.getElementById(t.trackId);i&&(i.removeEventListener("pause",this.handleAudioPaused),i.srcObject=null,i.remove(),t.setAudioElement(null)),this.audioSink&&0===this.audioSink.childElementCount&&(this.state.autoplayCheckPromise=void 0,this.state.autoplayFailed=void 0),Mi.d(this.TAG,"Audio track removed",t.trackId)},this.unpauseAudioTracks=()=>_i(this,null,(function*(){let e=[];this.autoPausedTracks.forEach((t=>{e.push(this.playAudioFor(t))})),yield Promise.all(e)})),this.connectAudioContext=(e,t)=>
8{var i;if(!Rr||!(null==(i=window.HMS)?void 0:i.GAIN_VALUE))return;let r=new AudioContext,n=r.createMediaElementSource(e),s=r.createGain();s.gain.value=window.HMS.GAIN_VALUE,n.connect(s),s.connect(r.destination),this.audioContextList.set(t,r)},this.notificationManager.addEventListener("track-added",this.handleTrackAdd),this.notificationManager.addEventListener("track-removed",this.handleTrackRemove),this.notificationManager.addEventListener("track-updated",this.handleTrackUpdate),this.eventBus.deviceChange.subscribe(this.handleAudioDeviceChange)}setListener(e){this.listener=e}addEventListener(e,t){this.eventEmitter.addListener(e,t)}removeEventListener(e,t){this.eventEmitter.removeListener(e,t)}get outputDevice(){return this.deviceManager.outputDevice}getVolume(){return this.volume}setVolume(e){this.store.updateAudioOutputVolume(e),this.volume=e}unblockAutoplay(){return _i(this,null,(function*(){this.autoPausedTracks.size>0&&this.unpauseAudioTracks()}))}init(e){if(this.state.initialized)return;this.state.initialized=!0;let t=document.createElement("div");t.id=`HMS-SDK-audio-sink-${yi()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t}cleanUp(){var e;null==(e=this.audioSink)||e.remove(),this.audioSink=void 0;for(let e of this.audioContextList.values())e.close();this.audioContextList.clear(),this.notificationManager.removeEventListener("track-added",this.handleTrackAdd),this.notificationManager.removeEventListener("track-removed",this.handleTrackRemove),this.notificationManager.removeEventListener("track-updated",this.handleTrackUpdate),this.eventBus.deviceChange.unsubscribe(this.handleAudioDeviceChange),this.autoPausedTracks=new Set,this.state=Ai({},Fn)}playAudioFor(e){return _i(this,null,(function*(){var t;let i=e.getAudioElement();if(i)try{let t=this.audioContextList.get(e.trackId);"suspended"===(null==t?void 0:t.state)&&(null==t||t.resume()),yield i.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),Mi.d(this.TAG,"Played track",e.trackId)}catch(i){if(this.autoPausedTracks.add(e),Mi.e(this.TAG,"Failed to play track",e.trackId,i),!this.state.autoplayFailed&&!(null==(t=null==i?void 0:i.message)?void 0:t.includes("new load request"))){this.state.autoplayFailed=!0;let e=Ui.TracksErrors.AutoplayBlocked(Li.AUTOPLAY,"");en.queue(gn.autoplayError()).flush(),this.eventEmitter.emit(Gn,{error:e})}}else Mi.w(this.TAG,"No audio element found on track",e.trackId)}))}}(this.store,this.notificationManager,this.deviceManager,this.eventBus),this.audioOutput=new class{constructor(e,t){this.deviceManager=e,this.audioSinkManager=t}getVolume(){return this.audioSinkManager.getVolume()}setVolume(e){if(e<0||e>100)throw Error("Please pass a valid number between 0-100");this.audioSinkManager.setVolume(e)}getDevice(){return this.deviceManager.outputDevice}setDevice(e){return this.deviceManager.updateOutputDevice(e)}unblockAutoplay(){return _i(this,null,(function*(){yield this.audioSinkManager.unblockAutoplay()}))}}(this.deviceManager,this.audioSinkManager),this.audioSinkManager.setListener(this.listener),this.audioSinkManager.addEventListener(Gn,this.handleAutoplayError),this.localTrackManager=new En(this.store,this.observer,this.deviceManager,this.eventBus),this.transport=new class{constructor(e,t,i,r,n){var s,o;this.observer=e,this.deviceManager=t,this.store=i,this.localTrackManager=r,this.eventBus=n,this.state=Sn.Disconnected,this.trackStates=new Map,this.publishConnection=null,this.subscribeConnection=null,this.retryScheduler=new class{constructor(e,t){this.inProgress=new Map,this.retryTaskIds=[],this.analyticsEventsService=e,this.onStateChange=t}schedule(e,t,i){return _i(this,arguments,(function*(e,t,i,r=5,n=!0){yield this.scheduleTask(e,t,n,i,r)}))}reset(){this.retryTaskIds.forEach((e=>clearTimeout(e))),this.retryTaskIds=[],this.inProgress.clear()}scheduleTask(e,t,i,r){return _i(this,arguments,(function*(e,t,i,r,n=5,s=0){if(Mi.d(wn,"schedule: ",{category:Cn[e],error:t}),0===s){let i=this.inProgress.get(e);if(i)return Mi.d(wn,`schedule: Already a task for ${Cn[e]} scheduled, waiting for its completion`),void(yield i.promise);let r=new class{constructor(e){this.promise=new Promise(((t,i)=>{this.resolve=t,this.reject=i,e(t,i)}))}}(((e,t)=>{}));this.inProgress.set(e,r),this.sendEvent(t,e)}let o=!1,a=Pn[e];for(let t in a){let i=a[parseInt(t)];try{let t=this.inProgress.get(i);t&&(Mi.d(wn,`schedule: Suspending retry task of ${Cn[e]}, waiting for ${Cn[i]} to recover`),yield t.promise,Mi.d(wn,`schedule: Resuming retry task ${Cn[e]}
8 as it's dependency ${Cn[i]} is recovered`))}catch(t){Mi.d(wn,`schedule: Stopping retry task of ${Cn[e]} as it's dependency ${Cn[i]} failed to recover`),o=!0;break}}if(s>=n||o){if(t.description+=`. [${Cn[e]}] Could not recover after ${s} tries`,o&&(t.description+=` Could not recover all of it's required dependencies - [${a.map((e=>Cn[e])).toString()}]`),t.isTerminal=!0,this.inProgress.delete(e),this.sendEvent(t,e),this.reset(),!i)throw t;return void this.onStateChange(Sn.Failed,t)}i&&this.onStateChange(Sn.Reconnecting,t);let c,l=this.getDelayForRetryCount(s);Mi.i(wn,`schedule: [${Cn[e]}] [failedRetryCount=${s}] Scheduling retry task in ${l}ms`);try{c=yield this.setTimeoutPromise(r,l)}catch(t){c=!1,Mi.w(wn,`[${Cn[e]}] Un-caught exception ${t.name} in retry-task, initiating retry`,t)}if(c){let t=this.inProgress.get(e);this.inProgress.delete(e),null==t||t.resolve(s),i&&0===this.inProgress.size&&this.onStateChange(Sn.Joined),Mi.i(wn,`schedule: [${Cn[e]}] [failedRetryCount=${s}] Recovered â»ï¸`)}else yield this.scheduleTask(e,t,i,r,n,s+1)}))}sendEvent(e,t){let i;switch(t){case Cn.ConnectFailed:i=gn.connect(e);break;case Cn.SignalDisconnect:i=gn.disconnect(e);break;case Cn.PublishIceConnectionFailed:i=gn.publish({error:e});break;case Cn.SubscribeIceConnectionFailed:i=gn.subscribeFail(e)}this.analyticsEventsService.queue(i).flush()}getDelayForRetryCount(e){let t=Math.pow(2,e),i=Math.random();return Math.round(1e3*Math.min(t+i,60))}setTimeoutPromise(e,t){return _i(this,null,(function*(){return new Promise(((i,r)=>{let n=window.setTimeout((()=>_i(this,null,(function*(){try{let t=yield e();t&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(n),1),i(t)}catch(e){r(e)}}))),t);this.retryTaskIds.push(n)}))}))}}(en,((e,t)=>_i(this,null,(function*(){e!==this.state&&(this.state=e,yield this.observer.onStateChange(this.state,t))})))),this.callbacks=new Map,this.signalObserver={onOffer:e=>_i(this,null,(function*(){try{yield this.subscribeConnection.setRemoteDescription(e),Mi.d(xn,`[SUBSCRIBE] Adding ${this.subscribeConnection.candidates.length} ice-candidates`,this.subscribeConnection.candidates);for(let e of this.subscribeConnection.candidates)yield this.subscribeConnection.addIceCandidate(e);this.subscribeConnection.candidates.length=0;let t=yield this.subscribeConnection.createAnswer();yield this.subscribeConnection.setLocalDescription(t),this.signal.answer(t),Mi.d(xn,"[role=SUBSCRIBE] onOffer renegotiation DONE â
")}catch(e){let t;throw Mi.d(xn,"[role=SUBSCRIBE] onOffer renegotiation FAILED â"),this.state=Sn.Failed,t=e instanceof xi?e:Ui.GenericErrors.Unknown(Li.PUBLISH,e.message),en.queue(gn.subscribeFail(t)).flush(),t}})),onTrickle:e=>_i(this,null,(function*(){let t=e.target===Di.Publish?this.publishConnection:this.subscribeConnection;null===t.remoteDescription?t.candidates.push(e.candidate):yield t.addIceCandidate(e.candidate)})),onNotification:e=>this.observer.onNotification(e),onServerError:e=>_i(this,null,(function*(){yield this.observer.onStateChange(Sn.Failed,e)})),onFailure:e=>{this.joinParameters&&this.retryScheduler.schedule(Cn.SignalDisconnect,e,this.retrySignalDisconnectTask)},onOffline:()=>_i(this,null,(function*(){Mi.d(xn,"socket offline",Sn[this.state]);try{this.state!==Sn.Leaving&&this.joinParameters&&this.retryScheduler.schedule(Cn.SignalDisconnect,Ui.WebSocketConnectionErrors.WebSocketConnectionLost(Li.RECONNECT_SIGNAL,"Network offline"),this.retrySignalDisconnectTask)}catch(e){console.error(e)}})),onOnline:()=>{Mi.d(xn,"socket online",Sn[this.state]),this.analyticsSignalTransport.flushFailedEvents()}},this.signal=new class{constructor(e){this.TAG="[ SIGNAL ]: ",this.isJoinCompleted=!1,this.pendingTrickle=[],this.socket=null,this.callbacks=new Map,this._isConnected=!1,this.id=0,this.observer=e,window.addEventListener("offline",(()=>{Mi.d(this.TAG,"Window network offline"),this.isConnected=!1})),window.addEventListener("online",(()=>{Mi.d(this.TAG,"Window network online")})),this.onCloseHandler=this.onCloseHandler.bind(this),this.onMessageHandler=this.onMessageHandler.bind(this)}get isConnected(){return this._isConnected}set isConnected(e){Mi.d(this.TAG,"isConnected set",{id:this.id,old:this._isConnected,new:e}),this._isConnected!==e&&(this._isConnected&&!e?(this._isConnected=e,this.observer.onOffline()):!this._isConnected&&e&&(this._isConnected=e,this.observer.onOnline()))}call(e,t){return _i(this,null,(function*(){let i=yi(),r={method:e,params:t,id:i,jsonrpc:"2.0"};this.socket.send(JSON.stringify(r));try{return yield new Promise(((e,t)=>{this.callbacks.set(i,{resolve:e,reject:t})}))}catch(t){let i=t;throw Ui.WebsocketMethodErrors.ServerErrors(Number(i.code),function(e){switch(e){case Cr.JOIN:return Li.JOIN;case Cr.OFFER:return Li.PUBLISH;case Cr.ANSWER:return Li.SUBSCRIBE;case Cr.TRACK_UPDATE:return Li.TRACK;default:return Li.NONE}}(e),i.message)}}))}notify(e,t){let i={method:e,params:t};this.socket.send(JSON.stringify(i))}open(e){return new Promise(((t,i)=>{this.socket&&(this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)),this.socket=new WebSocket(e);let r=e=>{Mi.e(this.TAG,"Error from websocket",e),i(Ui.WebSocketConnectionErrors.GenericConnect(Li.JOIN,`Error opening socket connection - ${e}`))};this.socket.addEventListener("error",r);let n=()=>{t(),this.isConnected=!0,this.id++,this.socket.removeEventListener("open",n),this.socket.removeEventListener("error",r),this.pingPongLoop(this.id)};this.socket.addEventListener("open",n),this.socket.addEventListener("close",this.onCloseHandler),this.socket.addEventListener("message",this.onMessageHandler)}))}close(){return _i(this,null,(function*(){let e=new Promise((e=>{this.socket.addEventListener("close",(()=>e()))}));return this.socket.close(1e3,"Normal Close"),this.isConnected=!1,this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler),e}))}join(e,t,i,r,n){return _i(this,null,(function*(){let s={name:e,disableVidAutoSub:r,data:t,offer:i,server_sub_degrade:n},o=yield this.call(Cr.JOIN,s);return this.isJoinCompleted=!0,this.pendingTrickle.forEach((({target:e,candidate:t})=>this.trickle(e,t))),this.pendingTrickle.length=0,Mi.d(this.TAG,`join: response=${JSON.stringify(o,null,1)}`),o}))}trickle(e,t){this.isJoinCompleted?this.notify(Cr.TRICKLE,{target:e,candidate:t}):this.pendingTrickle.push({target:e,candidate:t})}offer(e,t){return _i(this,null,(function*(){return yield this.call(Cr.OFFER,{desc:e,tracks:Object.fromEntries(t)})}
8))}answer(e){this.notify(Cr.ANSWER,{desc:e})}trackUpdate(e){this.notify(Cr.TRACK_UPDATE,{version:"1.0",tracks:Object.fromEntries(e)})}broadcast(e){return _i(this,null,(function*(){yield this.call(Cr.BROADCAST,Ai({version:"1.0"},e.toSignalParams()))}))}leave(){this.notify(Cr.LEAVE,{version:"1.0"})}endRoom(e,t){return _i(this,null,(function*(){yield this.call(Cr.END_ROOM,{lock:e,reason:t})}))}sendEvent(e){if(!this.isConnected)throw Error(`${this.TAG} not connected. Could not send event ${e}`);this.notify(Cr.ANALYTICS,e.toSignalParams())}ping(e){let t=Date.now(),i=new Promise((i=>{setTimeout((()=>{i(Date.now()-t)}),e+1)})),r=this.call(Cr.PING,{timestamp:t}).then((()=>Date.now()-t)).catch((()=>Date.now()-t));return Promise.race([i,r])}requestRoleChange(e){return _i(this,null,(function*(){yield this.call(Cr.ROLE_CHANGE_REQUEST,e)}))}acceptRoleChangeRequest(e){return _i(this,null,(function*(){yield this.call(Cr.ROLE_CHANGE,e)}))}requestTrackStateChange(e){return _i(this,null,(function*(){yield this.call(Cr.TRACK_UPDATE_REQUEST,e)}))}requestMultiTrackStateChange(e){return _i(this,null,(function*(){yield this.call(Cr.CHANGE_TRACK_MUTE_STATE_REQUEST,e)}))}removePeer(e){return _i(this,null,(function*(){yield this.call(Cr.PEER_LEAVE_REQUEST,e)}))}startRTMPOrRecording(e){return _i(this,null,(function*(){yield this.call(Cr.START_RTMP_OR_RECORDING_REQUEST,Ai({version:"1.0"},e))}))}stopRTMPAndRecording(){return _i(this,null,(function*(){yield this.call(Cr.STOP_RTMP_AND_RECORDING_REQUEST,{version:"1.0"})}))}startHLSStreaming(e){return _i(this,null,(function*(){yield this.call(Cr.START_HLS_STREAMING,Ai({version:"1.0"},e))}))}stopHLSStreaming(e){return _i(this,null,(function*(){yield this.call(Cr.STOP_HLS_STREAMING,Ai({version:"1.0"},e))}))}updatePeer(e){return _i(this,null,(function*(){yield this.call(Cr.UPDATE_PEER_METADATA,Ai({version:"1.0"},e))}))}onCloseHandler(e){Mi.d(`Websocket closed code=${e.code}`),this.isConnected=!1}onMessageHandler(e){let t=e.data,i=JSON.parse(t);if(i.id)this.handleResponseWithId(i);else{if(!i.method)throw Error(`WebSocket message has no 'method' or 'id' field, message=${i}`);this.handleResponseWithMethod(i)}}handleResponseWithId(e){let t=e,i=t.id;if(this.callbacks.has(i)){let e=this.callbacks.get(i);this.callbacks.delete(i),t.result?e.resolve(t.result):e.reject(t.error)}else this.observer.onNotification(t)}handleResponseWithMethod(e){switch(e.method){case Cr.OFFER:this.observer.onOffer(e.params);break;case Cr.TRICKLE:this.observer.onTrickle(e.params);break;case Cr.SERVER_ERROR:this.observer.onServerError(Ui.WebsocketMethodErrors.ServerErrors(Number(e.params.code),Li.NONE,e.params.message));break;case Cr.SERVER_WARNING:Mi.w(this.TAG,e.params);break;default:this.observer.onNotification(e)}}pingPongLoop(e){return _i(this,null,(function*(){var t,i;let r=(null==(t=window.HMS)?void 0:t.PING_TIMEOUT)||12e3;if(this.isConnected)if((yield this.ping(r))>r){let t=!1;void 0!==typeof document&&document.hidden&&(t=!0),Mi.d(this.TAG,`Pong timeout ${e}, pageHidden=${t}`),this.id===e&&(this.isConnected=!1)}else setTimeout((()=>this.pingPongLoop(e)),(null==(i=window.HMS)?void 0:i.PING_INTERVAL)||1e3)}))}}(this.signalObserver),this.analyticsSignalTransport=new class extends class{constructor(){this.TAG="AnalyticsTransport"}sendEvent(e){try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(e){Mi.w(this.TAG,"sendEvent failed",e)}}flushFailedEvents(){try{for(Mi.d(this.TAG,"Flushing failed events",this.failedEvents);this.failedEvents.size()>0;){let e=this.failedEvents.dequeue();e&&this.sendSingleEvent(e)}}catch(e){Mi.w(this.TAG,"flushFailedEvents failed",e)}}sendSingleEvent(e){try{Mi.d(this.TAG,"Sending event",{event:e}),this.transportProvider.sendEvent(e)}catch(t){throw Mi.w(this.TAG,`${this.transportProvider.constructor.name}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}}{constructor(e){super(),this.transportProvider=e,this.failedEvents=new An}}(this.signal),this.publishConnectionObserver={onRenegotiationNeeded:()=>_i(this,null,(function*(){yield this.performPublishRenegotiation()})),onIceConnectionChange:e=>_i(this,null,(function*(){Mi.d("publisher ice connection state change, ",e)})),onConnectionStateChange:e=>_i(this,null,(function*(){Mi.d("publisher connection state change, ",e),"failed"===e&&(yield this.handleIceConnectionFailure(Di.Publish))}))},this.subscribeConnectionObserver={onApiChannelMessage:e=>{this.observer.onNotification(JSON.parse(e))},onTrackAdd:e=>{Mi.d(xn,"[Subscribe] onTrackAdd",e),this.observer.onTrackAdd(e)},onTrackRemove:e=>{Mi.d(xn,"[Subscribe] onTrackRemove",e),this.observer.onTrackRemove(e)},onIceConnectionChange:e=>_i(this,null,(function*(){if(Mi.d("subscriber ice connection state change, ",e),"connected"===e){let e=this.callbacks.get(Zi);this.callbacks.delete(Zi),e&&e.promise.resolve(!0)}})),onConnectionStateChange:e=>_i(this,null,(function*(){if(Mi.d("subscriber connection state change, ",e),"failed"===e&&(yield this.handleIceConnectionFailure(Di.Subscribe)),"connected"===e){let e=this.callbacks.get(Zi);this.callbacks.delete(Zi),e&&e.promise.resolve(!0)}}))},this.retryPublishIceFailedTask=()=>_i(this,null,(function*(){if("connected"!==this.publishConnection.iceConnectionState||"connected"!==this.publishConnection.connectionState){let e=new Promise(((e,t)=>{this.callbacks.set(Yi,{promise:{resolve:e,reject:t},action:Li.RESTART_ICE,extra:{}})}));yield this.performPublishRenegotiation({iceRestart:!0}),yield e}return!0})),this.retrySubscribeIceFailedTask=()=>_i(this,null,(function*(){if("connected"!==this.subscribeConnection.iceConnectionState||"connected"!==this.subscribeConnection.connectionState){let e=new Promise(((e,t)=>{this.callbacks.set(Zi,{promise:{resolve:e,reject:t},action:Li.RESTART_ICE,extra:{}})})),t=new Promise((e=>{setTimeout(e,6e4,!1)}));return Promise.race([e,t])}return!0})),this.retrySignalDisconnectTask=()=>_i(this,null,(function*(){let e=this.signal.isConnected;if(Mi.d(xn,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),!this.signal.isConnected)try{yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId),e=!0}catch(t){e=!1}return e=this.signal.isConnected&&(yield this.retryPublishIceFailedTask()),this.signal.trackUpdate(this.trackStates),e})),this.webrtcInternals=new class{constructor(e,t,i,r){this.store=e,this.eventBus=t,this.publishConnection=i,this.subscribeConnection=r,this.TAG="[HMSWebrtcInternals]",this.interval=1e3,this.isMonitored=!1,this.handleStatsUpdate=()=>_i(this,null,(function*(){var e;yield null==(e=this.hmsStats)?void 0:e.updateStats(),this.eventBus.statsUpdate.publish(this.hmsStats)}))}getPublishPeerConnection(){return this.publishConnection}getSubscribePeerConnection(){return this.subscribeConnection}onStatsChange(e){return this.eventBus.statsUpdate.subscribe(e),()=>{this.eventBus.statsUpdate.unsubscribe(e)}}setPeerConnections({publish:e,subscribe:t}){var i,r;this.publishConnection=e,this.subscribeConnection=t,this.hmsStats=new class{constructor(e,t){var i;
8this.getStats=e,this.store=t,this.TAG="[HMSWebrtcStats]",this.peerStats={},this.trackStats={},this.localPeerID=null==(i=this.store.getLocalPeer())?void 0:i.peerId}getLocalPeerStats(){if(this.localPeerID)return this.peerStats[this.localPeerID]}getTrackStats(e){return this.trackStats[e]}updateStats(){return _i(this,null,(function*(){yield this.updateLocalPeerStats(),yield this.updateTrackStats()}))}updateLocalPeerStats(){return _i(this,null,(function*(){var e,t,i,r,n,s;if(!this.localPeerID)return;let o,a=this.getLocalPeerStats();try{o=yield null==(t=(e=this.getStats).publish)?void 0:t.call(e)}catch(e){Mi.e(this.TAG,"Error in getting publish stats",e)}let c,l=o&&Dn("publish",o,a);try{c=yield null==(r=(i=this.getStats).subscribe)?void 0:r.call(i)}catch(e){Mi.e(this.TAG,"Error in getting subscribe stats",e)}let d=c&&Dn("subscribe",c,a),{packetsLost:u,jitter:h}=(e=>{let t={packetsLost:0,jitter:0};return null==e||e.forEach((e=>{e.packetsLost&&(t.packetsLost+=e.packetsLost),e.jitter>t.jitter&&(t.jitter=e.jitter)})),t})(c),p=Nn(u,null==(n=null==a?void 0:a.subscribe)?void 0:n.packetsLost,null==d?void 0:d.timestamp,null==(s=null==a?void 0:a.subscribe)?void 0:s.timestamp),m=d&&Object.assign(d,{packetsLostRate:p,jitter:h,packetsLost:u});this.peerStats[this.localPeerID]={publish:l,subscribe:m}}))}updateTrackStats(){return _i(this,null,(function*(){var e;let t=this.store.getTracksMap(),i=((e,t)=>Array.from(new Set(e.concat(t))))(Object.keys(this.trackStats),Object.keys(t));for(let r of i){let i=t[r];if(i){let t=i.peerId&&(null==(e=this.store.getPeerById(i.peerId))?void 0:e.name),n=this.getTrackStats(i.trackId),s=yield In(this.getStats,i,t,n);s&&(this.trackStats[r]=s)}else delete this.trackStats[r]}}))}}({publish:null==(i=this.publishConnection)?void 0:i.getStats.bind(this.publishConnection),subscribe:null==(r=this.subscribeConnection)?void 0:r.getStats.bind(this.subscribeConnection)},this.store)}start(){return _i(this,null,(function*(){this.stop(),this.isMonitored=!0,Mi.d(this.TAG,"Starting Webrtc Stats Monitor"),this.startLoop().then((()=>Mi.d(this.TAG,"Stopping Webrtc Stats Monitor"))).catch((e=>Mi.e(this.TAG,e.message)))}))}stop(){this.isMonitored=!1}startLoop(){return _i(this,null,(function*(){for(;this.isMonitored;)yield this.handleStatsUpdate(),yield Kr(this.interval)}))}cleanUp(){this.stop(),this.eventBus.statsUpdate.removeAllListeners()}}(this.store,this.eventBus,null==(s=this.publishConnection)?void 0:s.nativeConnection,null==(o=this.subscribeConnection)?void 0:o.nativeConnection)}getLocalScreen(e,t){return _i(this,null,(function*(){try{return yield this.localTrackManager.getLocalScreen(e,t)}catch(i){throw i instanceof xi&&en.queue(gn.publish({error:i,devices:this.deviceManager.getDevices(),settings:new Lr(e,t,!1)})).flush(),i}}))}getWebrtcInternals(){return this.webrtcInternals}join(e,t,i,r="https://prod-init.100ms.live/init",n=!1,s=!1){return _i(this,null,(function*(){this.setTransportStateForJoin(),this.joinParameters=new class{constructor(e,t,i,r,n,s,o){this.authToken=e,this.peerId=t,this.peerName=i,this.data=r,this.endpoint=n,this.autoSubscribeVideo=s,this.serverSubDegrade=o}}(e,t,i.name,i.metaData,r,n,s),Mi.d(xn,"join: started â°");let o=new Date;try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t)),this.initConfig&&(yield this.connectionJoin(i.name,i.metaData,this.initConfig.rtcConfiguration,n,s))}catch(t){Mi.e(xn,`join: failed â [token=${e}]`,t),this.state=Sn.Failed,t instanceof xi&&en.queue(gn.join(o,new Date,t)).flush();let i=t;throw i.isTerminal=500===i.code,yield this.observer.onStateChange(this.state,i),i}Mi.d(xn,"â
join: successful"),this.state=Sn.Joined,this.observer.onStateChange(this.state)}))}connect(e,t,i){return _i(this,null,(function*(){try{return yield this.internalConnect(e,t,i)}catch(r){if(!(r instanceof xi&&([Ni.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,Ni.InitAPIErrors.ENDPOINT_UNREACHABLE].includes(r.code)||r.code.toString().startsWith("5")||r.code.toString().startsWith("429"))))throw r;{let n=()=>_i(this,null,(function*(){return yield this.internalConnect(e,t,i),Boolean(this.initConfig&&this.initConfig.endpoint)}));yield this.retryScheduler.schedule(Cn.ConnectFailed,r,n,5,!1)}}}))}leave(){return _i(this,null,(function*(){var e,t,i,r;en.removeTransport(this.analyticsSignalTransport),this.retryScheduler.reset(),this.joinParameters=void 0;try{this.state=Sn.Leaving,null==(e=this.webrtcInternals)||e.cleanUp(),null==(t=this.trackDegradationController)||t.cleanUp(),yield null==(i=this.publishConnection)?void 0:i.close(),yield null==(r=this.subscribeConnection)?void 0:r.close(),this.signal.isConnected&&(this.signal.leave(),yield this.signal.close())}catch(e){e instanceof xi&&en.queue(gn.disconnect(e)).flush(),Mi.e(xn,"leave: FAILED â",e)}finally{this.state=Sn.Disconnected,this.observer.onStateChange(this.state)}}
8))}publish(e){return _i(this,null,(function*(){for(let t of e)try{yield this.publishTrack(t)}catch(e){e instanceof xi&&en.queue(gn.publish({devices:this.deviceManager.getDevices(),error:e})).flush()}}))}unpublish(e){return _i(this,null,(function*(){for(let t of e)yield this.unpublishTrack(t)}))}sendMessage(e){return _i(this,null,(function*(){yield this.signal.broadcast(e)}))}trackUpdate(e){let t=Array.from(this.trackStates.values()).find((t=>e.type===t.type&&e.source===t.source));if(t){let i=new Rn(Ii(Ai({},t),{mute:!e.enabled}));this.trackStates.set(t.track_id,i),Mi.d(xn,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[t.track_id,i]]))}}changeRole(e,t,i=!1){return _i(this,null,(function*(){yield this.signal.requestRoleChange({requested_for:e.peerId,role:t,force:i})}))}acceptRoleChange(e){return _i(this,null,(function*(){yield this.signal.acceptRoleChangeRequest({role:e.role.name,token:e.token})}))}endRoom(e,t){return _i(this,null,(function*(){yield this.signal.endRoom(e,t)}))}removePeer(e,t){return _i(this,null,(function*(){yield this.signal.removePeer({requested_for:e,reason:t})}))}startRTMPOrRecording(e){return _i(this,null,(function*(){var t;(null==(t=e.rtmpURLs)?void 0:t.length)?yield this.signal.startRTMPOrRecording({meeting_url:e.meetingURL,record:e.record,rtmp_urls:e.rtmpURLs}):yield this.signal.startRTMPOrRecording({meeting_url:e.meetingURL,record:e.record})}))}stopRTMPOrRecording(){return _i(this,null,(function*(){yield this.signal.stopRTMPAndRecording()}))}startHLSStreaming(e){return _i(this,null,(function*(){let t={variants:e.variants.map((e=>{let t={meeting_url:e.meetingURL};return e.metadata&&(t.metadata=e.metadata),t}))};e.recording&&(t.recording={single_file_per_layer:e.recording.singleFilePerLayer,hls_vod:e.recording.hlsVod}),yield this.signal.startHLSStreaming(t)}))}stopHLSStreaming(e){return _i(this,null,(function*(){if(e){let t={variants:null==e?void 0:e.variants.map((e=>{let t={meeting_url:e.meetingURL};return e.metadata&&(t.metadata=e.metadata),t}))};yield this.signal.stopHLSStreaming(t)}yield this.signal.stopHLSStreaming()}))}changeName(e){return _i(this,null,(function*(){yield this.signal.updatePeer({name:e})}))}changeMetadata(e){return _i(this,null,(function*(){yield this.signal.updatePeer({data:e})}))}changeTrackState(e){return _i(this,null,(function*(){yield this.signal.requestTrackStateChange(e)}))}changeMultiTrackState(e){return _i(this,null,(function*(){yield this.signal.requestMultiTrackStateChange(e)}))}publishTrack(e){return _i(this,null,(function*(){e.publishedTrackId=e.nativeTrack.id,Mi.d(xn,`â³ publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,e),this.trackStates.set(e.publishedTrackId,new Rn(e));let t=new Promise(((e,t)=>{this.callbacks.set(Yi,{promise:{resolve:e,reject:t},action:Li.PUBLISH,extra:{}})})),i=e.stream;i.setConnection(this.publishConnection);let r=this.store.getSimulcastLayers(e.source);i.addTransceiver(e,r),Mi.time(`publish-${e.trackId}-${e.type}`),yield t,Mi.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e);let n=e.settings.maxBitrate;n&&(yield i.setMaxBitrate(n,e).then((()=>{Mi.d(xn,`Setting maxBitrate for ${e.source} ${e.type} to ${n} kpbs`)})).catch((e=>Mi.e(xn,"Failed setting maxBitrate",e)))),Mi.d(xn,`â
publishTrack: trackId=${e.trackId}`,e,this.callbacks)}))}unpublishTrack(e){return _i(this,null,(function*(){if(Mi.d(xn,`â³ unpublishTrack: trackId=${e.trackId}`,e),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId))this.trackStates.delete(e.publishedTrackId);else{let t=Array.from(this.trackStates.values()).find((t=>e.type===t.type&&e.source===t.source));t&&this.trackStates.delete(t.track_id)}let t=new Promise(((e,t)=>{this.callbacks.set(Yi,{promise:{resolve:e,reject:t},action:Li.UNPUBLISH,extra:{}})}));e.stream.removeSender(e),yield t,yield e.cleanup(),this.store.removeTrack(e.trackId),Mi.d(xn,`â
unpublishTrack: trackId=${e.trackId}`,this.callbacks)}))}connectionJoin(e,t,i,r,n){return _i(this,arguments,(function*(e,t,i,r,n,s={offerToReceiveAudio:!1,offerToReceiveVideo:!1}){this.publishConnection=new ar(this.signal,i,this.publishConnectionObserver,this),this.subscribeConnection=new kr(this.signal,i,this.subscribeConnectionObserver,n);try{Mi.d(xn,"â³ join: Negotiating over PUBLISH connection");let i=yield this.publishConnection.createOffer(s,new Map);yield this.publishConnection.setLocalDescription(i);let o=yield this.signal.join(e,t,i,!r,n);yield this.publishConnection.setRemoteDescription(o);for(let e of this.publishConnection.candidates||[])yield this.publishConnection.addIceCandidate(e);this.publishConnection.initAfterJoin(),yield this.initRtcStatsMonitor(),Mi.d(xn,"â
join: Negotiated over PUBLISH connection")}catch(e){throw this.state=Sn.Failed,e}}))}performPublishRenegotiation(e){return _i(this,null,(function*(){Mi.d(xn,"â³ [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(Yi);if(t)try{let i=yield this.publishConnection.createOffer(e,this.trackStates);yield this.publishConnection.setLocalDescription(i),Mi.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(Yi),Mi.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),Mi.d(xn,"[role=PUBLISH] onRenegotiationNeeded DONE â
")}catch(e){let i;i=e instanceof xi?e:Ui.GenericErrors.Unknown(Li.PUBLISH,e.message),t.promise.reject(i),Mi.d(xn,"[role=PUBLISH] onRenegotiationNeeded FAILED â")}}))}handleIceConnectionFailure(e){return _i(this,null,(function*(){e===Di.Publish?this.retryScheduler.schedule(Cn.PublishIceConnectionFailed,Ui.WebrtcErrors.ICEFailure(Li.PUBLISH),this.retryPublishIceFailedTask):this.retryScheduler.schedule(Cn.SubscribeIceConnectionFailed,Ui.WebrtcErrors.ICEFailure(Li.SUBSCRIBE),this.retrySubscribeIceFailedTask,1)}))}internalConnect(e,t,i){return _i(this,null,(function*(){Mi.d(xn,"connect: started â°");let r=new Date;try{this.initConfig=yield class{static fetchInitConfig(e,t,i="https://prod-init.100ms.live",r=""){return _i(this,null,(function*(){Mi.d(wr,`fetchInitConfig: initEndpoint=${i} token=${e} peerId=${t} region=${r} `);let n,s,o=function(e,t,i){try{let r=new URL("/init",e);return i&&i.trim().length>0&&r.searchParams.set("region",i.trim()),r.searchParams.set("peer_id",t),r.searchParams.set("user_agent",Pr),r.toString()}catch(e){let t=e;throw Mi.e(wr,t.name,t.message),t}}(i,t,r);try{n=yield fetch(o,{headers:{Authorization:`Bearer ${e}`}});let t=yield n.json();if(404===n.status)throw Ui.InitAPIErrors.EndpointUnreachable(Li.INIT,t.message||n.statusText);if(200!==(null==n?void 0:n.status))throw Ui.InitAPIErrors.ServerErrors(t.code||n.status,Li.INIT,t.message||(null==n?void 0:n.statusText));s=t,Mi.d(wr,`config is ${JSON.stringify(s,null,2)}`)}catch(e){let t=e;throw"Failed to fetch"===t.message||t.message.includes("NetworkError")?Ui.InitAPIErrors.EndpointUnreachable(Li.INIT,t.message):t}return function(e){return Ii(Ai({},e),{rtcConfiguration:Ii(Ai({},e.rtcConfiguration),{iceServers:e.rtcConfiguration.ice_servers})})}(s)}))}}.fetchInitConfig(e,i,t),yield this.openSignal(e,i),Mi.d(xn,"Adding Analytics Transport: JsonRpcSignal"),en.addTransport(this.analyticsSignalTransport),en.flush()}catch(e){throw e instanceof xi&&en.queue(gn.connect(e,r,new Date,t)).flush(),Mi.d(xn,"â internal
8connect: failed",e),e}}))}openSignal(e,t){return _i(this,null,(function*(){if(!this.initConfig)throw Ui.WebSocketConnectionErrors.GenericConnect(Li.INIT,"Init Config not found");Mi.d(xn,"â³ internal connect: connecting to ws endpoint",this.initConfig.endpoint);let i=new URL(this.initConfig.endpoint);i.searchParams.set("peer",t),i.searchParams.set("token",e),i.searchParams.set("user_agent",Pr),this.endpoint=i.toString(),yield this.signal.open(this.endpoint),Mi.d(xn,"â
internal connect: connected to ws endpoint")}))}initRtcStatsMonitor(){return _i(this,null,(function*(){var e,t,i,r,n;null==(i=this.webrtcInternals)||i.setPeerConnections({publish:null==(e=this.publishConnection)?void 0:e.nativeConnection,subscribe:null==(t=this.subscribeConnection)?void 0:t.nativeConnection}),this.store.getSubscribeDegradationParams()&&((null==(r=this.joinParameters)?void 0:r.serverSubDegrade)||(this.trackDegradationController=new class{constructor(e,t){this.store=e,this.eventBus=t,this.TAG="[TrackDegradationController]",this.MAX_RECOVER_GRACE_PERIOD=120,this.recoverAttemptCount=0,this.packetsLost=0;let i=this.store.getSubscribeDegradationParams();this.PACKETS_LOST_THRESHOLD=i.packetLossThreshold,this.MIN_DEGRADE_GRACE_PERIOD=i.degradeGracePeriodSeconds,this.MIN_RECOVER_GRACE_PERIOD=i.recoverGracePeriodSeconds,this.degradeGracePeriod=this.MIN_DEGRADE_GRACE_PERIOD,this.recoverGracePeriod=this.MIN_RECOVER_GRACE_PERIOD}get isAttemptingRecover(){return Boolean(this.recoveringTrack)}handleRtcStatsChange(e){let t=e>this.packetsLost+this.PACKETS_LOST_THRESHOLD;this.packetsLost=e,t?this.degrade():this.recover()}degrade(){if(!(this.degradeGracePeriod>0))return this.isAttemptingRecover?this.cancelRecovery():(Mi.d(this.TAG,"Packet loss increased, Degrading",{packetsLost:this.packetsLost}),this.degradeActiveTracksByHalf(),this.degradeGracePeriod=this.MIN_DEGRADE_GRACE_PERIOD,void(this.recoverGracePeriod=this.MIN_RECOVER_GRACE_PERIOD));this.degradeGracePeriod--}recover(){this.degradeGracePeriod=this.MIN_DEGRADE_GRACE_PERIOD,this.recoverGracePeriod>0?this.recoverGracePeriod--:(this.recoveringTrack=this.getActiveTracks(!0).find((e=>e.degraded)),this.recoveringTrack&&(Mi.d(this.TAG,"Packet lost stable, recovering track",this.recoveringTrack),this.recoveringTrack.setDegraded(!1),this.eventBus.trackRestored.publish(this.recoveringTrack),this.recoverGracePeriod=this.MIN_RECOVER_GRACE_PERIOD))}cleanUp(){this.eventBus.trackDegraded.removeAllListeners(),this.eventBus.trackRestored.removeAllListeners()}degradeActiveTracksByHalf(){let e=this.getActiveTracks(!1);if(!e.length)return;Mi.d(this.TAG,{activeTracks:[...e]});let t=Math.ceil(e.length/2);for(;t--;){let t=e.pop();t.setDegraded(!0),this.eventBus.trackDegraded.publish(t)}}getActiveTracks(e){return this.store.getRemoteVideoTracks().filter((t=>t.hasSinks()&&(!t.degraded||e))).sort(((e,t)=>{let i=this.store.getComparator().getTrackComparators();return-1*(i.screenShare(e,t)||i.rolePriority(e,t)||i.peerAudioLevel(e,t)||this.store.getComparator().stringComparator(e.trackId,t.trackId))})).slice(0)}cancelRecovery(){this.recoveringTrack&&(this.recoveringTrack.setDegraded(!0),this.eventBus.trackDegraded.publish(this.recoveringTrack)),this.recoveringTrack=void 0,this.recoverAttemptCount++,this.recoverGracePeriod=this.getDelayForRecoverCount(this.recoverAttemptCount),this.degradeGracePeriod=this.MIN_DEGRADE_GRACE_PERIOD,Mi.d(this.TAG,"Recover Attempt Failed",{count:this.recoverAttemptCount,delay:this.recoverGracePeriod})}getDelayForRecoverCount(e){let t=this.MIN_RECOVER_GRACE_PERIOD+this.MIN_RECOVER_GRACE_PERIOD*e;return Math.min(t,this.MAX_RECOVER_GRACE_PERIOD)}}(this.store,this.eventBus),this.eventBus.statsUpdate.subscribe((e=>{var t,i,r;null==(r=this.trackDegradationController)||r.handleRtcStatsChange((null==(i=null==(t=e.getLocalPeerStats())?void 0:t.subscribe)?void 0:i.packetsLost)||0)}))),this.eventBus.trackDegraded.subscribe((e=>{en.queue(gn.degradationStats(e,!0)).flush(),this.observer.onTrackDegrade(e)})),this.eventBus.trackRestored.subscribe((e=>{en.queue(gn.degradationStats(e,!1)).flush(),this.observer.onTrackRestore(e)}))),yield null==(n=this.webrtcInternals)?void 0:n.start()}))}setTransportStateForJoin(){if(this.state===Sn.Failed&&(this.state=Sn.Disconnected),this.state!==Sn.Disconnected&&this.state!==Sn.Reconnecting)throw Ui.WebsocketMethodErrors.AlreadyJoined(Li.JOIN,`Cannot join a meeting in ${this.state}`);this.state===Sn.Disconnected&&(this.state=Sn.Connecting,this.observer.onStateChange(this.state))}}(this.observer,this.deviceManager,this.store,this.localTrackManager,this.eventBus)}validateJoined(e){if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,`Not connected - ${e}`)}getWebrtcInternals(){var e;return null==(e=this.transport)?void 0:e.getWebrtcInternals()}getPlaylistManager(){return this.playlistManager}getRecordingState(){var e;return null==(e=this.store.getRoom())?void 0:e.recording}getRTMPState(){var e;return null==(e=this.store.getRoom())?void 0:e.rtmp}getHLSState(){var e;return null==(e=this.store.getRoom())?void 0:e.hls}get localPeer(){var e;return null==(e=this.store)?void 0:e.getLocalPeer()}preview(e,t){return _i(this,null,(function*(){return Vi(),ji(),this.sdkState.isPreviewInProgress?Promise.reject(Ui.GenericErrors.PreviewAlreadyInProgress(Li.PREVIEW,"Preview already called")):(this.setUpPreview(e,t),e.alwaysRequestPermissions&&this.localTrackManager.requestPermissions().then((()=>_i(this,null,(function*(){yield this.initDeviceManagers()})))),new Promise(((i,r)=>{let n=()=>_i(this,null,(function*(){var r;this.notificationManager.removeEventListener("policy-change",n);let s=yield this.localTrackManager.getTracksToPublish(e.settings||zn);
8s.forEach((e=>this.setLocalPeerTrack(e))),(null==(r=this.localPeer)?void 0:r.audioTrack)&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),t.onPreview(this.store.getRoom(),s),this.sdkState.isPreviewInProgress=!1,i()}));this.notificationManager.addEventListener("policy-change",n),this.transport.connect(e.authToken,e.initEndpoint||"https://prod-init.100ms.live/init",this.localPeer.peerId).catch((e=>{var t;null==(t=this.errorListener)||t.onError(e),this.sdkState.isPreviewInProgress=!1,r(e)}))})))}))}join(e,t){var i,r,n;if(Vi(),ji(),this.sdkState.isPreviewInProgress)throw Ui.GenericErrors.NotReady(Li.JOIN,"Preview is in progress, can't join");let{roomId:s,userId:o,role:a}=Un(e.authToken);null==(r=null==(i=this.localPeer)?void 0:i.audioTrack)||r.destroyAudioLevelMonitor(),this.listener=t,this.commonSetup(e,s,t),this.removeDevicesFromConfig(e),this.store.setConfig(e),this.localPeer?(this.localPeer.name=e.userName,this.localPeer.role=this.store.getPolicyForRole(a),this.localPeer.customerUserId=o,this.localPeer.metadata=e.metaData||""):(this.notificationManager.addEventListener("role-change",(e=>{this.store.setPublishParams(e.detail.params.role.publishParams)})),this.createAndAddLocalPeerToStore(e,a,o)),this.roleChangeManager=new class{constructor(e,t,i,r,n){this.store=e,this.transport=t,this.publish=i,this.removeAuxillaryTrack=r,this.listener=n,this.handleLocalPeerRoleUpdate=e=>_i(this,null,(function*(){var t,i;let r=this.store.getLocalPeer();if(!r)return;let n=e.detail.oldRole,s=e.detail.newRole,o=n.publishParams.allowed||[],a=s.publishParams.allowed||[],c={removeVideo:!1,removeAudio:!1,removeScreen:!1};o.length>0&&(0===a.length?(c.removeVideo=!0,c.removeAudio=!0,c.removeScreen=!0):(o.includes("video")&&!a.includes("video")&&(c.removeVideo=!0),o.includes("audio")&&!a.includes("audio")&&(c.removeAudio=!0),o.includes("screen")&&!a.includes("screen")&&(c.removeScreen=!0))),yield this.removeLocalTracks(c),this.store.setPublishParams(s.publishParams);let l=(null==(t=this.store.getConfig())?void 0:t.settings)||{isAudioMuted:!0,isVideoMuted:!0,audioInputDeviceId:"default",videoDeviceId:"default",audioOutputDeviceId:"default"};yield this.publish(Ii(Ai({},l),{isAudioMuted:!0,isVideoMuted:!0})),null==(i=this.listener)||i.onPeerUpdate($i.ROLE_UPDATED,r)}))}removeLocalTracks(e){return _i(this,arguments,(function*({removeVideo:e,removeAudio:t,removeScreen:i}){var r;let n=this.store.getLocalPeer();if(!n)return;let s=[];(null==n?void 0:n.videoTrack)&&e&&(s.push(n.videoTrack),n.videoTrack=void 0),(null==n?void 0:n.audioTrack)&&t&&(s.push(n.audioTrack),n.audioTrack=void 0),yield this.transport.unpublish(s);for(let e of s)null==(r=this.listener)||r.onTrackUpdate(Ki.TRACK_REMOVED,e,n);if(n.auxiliaryTracks&&i){let e=[...n.auxiliaryTracks];for(let t of e)"screen"===t.source&&(yield this.removeAuxillaryTrack(t.trackId))}}))}}(this.store,this.transport,this.publish.bind(this),this.removeTrack.bind(this),this.listener),this.notificationManager.addEventListener("local-peer-role-update",this.roleChangeManager.handleLocalPeerRoleUpdate),Mi.d(this.TAG,"SDK Store",this.store),Mi.d(this.TAG,`â³ Joining room ${s}`),Mi.time(`join-room-${s}`),this.transport.join(e.authToken,this.localPeer.peerId,{name:e.userName,metaData:e.metaData||""},e.initEndpoint,e.autoVideoSubscribe,(null==(n=window.HMS)?void 0:n.SERVER_SUB_DEGRADE)||!1).then((()=>_i(this,null,(function*(){Mi.d(this.TAG,`â
Joined room ${s}`),this.notifyJoin(),this.publishParams&&!this.sdkState.published&&!br&&(yield this.publish(e.settings||zn))})))).catch((e=>{var t;null==(t=this.listener)||t.onError(e),Mi.e(this.TAG,"Unable to join room",e)})).then((()=>{Mi.timeEnd(`join-room-${s}`)}))}stringifyMetadata(e){e.metaData&&"string"!=typeof e.metaData&&JSON.stringify(e.metaData)}cleanUp(){var e,t;this.store.cleanUp(),this.cleanDeviceManagers(),sn.cleanup(),this.playlistManager.cleanup(),Mi.cleanUp(),this.sdkState=Ai({},Jn),this.localPeer&&(null==(e=this.localPeer.audioTrack)||e.cleanup(),this.localPeer.audioTrack=void 0,null==(t=this.localPeer.videoTrack)||t.cleanup(),this.localPeer.videoTrack=void 0),this.listener=void 0,this.roleChangeManager&&this.notificationManager.removeEventListener("local-peer-role-update",this.roleChangeManager.handleLocalPeerRoleUpdate)}leave(){return _i(this,null,(function*(){var e;let t=this.store.getRoom();if(t){let i=t.id;Mi.d(this.TAG,`â³ Leaving room ${i}`),yield null==(e=this.transport)?void 0:e.leave(),this.cleanUp(),Mi.d(this.TAG,`â
Left room ${i}`)}}))}getLocalPeer(){return this.store.getLocalPeer()}getPeers(){let e=this.store.getPeers();return Mi.d(this.TAG,"Got peers",e),e}getAudioOutput(){return this.audioOutput}sendMessage(e,t){this.sendMessageInternal({message:t,type:e})}sendBroadcastMessage(e,t){return _i(this,null,(function*(){return yield this.sendMessageInternal({message:e,type:t})}))}sendGroupMessage(e,t,i){return _i(this,null,(function*(){let r=this.store.getKnownRoles();if(0===(t.filter((e=>r[e.name]))||[]).length)throw Ui.GenericErrors.ValidationFailed("No valid role is present",t);return yield this.sendMessageInternal({message:e,recipientRoles:t,type:i})}))}sendDirectMessage(e,t,i){return _i(this,null,(function*(){var r;if(!this.store.getPeerById(t.peerId))throw Ui.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);if((null==(r=this.localPeer)?void 0:r.peerId)===t.peerId)throw Ui.GenericErrors.ValidationFailed("Cannot send message to self");return yield this.sendMessageInternal({message:e,recipientPeer:t,type:i})}))}sendMessageInternal(e){return _i(this,arguments,(function*({recipientRoles:e,recipientPeer:t,type:i="chat",message:r}){if(""===r.replace(/\u200b/g," ").trim())throw Mi.w(this.TAG,"sendMessage","Ignoring empty message send"),Ui.GenericErrors.ValidationFailed("Empty message not allowed");let n=new Nr({sender:this.localPeer,type:i,message:r,recipientPeer:t,recipientRoles:e,time:new Date});
8return Mi.d(this.TAG,"Sending Message:: ",n),yield this.transport.sendMessage(n),n}))}startScreenShare(e,t=!1){return _i(this,null,(function*(){var i,r,n;let s=this.publishParams;if(!s)return;let{allowed:o}=s;if(!o||!o.includes("screen"))return void Mi.e(this.TAG,`Role ${null==(i=this.localPeer)?void 0:i.role} cannot share screen`);if(null==(n=null==(r=this.localPeer)?void 0:r.auxiliaryTracks)?void 0:n.find((e=>"screen"===e.source)))throw Error("Cannot share multiple screens");let a=yield this.getScreenshareTracks(s,e,t);if(!this.localPeer)return Mi.d(this.TAG,"Screenshared when not connected"),void a.forEach((e=>{e.cleanup()}));yield this.transport.publish(a),a.forEach((e=>{var t,i,r;e.peerId=null==(t=this.localPeer)?void 0:t.peerId,null==(i=this.localPeer)||i.auxiliaryTracks.push(e),null==(r=this.listener)||r.onTrackUpdate(Ki.TRACK_ADDED,e,this.localPeer)}))}))}stopEndedScreenshare(e){return _i(this,null,(function*(){Mi.d(this.TAG,"â
Screenshare ended natively"),yield this.stopScreenShare(),e()}))}stopScreenShare(){return _i(this,null,(function*(){var e;Mi.d(this.TAG,"â
Screenshare ended from app");let t=null==(e=this.localPeer)?void 0:e.auxiliaryTracks.filter((e=>"screen"===e.source));if(t)for(let e of t)yield this.removeTrack(e.trackId)}))}addTrack(e,t="regular"){return _i(this,null,(function*(){var i,r,n,s;if(!e)return void Mi.w(this.TAG,"Please pass a valid MediaStreamTrack");if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot addTrack");if(this.localPeer.auxiliaryTracks.find((t=>t.trackId===e.id)))return;let o=e.kind,a=new MediaStream([e]),c=new vn(a),l=new("audio"===o?cn:bn)(c,e,t,this.eventBus);this.setPlaylistSettings({track:e,hmsTrack:l,source:t}),yield null==(i=this.transport)?void 0:i.publish([l]),l.peerId=null==(r=this.localPeer)?void 0:r.peerId,null==(n=this.localPeer)||n.auxiliaryTracks.push(l),null==(s=this.listener)||s.onTrackUpdate(Ki.TRACK_ADDED,l,this.localPeer)}))}removeTrack(e){return _i(this,null,(function*(){var t;if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot removeTrack");let i=this.localPeer.auxiliaryTracks.findIndex((t=>t.trackId===e));if(i>-1){let e=this.localPeer.auxiliaryTracks[i];yield this.transport.unpublish([e]),this.localPeer.auxiliaryTracks.splice(i,1),null==(t=this.listener)||t.onTrackUpdate(Ki.TRACK_REMOVED,e,this.localPeer)}else Mi.w(this.TAG,`No track found for ${e}`)}))}setAnalyticsLevel(e){en.level=e}setLogLevel(e){Mi.level=e}addAudioListener(e){this.audioListener=e,this.notificationManager.setAudioListener(e)}changeRole(e,t,i=!1){return _i(this,null,(function*(){var r;!e.role||e.role.name===t||(yield null==(r=this.transport)?void 0:r.changeRole(e,t,i))}))}acceptChangeRole(e){return _i(this,null,(function*(){var t;yield null==(t=this.transport)?void 0:t.acceptRoleChange(e)}))}endRoom(e,t){return _i(this,null,(function*(){var i;if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot end room");yield null==(i=this.transport)?void 0:i.endRoom(e,t),yield this.leave()}))}removePeer(e,t){return _i(this,null,(function*(){var i;if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot remove peer");if(!this.store.getPeerById(e.peerId))throw Ui.GenericErrors.ValidationFailed("Invalid peer, given peer not present in room",e);yield null==(i=this.transport)?void 0:i.removePeer(e.peerId,t)}))}startRTMPOrRecording(e){return _i(this,null,(function*(){var t;if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot start streaming or recording");yield null==(t=this.transport)?void 0:t.startRTMPOrRecording(e)}))}stopRTMPAndRecording(){return _i(this,null,(function*(){var e;if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot stop streaming or recording");yield null==(e=this.transport)?void 0:e.stopRTMPOrRecording()}))}startHLSStreaming(e){return _i(this,null,(function*(){var t;if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot start HLS streaming");yield null==(t=this.transport)?void 0:t.startHLSStreaming(e)}))}stopHLSStreaming(e){return _i(this,null,(function*(){var t;if(!this.localPeer)throw Ui.GenericErrors.NotConnected(Li.VALIDATION,"No local peer present, cannot stop HLS streaming");yield null==(t=this.transport)?void 0:t.stopHLSStreaming(e)}))}changeName(e){return _i(this,null,(function*(){var t;this.validateJoined("changeName"),yield null==(t=this.transport)?void 0:t.changeName(e),this.notificationManager.updateLocalPeer({name:e})}))}changeMetadata(e){return _i(this,null,(function*(){var t;this.validateJoined("changeMetadata"),yield null==(t=this.transport)?void 0:t.changeMetadata(e),this.notificationManager.updateLocalPeer({metadata:e})}))}getRoles(){return Object.values(this.store.getKnownRoles())}changeTrackState(e,t){return _i(this,null,(function*(){var i;if(e.type===pr.VIDEO&&"regular"!==e.source)return void Mi.w(this.TAG,"Mut
8ing non-regular video tracks is currently not supported");if(e.enabled===t)return void Mi.w(this.TAG,`Aborting change track state, track already has enabled - ${t}`,e);if(!this.store.getTrackById(e.trackId))throw Ui.GenericErrors.ValidationFailed("No track found for change track state",e);let r=this.store.getPeerByTrackId(e.trackId);if(!r)throw Ui.GenericErrors.ValidationFailed("No peer found for change track state",e);yield null==(i=this.transport)?void 0:i.changeTrackState({requested_for:r.peerId,track_id:e.trackId,stream_id:e.stream.id,mute:!t})}))}changeMultiTrackState(e){return _i(this,null,(function*(){var t;if("boolean"!=typeof e.enabled)throw Ui.GenericErrors.ValidationFailed("Pass a boolean for enabled");let{enabled:i,roles:r,type:n,source:s}=e;yield null==(t=this.transport)?void 0:t.changeMultiTrackState({value:!i,type:n,source:s,roles:null==r?void 0:r.map((e=>null==e?void 0:e.name))})}))}publish(e){return _i(this,null,(function*(){let t=yield this.localTrackManager.getTracksToPublish(e);yield this.setAndPublishTracks(t),this.sdkState.published=!0}))}setAndPublishTracks(e){return _i(this,null,(function*(){var t;for(let i of e)yield this.transport.publish([i]),this.setLocalPeerTrack(i),null==(t=this.listener)||t.onTrackUpdate(Ki.TRACK_ADDED,i,this.localPeer);yield this.initDeviceManagers()}))}setLocalPeerTrack(e){var t;switch(e.peerId=null==(t=this.localPeer)?void 0:t.peerId,e.type){case pr.AUDIO:this.localPeer.audioTrack=e;break;case pr.VIDEO:this.localPeer.videoTrack=e}}initDeviceManagers(){return _i(this,null,(function*(){var e,t,i;this.sdkState.deviceManagersInitialised||(this.sdkState.deviceManagersInitialised=!0,this.eventBus.deviceChange.subscribe(this.handleDeviceChange),yield this.deviceManager.init(),this.deviceManager.updateOutputDevice(null==(t=null==(e=sn.getSelection())?void 0:e.audioOutput)?void 0:t.deviceId),this.audioSinkManager.init(null==(i=this.store.getConfig())?void 0:i.audioSinkElementId))}))}cleanDeviceManagers(){this.eventBus.deviceChange.subscribe(this.handleDeviceChange),this.deviceManager.cleanUp(),this.audioSinkManager.removeEventListener(Gn,this.handleAutoplayError),this.audioSinkManager.cleanUp()}initPreviewTrackAudioLevelMonitor(){var e;let t=null==(e=this.localPeer)?void 0:e.audioTrack;null==t||t.initAudioLevelMonitor(),this.eventBus.trackAudioLevelUpdate.subscribe((e=>{var i;let r=e&&e.track.trackId===(null==t?void 0:t.trackId)?[{audioLevel:e.audioLevel,peer:this.localPeer,track:t}]:[];this.store.updateSpeakers(r),null==(i=this.audioListener)||i.onAudioLevelUpdate(r)})),this.eventBus.localAudioSilence.subscribe(this.sendAudioPresenceFailed)}get publishParams(){var e;return null==(e=this.store)?void 0:e.getPublishParams()}notifyJoin(){var e;let t=this.store.getLocalPeer(),i=this.store.getRoom();i.joinedAt=new Date,(null==t?void 0:t.role)?null==(e=this.listener)||e.onJoin(i):this.notificationManager.once("policy-change",(()=>{var e;null==(e=this.listener)||e.onJoin(i)}))}setUpPreview(e,t){this.listener=t,this.sdkState.isPreviewInProgress=!0;let{roomId:i,userId:r,role:n}=Un(e.authToken);this.commonSetup(e,i,t),this.store.setConfig(e),this.createAndAddLocalPeerToStore(e,n,r),Mi.d(this.TAG,"SDK Store",this.store)}setPlaylistSettings(e){return _i(this,arguments,(function*({track:e,hmsTrack:t,source:i}){if("videoplaylist"===i){let i={};if("audio"===e.kind)i.maxBitrate=64;else{i.maxBitrate=1e3;let{width:t,height:r}=e.getSettings();i.width=t,i.height=r}yield t.setSettings(i)}else"audioplaylist"===i&&(yield t.setSettings({maxBitrate:64}))}))}createAndAddLocalPeerToStore(e,t,i){let r=this.store.getPolicyForRole(t),n=new Fr({name:e.userName||"",customerUserId:i,metadata:e.metaData||"",role:r});this.store.addPeer(n)}commonSetup(e,t,i){this.stringifyMetadata(e),this.errorListener=i,this.deviceChangeListener=i,this.initStoreAndManagers(),this.store.setErrorListener(this.errorListener),this.store.getRoom()||this.store.setRoom(new class{constructor(e,t){this.id=e,this.store=t,this.recording={server:{running:!1},browser:{running:!1},hls:{running:!1}},this.rtmp={running:!1},this.hls={running:!1,variants:[]}}get localPeer(){return this.store.getLocalPeer()}get peers(){return this.store.getPeers()}}(t,this.store))}removeDevicesFromConfig(e){this.store.getConfig()&&e.settings&&(delete e.settings.audioOutputDeviceId,delete e.settings.videoDeviceId,delete e.settings.audioInputDeviceId)}getScreenshareTracks(e,t,i){return _i(this,null,(function*(){let{screen:r}=e,n=this.store.getSimulcastDimensions("screen"),[s,o]=yield this.transport.getLocalScreen((new Dr).maxBitrate(r.bitRate,!1).codec(r.codec).maxFramerate(r.frameRate).setWidth((null==n?void 0:n.width)||r.width).setHeight((null==n?void 0:n.height)||r.height).build(),(new Ir).build()),a=()=>{this.stopEndedScreenshare(t)},c=[];if(i){if(s.nativeTrack.stop(),!o)throw Error("Select share audio when sharing screen");c.push(o),o.nativeTrack.onended=a}else c.push(s),s.nativeTrack.onended=a,o&&c.push(o);return c}))}},this.actions=new class{constructor(e,t,i){this.hmsSDKTracks={},this.hmsSDKPeers={},this.isRoomJoinCalled=!1,this.setProgress=({type:e,progress:t})=>{this.setState((i=>{i.playlist[e].progress=t,i.playlist[e].currentTime=this.sdk.getPlaylistManager().getCurrentTime(e)}),"playlistProgress")},this.syncPlaylistState=e=>{this.setState((e=>{Object.assign(e.playlist,Rs.convertPlaylist(this.sdk.getPlaylistManager()))}),e)},this.sendPeerUpdateNotification=(e,t)=>{let i=this.store.getState(Ro(t.peerId)),r="peerUpdate";
8r=xo[e],this.syncRoomState(r),i||(i=this.store.getState(Ro(t.peerId))),this.hmsNotifications.sendPeerUpdate(e,i)},this.setState=(e,t)=>this.store.namedSetState(e,t),this.store=e,this.sdk=t,this.hmsNotifications=i}unblockAudio(){return ds(this,null,(function*(){yield this.sdk.getAudioOutput().unblockAutoplay()}))}setVolume(e,t){t?this.setTrackVolume(e,t):(this.sdk.getAudioOutput().setVolume(e),this.syncRoomState("setOutputVolume"))}setAudioOutputDevice(e){this.sdk.getAudioOutput().setDevice(e)&&this.setState((t=>{t.settings.audioOutputDeviceId=e}),"setAudioOutputDevice")}setPreferredLayer(e,t){let i=this.hmsSDKTracks[e];i?i instanceof Er?(i.preferLayer(t),this.updateVideoLayer(e,"setPreferredLayer")):To.w(`track ${e} is not an video track`):this.logPossibleInconsistency(`track ${e} not present, unable to set preffer layer`)}preview(e){return ds(this,null,(function*(){if(this.isRoomJoinCalled)return void this.logPossibleInconsistency("attempting to call preview after join was called");let t=this.store.getState(to);if(t!==Xn.Preview&&t!==Xn.Connecting)try{this.setState((e=>{e.room.roomState=Xn.Connecting}),"connecting"),yield this.sdkPreviewWithListeners(e)}catch(e){throw To.e("Cannot show preview. Failed to connect to room - ",e),e}else this.logPossibleInconsistency("attempting to call preview while room is in preview/connecting")}))}join(e){if(this.isRoomJoinCalled)this.logPossibleInconsistency("room join is called again");else try{this.sdkJoinWithListeners(e),this.isRoomJoinCalled=!0,this.setState((e=>{e.room.roomState=Xn.Connecting}),"join")}catch(e){throw this.isRoomJoinCalled=!1,To.e("Failed to connect to room - ",e),e}}leave(){return ds(this,null,(function*(){if(!this.store.getState(io))return void this.logPossibleInconsistency("room leave is called when no room is connected");let e=this.store.getState(to);return this.setState((e=>{e.room.roomState=Xn.Disconnecting}),"leaving"),this.sdk.leave().then((()=>{this.resetState("leave"),To.i("left room")})).catch((t=>{To.e("error in leaving room - ",t),this.setState((t=>{t.room.roomState=e}),"revertLeave")}))}))}setScreenShareEnabled(e,t){return ds(this,null,(function*(){e?yield this.startScreenShare(t):yield this.stopScreenShare()}))}addTrack(e,t="regular"){return ds(this,null,(function*(){yield this.sdk.addTrack(e,t),this.syncRoomState("addTrack")}))}removeTrack(e){return ds(this,null,(function*(){yield this.sdk.removeTrack(e),this.syncRoomState("removeTrack")}))}setLocalAudioEnabled(e){return ds(this,null,(function*(){let t=this.store.getState(Ks);t&&(yield this.setEnabledTrack(t,e))}))}setLocalVideoEnabled(e){return ds(this,null,(function*(){let t=this.store.getState(Hs);t&&(yield this.setEnabledTrack(t,e))}))}setEnabledTrack(e,t){return ds(this,null,(function*(){var i;if((null==(i=this.store.getState().tracks[e])?void 0:i.enabled)===t)return void this.logPossibleInconsistency(`local track[${e}] enabled state - ${t}`);this.setState((i=>{i.tracks[e]?i.tracks[e].displayEnabled=t:this.logPossibleInconsistency("track id not found for setEnabled")}),"displayEnabled");try{yield this.setEnabledSDKTrack(e,t),this.syncRoomState("setEnabled")}catch(i){throw this.setState((i=>{i.tracks[e].displayEnabled=!t}),"rollbackDisplayEnabled"),this.hmsNotifications.sendError(Rs.convertException(i)),i}let r=t?Ki.TRACK_UNMUTED:Ki.TRACK_MUTED;this.hmsNotifications.sendTrackUpdate(r,e)}))}setAudioSettings(e){return ds(this,null,(function*(){let t=this.store.getState(Ks);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))}))}setVideoSettings(e){return ds(this,null,(function*(){let t=this.store.getState(Hs);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))}))}sendMessage(e){this.sendBroadcastMessage(e)}sendBroadcastMessage(e,t){return ds(this,null,(function*(){let i=yield this.sdk.sendBroadcastMessage(e,t);this.updateMessageInStore(i,{message:e,type:t})}))}sendGroupMessage(e,t,i){return ds(this,null,(function*(){let r=this.store.getState(ro),n=t.map((e=>r[e])),s=yield this.sdk.sendGroupMessage(e,n,i);this.updateMessageInStore(s,{message:e,recipientRoles:t,type:i})}))}sendDirectMessage(e,t,i){return ds(this,null,(function*(){let r=this.hmsSDKPeers[t],n=yield this.sdk.sendDirectMessage(e,r,i);this.updateMessageInStore(n,{message:e,recipientPeer:r.peerId,type:i})}))}updateMessageInStore(e,t){if(!e)throw To.w("sendMessage","Failed to send message",t),Error(`sendMessage Failed - ${JSON.stringify(t)}`);let i=Rs.convertMessage(e);return i.read=!0,i.senderName="You",this.onHMSMessage(i),i}setMessageRead(e,t){this.setState((i=>{t?i.messages.byID[t]?i.messages.byID[t].read=e:this.logPossibleInconsistency("no message with id is found"):i.messages.allIDs.forEach((t=>{i.messages.byID[t].read=e}))}),"setMessageRead")}
8attachVideo(e,t){return ds(this,null,(function*(){if(this.localAndVideoUnmuting(e))return new Promise((i=>{let r=this.store.subscribe((n=>ds(this,null,(function*(){n&&(yield this.attachVideoInternal(e,t),r(),i())}))),Js)}));yield this.attachVideoInternal(e,t)}))}detachVideo(e,t){return ds(this,null,(function*(){let i=this.hmsSDKTracks[e];i&&"video"===i.type?(yield i.removeSink(t),this.updateVideoLayer(e,"detachVideo")):this.logPossibleInconsistency("no video track found to remove sink")}))}addPluginToVideoTrack(e,t){return ds(this,null,(function*(){return this.addRemoveVideoPlugin(e,"add",t)}))}addPluginToAudioTrack(e){return ds(this,null,(function*(){return this.addRemoveAudioPlugin(e,"add")}))}removePluginFromVideoTrack(e){return ds(this,null,(function*(){return this.addRemoveVideoPlugin(e,"remove")}))}removePluginFromAudioTrack(e){return ds(this,null,(function*(){return this.addRemoveAudioPlugin(e,"remove")}))}changeRole(e,t,i=!1){return ds(this,null,(function*(){let r=this.hmsSDKPeers[e];r?yield this.sdk.changeRole(r,t,i):this.logPossibleInconsistency(`Unknown peer ID given ${e} for changerole`)}))}acceptChangeRole(e){return ds(this,null,(function*(){let t=e.requestedBy?this.hmsSDKPeers[e.requestedBy.id]:void 0;t||To.w(`peer for which role change is requested no longer available - ${e.requestedBy}`);let i={requestedBy:t,role:e.role,token:e.token};yield this.sdk.acceptChangeRole(i),this.removeRoleChangeRequest(e)}))}rejectChangeRole(e){this.removeRoleChangeRequest(e)}endRoom(e,t){return ds(this,null,(function*(){let i=this.store.getState(so);if(!(null==i?void 0:i.endRoom))return void To.w("You are not allowed to perform this action - endRoom");let r=this.store.getState(to);this.setState((e=>{e.room.roomState=Xn.Disconnecting}),"endingRoom");try{yield this.sdk.endRoom(e,t),this.resetState("endRoom")}catch(e){To.e("error in ending room - ",e),this.setState((e=>{e.room.roomState=r}),"revertEndRoom")}}))}removePeer(e,t){return ds(this,null,(function*(){let i=this.hmsSDKPeers[e];i&&!i.isLocal?yield this.sdk.removePeer(i,t):this.logPossibleInconsistency(`No remote peer found for peerID - ${e}`)}))}startRTMPOrRecording(e){return ds(this,null,(function*(){yield this.sdk.startRTMPOrRecording(e)}))}stopRTMPAndRecording(){return ds(this,null,(function*(){yield this.sdk.stopRTMPAndRecording()}))}startHLSStreaming(e){return ds(this,null,(function*(){yield this.sdk.startHLSStreaming(e)}))}stopHLSStreaming(e){return ds(this,null,(function*(){yield this.sdk.stopHLSStreaming(e)}))}changeName(e){return ds(this,null,(function*(){yield this.sdk.changeName(e)}))}changeMetadata(e){return ds(this,null,(function*(){"string"!=typeof e&&(e=JSON.stringify(e)),yield this.sdk.changeMetadata(e)}))}setRemoteTrackEnabled(e,t){return ds(this,null,(function*(){if("string"==typeof e){let i=this.hmsSDKTracks[e];i&&function(e){return e instanceof yr||e instanceof Er}(i)?yield this.sdk.changeTrackState(i,t):this.logPossibleInconsistency(`No remote track with ID ${e} found for change track state`)}else Array.isArray(e)&&e.forEach((e=>this.setRemoteTrackEnabled(e,t)))}))}setRemoteTracksEnabled(e){return ds(this,null,(function*(){let t={enabled:e.enabled,type:e.type,source:e.source};if(e.roles){let i=this.store.getState(ro);t.roles=e.roles.map((e=>i[e]))}yield this.sdk.changeMultiTrackState(t)}))}setLogLevel(e){To.level=e,this.sdk.setLogLevel(e)}resetState(e="resetState"){this.setState((e=>{Object.assign(e,vs())}),e),this.isRoomJoinCalled=!1,this.hmsSDKTracks={},To.cleanUp()}sdkJoinWithListeners(e){this.sdk.join(e,{onJoin:this.onJoin.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this),onMessageReceived:this.onMessageReceived.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onRoleChangeRequest:this.onRoleChangeRequest.bind(this),onRoleUpdate:this.onRoleUpdate.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onChangeTrackStateRequest:this.onChangeTrackStateRequest.bind(this),onChangeMultiTrackStateRequest:this.onChangeMultiTrackStateRequest.bind(this),onRemovedFromRoom:this.onRemovedFromRoom.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)})}onRemovedFromRoom(e){var t;let i=this.store.getState(Ro(null==(t=e.requestedBy)?void 0:t.peerId));this.hmsNotifications.sendLeaveRoom(ls(cs({},e),{requestedBy:i||void 0}));let r=e.roomEnded||!i?"roomEnded":"removedFromRoom";To.i(`resetting state after peer removed ${r}`,e),this.resetState(r)}onDeviceChange(e){let t=e.devices;if(!t)return;let i=this.store.getState(Bs);if(this.setState((e=>{Ss(e.devices.audioInput,t.audioInput)||(e.devices.audioInput=t.audioInput),Ss(e.devices.videoInput,t.videoInput)||(e.devices.videoInput=t.videoInput),Ss(e.devices.audioOutput,t.audioOutput)||(e.devices.audioOutput=t.audioOutput),this.hmsSDKPeers[null==i?void 0:i.id]&&Object.assign(e.settings,this.getMediaSettings(this.hmsSDKPeers[null==i?void 0:i.id]))}),"deviceChange"),e.selection){let t=Rs.convertDeviceChangeUpdate(e);this.hmsNotifications.sendDeviceChange(t)}
8}sdkPreviewWithListeners(e){return ds(this,null,(function*(){yield this.sdk.preview(e,{onPreview:this.onPreview.bind(this),onError:this.onError.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)})}))}startScreenShare(e){return ds(this,null,(function*(){this.store.getState(Qs)?this.logPossibleInconsistency("start screenshare is called while it's on"):(yield this.sdk.startScreenShare((()=>this.syncRoomState("screenshareStopped")),e),this.syncRoomState("startScreenShare"))}))}stopScreenShare(){return ds(this,null,(function*(){this.store.getState(Qs)?(yield this.sdk.stopScreenShare(),this.syncRoomState("stopScreenShare")):this.logPossibleInconsistency("stop screenshare is called while it's not on")}))}attachVideoInternal(e,t){return ds(this,null,(function*(){let i=this.hmsSDKTracks[e];i&&"video"===i.type?(yield i.addSink(t),this.updateVideoLayer(e,"attachVideo")):this.logPossibleInconsistency("no video track found to add sink")}))}syncRoomState(e){To.time(`store-sync-${e}`);let t={},i=[],r={},n={},s={},o=this.sdk.getPeers();for(let e of o){let o=Rs.convertPeer(e);t[o.id]=o,i.push(o.id),this.hmsSDKPeers[o.id]=e;let a=[e.audioTrack,e.videoTrack,...e.auxiliaryTracks];for(let e of a){if(!e)continue;let t=Rs.convertTrack(e);r[t.id]=t,n[e.trackId]=e}o.isLocal&&Object.assign(s,this.getMediaSettings(e))}let a=this.sdk.getRecordingState(),c=this.sdk.getRTMPState(),l=this.sdk.getHLSState();this.setState((e=>{e.room.peers=i;let o=e.peers,d=e.tracks;((e,t)=>
8{let i=bs(Object.keys(e),Object.keys(t));for(let r of i){let i=e[r],n=t[r];Ts(i,n)?(Ss(i.auxiliaryTracks,n.auxiliaryTracks)&&(n.auxiliaryTracks=i.auxiliaryTracks),Object.assign(i,n)):Es(i,n)?delete e[r]:ks(i,n)&&(e[r]=n)}})(o,t),((e,t)=>{let i=bs(Object.keys(e),Object.keys(t));for(let r of i){let i=e[r],n=t[r];Ts(i,n)?(ys(i,n),Object.assign(i,n)):Es(i,n)?delete e[r]:ks(i,n)&&(e[r]=n)}})(d,r),Object.assign(e.settings,s),this.hmsSDKTracks=n,Object.assign(e.roles,Rs.convertRoles(this.sdk.getRoles())),Object.assign(e.playlist,Rs.convertPlaylist(this.sdk.getPlaylistManager())),Object.assign(e.room,Rs.convertRecordingStreamingState(a,c,l))}),e),To.timeEnd(`store-sync-${e}`)}onPreview(e){this.setState((t=>{Object.assign(t.room,Rs.convertRoom(e)),t.room.roomState=Xn.Preview}),"previewStart"),this.syncRoomState("previewSync")}onJoin(e){let t=this.sdk.getPlaylistManager();this.audioPlaylist=new Mo(t,ms.audio,this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new Mo(t,ms.video,this.syncRoomState.bind(this),this.store),this.syncRoomState("joinSync"),this.setState((t=>{Object.assign(t.room,Rs.convertRoom(e)),t.room.isConnected=!0,t.room.roomState=Xn.Connected}),"joined"),t.onProgress(this.setProgress),t.onNewTrackStart((e=>{this.syncPlaylistState(`${e.type}PlaylistUpdate`)})),t.onPlaylistEnded((e=>{this.syncPlaylistState(`${e}PlaylistEnded`)})),t.onCurrentTrackEnded((e=>{this.hmsNotifications.sendPlaylistTrackEnded(Rs.convertPlaylistItem(t,e)),this.syncPlaylistState(`${e.type}PlaylistItemEnded`)}))}onRoomUpdate(e,t){this.setState((e=>{Object.assign(e.room,Rs.convertRoom(t))}),"RoomUpdate")}onPeerUpdate(e,t){if(![$i.BECAME_DOMINANT_SPEAKER,$i.RESIGNED_DOMINANT_SPEAKER].includes(e)){if(Array.isArray(t)){this.syncRoomState("peersJoined");let e=[];for(let i of t){let t=this.store.getState(Ro(i.peerId));t&&e.push(t)}return void this.hmsNotifications.sendPeerList(e)}this.sendPeerUpdateNotification(e,t)}}onTrackUpdate(e,t,i){if(e===Ki.TRACK_REMOVED)this.hmsNotifications.sendTrackUpdate(e,t.trackId),this.handleTrackRemove(t,i);else{let i=e===Ki.TRACK_ADDED?"trackAdded":"trackUpdate";this.syncRoomState(i),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=Rs.convertMessage(e);t.read=!1,this.onHMSMessage(t),this.hmsNotifications.sendMessageReceived(t)}onHMSMessage(e){this.setState((t=>{e.id=String(this.store.getState(Xs)+1),t.messages.byID[e.id]=e,t.messages.allIDs.push(e.id)}),"newMessage")}onAudioLevelUpdate(e){this.setState((t=>{let i={};e.forEach((e=>{if(!e.track||!e.peer)return;let r=e.track.trackId;i[r]=e.audioLevel,t.speakers[r]||(t.speakers[r]={audioLevel:e.audioLevel,peerID:e.peer.peerId,trackID:r})}));let r=Object.entries(t.speakers);for(let[e,n]of r)n.audioLevel=i[e]||0,0===n.audioLevel&&delete t.speakers[e]}),"audioLevel")}onChangeTrackStateRequest(e){var t;let i=this.store.getState(Ro(null==(t=e.requestedBy)?void 0:t.peerId)),r=this.getStoreLocalTrackIDfromSDKTrack(e.track),n=this.store.getState(Co(r));if(!n)return this.logPossibleInconsistency(`Not found track for which track state change was requested, ${e.track}`);e.enabled||this.syncRoomState("changeTrackStateRequest"),this.hmsNotifications.sendChangeTrackStateRequest({requestedBy:i||void 0,track:n,enabled:e.enabled})}onChangeMultiTrackStateRequest(e){var t;let i=this.store.getState(Ro(null==(t=e.requestedBy)?void 0:t.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let r=[],n=this.store.getState(Us);for(let t of e.tracks){let e=this.getStoreLocalTrackIDfromSDKTrack(t);e&&n[e]&&r.push(n[e])}this.hmsNotifications.sendChangeMultiTrackStateRequest({requestedBy:i||void 0,tracks:r,enabled:e.enabled,type:e.type,source:e.source})}onReconnected(){this.syncRoomState("reconnectedSync"),this.hmsNotifications.sendReconnected(),this.setState((e=>{e.room.roomState=Xn.Connected}),"reconnected")}onReconnecting(e){let t=Rs.convertException(e);To.e("Reconnection: received error from sdk",t),this.hmsNotifications.sendReconnecting(t),this.setState((e=>{e.room.roomState=Xn.Reconnecting,e.errors.push(t)}),"reconnecting")}onError(e){let t=Rs.convertException(e);t.isTerminal?(this.leave().then((()=>To.e("error from SDK, left room."))),this.setState((e=>{e.room.roomState=Xn.Failed,e.errors.push(t)}),"errorTerminal")):this.store.getState().errors.length<50&&this.setState((e=>{e.errors.push(t)}),"error"),this.hmsNotifications.sendError(t),To.e("received error from sdk",t)}updateVideoLayer(e,t){let i=this.hmsSDKTracks[e];i&&i instanceof Er&&this.setState((t=>{t.tracks[e].layer=i.getSimulcastLayer()}),t)}handleTrackRemove(e,t){this.setState((i=>{let r=i.peers[t.peerId],n=i.tracks,s=e.trackId;if(this.isSameStoreSDKTrack(s,null==r?void 0:r.audioTrack))null==r||delete r.audioTrack;else if(this.isSameStoreSDKTrack(s,null==r?void 0:r.videoTrack))null==r||delete r.videoTrack;else{let e=null==r?void 0:r.auxiliaryTracks.indexOf(s);e>-1&&this.isSameStoreSDKTrack(s,null==r?void 0:r.auxiliaryTracks[e])&&(null==r||r.auxiliaryTracks.splice(e,1))}delete n[s],delete this.hmsSDKTracks[s]}),"trackRemoved")}setEnabledSDKTrack(e,t){return ds(this,null,(function*(){let i=this.hmsSDKTracks[e];i?yield i.setEnabled(t):this.logPossibleInconsistency(`track ${e} not present, unable to enabled/disable`)}))}setSDKLocalVideoTrackSettings(e,t){return ds(this,null,(function*(){let i=this.hmsSDKTracks[e];i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)}))}setSDKLocalAudioTrackSettings(e,t){return ds(this,null,(function*(){let i=this.hmsSDKTracks[e];i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)}))}getMediaSettings(e){var t;let i=this.store.getState(Gs),r=e.audioTrack,n=e.videoTrack;return{audioInputDeviceId:(null==r?void 0:r.settings.deviceId)||i.audioInputDeviceId,videoInputDeviceId:(null==n?void 0:n.settings.deviceId)||i.videoInputDeviceId,audioOutputDeviceId:null==(t=this.sdk.getAudioOutput().getDevice()
8)?void 0:t.deviceId}}setTrackVolume(e,t){let i=this.hmsSDKTracks[t];i?i instanceof fr?(i.setVolume(e),this.setState((i=>{let r=i.tracks[t];r&&(r.volume=e)}),"trackVolume")):To.w(`track ${t} is not an audio track`):this.logPossibleInconsistency(`track ${t} not present, unable to set volume`)}localAndVideoUnmuting(e){if(this.store.getState(Bs).videoTrack!==e)return!1;let t=this.store.getState(Ys),i=this.store.getState(Js);return t&&!i}logPossibleInconsistency(e){To.w("possible inconsistency detected - ",e)}addRemoveVideoPlugin(e,t,i){return ds(this,null,(function*(){if(!e)return void To.w("Invalid plugin received in store");let r=this.store.getState(Hs);if(r){let n=this.hmsSDKTracks[r];n?("add"===t?yield n.addPlugin(e,i):"remove"===t&&(yield n.removePlugin(e)),this.syncRoomState(`${t}VideoPlugin`)):this.logPossibleInconsistency(`track ${r} not present, unable to remove plugin`)}}))}addRemoveAudioPlugin(e,t){return ds(this,null,(function*(){if(!e)return void To.w("Invalid plugin received in store");let i=this.store.getState(Ks);if(i){let r=this.hmsSDKTracks[i];r?("add"===t?yield r.addPlugin(e):"remove"===t&&(yield r.removePlugin(e)),this.syncRoomState(`${t}AudioPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to remove plugin`)}}))}isSameStoreSDKTrack(e,t){var i;return!!t&&(null==(i=this.hmsSDKTracks[t])?void 0:i.trackId)===e}onRoleChangeRequest(e){this.setState((t=>{0===t.roleChangeRequests.length&&t.roleChangeRequests.push(Rs.convertRoleChangeRequest(e))}),"roleChangeRequest")}removeRoleChangeRequest(e){this.setState((t=>{let i=t.roleChangeRequests.findIndex((t=>t.token===e.token));-1!==i&&t.roleChangeRequests.splice(i,1)}),"removeRoleChangeRequest")}onRoleUpdate(){this.syncRoomState("roleUpdate")}getStoreLocalTrackIDfromSDKTrack(e){return this.store.getState(Ws).find((t=>this.hmsSDKTracks[t].trackId===e.trackId))}}(this.store,this.sdk,this.notifications)),this.initialTriggerOnSubscribe=!1,Rr&&(window.__hms=this)}triggerOnSubscribe(){this.initialTriggerOnSubscribe||(Jo.makeStoreTriggerOnSubscribe(this.store),this.initialTriggerOnSubscribe=!0)}getStore(){return this.store}getHMSActions(){return this.actions}getActions(){return this.actions}getNotifications(){return{onNotification:this.notifications.onNotification}}static createNewHMSStore(e,t){let i=Ye((()=>t())),r=i.setState;i.setState=e=>{let t="function"==typeof e?Je(e):e;r(t)};let n=i.getState;i.getState=e=>{if(e){let t=e.name||"byIDSelector";window.selectorsCount||(window.selectorsCount={}),window.selectorsCount[t]=(window.selectorsCount[t]||0)+1;let i=performance.now(),r=e(n()),s=performance.now()-i;return s>1&&(window.expensiveSelectors=window.expensiveSelectors||new Map,window.expensiveSelectors.set(t,s)),r}return n()},Jo.compareWithShallowCheckInSubscribe(i);let s=Jo.setUpDevtools(i,e);return ls(cs({},i),{namedSetState:s})}static makeStoreTriggerOnSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,n)=>(i(e.getState(r),void 0),t(i,r,n))}static compareWithShallowCheckInSubscribe(e){let t=e.subscribe;e.subscribe=(e,i,r)=>(i||(i=e=>e),t(e,i,r=r||Qe))}static setUpDevtools(e,t){let i;try{i=window.__REDUX_DEVTOOLS_EXTENSION__||window.top.__REDUX_DEVTOOLS_EXTENSION__}catch(e){}if(!i)return t=>{e.setState(t)};let r=i.connect(Jo.devtoolsOptions(t));r.prefix=t?`${t} > `:"";let n=e.setState;return e.setState=t=>{n(t),r.send(`${r.prefix}setState`,e.getState())},r.subscribe(Jo.devtoolsSubscribe(r,e,n)),r.send("setUpStore",e.getState()),(t,i)=>{n(t);let s=i||`${r.prefix}action`;r.send(s,e.getState())}}static devtoolsOptions(e){return{name:e,actionsBlacklist:["audioLevel","playlistProgress"]}}static devtoolsSubscribe(e,t,i){return r=>{var n,s,o,a;if("DISPATCH"===r.type&&r.state)["JUMP_TO_ACTION","JUMP_TO_STATE"].includes(r.payload.type)?i(JSON.parse(r.state)):t.setState(JSON.parse(r.state));else if("DISPATCH"===r.type&&"COMMIT"===(null==(n=r.payload)?void 0:n.type))e.init(t.getState());else if("DISPATCH"===r.type&&"IMPORT_STATE"===(null==(s=r.payload)?void 0:s.type)){let n=null==(o=r.payload.nextLiftedState)?void 0:o.actionsById;((null==(a=r.payload.nextLiftedState)?void 0:a.computedStates)||[]).forEac
8h((({state:r},s)=>{let o=n[s]||`${e.prefix}setState`;0===s?e.init(r):(i(r),e.send(o,t.getState()))}))}}}};const Yo=new Jo;Yo.triggerOnSubscribe();const Qo=Yo.getHMSActions(),Zo=Yo.getStore();Yo.getNotifications();function Xo(e){let i,r,s,o,a,m,y,k,S,b,R,C,P,w,A,I,_,D;return{c(){i=u("main"),r=u("form"),s=u("header"),s.textContent="Join Room",o=p(),a=u("label"),m=h("Username\n "),y=u("input"),k=p(),S=u("label"),b=h("Role\n "),R=u("select"),C=u("option"),C.textContent="Speaker",P=u("option"),P.textContent="Listener",w=u("option"),w.textContent="Moderator",A=p(),I=u("button"),I.textContent="Join",f(s,"class","svelte-18nb4q8"),f(y,"id","username"),f(y,"type","text"),f(y,"placeholder","Username"),f(y,"class","svelte-18nb4q8"),f(a,"for","username"),f(a,"class","svelte-18nb4q8"),C.__value="speaker",C.value=C.__value,P.__value="listener",P.value=P.__value,w.__value="moderator",w.value=w.__value,f(R,"name","role"),f(R,"class","svelte-18nb4q8"),void 0===e[1]&&O((()=>e[4].call(R))),f(S,"class","svelte-18nb4q8"),f(I,"class","svelte-18nb4q8"),f(i,"class","svelte-18nb4q8")},m(t,n){l(t,i,n),c(i,r),c(r,s),c(r,o),c(r,a),c(a,m),c(a,y),T(y,e[0]),c(r,k),c(r,S),c(S,b),c(S,R),c(R,C),c(R,P),c(R,w),E(R,e[1]),c(r,A),c(r,I),_||(D=[v(y,"input",e[3]),v(R,"change",e[4]),v(I,"click",g(e[2]))],_=!0)},p(e,[t]){1&t&&y.value!==e[0]&&T(y,e[0]),2&t&&E(R,e[1])},i:t,o:t,d(e){e&&d(i),_=!1,n(D)}}}function ea(e,t,i){let r="",n="";return[r,n,async()=>{if(r&&n)try{const e=await(async(e,t)=>{let i={user_id:t,role:e.toLowerCase(),room_id:"61f1ad914f6b0218f23b7ce5"};const r=await fetch("https://prod-in.100ms.live/hmsapi/dro.app.100ms.live/api/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return(await r.json()).token})(n,r),t={userName:r,authToken:e,settings:{isAudioMuted:!0,isVideoMuted:!1},rememberDeviceSelection:!0}
8;Qo.join(t)}catch(e){console.log("Token API Error",e)}},function(){r=this.value,i(0,r)},function(){n=function(e){const t=e.querySelector(":checked")||e.options[0];return t&&t.__value}(this),i(1,n)}]}class ta extends J{constructor(e){super(),z(this,e,ea,Xo,o,{})}}function ia(e){let t,i,r,s,o,a,m,g,T,E=e[4]?"Unmute":"Mute";return{c(){t=u("div"),i=u("button"),r=h(E),s=p(),o=u("button"),o.textContent="Make Speaker",a=p(),m=u("button"),m.textContent="Make Listener",f(i,"class","svelte-1szb8gt"),f(o,"class","svelte-1szb8gt"),f(m,"class","svelte-1szb8gt"),f(t,"class","context svelte-1szb8gt"),k(t,"open",e[2])},m(n,d){l(n,t,d),c(t,i),c(i,r),c(t,s),c(t,o),c(t,a),c(t,m),g||(T=[v(i,"click",e[5]),v(o,"click",e[8]),v(m,"click",e[9])],g=!0)},p(e,i){16&i&&E!==(E=e[4]?"Unmute":"Mute")&&y(r,E),4&i&&k(t,"open",e[2])},d(e){e&&d(t),g=!1,n(T)}}}function ra(e){let i,r,n,s,o,a,m,g,T,E,k,S,b=(e[0]?e[0].name:"")+"",R=e[0]&&e[0].isLocal?" (You)":"",C="moderator"==e[1]&&!e[0].isLocal&&ia(e);return{c(){i=u("div"),r=u("div"),n=u("div"),s=u("p"),o=h(e[3]),a=p(),m=u("p"),g=h(b),T=h(R),E=p(),C&&C.c(),f(s,"class","svelte-1szb8gt"),f(n,"class","image svelte-1szb8gt"),f(m,"class","svelte-1szb8gt"),f(r,"class","content svelte-1szb8gt"),f(i,"class","peer svelte-1szb8gt")},m(t,d){l(t,i,d),c(i,r),c(r,n),c(n,s),c(s,o),c(r,a),c(r,m),c(m,g),c(m,T),c(i,E),C&&C.m(i,null),k||(S=v(r,"click",e[7]),k=!0)},p(e,[t]){8&t&&y(o,e[3]),1&t&&b!==(b=(e[0]?e[0].name:"")+"")&&y(g,b),1&t&&R!==(R=e[0]&&e[0].isLocal?" (You)":"")&&y(T,R),"moderator"!=e[1]||e[0].isLocal?C&&(C.d(1),C=null):C?C.p(e,t):(C=ia(e),C.c(),C.m(i,null))},i:t,o:t,d(e){e&&d(i),C&&C.d(),k=!1,S()}}}function na(e,t,i){let{peer:r=null}=t,{localPeerRole:n=""}=t,s=!1,o="",a=!1;const c=e=>{Qo.changeRole(r.id,e,!0)};C((async()=>{Zo.subscribe((e=>{}),Ao(r?.id))})),C((async()=>{Zo.subscribe((e=>{i(4,a=!e)}),Io(r?.id))}));return e.$$set=e=>{"peer"in e&&i(0,r=e.peer),"localPeerRole"in e&&i(1,n=e.localPeerRole)},e.$$.update=()=>{1&e.$$.dirty&&i(3,o=r?r.name.split(" ")[0][0].toUpperCase():"")},[r,n,s,o,a,()=>{Qo.setRemoteTrackEnabled(r.audioTrack,a)},c,()=>i(2,s=!s),()=>c("speaker"),()=>c("listener")]}class sa extends J{constructor(e){super(),z(this,e,na,ra,o,{peer:0,localPeerRole:1})}}const oa=[];const aa=function(e,i=t){let r;const n=new Set;function s(t){if(o(e,t)&&(e=t,r)){const t=!oa.length;for(const t of n)t[1](),oa.push(t,e);if(t){for(let e=0;e<oa.length;e+=2)oa[e][0](oa[e+1]);oa.length=0}}}return{set:s,update:function(t){s(t(e))},subscribe:function(o,a=t){const c=[o,a];return n.add(c),1===n.size&&(r=i(s)||t),o(e),()=>{n.delete(c),0===n.size&&(r(),r=null)}}}}([]);function ca(e,t,i){const r=e.slice();return r[7]=t[i],r}function la(e,t){let i,r,n;return r=new sa({props:{localPeerRole:t[1],peer:t[7]}}),{key:e,first:null,c(){i=m(),K(r.$$.fragment),this.first=i},m(e,t){l(e,i,t),H(r,e,t),n=!0},p(e,i){t=e;const n={};2&i&&(n.localPeerRole=t[1]),1&i&&(n.peer=t[7]),r.$set(n)},i(e){n||(V(r.$$.fragment,e),n=!0)},o(e){B(r.$$.fragment,e),n=!1},d(e){e&&d(i),q(r,e)}}}function da(e){let t,i,r,n,s=e[2]?"Mute":"Unmute";return{c(){t=u("button"),i=h(s),f(t,"class","mute svelte-13cilhz")},m(s,o){l(s,t,o),c(t,i),r||(n=v(t,"click",e[3]),r=!0)},p(e,t){4&t&&s!==(s=e[2]?"Mute":"Unmute")&&y(i,s)},d(e){e&&d(t),r=!1,n()}}}function ua(e){let t,i,r,n,s,o,a,h,m,g,y,T=[],E=new Map,k=e[0];const S=e=>e[7].id;for(let t=0;t<k.length;t+=1){let i=ca(e,k,t),r=S(i);E.set(r,T[t]=la(r,i))}let b="listener"!=e[1]&&da(e);return{c(){t=u("main"),i=u("h1"),i.textContent="Welcome To The Room",r=p(),n=u("section");for(let e=0;e<T.length;e+=1)T[e].c();s=p(),o=u("div"),b&&b.c(),a=p(),h=u("button"),h.textContent="Leave Room",f(i,"class","svelte-13cilhz"),f(n,"class","peers svelte-13cilhz"),f(h,"class","leave svelte-13cilhz"),f(o,"class","buttons svelte-13cilhz"),f(t,"class","svelte-13cilhz")},m(d,u){l(d,t,u),c(t,i),c(t,r),c(t,n);for(let e=0;e<T.length;e+=1)T[e].m(n,null);c(t,s),c(t,o),b&&b.m(o,null),c(o,a),c(o,h),m=!0,g||(y=v(h,"click",e[4]),g=!0)},p(e,[t]){3&t&&(k=e[0],F(),T=function(e,t,i,r,n,s,o,a,c,l,d,u){let h=e.length,p=s.length,m=h;const v={};for(;m--;)v[e[m].key]=m;const g=[],f=new Map,y=new Map;for(m=p;m--;){const e=u(n,s,m),a=i(e);let c=o.get(a);c?r&&c.p(e,t):(c=l(a,e),c.c()),f.set(a,g[m]=c),a in v&&y.set(a,Math.abs(m-v[a]))}const T=new Set,E=new Set;function k(e){V(e,1),e.m(a,d),o.set(e.key,e),d=e.first,p--}for(;h&&p;){const t=g[p-1],i=e[h-1],r=t.key,n=i.key;t===i?(d=t.first,h--,p--):f.has(n)?!o.has(r)||T.has(r)?k(t):E.has(n)?h--:y.get(r)>y.get(n)?(E.add(r),k(t)):(T.add(n),h--):(c(i,o),h--)}for(;h--;){const t=e[h];f.has(t.key)||c(t,o)}for(;p;)k(g[p-1]);return g}(T,t,S,1,e,k,E,n,$,la,null,ca),j()),"listener"!=e[1]?b?b.p(e,t):(b=da(e),b.c(),b.m(o,a)):b&&(b.d(1),b=null)},i(e){if(!m){for(let e=0;e<k.length;e+=1)V(T[e]);m=!0}},o(e){for(let e=0;e<T.length;e+=1)B(T[e]);m=!1},d(e){e&&d(t);for(let e=0;e<T.length;e+=1)T[e].d();b&&b.d(),g=!1,y()}}}function ha(e,t,i){let r;a(e,aa,(e=>i(5,r=e)));let n=[],s="",o=null;const c=e=>{let t=Zo.getState(no);i(1,s=t?t.name:""),i(2,o=Zo.getState(zs)),aa.set(e)};C((async()=>{Zo.subscribe(c,js)}));const l=()=>Qo.leave();return function(e){R().$$.on_destroy.push(e)}(l),e.$$.update=()=>{32&e.$$.dirty&&i(0,n=r)},[n,s,o,async()=>{await Qo.setLocalAudioEnabled(!o),i(2,o=Zo.getState(zs))},l,r]}class pa extends J{constructor(e){super(),z(this,e,ha,ua,o,{})}}function ma(e){let t,i,r;var n=e[0];return n&&(t=new n({})),{c(){t&&K(t.$$.fragment),i=m()},m(e,n){t&&H(t,e,n),l(e,i,n),r=!0},p(e,[r]){if(n!==(n=e[0])){if(t){F();const e=t;B(e.$$.fragment,1,0,(()=>{q(e,1)})),j()}n?(t=new n({}),K(t.$$.fragment),V(t.$$.fragment,1),H(t,i.parentNode,i)):t=null}},i(e){r||(t&&V(t.$$.fragment,e),r=!0)},o(e){t&&B(t.$$.fragment,e),r=!1},d(e){e&&d(i),t&&q(t,e)}}}function va(e,t,i){let r;Z("/",(()=>i(0,r=ta))),Z("/room",(()=>i(0,r=pa))),Z.start();const n=e=>{e?Z.redirect("/room"):Z.redirect("/")};return C((async()=>{Zo.subscribe(n,Fs)})),[r]}return new class extends J{constructor(e){super(),z(this,e,va,ma,o,{})}}({target:document.body,props:{}})}(); 9//# sourceMappingURL=bundle.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.