@elevenlabs/convai-widget-embed 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- (function(){"use strict";var vi,j,Xa,Qa,wn,Za,ec,tc,nc,ps,ms,gs,ic,bi={},rc=[],Tp=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,yi=Array.isArray;function yt(t,e){for(var n in e)t[n]=e[n];return t}function vs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function fe(t,e,n){var i,r,s,o={};for(s in e)s=="key"?i=e[s]:s=="ref"?r=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?vi.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return ki(t,o,i,r,null)}function ki(t,e,n,i,r){var s={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r??++Xa,__i:-1,__u:0};return r==null&&j.vnode!=null&&j.vnode(s),s}function sc(){return{current:null}}function ge(t){return t.children}function nt(t,e){this.props=t,this.context=e}function Fn(t,e){if(e==null)return t.__?Fn(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?Fn(t):null}function oc(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return oc(t)}}function bs(t){(!t.__d&&(t.__d=!0)&&wn.push(t)&&!Ji.__r++||Za!=j.debounceRendering)&&((Za=j.debounceRendering)||ec)(Ji)}function Ji(){for(var t,e,n,i,r,s,o,a=1;wn.length;)wn.length>a&&wn.sort(tc),t=wn.shift(),a=wn.length,t.__d&&(n=void 0,r=(i=(e=t).__v).__e,s=[],o=[],e.__P&&((n=yt({},i)).__v=i.__v+1,j.vnode&&j.vnode(n),ys(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??Fn(i),!!(32&i.__u),o),n.__v=i.__v,n.__.__k[n.__i]=n,uc(s,n,o),n.__e!=r&&oc(n)));Ji.__r=0}function ac(t,e,n,i,r,s,o,a,c,l,d){var u,h,p,g,f,m,v,y=i&&i.__k||rc,_=e.length;for(c=xp(n,e,y,c,_),u=0;u<_;u++)(p=n.__k[u])!=null&&(h=p.__i==-1?bi:y[p.__i]||bi,p.__i=u,m=ys(t,p,h,r,s,o,a,c,l,d),g=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&Cs(h.ref,null,p),d.push(p.ref,p.__c||g,p)),f==null&&g!=null&&(f=g),(v=!!(4&p.__u))||h.__k===p.__k?c=cc(p,c,t,v):typeof p.type=="function"&&m!==void 0?c=m:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=f,c}function xp(t,e,n,i,r){var s,o,a,c,l,d=n.length,u=d,h=0;for(t.__k=new Array(r),s=0;s<r;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(c=s+h,(o=t.__k[s]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?ki(null,o,null,null,null):yi(o)?ki(ge,{children:o},null,null,null):o.constructor==null&&o.__b>0?ki(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,a=null,(l=o.__i=Ep(o,n,c,u))!=-1&&(u--,(a=n[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(r>d?h--:r<d&&h++),typeof o.type!="function"&&(o.__u|=4)):l!=c&&(l==c-1?h--:l==c+1?h++:(l>c?h--:h++,o.__u|=4))):t.__k[s]=null;if(u)for(s=0;s<d;s++)(a=n[s])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=Fn(a)),fc(a,a));return i}function cc(t,e,n,i){var r,s;if(typeof t.type=="function"){for(r=t.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=t,e=cc(r[s],e,n,i));return e}t.__e!=e&&(i&&(e&&t.type&&!e.parentNode&&(e=Fn(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Mt(t,e){return e=e||[],t==null||typeof t=="boolean"||(yi(t)?t.some(function(n){Mt(n,e)}):e.push(t)),e}function Ep(t,e,n,i){var r,s,o,a=t.key,c=t.type,l=e[n],d=l!=null&&(2&l.__u)==0;if(l===null&&t.key==null||d&&a==l.key&&c==l.type)return n;if(i>(d?1:0)){for(r=n-1,s=n+1;r>=0||s<e.length;)if((l=e[o=r>=0?r--:s++])!=null&&(2&l.__u)==0&&a==l.key&&c==l.type)return o}return-1}function lc(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Tp.test(e)?n:n+"px"}function Yi(t,e,n,i,r){var s,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||lc(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||lc(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(nc,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?i?n.u=i.u:(n.u=ps,t.addEventListener(e,s?gs:ms,s)):t.removeEventListener(e,s?gs:ms,s);else{if(r=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function dc(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ps++;else if(e.t<n.u)return;return n(j.event?j.event(e):e)}}}function ys(t,e,n,i,r,s,o,a,c,l){var d,u,h,p,g,f,m,v,y,_,k,w,S,x,I,O,R,A=e.type;if(e.constructor!=null)return null;128&n.__u&&(c=!!(32&n.__u),s=[a=e.__e=n.__e]),(d=j.__b)&&d(e);e:if(typeof A=="function")try{if(v=e.props,y="prototype"in A&&A.prototype.render,_=(d=A.contextType)&&i[d.__c],k=d?_?_.props.value:d.__:i,n.__c?m=(u=e.__c=n.__c).__=u.__E:(y?e.__c=u=new A(v,k):(e.__c=u=new nt(v,k),u.constructor=A,u.render=Rp),_&&_.sub(u),u.props=v,u.state||(u.state={}),u.context=k,u.__n=i,h=u.__d=!0,u.__h=[],u._sb=[]),y&&u.__s==null&&(u.__s=u.state),y&&A.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=yt({},u.__s)),yt(u.__s,A.getDerivedStateFromProps(v,u.__s))),p=u.props,g=u.state,u.__v=e,h)y&&A.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),y&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(y&&A.getDerivedStateFromProps==null&&v!==p&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(v,k),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(v,u.__s,k)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(u.props=v,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(M){M&&(M.__=e)}),w=0;w<u._sb.length;w++)u.__h.push(u._sb[w]);u._sb=[],u.__h.length&&o.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(v,u.__s,k),y&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(p,g,f)})}if(u.context=k,u.props=v,u.__P=t,u.__e=!1,S=j.__r,x=0,y){for(u.state=u.__s,u.__d=!1,S&&S(e),d=u.render(u.props,u.state,u.context),I=0;I<u._sb.length;I++)u.__h.push(u._sb[I]);u._sb=[]}else do u.__d=!1,S&&S(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++x<25);u.state=u.__s,u.getChildContext!=null&&(i=yt(yt({},i),u.getChildContext())),y&&!h&&u.getSnapshotBeforeUpdate!=null&&(f=u.getSnapshotBeforeUpdate(p,g)),O=d,d!=null&&d.type===ge&&d.key==null&&(O=hc(d.props.children)),a=ac(t,yi(O)?O:[O],e,n,i,r,s,o,a,c,l),u.base=e.__e,e.__u&=-161,u.__h.length&&o.push(u),m&&(u.__E=u.__=null)}catch(M){if(e.__v=null,c||s!=null)if(M.then){for(e.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,e.__e=a}else{for(R=s.length;R--;)vs(s[R]);ks(e)}else e.__e=n.__e,e.__k=n.__k,M.then||ks(e);j.__e(M,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Pp(n.__e,e,n,i,r,s,o,c,l);return(d=j.diffed)&&d(e),128&e.__u?void 0:a}function ks(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(ks)}function uc(t,e,n){for(var i=0;i<n.length;i++)Cs(n[i],n[++i],n[++i]);j.__c&&j.__c(e,t),t.some(function(r){try{t=r.__h,r.__h=[],t.some(function(s){s.call(r)})}catch(s){j.__e(s,r.__v)}})}function hc(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:yi(t)?t.map(hc):yt({},t)}function Pp(t,e,n,i,r,s,o,a,c){var l,d,u,h,p,g,f,m=n.props,v=e.props,y=e.type;if(y=="svg"?r="http://www.w3.org/2000/svg":y=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((p=s[l])&&"setAttribute"in p==!!y&&(y?p.localName==y:p.nodeType==3)){t=p,s[l]=null;break}}if(t==null){if(y==null)return document.createTextNode(v);t=document.createElementNS(r,y,v.is&&v),a&&(j.__m&&j.__m(e,s),a=!1),s=null}if(y==null)m===v||a&&t.data==v||(t.data=v);else{if(s=s&&vi.call(t.childNodes),m=n.props||bi,!a&&s!=null)for(m={},l=0;l<t.attributes.length;l++)m[(p=t.attributes[l]).name]=p.value;for(l in m)if(p=m[l],l!="children"){if(l=="dangerouslySetInnerHTML")u=p;else if(!(l in v)){if(l=="value"&&"defaultValue"in v||l=="checked"&&"defaultChecked"in v)continue;Yi(t,l,null,p,r)}}for(l in v)p=v[l],l=="children"?h=p:l=="dangerouslySetInnerHTML"?d=p:l=="value"?g=p:l=="checked"?f=p:a&&typeof p!="function"||m[l]===p||Yi(t,l,p,m[l],r);if(d)a||u&&(d.__html==u.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(u&&(t.innerHTML=""),ac(e.type=="template"?t.content:t,yi(h)?h:[h],e,n,i,y=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,o,s?s[0]:n.__k&&Fn(n,0),a,c),s!=null)for(l=s.length;l--;)vs(s[l]);a||(l="value",y=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[l]||y=="progress"&&!g||y=="option"&&g!=m[l])&&Yi(t,l,g,m[l],r),l="checked",f!=null&&f!=t[l]&&Yi(t,l,f,m[l],r))}return t}function Cs(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(r){j.__e(r,n)}}function fc(t,e,n){var i,r;if(j.unmount&&j.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||Cs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){j.__e(s,e)}i.base=i.__P=null}if(i=t.__k)for(r=0;r<i.length;r++)i[r]&&fc(i[r],e,n||typeof t.type!="function");n||vs(t.__e),t.__c=t.__=t.__e=void 0}function Rp(t,e,n){return this.constructor(t,n)}function en(t,e,n){var i,r,s,o;e==document&&(e=document.documentElement),j.__&&j.__(t,e),r=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],ys(e,t=(!i&&n||e).__k=fe(ge,null,[t]),r||bi,bi,e.namespaceURI,!i&&n?[n]:r?null:e.firstChild?vi.call(e.childNodes):null,s,!i&&n?n:r?r.__e:e.firstChild,i,o),uc(s,t,o)}function _s(t,e){en(t,e,_s)}function ws(t,e,n){var i,r,s,o,a=yt({},t.props);for(s in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)s=="key"?i=e[s]:s=="ref"?r=e[s]:a[s]=e[s]===void 0&&o!=null?o[s]:e[s];return arguments.length>2&&(a.children=arguments.length>3?vi.call(arguments,2):n),ki(t.type,a,i||t.key,r||t.ref,null)}function Ae(t){function e(n){var i,r;return this.getChildContext||(i=new Set,(r={})[e.__c]=this,this.getChildContext=function(){return r},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&i.forEach(function(o){o.__e=!0,bs(o)})},this.sub=function(s){i.add(s);var o=s.componentWillUnmount;s.componentWillUnmount=function(){i&&i.delete(s),o&&o.call(s)}}),n.children}return e.__c="__cC"+ic++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}vi=rc.slice,j={__e:function(t,e,n,i){for(var r,s,o;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(t)),o=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(t,i||{}),o=r.__d),o)return r.__E=r}catch(a){t=a}throw t}},Xa=0,Qa=function(t){return t!=null&&t.constructor==null},nt.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=yt({},this.state),typeof t=="function"&&(t=t(yt({},n),this.props)),t&&yt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),bs(this))},nt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),bs(this))},nt.prototype.render=ge,wn=[],ec=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,tc=function(t,e){return t.__v.__b-e.__v.__b},Ji.__r=0,nc=/(PointerCapture)$|Capture$/i,ps=0,ms=dc(!1),gs=dc(!0),ic=0;function Xi(){return Xi=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Xi.apply(this,arguments)}var Ip=["context","children"];function Op(t,e,n,i){function r(){var s=Reflect.construct(HTMLElement,[],r);return s._vdomComponent=t,s._root=i&&i.shadow?s.attachShadow({mode:i.mode||"open"}):s,s}return(r.prototype=Object.create(HTMLElement.prototype)).constructor=r,r.prototype.connectedCallback=Ap,r.prototype.attributeChangedCallback=Mp,r.prototype.disconnectedCallback=Np,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),r.observedAttributes=n,n.forEach(function(s){Object.defineProperty(r.prototype,s,{get:function(){return this._vdom.props[s]},set:function(o){this._vdom?this.attributeChangedCallback(s,null,o):(this._props||(this._props={}),this._props[s]=o,this.connectedCallback());var a=typeof o;o!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(s,o)}})}),customElements.define(e||t.tagName||t.displayName||t.name,r)}function Dp(t){this.getChildContext=function(){return t.context};var e=t.children,n=(function(i,r){if(i==null)return{};var s,o,a={},c=Object.keys(i);for(o=0;o<c.length;o++)r.indexOf(s=c[o])>=0||(a[s]=i[s]);return a})(t,Ip);return ws(e,n)}function Ap(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=fe(Dp,Xi({},this._props,{context:t.detail.context}),gc(this,this._vdomComponent)),(this.hasAttribute("hydrate")?_s:en)(this._vdom,this._root)}function pc(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Mp(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[pc(t)]=n,this._vdom=ws(this._vdom,i),en(this._vdom,this._root)}}function Np(){en(this._vdom=null,this._root)}function mc(t,e){var n=this;return fe("slot",Xi({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(r){r.stopPropagation(),r.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function gc(t,e){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var n=[],i={},r=0,s=t.attributes,o=t.childNodes;for(r=s.length;r--;)s[r].name!=="slot"&&(i[s[r].name]=s[r].value,i[pc(s[r].name)]=s[r].value);for(r=o.length;r--;){var a=gc(o[r],null),c=o[r].slot;c?i[c]=fe(mc,{name:c},a):n[r]=a}var l=e?fe(mc,null,n):n;return fe(e||t.nodeName.toLowerCase(),i,l)}var Lp=0;function b(t,e,n,i,r,s){e||(e={});var o,a,c=e;if("ref"in c)for(a in c={},e)a=="ref"?o=e[a]:c[a]=e[a];var l={type:t,props:c,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Lp,__i:-1,__u:0,__source:r,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(a in o)c[a]===void 0&&(c[a]=o[a]);return j.vnode&&j.vnode(l),l}var Nt,ae,Ss,vc,Bn=0,bc=[],ve=j,yc=ve.__b,kc=ve.__r,Cc=ve.diffed,_c=ve.__c,wc=ve.unmount,Sc=ve.__;function Sn(t,e){ve.__h&&ve.__h(ae,t,Bn||e),Bn=0;var n=ae.__H||(ae.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function F(t){return Bn=1,Qi(xc,t)}function Qi(t,e,n){var i=Sn(Nt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):xc(void 0,e),function(a){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,a);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=ae,!ae.__f)){var r=function(a,c,l){if(!i.__c.__H)return!0;var d=i.__c.__H.__.filter(function(h){return!!h.__c});if(d.every(function(h){return!h.__N}))return!s||s.call(this,a,c,l);var u=i.__c.props!==a;return d.forEach(function(h){if(h.__N){var p=h.__[0];h.__=h.__N,h.__N=void 0,p!==h.__[0]&&(u=!0)}}),s&&s.call(this,a,c,l)||u};ae.__f=!0;var s=ae.shouldComponentUpdate,o=ae.componentWillUpdate;ae.componentWillUpdate=function(a,c,l){if(this.__e){var d=s;s=void 0,r(a,c,l),s=d}o&&o.call(this,a,c,l)},ae.shouldComponentUpdate=r}return i.__N||i.__}function H(t,e){var n=Sn(Nt++,3);!ve.__s&&Rs(n.__H,e)&&(n.__=t,n.u=e,ae.__H.__h.push(n))}function Lt(t,e){var n=Sn(Nt++,4);!ve.__s&&Rs(n.__H,e)&&(n.__=t,n.u=e,ae.__h.push(n))}function B(t){return Bn=5,ce(function(){return{current:t}},[])}function Ts(t,e,n){Bn=6,Lt(function(){if(typeof t=="function"){var i=t(e());return function(){t(null),i&&typeof i=="function"&&i()}}if(t)return t.current=e(),function(){return t.current=null}},n==null?n:n.concat(t))}function ce(t,e){var n=Sn(Nt++,7);return Rs(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function z(t,e){return Bn=8,ce(function(){return t},e)}function tn(t){var e=ae.context[t.__c],n=Sn(Nt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ae)),e.props.value):t.__}function xs(t,e){ve.useDebugValue&&ve.useDebugValue(e?e(t):t)}function Up(t){var e=Sn(Nt++,10),n=F();return e.__=t,ae.componentDidCatch||(ae.componentDidCatch=function(i,r){e.__&&e.__(i,r),n[1](i)}),[n[0],function(){n[1](void 0)}]}function Es(){var t=Sn(Nt++,11);if(!t.__){for(var e=ae.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function Fp(){for(var t;t=bc.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Zi),t.__H.__h.forEach(Ps),t.__H.__h=[]}catch(e){t.__H.__h=[],ve.__e(e,t.__v)}}ve.__b=function(t){ae=null,yc&&yc(t)},ve.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Sc&&Sc(t,e)},ve.__r=function(t){kc&&kc(t),Nt=0;var e=(ae=t.__c).__H;e&&(Ss===ae?(e.__h=[],ae.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Zi),e.__h.forEach(Ps),e.__h=[],Nt=0)),Ss=ae},ve.diffed=function(t){Cc&&Cc(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(bc.push(e)!==1&&vc===ve.requestAnimationFrame||((vc=ve.requestAnimationFrame)||Bp)(Fp)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ss=ae=null},ve.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Zi),n.__h=n.__h.filter(function(i){return!i.__||Ps(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],ve.__e(i,n.__v)}}),_c&&_c(t,e)},ve.unmount=function(t){wc&&wc(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{Zi(i)}catch(r){e=r}}),n.__H=void 0,e&&ve.__e(e,n.__v))};var Tc=typeof requestAnimationFrame=="function";function Bp(t){var e,n=function(){clearTimeout(i),Tc&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Tc&&(e=requestAnimationFrame(n))}function Zi(t){var e=ae,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ae=e}function Ps(t){var e=ae;t.__c=t.__(),ae=e}function Rs(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function xc(t,e){return typeof e=="function"?e(t):e}function Ec(t,e){for(var n in e)t[n]=e[n];return t}function Is(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var i in e)if(i!=="__source"&&t[i]!==e[i])return!0;return!1}function Os(t,e){var n=e(),i=F({t:{__:n,u:e}}),r=i[0].t,s=i[1];return Lt(function(){r.__=n,r.u=e,Ds(r)&&s({t:r})},[t,n,e]),H(function(){return Ds(r)&&s({t:r}),t(function(){Ds(r)&&s({t:r})})},[t]),n}function Ds(t){var e,n,i=t.u,r=t.__;try{var s=i();return!((e=r)===(n=s)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function As(t){t()}function Ms(t){return t}function Ns(){return[!1,As]}var Ls=Lt;function er(t,e){this.props=t,this.context=e}function tr(t,e){function n(r){var s=this.props.ref,o=s==r.ref;return!o&&s&&(s.call?s(null):s.current=null),e?!e(this.props,r)||!o:Is(this.props,r)}function i(r){return this.shouldComponentUpdate=n,fe(t,r)}return i.displayName="Memo("+(t.displayName||t.name)+")",i.prototype.isReactComponent=!0,i.__f=!0,i.type=t,i}(er.prototype=new nt).isPureReactComponent=!0,er.prototype.shouldComponentUpdate=function(t,e){return Is(this.props,t)||Is(this.state,e)};var Pc=j.__b;j.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Pc&&Pc(t)};var jp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Y(t){function e(n){var i=Ec({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=jp,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Rc=function(t,e){return t==null?null:Mt(Mt(t).map(e))},nn={map:Rc,forEach:Rc,count:function(t){return t?Mt(t).length:0},only:function(t){var e=Mt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Mt},Vp=j.__e;j.__e=function(t,e,n,i){if(t.then){for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),r.__c(t,e)}Vp(t,e,n,i)};var Ic=j.unmount;function Oc(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),t.__c.__H=null),(t=Ec({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(i){return Oc(i,e,n)})),t}function Dc(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return Dc(i,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function Ci(){this.__u=0,this.o=null,this.__b=null}function Ac(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Mc(t){var e,n,i;function r(s){if(e||(e=t()).then(function(o){n=o.default||o},function(o){i=o}),i)throw i;if(!n)throw e;return fe(n,s)}return r.displayName="Lazy",r.__f=!0,r}function jn(){this.i=null,this.l=null}j.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Ic&&Ic(t)},(Ci.prototype=new nt).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var r=Ac(i.__v),s=!1,o=function(){s||(s=!0,n.__R=null,r?r(a):a())};n.__R=o;var a=function(){if(!--i.__u){if(i.state.__a){var c=i.state.__a;i.__v.__k[0]=Dc(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(o,o)},Ci.prototype.componentWillUnmount=function(){this.o=[]},Ci.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Oc(this.__b,n,i.__O=i.__P)}this.__b=null}var r=e.__a&&fe(ge,null,t.fallback);return r&&(r.__u&=-33),[fe(ge,null,e.__a?null:t.children),r]};var Nc=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};function qp(t){return this.getChildContext=function(){return t.context},t.children}function $p(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){en(null,e.v),e.v=null,e.h=null},e.h&&e.h!==n&&e.componentWillUnmount(),!e.v){for(var i=e.__v;i!==null&&!i.__m&&i.__!==null;)i=i.__;e.h=n,e.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:i.__m},contains:function(){return!0},insertBefore:function(r,s){this.childNodes.push(r),e.h.insertBefore(r,s)},removeChild:function(r){this.childNodes.splice(this.childNodes.indexOf(r)>>>1,1),e.h.removeChild(r)}}}en(fe(qp,{context:e.context},t.__v),e.v)}function nr(t,e){var n=fe($p,{__v:t,h:e});return n.containerInfo=e,n}(jn.prototype=new nt).__a=function(t){var e=this,n=Ac(e.__v),i=e.l.get(t);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Nc(e,t,i)):r()};n?n(s):s()}},jn.prototype.render=function(t){this.i=null,this.l=new Map;var e=Mt(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},jn.prototype.componentDidUpdate=jn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Nc(t,n,e)})};var Lc=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,zp=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Wp=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Hp=/[A-Z0-9]/g,Gp=typeof document<"u",Kp=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function Uc(t,e,n){return e.__k==null&&(e.textContent=""),en(t,e),typeof n=="function"&&n(),t?t.__c:null}function Fc(t,e,n){return _s(t,e),typeof n=="function"&&n(),t?t.__c:null}nt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(nt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Bc=j.event;function Jp(){}function Yp(){return this.cancelBubble}function Xp(){return this.defaultPrevented}j.event=function(t){return Bc&&(t=Bc(t)),t.persist=Jp,t.isPropagationStopped=Yp,t.isDefaultPrevented=Xp,t.nativeEvent=t};var Us,Qp={enumerable:!1,configurable:!0,get:function(){return this.class}},jc=j.vnode;j.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,i=e.type,r={},s=i.indexOf("-")===-1;for(var o in n){var a=n[o];if(!(o==="value"&&"defaultValue"in n&&a==null||Gp&&o==="children"&&i==="noscript"||o==="class"||o==="className")){var c=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?o="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||Kp(n.type)?c==="onfocus"?o="onfocusin":c==="onblur"?o="onfocusout":Wp.test(o)&&(o=c):c=o="oninput":s&&zp.test(o)?o=o.replace(Hp,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&r[o=c]&&(o="oninputCapture"),r[o]=a}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=Mt(n.children).forEach(function(l){l.props.selected=r.value.indexOf(l.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=Mt(n.children).forEach(function(l){l.props.selected=r.multiple?r.defaultValue.indexOf(l.props.value)!=-1:r.defaultValue==l.props.value})),n.class&&!n.className?(r.class=n.class,Object.defineProperty(r,"className",Qp)):(n.className&&!n.class||n.class&&n.className)&&(r.class=r.className=n.className),e.props=r})(t),t.$$typeof=Lc,jc&&jc(t)};var Vc=j.__r;j.__r=function(t){Vc&&Vc(t),Us=t.__c};var qc=j.diffed;j.diffed=function(t){qc&&qc(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value),Us=null};var $c={ReactCurrentDispatcher:{current:{readContext:function(t){return Us.__n[t.__c].props.value},useCallback:z,useContext:tn,useDebugValue:xs,useDeferredValue:Ms,useEffect:H,useId:Es,useImperativeHandle:Ts,useInsertionEffect:Ls,useLayoutEffect:Lt,useMemo:ce,useReducer:Qi,useRef:B,useState:F,useSyncExternalStore:Os,useTransition:Ns}}},Zp="18.3.1";function zc(t){return fe.bind(null,t)}function Ut(t){return!!t&&t.$$typeof===Lc}function Wc(t){return Ut(t)&&t.type===ge}function Hc(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function _i(t){return Ut(t)?ws.apply(null,arguments):t}function Gc(t){return!!t.__k&&(en(null,t),!0)}function Kc(t){return t&&(t.base||t.nodeType===1&&t)||null}var Jc=function(t,e){return t(e)},ir=function(t,e){return t(e)},Yc=ge,Xc=Ut,Ft={useState:F,useId:Es,useReducer:Qi,useEffect:H,useLayoutEffect:Lt,useInsertionEffect:Ls,useTransition:Ns,useDeferredValue:Ms,useSyncExternalStore:Os,startTransition:As,useRef:B,useImperativeHandle:Ts,useMemo:ce,useCallback:z,useContext:tn,useDebugValue:xs,version:"18.3.1",Children:nn,render:Uc,hydrate:Fc,unmountComponentAtNode:Gc,createPortal:nr,createElement:fe,createContext:Ae,createFactory:zc,cloneElement:_i,createRef:sc,Fragment:ge,isValidElement:Ut,isElement:Xc,isFragment:Wc,isMemo:Hc,findDOMNode:Kc,Component:nt,PureComponent:er,memo:tr,forwardRef:Y,flushSync:ir,unstable_batchedUpdates:Jc,StrictMode:Yc,Suspense:Ci,SuspenseList:jn,lazy:Mc,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:$c};const Qc=Object.freeze(Object.defineProperty({__proto__:null,Children:nn,Component:nt,Fragment:ge,PureComponent:er,StrictMode:Yc,Suspense:Ci,SuspenseList:jn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:$c,cloneElement:_i,createContext:Ae,createElement:fe,createFactory:zc,createPortal:nr,createRef:sc,default:Ft,findDOMNode:Kc,flushSync:ir,forwardRef:Y,hydrate:Fc,isElement:Xc,isFragment:Wc,isMemo:Hc,isValidElement:Ut,lazy:Mc,memo:tr,render:Uc,startTransition:As,unmountComponentAtNode:Gc,unstable_batchedUpdates:Jc,useCallback:z,useContext:tn,useDebugValue:xs,useDeferredValue:Ms,useEffect:H,useErrorBoundary:Up,useId:Es,useImperativeHandle:Ts,useInsertionEffect:Ls,useLayoutEffect:Lt,useMemo:ce,useReducer:Qi,useRef:B,useState:F,useSyncExternalStore:Os,useTransition:Ns,version:Zp},Symbol.toStringTag,{value:"Module"}));var em=Symbol.for("preact-signals");function rr(){if(rn>1)rn--;else{for(var t,e=!1;wi!==void 0;){var n=wi;for(wi=void 0,Fs++;n!==void 0;){var i=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&nl(n))try{n.c()}catch(r){e||(t=r,e=!0)}n=i}}if(Fs=0,rn--,e)throw t}}function Zc(t){if(rn>0)return t();rn++;try{return t()}finally{rr()}}var ie=void 0;function el(t){var e=ie;ie=void 0;try{return t()}finally{ie=e}}var wi=void 0,rn=0,Fs=0,sr=0;function tl(t){if(ie!==void 0){var e=t.n;if(e===void 0||e.t!==ie)return e={i:0,S:t,p:ie.s,n:void 0,t:ie,e:void 0,x:void 0,r:e},ie.s!==void 0&&(ie.s.n=e),ie.s=e,t.n=e,32&ie.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=ie.s,e.n=void 0,ie.s.n=e,ie.s=e),e}}function Me(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e==null?void 0:e.watched,this.Z=e==null?void 0:e.unwatched,this.name=e==null?void 0:e.name}Me.prototype.brand=em,Me.prototype.h=function(){return!0},Me.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:el(function(){var i;(i=e.W)==null||i.call(e)}))},Me.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,i=t.x;n!==void 0&&(n.x=i,t.e=void 0),i!==void 0&&(i.e=n,t.x=void 0),t===this.t&&(this.t=i,i===void 0&&el(function(){var r;(r=e.Z)==null||r.call(e)}))}},Me.prototype.subscribe=function(t){var e=this;return qn(function(){var n=e.value,i=ie;ie=void 0;try{t(n)}finally{ie=i}},{name:"sub"})},Me.prototype.valueOf=function(){return this.value},Me.prototype.toString=function(){return this.value+""},Me.prototype.toJSON=function(){return this.value},Me.prototype.peek=function(){var t=ie;ie=void 0;try{return this.value}finally{ie=t}},Object.defineProperty(Me.prototype,"value",{get:function(){var t=tl(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Fs>100)throw new Error("Cycle detected");this.v=t,this.i++,sr++,rn++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{rr()}}}});function Ge(t,e){return new Me(t,e)}function nl(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function il(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function rl(t){for(var e=t.s,n=void 0;e!==void 0;){var i=e.p;e.i===-1?(e.S.U(e),i!==void 0&&(i.n=e.n),e.n!==void 0&&(e.n.p=i)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=i}t.s=n}function Tn(t,e){Me.call(this,void 0),this.x=t,this.s=void 0,this.g=sr-1,this.f=4,this.W=e==null?void 0:e.watched,this.Z=e==null?void 0:e.unwatched,this.name=e==null?void 0:e.name}Tn.prototype=new Me,Tn.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===sr))return!0;if(this.g=sr,this.f|=1,this.i>0&&!nl(this))return this.f&=-2,!0;var t=ie;try{il(this),ie=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return ie=t,rl(this),this.f&=-2,!0},Tn.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}Me.prototype.S.call(this,t)},Tn.prototype.U=function(t){if(this.t!==void 0&&(Me.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},Tn.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(Tn.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=tl(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function Ke(t,e){return new Tn(t,e)}function sl(t){var e=t.u;if(t.u=void 0,typeof e=="function"){rn++;var n=ie;ie=void 0;try{e()}catch(i){throw t.f&=-2,t.f|=8,Bs(t),i}finally{ie=n,rr()}}}function Bs(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,sl(t)}function tm(t){if(ie!==this)throw new Error("Out-of-order effect");rl(this),ie=t,this.f&=-2,8&this.f&&Bs(this),rr()}function Vn(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e==null?void 0:e.name}Vn.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Vn.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,sl(this),il(this),rn++;var t=ie;return ie=this,tm.bind(this,t)},Vn.prototype.N=function(){2&this.f||(this.f|=2,this.o=wi,wi=this)},Vn.prototype.d=function(){this.f|=8,1&this.f||Bs(this)},Vn.prototype.dispose=function(){this.d()};function qn(t,e){var n=new Vn(t,e);try{n.c()}catch(r){throw n.d(),r}var i=n.d.bind(n);return i[Symbol.dispose]=i,i}var js,or,Vs,ol=[],al=[];qn(function(){js=this.N})();function $n(t,e){j[t]=e.bind(null,j[t]||function(){})}function ar(t){Vs&&Vs(),Vs=t&&t.S()}function cl(t){var e=this,n=t.data,i=Je(n);i.value=n;var r=ce(function(){for(var a=e,c=e.__v;c=c.__;)if(c.__c){c.__c.__$f|=4;break}var l=Ke(function(){var p=i.value.value;return p===0?0:p===!0?"":p||""}),d=Ke(function(){return!Array.isArray(l.value)&&!Qa(l.value)}),u=qn(function(){if(this.N=ll,d.value){var p=l.value;a.__v&&a.__v.__e&&a.__v.__e.nodeType===3&&(a.__v.__e.data=p)}}),h=e.__$u.d;return e.__$u.d=function(){u(),h.call(this)},[d,l]},[]),s=r[0],o=r[1];return s.value?o.peek():o.value}cl.displayName="ReactiveTextNode",Object.defineProperties(Me.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:cl},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),$n("__b",function(t,e){if(typeof e.type=="function"&&typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent(),typeof e.type=="string"){var n,i=e.props;for(var r in i)if(r!=="children"){var s=i[r];s instanceof Me&&(n||(e.__np=n={}),n[r]=s,i[r]=s.peek())}}t(e)}),$n("__r",function(t,e){if(typeof e.type=="function"&&typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.enterComponent(e.type.displayName||e.type.name||"Unknown"),e.type!==ge){ar();var n,i=e.__c;i&&(i.__$f&=-2,(n=i.__$u)===void 0&&(i.__$u=n=(function(r){var s;return qn(function(){s=this}),s.c=function(){i.__$f|=1,i.setState({})},s})())),or=i,ar(n)}t(e)}),$n("__e",function(t,e,n,i){typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent(),ar(),or=void 0,t(e,n,i)}),$n("diffed",function(t,e){typeof e.type=="function"&&typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent(),ar(),or=void 0;var n;if(typeof e.type=="string"&&(n=e.__e)){var i=e.__np,r=e.props;if(i){var s=n.U;if(s)for(var o in s){var a=s[o];a!==void 0&&!(o in i)&&(a.d(),s[o]=void 0)}else s={},n.U=s;for(var c in i){var l=s[c],d=i[c];l===void 0?(l=nm(n,c,d,r),s[c]=l):l.o(d,r)}}}t(e)});function nm(t,e,n,i){var r=e in t&&t.ownerSVGElement===void 0,s=Ge(n);return{o:function(o,a){s.value=o,i=a},d:qn(function(){this.N=ll;var o=s.value.value;i[e]!==o&&(i[e]=o,r?t[e]=o:o?t.setAttribute(e,o):t.removeAttribute(e))})}}$n("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var i=n.U;if(i){n.U=void 0;for(var r in i){var s=i[r];s&&s.d()}}}}else{var o=e.__c;if(o){var a=o.__$u;a&&(o.__$u=void 0,a.d())}}t(e)}),$n("__h",function(t,e,n,i){(i<3||i===9)&&(e.__$f|=2),t(e,n,i)}),nt.prototype.shouldComponentUpdate=function(t,e){var n=this.__$u,i=n&&n.s!==void 0;for(var r in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(i||s||4&this.__$f)||1&this.__$f)return!0}else if(!(i||4&this.__$f)||3&this.__$f)return!0;for(var o in t)if(o!=="__source"&&t[o]!==this.props[o])return!0;for(var a in this.props)if(!(a in t))return!0;return!1};function Je(t,e){return F(function(){return Ge(t,e)})[0]}function de(t,e){var n=B(t);return n.current=t,or.__$f|=4,ce(function(){return Ke(function(){return n.current()},e)},[])}var im=typeof requestAnimationFrame>"u"?setTimeout:function(t){var e=function(){clearTimeout(n),cancelAnimationFrame(i),t()},n=setTimeout(e,35),i=requestAnimationFrame(e)},rm=function(t){queueMicrotask(function(){queueMicrotask(t)})};function sm(){Zc(function(){for(var t;t=ol.shift();)js.call(t)})}function om(){ol.push(this)===1&&(j.requestAnimationFrame||im)(sm)}function am(){Zc(function(){for(var t;t=al.shift();)js.call(t)})}function ll(){al.push(this)===1&&(j.requestAnimationFrame||rm)(am)}function Bt(t,e){var n=B(t);n.current=t,H(function(){return qn(function(){return this.N=om,n.current()},e)},[])}function cm(t,e){return e.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(i){if(i!=="default"&&!(i in t)){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}})}),Object.freeze(t)}var lm=Object.defineProperty,dm=(t,e,n)=>e in t?lm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dl=(t,e,n)=>dm(t,typeof e!="symbol"?e+"":e,n);let Fe=class{constructor(){dl(this,"_locking"),dl(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const n=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>n),i}};function ye(t,e){if(!t)throw new Error(e)}const um=34028234663852886e22,hm=-34028234663852886e22,fm=4294967295,pm=2147483647,mm=-2147483648;function cr(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>pm||t<mm)throw new Error("invalid int 32: "+t)}function qs(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>fm||t<0)throw new Error("invalid uint 32: "+t)}function ul(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>um||t<hm))throw new Error("invalid float 32: "+t)}const hl=Symbol("@bufbuild/protobuf/enum-type");function gm(t){const e=t[hl];return ye(e,"missing enum type on enum object"),e}function fl(t,e,n,i){t[hl]=pl(e,n.map(r=>({no:r.no,name:r.name,localName:t[r.no]})))}function pl(t,e,n){const i=Object.create(null),r=Object.create(null),s=[];for(const o of e){const a=ml(o);s.push(a),i[o.name]=a,r[o.no]=a}return{typeName:t,values:s,findName(o){return i[o]},findNumber(o){return r[o]}}}function vm(t,e,n){const i={};for(const r of e){const s=ml(r);i[s.localName]=s.no,i[s.no]=s.localName}return fl(i,t,e),i}function ml(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class $s{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,n){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(n);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,n){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(n);return r.readMessage(i,e,s,this),this}fromJsonString(e,n){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,n)}toBinary(e){const n=this.getType(),i=n.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const n=this.getType(),i=n.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var n;const i=this.toJson(e);return JSON.stringify(i,null,(n=e==null?void 0:e.prettySpaces)!==null&&n!==void 0?n:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function bm(t,e,n,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),o={[s]:function(a){t.util.initFields(this),t.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new $s),Object.assign(o,{runtime:t,typeName:e,fields:t.util.newFieldList(n),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return t.util.equals(o,a,c)}}),o}function ym(){let t=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function zs(t,e,n){for(let s=0;s<28;s=s+7){const o=t>>>s,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(n.push(c),!a)return}const i=t>>>28&15|(e&7)<<4,r=e>>3!=0;if(n.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const o=e>>>s,a=!!(o>>>7),c=(a?o|128:o)&255;if(n.push(c),!a)return}n.push(e>>>31&1)}}const lr=4294967296;function gl(t){const e=t[0]==="-";e&&(t=t.slice(1));const n=1e6;let i=0,r=0;function s(o,a){const c=Number(t.slice(o,a));r*=n,i=i*n+c,i>=lr&&(r=r+(i/lr|0),i=i%lr)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?bl(i,r):Ws(i,r)}function km(t,e){let n=Ws(t,e);const i=n.hi&2147483648;i&&(n=bl(n.lo,n.hi));const r=vl(n.lo,n.hi);return i?"-"+r:r}function vl(t,e){if({lo:t,hi:e}=Cm(t,e),e<=2097151)return String(lr*e+t);const n=t&16777215,i=(t>>>24|e<<8)&16777215,r=e>>16&65535;let s=n+i*6777216+r*6710656,o=i+r*8147497,a=r*2;const c=1e7;return s>=c&&(o+=Math.floor(s/c),s%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+yl(o)+yl(s)}function Cm(t,e){return{lo:t>>>0,hi:e>>>0}}function Ws(t,e){return{lo:t|0,hi:e|0}}function bl(t,e){return e=~e,t?t=~t+1:e+=1,Ws(t,e)}const yl=t=>{const e=String(t);return"0000000".slice(e.length)+e};function kl(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function _m(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function wm(){const t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>s||l<r)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return t.setBigInt64(0,this.parse(c),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(c){return t.setBigInt64(0,this.uParse(c),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(c,l){return t.setInt32(0,c,!0),t.setInt32(4,l,!0),t.getBigInt64(0,!0)},uDec(c,l){return t.setInt32(0,c,!0),t.setInt32(4,l,!0),t.getBigUint64(0,!0)}}}const n=r=>ye(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>ye(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),n(r),gl(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),gl(r)},dec(r,s){return km(r,s)},uDec(r,s){return vl(r,s)}}}const pe=wm();var P;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(P||(P={}));var sn;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"})(sn||(sn={}));function on(t,e,n){if(e===n)return!0;if(t==P.BYTES){if(!(e instanceof Uint8Array)||!(n instanceof Uint8Array)||e.length!==n.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==n[i])return!1;return!0}switch(t){case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return e==n}return!1}function zn(t,e){switch(t){case P.BOOL:return!1;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return e==0?pe.zero:"0";case P.DOUBLE:case P.FLOAT:return 0;case P.BYTES:return new Uint8Array(0);case P.STRING:return"";default:return 0}}function Cl(t,e){switch(t){case P.BOOL:return e===!1;case P.STRING:return e==="";case P.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var _e;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(_e||(_e={}));class Sm{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let n=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)n.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(qs(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return cr(e),kl(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.textEncoder.encode(e);return this.uint32(n.byteLength),this.raw(n)}float(e){ul(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){qs(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){cr(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return cr(e),e=(e<<1^e>>31)>>>0,kl(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),r=pe.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),r=pe.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}int64(e){let n=pe.enc(e);return zs(n.lo,n.hi,this.buf),this}sint64(e){let n=pe.enc(e),i=n.hi>>31,r=n.lo<<1^i,s=(n.hi<<1|n.lo>>>31)^i;return zs(r,s,this.buf),this}uint64(e){let n=pe.uEnc(e);return zs(n.lo,n.hi,this.buf),this}}class Tm{constructor(e,n){this.varint64=ym,this.uint32=_m,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=n??new TextDecoder}tag(){let e=this.uint32(),n=e>>>3,i=e&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(e,n){let i=this.pos;switch(e){case _e.Varint:for(;this.buf[this.pos++]&128;);break;case _e.Bit64:this.pos+=4;case _e.Bit32:this.pos+=4;break;case _e.LengthDelimited:let r=this.uint32();this.pos+=r;break;case _e.StartGroup:for(;;){const[s,o]=this.tag();if(o===_e.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return pe.dec(...this.varint64())}uint64(){return pe.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),i=-(e&1);return e=(e>>>1|(n&1)<<31)^i,n=n>>>1^i,pe.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return pe.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return pe.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(){return this.textDecoder.decode(this.bytes())}}function xm(t,e,n,i){let r;return{typeName:e,extendee:n,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=t.util.newFieldList([s]).list()[0]}return r},runtime:t}}function _l(t){const e=t.field.localName,n=Object.create(null);return n[e]=Em(t),[n,()=>n[e]]}function Em(t){const e=t.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return zn(e.T,e.L);case"message":const n=e.T,i=new n;return n.fieldWrapper?n.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function Pm(t,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let n=t.length-1;n>=0;--n)if(t[n].no==e.no)return[t[n]];return[]}return t.filter(n=>n.no===e.no)}let jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),dr=[];for(let t=0;t<jt.length;t++)dr[jt[t].charCodeAt(0)]=t;dr[45]=jt.indexOf("+"),dr[95]=jt.indexOf("/");const wl={dec(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let n=new Uint8Array(e),i=0,r=0,s,o=0;for(let a=0;a<t.length;a++){if(s=dr[t.charCodeAt(a)],s===void 0)switch(t[a]){case"=":r=0;case`
2
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:n[i++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:n[i++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:n[i++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return n.subarray(0,i)},enc(t){let e="",n=0,i,r=0;for(let s=0;s<t.length;s++)switch(i=t[s],n){case 0:e+=jt[i>>2],r=(i&3)<<4,n=1;break;case 1:e+=jt[r|i>>4],r=(i&15)<<2,n=2;break;case 2:e+=jt[r|i>>6],e+=jt[i&63],n=0;break}return n&&(e+=jt[r],e+="=",n==1&&(e+="=")),e}};function Rm(t,e,n){Tl(e,t);const i=e.runtime.bin.makeReadOptions(n),r=Pm(t.getType().runtime.bin.listUnknownFields(t),e.field),[s,o]=_l(e);for(const a of r)e.runtime.bin.readField(s,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function Im(t,e,n,i){Tl(e,t);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(Sl(t,e)){const l=t.getType().runtime.bin.listUnknownFields(t).filter(d=>d.no!=e.field.no);t.getType().runtime.bin.discardUnknownFields(t);for(const d of l)t.getType().runtime.bin.onUnknownField(t,d.no,d.wireType,d.data)}const o=s.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,n,o,s);const c=r.readerFactory(o.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);t.getType().runtime.bin.onUnknownField(t,l,d,u)}}function Sl(t,e){const n=t.getType();return e.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(t).find(i=>i.no==e.field.no)}function Tl(t,e){ye(t.extendee.typeName==e.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function xl(t,e){const n=t.localName;if(t.repeated)return e[n].length>0;if(t.oneof)return e[t.oneof.localName].case===n;switch(t.kind){case"enum":case"scalar":return t.opt||t.req?e[n]!==void 0:t.kind=="enum"?e[n]!==t.T.values[0].no:!Cl(t.T,e[n]);case"message":return e[n]!==void 0;case"map":return Object.keys(e[n]).length>0}}function El(t,e){const n=t.localName,i=!t.opt&&!t.req;if(t.repeated)e[n]=[];else if(t.oneof)e[t.oneof.localName]={case:void 0};else switch(t.kind){case"map":e[n]={};break;case"enum":e[n]=i?t.T.values[0].no:void 0;break;case"scalar":e[n]=i?zn(t.T,t.L):void 0;break;case"message":e[n]=void 0;break}}function Vt(t,e){if(t===null||typeof t!="object"||!Object.getOwnPropertyNames($s.prototype).every(i=>i in t&&typeof t[i]=="function"))return!1;const n=t.getType();return n===null||typeof n!="function"||!("typeName"in n)||typeof n.typeName!="string"?!1:e===void 0?!0:n.typeName==e.typeName}function Pl(t,e){return Vt(e)||!t.fieldWrapper?e:t.fieldWrapper.wrapField(e)}P.DOUBLE,P.FLOAT,P.INT64,P.UINT64,P.INT32,P.UINT32,P.BOOL,P.STRING,P.BYTES;const Rl={ignoreUnknownFields:!1},Il={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Om(t){return t?Object.assign(Object.assign({},Rl),t):Rl}function Dm(t){return t?Object.assign(Object.assign({},Il),t):Il}const ur=Symbol(),hr=Symbol();function Am(){return{makeReadOptions:Om,makeWriteOptions:Dm,readMessage(t,e,n,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(kt(e)));i=i??new t;const r=new Map,s=n.typeRegistry;for(const[o,a]of Object.entries(e)){const c=t.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=r.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));r.set(c.oneof,o)}Ol(i,a,c,n,t)}else{let l=!1;if(s!=null&&s.findExtension&&o.startsWith("[")&&o.endsWith("]")){const d=s.findExtension(o.substring(1,o.length-1));if(d&&d.extendee.typeName==t.typeName){l=!0;const[u,h]=_l(d);Ol(u,a,d.field,n,d),Im(i,d,h(),n)}}if(!l&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(t,e){const n=t.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!xl(r,t)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Nm(r))continue}const o=r.oneof?t[r.oneof.localName].value:t[r.localName],a=Dl(r,o,e);a!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=a)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const o of n.runtime.bin.listUnknownFields(t)){const a=s.findExtensionFor(n.typeName,o.no);if(a&&Sl(t,a)){const c=Rm(t,a,e),l=Dl(a.field,c,e);l!==void 0&&(i[a.field.jsonName]=l)}}}catch(s){const o=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?": ".concat(a):""))}return i},readScalar(t,e,n){return Si(t,e,n??sn.BIGINT,!0)},writeScalar(t,e,n){if(e!==void 0&&(n||Cl(t,e)))return fr(t,e)},debug:kt}}function kt(t){if(t===null)return"null";switch(typeof t){case"object":return Array.isArray(t)?"array":"object";case"string":return t.length>100?"string":'"'.concat(t.split('"').join('\\"'),'"');default:return String(t)}}function Ol(t,e,n,i,r){let s=n.localName;if(n.repeated){if(ye(n.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(kt(e)));const o=t[s];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(kt(a)));switch(n.kind){case"message":o.push(n.T.fromJson(a,i));break;case"enum":const c=Hs(n.T,a,i.ignoreUnknownFields,!0);c!==hr&&o.push(c);break;case"scalar":try{o.push(Si(n.T,a,n.L,!0))}catch(l){let d="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(kt(a));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}}else if(n.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(kt(e)));const o=t[s];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let l;try{l=Mm(n.K,a)}catch(d){let u="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(kt(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(n.V.kind){case"message":o[l]=n.V.T.fromJson(c,i);break;case"enum":const d=Hs(n.V.T,c,i.ignoreUnknownFields,!0);d!==hr&&(o[l]=d);break;case"scalar":try{o[l]=Si(n.V.T,c,sn.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(kt(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(n.oneof&&(t=t[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const o=n.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=t[s];Vt(a)?a.fromJson(e,i):(t[s]=a=o.fromJson(e,i),o.fieldWrapper&&!n.oneof&&(t[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Hs(n.T,e,i.ignoreUnknownFields,!1);switch(c){case ur:El(n,t);break;case hr:break;default:t[s]=c;break}break;case"scalar":try{const l=Si(n.T,e,n.L,!1);switch(l){case ur:El(n,t);break;default:t[s]=l;break}}catch(l){let d="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(kt(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Mm(t,e){if(t===P.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Si(t,e,sn.BIGINT,!0).toString()}function Si(t,e,n,i){if(e===null)return i?zn(t,n):ur;switch(t){case P.DOUBLE:case P.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return t==P.FLOAT&&ul(r),r;case P.INT32:case P.FIXED32:case P.SFIXED32:case P.SINT32:case P.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return t==P.UINT32||t==P.FIXED32?qs(s):cr(s),s;case P.INT64:case P.SFIXED64:case P.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=pe.parse(e);return n?o.toString():o;case P.FIXED64:case P.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=pe.uParse(e);return n?a.toString():a;case P.BOOL:if(typeof e!="boolean")break;return e;case P.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case P.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return wl.dec(e)}throw new Error}function Hs(t,e,n,i){if(e===null)return t.typeName=="google.protobuf.NullValue"?0:i?t.values[0].no:ur;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=t.findName(e);if(r!==void 0)return r.no;if(n)return hr;break}throw new Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(kt(e)))}function Nm(t){return t.repeated||t.kind=="map"?!0:!(t.oneof||t.kind=="message"||t.opt||t.req)}function Dl(t,e,n){if(t.kind=="map"){ye(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(t.V.kind){case"scalar":for(const[o,a]of r)i[o.toString()]=fr(t.V.T,a);break;case"message":for(const[o,a]of r)i[o.toString()]=a.toJson(n);break;case"enum":const s=t.V.T;for(const[o,a]of r)i[o.toString()]=Gs(s,a,n.enumAsInteger);break}return n.emitDefaultValues||r.length>0?i:void 0}if(t.repeated){ye(Array.isArray(e));const i=[];switch(t.kind){case"scalar":for(let r=0;r<e.length;r++)i.push(fr(t.T,e[r]));break;case"enum":for(let r=0;r<e.length;r++)i.push(Gs(t.T,e[r],n.enumAsInteger));break;case"message":for(let r=0;r<e.length;r++)i.push(e[r].toJson(n));break}return n.emitDefaultValues||i.length>0?i:void 0}switch(t.kind){case"scalar":return fr(t.T,e);case"enum":return Gs(t.T,e,n.enumAsInteger);case"message":return Pl(t.T,e).toJson(n)}}function Gs(t,e,n){var i;if(ye(typeof e=="number"),t.typeName=="google.protobuf.NullValue")return null;if(n)return e;const r=t.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function fr(t,e){switch(t){case P.INT32:case P.SFIXED32:case P.SINT32:case P.FIXED32:case P.UINT32:return ye(typeof e=="number"),e;case P.FLOAT:case P.DOUBLE:return ye(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case P.STRING:return ye(typeof e=="string"),e;case P.BOOL:return ye(typeof e=="boolean"),e;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return ye(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case P.BYTES:return ye(e instanceof Uint8Array),wl.enc(e)}}const Wn=Symbol("@bufbuild/protobuf/unknown-fields"),Al={readUnknownFields:!0,readerFactory:t=>new Tm(t)},Ml={writeUnknownFields:!0,writerFactory:()=>new Sm};function Lm(t){return t?Object.assign(Object.assign({},Al),t):Al}function Um(t){return t?Object.assign(Object.assign({},Ml),t):Ml}function Fm(){return{makeReadOptions:Lm,makeWriteOptions:Um,listUnknownFields(t){var e;return(e=t[Wn])!==null&&e!==void 0?e:[]},discardUnknownFields(t){delete t[Wn]},writeUnknownFields(t,e){const i=t[Wn];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(t,e,n,i){const r=t;Array.isArray(r[Wn])||(r[Wn]=[]),r[Wn].push({no:e,wireType:n,data:i})},readMessage(t,e,n,i,r){const s=t.getType(),o=r?e.len:e.pos+n;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(r===!0&&c==_e.EndGroup));){const l=s.fields.find(a);if(!l){const d=e.skip(c,a);i.readUnknownFields&&this.onUnknownField(t,a,c,d);continue}Nl(t,e,l,c,i)}if(r&&(c!=_e.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:Nl,writeMessage(t,e,n){const i=t.getType();for(const r of i.fields.byNumber()){if(!xl(r,t)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?t[r.oneof.localName].value:t[r.localName];Ll(r,s,e,n)}return n.writeUnknownFields&&this.writeUnknownFields(t,e),e},writeField(t,e,n,i){e!==void 0&&Ll(t,e,n,i)}}}function Nl(t,e,n,i,r){let{repeated:s,localName:o}=n;switch(n.oneof&&(t=t[n.oneof.localName],t.case!=o&&delete t.value,t.case=o,o="value"),n.kind){case"scalar":case"enum":const a=n.kind=="enum"?P.INT32:n.T;let c=mr;if(n.kind=="scalar"&&n.L>0&&(c=jm),s){let h=t[o];if(i==_e.LengthDelimited&&a!=P.STRING&&a!=P.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,a))}else h.push(c(e,a))}else t[o]=c(e,a);break;case"message":const l=n.T;s?t[o].push(pr(e,new l,r,n)):Vt(t[o])?pr(e,t[o],r,n):(t[o]=pr(e,new l,r,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(t[o]=l.fieldWrapper.unwrapField(t[o])));break;case"map":let[d,u]=Bm(n,e,r);t[o][d]=u;break}}function pr(t,e,n,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,t,s?i.no:t.uint32(),n,s),e}function Bm(t,e,n){const i=e.uint32(),r=e.pos+i;let s,o;for(;e.pos<r;){const[a]=e.tag();switch(a){case 1:s=mr(e,t.K);break;case 2:switch(t.V.kind){case"scalar":o=mr(e,t.V.T);break;case"enum":o=e.int32();break;case"message":o=pr(e,new t.V.T,n,void 0);break}break}}if(s===void 0&&(s=zn(t.K,sn.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),o===void 0)switch(t.V.kind){case"scalar":o=zn(t.V.T,sn.BIGINT);break;case"enum":o=t.V.T.values[0].no;break;case"message":o=new t.V.T;break}return[s,o]}function jm(t,e){const n=mr(t,e);return typeof n=="bigint"?n.toString():n}function mr(t,e){switch(e){case P.STRING:return t.string();case P.BOOL:return t.bool();case P.DOUBLE:return t.double();case P.FLOAT:return t.float();case P.INT32:return t.int32();case P.INT64:return t.int64();case P.UINT64:return t.uint64();case P.FIXED64:return t.fixed64();case P.BYTES:return t.bytes();case P.FIXED32:return t.fixed32();case P.SFIXED32:return t.sfixed32();case P.SFIXED64:return t.sfixed64();case P.SINT64:return t.sint64();case P.UINT32:return t.uint32();case P.SINT32:return t.sint32()}}function Ll(t,e,n,i){ye(e!==void 0);const r=t.repeated;switch(t.kind){case"scalar":case"enum":let s=t.kind=="enum"?P.INT32:t.T;if(r)if(ye(Array.isArray(e)),t.packed)qm(n,s,t.no,e);else for(const o of e)Ti(n,s,t.no,o);else Ti(n,s,t.no,e);break;case"message":if(r){ye(Array.isArray(e));for(const o of e)Ul(n,i,t,o)}else Ul(n,i,t,e);break;case"map":ye(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))Vm(n,i,t,o,a);break}}function Vm(t,e,n,i,r){t.tag(n.no,_e.LengthDelimited),t.fork();let s=i;switch(n.K){case P.INT32:case P.FIXED32:case P.UINT32:case P.SFIXED32:case P.SINT32:s=Number.parseInt(i);break;case P.BOOL:ye(i=="true"||i=="false"),s=i=="true";break}switch(Ti(t,n.K,1,s),n.V.kind){case"scalar":Ti(t,n.V.T,2,r);break;case"enum":Ti(t,P.INT32,2,r);break;case"message":ye(r!==void 0),t.tag(2,_e.LengthDelimited).bytes(r.toBinary(e));break}t.join()}function Ul(t,e,n,i){const r=Pl(n.T,i);n.delimited?t.tag(n.no,_e.StartGroup).raw(r.toBinary(e)).tag(n.no,_e.EndGroup):t.tag(n.no,_e.LengthDelimited).bytes(r.toBinary(e))}function Ti(t,e,n,i){ye(i!==void 0);let[r,s]=Fl(e);t.tag(n,r)[s](i)}function qm(t,e,n,i){if(!i.length)return;t.tag(n,_e.LengthDelimited).fork();let[,r]=Fl(e);for(let s=0;s<i.length;s++)t[r](i[s]);t.join()}function Fl(t){let e=_e.Varint;switch(t){case P.BYTES:case P.STRING:e=_e.LengthDelimited;break;case P.DOUBLE:case P.FIXED64:case P.SFIXED64:e=_e.Bit64;break;case P.FIXED32:case P.SFIXED32:case P.FLOAT:e=_e.Bit32;break}const n=P[t].toLowerCase();return[e,n]}function $m(){return{setEnumType:fl,initPartial(t,e){if(t===void 0)return;const n=e.getType();for(const i of n.fields.byMember()){const r=i.localName,s=e,o=t;if(o[r]!=null)switch(i.kind){case"oneof":const a=o[r].case;if(a===void 0)continue;const c=i.findField(a);let l=o[r].value;c&&c.kind=="message"&&!Vt(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===P.BYTES&&(l=xi(l)),s[r]={case:a,value:l};break;case"scalar":case"enum":let d=o[r];i.T===P.BYTES&&(d=i.repeated?d.map(xi):xi(d)),s[r]=d;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===P.BYTES)for(const[p,g]of Object.entries(o[r]))s[r][p]=xi(g);else Object.assign(s[r],o[r]);break;case"message":const h=i.V.T;for(const p of Object.keys(o[r])){let g=o[r][p];h.fieldWrapper||(g=new h(g)),s[r][p]=g}break}break;case"message":const u=i.T;if(i.repeated)s[r]=o[r].map(h=>Vt(h,u)?h:new u(h));else{const h=o[r];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?s[r]=xi(h):s[r]=h:s[r]=Vt(h,u)?h:new u(h)}break}}},equals(t,e,n){return e===n?!0:!e||!n?!1:t.fields.byMember().every(i=>{const r=e[i.localName],s=n[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((o,a)=>i.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>on(i.T,o,s[a]));case"enum":return r.every((o,a)=>on(P.INT32,o,s[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=r,a=s;return i.T.fieldWrapper&&(o!==void 0&&!Vt(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!Vt(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return on(P.INT32,r,s);case"scalar":return on(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=i.findField(r.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(r.value,s.value);case"enum":return on(P.INT32,r.value,s.value);case"scalar":return on(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const d=i.V.T;return l.every(h=>d.equals(r[h],s[h]));case"enum":return l.every(h=>on(P.INT32,r[h],s[h]));case"scalar":const u=i.V.T;return l.every(h=>on(u,r[h],s[h]))}break}})},clone(t){const e=t.getType(),n=new e,i=n;for(const r of e.fields.byMember()){const s=t[r.localName];let o;if(r.repeated)o=s.map(gr);else if(r.kind=="map"){o=i[r.localName];for(const[a,c]of Object.entries(s))o[a]=gr(c)}else r.kind=="oneof"?o=r.findField(s.case)?{case:s.case,value:gr(s.value)}:{case:void 0}:o=gr(s);i[r.localName]=o}for(const r of e.runtime.bin.listUnknownFields(t))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return n}}}function gr(t){if(t===void 0)return t;if(Vt(t))return t.clone();if(t instanceof Uint8Array){const e=new Uint8Array(t.byteLength);return e.set(t),e}return t}function xi(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function zm(t,e,n){return{syntax:t,json:Am(),bin:Fm(),util:Object.assign(Object.assign({},$m()),{newFieldList:e,initFields:n}),makeMessageType(i,r,s){return bm(this,i,r,s)},makeEnum:vm,makeEnumType:pl,getEnumType:gm,makeExtension(i,r,s){return xm(this,i,r,s)}}}class Wm{constructor(e,n){this._fields=e,this._normalizer=n}findJsonName(e){if(!this.jsonNames){const n={};for(const i of this.list())n[i.jsonName]=n[i.name]=i;this.jsonNames=n}return this.jsonNames[e]}find(e){if(!this.numbers){const n={};for(const i of this.list())n[i.no]=i;this.numbers=n}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,n)=>e.no-n.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let n;for(const i of this.list())i.oneof?i.oneof!==n&&(n=i.oneof,e.push(n)):e.push(i)}return this.members}}function Bl(t,e){const n=jl(t);return e?n:Xm(Ym(n))}function Hm(t){return Bl(t,!1)}const Gm=jl;function jl(t){let e=!1;const n=[];for(let i=0;i<t.length;i++){let r=t.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),n.push(r);break}}return n.join("")}const Km=new Set(["constructor","toString","toJSON","valueOf"]),Jm=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Vl=t=>"".concat(t,"$"),Ym=t=>Jm.has(t)?Vl(t):t,Xm=t=>Km.has(t)?Vl(t):t;class Qm{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Hm(e)}addField(e){ye(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let n=0;n<this.fields.length;n++)this._lookup[this.fields[n].localName]=this.fields[n]}return this._lookup[e]}}function Zm(t,e){var n,i,r,s,o,a;const c=[];let l;for(const d of typeof t=="function"?t():t){const u=d;if(u.localName=Bl(d.name,d.oneof!==void 0),u.jsonName=(n=d.jsonName)!==null&&n!==void 0?n:Gm(d.name),u.repeated=(i=d.repeated)!==null&&i!==void 0?i:!1,d.kind=="scalar"&&(u.L=(r=d.L)!==null&&r!==void 0?r:sn.BIGINT),u.delimited=(s=d.delimited)!==null&&s!==void 0?s:!1,u.req=(o=d.req)!==null&&o!==void 0?o:!1,u.opt=(a=d.opt)!==null&&a!==void 0?a:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=P.BYTES&&d.T!=P.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new Qm(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const T=zm("proto3",t=>new Wm(t,e=>Zm(e)),t=>{for(const e of t.getType().fields.byMember()){if(e.opt)continue;const n=e.localName,i=t;if(e.repeated){i[n]=[];continue}switch(e.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=zn(e.T,e.L);break}}});class Be extends $s{constructor(e){super(),this.seconds=pe.zero,this.nanos=0,T.util.initPartial(e,this)}fromJson(e,n){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(T.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=pe.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const n=Number(this.seconds)*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(n).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Be.fromDate(new Date)}static fromDate(e){const n=e.getTime();return new Be({seconds:pe.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(e,n){return new Be().fromBinary(e,n)}static fromJson(e,n){return new Be().fromJson(e,n)}static fromJsonString(e,n){return new Be().fromJsonString(e,n)}static equals(e,n){return T.util.equals(Be,e,n)}}Be.runtime=T,Be.typeName="google.protobuf.Timestamp",Be.fields=T.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const eg=T.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Be},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:tg,repeated:!0},{no:5,name:"events",kind:"message",T:ig,repeated:!0}]),tg=T.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:ng,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ng=T.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Be},{no:3,name:"value",kind:"scalar",T:2}]),ig=T.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Be},{no:7,name:"normalized_end_timestamp",kind:"message",T:Be,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ql=T.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),st=T.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Te=T.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Ks=T.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Ei=T.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Pi=T.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ot=T.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),Hn=T.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),rg=T.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Re=T.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),vr=T.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:br,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:nd}]),br=T.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),sg=T.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:T.getEnumType(Te),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),xn=T.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:T.getEnumType(Gn)},{no:4,name:"tracks",kind:"message",T:Kn,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:sg},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:T.getEnumType(Ri)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:T.getEnumType(ot)},{no:18,name:"kind_details",kind:"enum",T:T.getEnumType(og),repeated:!0}]),Gn=T.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ri=T.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),og=T.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Ye=T.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ag=T.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:En,repeated:!0}]),Kn=T.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:T.getEnumType(st)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:T.getEnumType(Te)},{no:10,name:"layers",kind:"message",T:En,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:ag,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:T.getEnumType(Ye)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:nd},{no:19,name:"audio_features",kind:"enum",T:T.getEnumType(Re),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(ql)}]),En=T.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(Ks)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),je=T.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:T.getEnumType(G)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:zl,oneof:"value"},{no:3,name:"speaker",kind:"message",T:cg,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Wl,oneof:"value"},{no:7,name:"transcription",kind:"message",T:lg,oneof:"value"},{no:8,name:"metrics",kind:"message",T:eg,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Js,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Hl,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Gl,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Kl,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Xs,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Qs,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Zs,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),G=T.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),cg=T.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:$l,repeated:!0}]),$l=T.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),zl=T.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Wl=T.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),lg=T.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:dg,repeated:!0}]),dg=T.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),Js=T.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),Hl=T.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),Gl=T.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Kl=T.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Jl,oneof:"value"}]),Jl=T.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),Yl=T.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Xl=T.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:T.getEnumType(Ql)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),Ql=T.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),ug=T.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:T.getEnumType(Zl)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),Zl=T.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),ed=T.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:td},{no:2,name:"screen",kind:"message",T:td},{no:3,name:"resume_connection",kind:"enum",T:T.getEnumType(Pi)},{no:4,name:"disabled_codecs",kind:"message",T:hg},{no:5,name:"force_relay",kind:"enum",T:T.getEnumType(Pi)}]),td=T.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:T.getEnumType(Pi)}]),hg=T.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:br,repeated:!0},{no:2,name:"publish",kind:"message",T:br,repeated:!0}]),nd=T.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Ys=T.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),id=T.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:T.getEnumType(Ys)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),rd=T.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Xs=T.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:T.getEnumType(Ye)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:id,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:rd,oneof:"content_header"}],{localName:"DataStream_Header"}),Qs=T.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),Zs=T.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),at=T.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),eo=T.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),fg=T.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),pg=T.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Pn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Pn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:io,oneof:"message"},{no:4,name:"add_track",kind:"message",T:no,oneof:"message"},{no:5,name:"mute",kind:"message",T:ro,oneof:"message"},{no:6,name:"subscription",kind:"message",T:yr,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:od,oneof:"message"},{no:8,name:"leave",kind:"message",T:kr,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:cd,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:hd,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:fd,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ct,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ld,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:gd,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ad,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:yg,oneof:"message"}]),sd=T.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:mg,oneof:"message"},{no:2,name:"answer",kind:"message",T:Pn,oneof:"message"},{no:3,name:"offer",kind:"message",T:Pn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:io,oneof:"message"},{no:5,name:"update",kind:"message",T:bg,oneof:"message"},{no:6,name:"track_published",kind:"message",T:so,oneof:"message"},{no:8,name:"leave",kind:"message",T:kr,oneof:"message"},{no:9,name:"mute",kind:"message",T:ro,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:kg,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Cg,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:wg,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Tg,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Eg,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Pg,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:vg,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:gg,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Ig,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ag,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Mg,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Ng,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Rg,oneof:"message"}]),to=T.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),no=T.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:T.getEnumType(st)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:T.getEnumType(Te)},{no:9,name:"layers",kind:"message",T:En,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:to,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:T.getEnumType(Ye)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(ql)},{no:17,name:"audio_features",kind:"enum",T:T.getEnumType(Re),repeated:!0}]),io=T.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:T.getEnumType(at)},{no:3,name:"final",kind:"scalar",T:8}]),ro=T.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),mg=T.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:vr},{no:2,name:"participant",kind:"message",T:xn},{no:3,name:"other_participants",kind:"message",T:xn,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:dd,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:ed},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Xl},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:br,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),gg=T.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:dd,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ed},{no:3,name:"server_info",kind:"message",T:Xl},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),so=T.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Kn}]),vg=T.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Pn=T.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),bg=T.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:xn,repeated:!0}]),yr=T.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Yl,repeated:!0}]),od=T.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:T.getEnumType(Ks)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),ad=T.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:T.getEnumType(Re),repeated:!0}]),yg=T.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),kr=T.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:T.getEnumType(ot)},{no:3,name:"action",kind:"enum",T:T.getEnumType(Jn)},{no:4,name:"regions",kind:"message",T:Og}]),Jn=T.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),cd=T.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:En,repeated:!0}]),ld=T.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),dd=T.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),kg=T.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:$l,repeated:!0}]),Cg=T.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:vr}]),_g=T.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:T.getEnumType(Ei)},{no:3,name:"score",kind:"scalar",T:2}]),wg=T.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:_g,repeated:!0}]),Sg=T.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:T.getEnumType(eo)}]),Tg=T.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Sg,repeated:!0}]),oo=T.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(Ks)},{no:2,name:"enabled",kind:"scalar",T:8}]),xg=T.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:oo,repeated:!0}]),Eg=T.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:oo,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:xg,repeated:!0}]),ud=T.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),hd=T.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:ud,repeated:!0}]),Pg=T.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),Rg=T.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:vr},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:xn},{no:4,name:"other_participants",kind:"message",T:xn,repeated:!0}]),fd=T.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Pn},{no:2,name:"subscription",kind:"message",T:yr},{no:3,name:"publish_tracks",kind:"message",T:so,repeated:!0},{no:4,name:"data_channels",kind:"message",T:md,repeated:!0},{no:5,name:"offer",kind:"message",T:Pn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:pd,repeated:!0}]),pd=T.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),md=T.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:T.getEnumType(at)}]),Ct=T.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:T.getEnumType(fg),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),gd=T.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Ig=T.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Og=T.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Dg,repeated:!0}]),Dg=T.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),Ag=T.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:T.getEnumType(rg)}]),Mg=T.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:T.getEnumType(ao)},{no:3,name:"message",kind:"scalar",T:9}]),ao=T.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Ng=T.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Lg(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Cr={exports:{}},Ug=Cr.exports,vd;function Fg(){return vd||(vd=1,(function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(Ug,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(f,m){var v=f[m];if(typeof v.bind=="function")return v.bind(f);try{return Function.prototype.bind.call(v,f)}catch{return function(){return Function.prototype.apply.apply(v,[f,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(f){return f==="debug"&&(f="log"),typeof console===n?!1:f==="trace"&&i?c:console[f]!==void 0?a(console,f):console.log!==void 0?a(console,"log"):e}function d(){for(var f=this.getLevel(),m=0;m<r.length;m++){var v=r[m];this[v]=m<f?e:this.methodFactory(v,f,this.name)}if(this.log=this.debug,typeof console===n&&f<this.levels.SILENT)return"No console available for logging"}function u(f){return function(){typeof console!==n&&(d.call(this),this[f].apply(this,arguments))}}function h(f,m,v){return l(f)||u.apply(this,arguments)}function p(f,m){var v=this,y,_,k,w="loglevel";typeof f=="string"?w+=":"+f:typeof f=="symbol"&&(w=void 0);function S(A){var M=(r[A]||"silent").toUpperCase();if(!(typeof window===n||!w)){try{window.localStorage[w]=M;return}catch{}try{window.document.cookie=encodeURIComponent(w)+"="+M+";"}catch{}}}function x(){var A;if(!(typeof window===n||!w)){try{A=window.localStorage[w]}catch{}if(typeof A===n)try{var M=window.document.cookie,q=encodeURIComponent(w),$=M.indexOf(q+"=");$!==-1&&(A=/^([^;]+)/.exec(M.slice($+q.length+1))[1])}catch{}return v.levels[A]===void 0&&(A=void 0),A}}function I(){if(!(typeof window===n||!w)){try{window.localStorage.removeItem(w)}catch{}try{window.document.cookie=encodeURIComponent(w)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function O(A){var M=A;if(typeof M=="string"&&v.levels[M.toUpperCase()]!==void 0&&(M=v.levels[M.toUpperCase()]),typeof M=="number"&&M>=0&&M<=v.levels.SILENT)return M;throw new TypeError("log.setLevel() called with invalid level: "+A)}v.name=f,v.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},v.methodFactory=m||h,v.getLevel=function(){return k??_??y},v.setLevel=function(A,M){return k=O(A),M!==!1&&S(k),d.call(v)},v.setDefaultLevel=function(A){_=O(A),x()||v.setLevel(A,!1)},v.resetLevel=function(){k=null,I(),d.call(v)},v.enableAll=function(A){v.setLevel(v.levels.TRACE,A)},v.disableAll=function(A){v.setLevel(v.levels.SILENT,A)},v.rebuild=function(){if(o!==v&&(y=O(o.getLevel())),d.call(v),o===v)for(var A in s)s[A].rebuild()},y=O(o?o.getLevel():"WARN");var R=x();R!=null&&(k=O(R)),d.call(v)}o=new p,o.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var v=s[m];return v||(v=s[m]=new p(m,o.methodFactory)),v};var g=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return s},o.default=o,o})})(Cr)),Cr.exports}var _r=Fg(),co;(function(t){t[t.trace=0]="trace",t[t.debug=1]="debug",t[t.info=2]="info",t[t.warn=3]="warn",t[t.error=4]="error",t[t.silent=5]="silent"})(co||(co={}));var ct;(function(t){t.Default="livekit",t.Room="livekit-room",t.Participant="livekit-participant",t.Track="livekit-track",t.Publication="livekit-track-publication",t.Engine="livekit-engine",t.Signal="livekit-signal",t.PCManager="livekit-pc-manager",t.PCTransport="livekit-pc-transport",t.E2EE="lk-e2ee"})(ct||(ct={}));let X=_r.getLogger("livekit");Object.values(ct).map(t=>_r.getLogger(t)),X.setDefaultLevel(co.info);function qt(t){const e=_r.getLogger(t);return e.setDefaultLevel(X.getLevel()),e}const Bg=_r.getLogger("lk-e2ee"),Ii=7e3,jg=[0,300,4*300,9*300,16*300,Ii,Ii,Ii,Ii,Ii];class Vg{constructor(e){this._retryDelays=e!==void 0?[...e]:jg}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const n=this._retryDelays[e.retryCount];return e.retryCount<=1?n:n+Math.random()*1e3}}function qg(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function C(t,e,n,i){function r(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(d){try{l(i.next(d))}catch(u){o(u)}}function c(d){try{l(i.throw(d))}catch(u){o(u)}}function l(d){d.done?s(d.value):r(d.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function bd(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function $t(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof bd=="function"?bd(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var wr={exports:{}},yd;function $g(){if(yd)return wr.exports;yd=1;var t=typeof Reflect=="object"?Reflect:null,e=t&&typeof t.apply=="function"?t.apply:function(w,S,x){return Function.prototype.apply.call(w,S,x)},n;t&&typeof t.ownKeys=="function"?n=t.ownKeys:Object.getOwnPropertySymbols?n=function(w){return Object.getOwnPropertyNames(w).concat(Object.getOwnPropertySymbols(w))}:n=function(w){return Object.getOwnPropertyNames(w)};function i(k){console&&console.warn&&console.warn(k)}var r=Number.isNaN||function(w){return w!==w};function s(){s.init.call(this)}wr.exports=s,wr.exports.once=v,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(k){if(typeof k!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof k)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(k){if(typeof k!="number"||k<0||r(k))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+k+".");o=k}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(w){if(typeof w!="number"||w<0||r(w))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+w+".");return this._maxListeners=w,this};function c(k){return k._maxListeners===void 0?s.defaultMaxListeners:k._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(w){for(var S=[],x=1;x<arguments.length;x++)S.push(arguments[x]);var I=w==="error",O=this._events;if(O!==void 0)I=I&&O.error===void 0;else if(!I)return!1;if(I){var R;if(S.length>0&&(R=S[0]),R instanceof Error)throw R;var A=new Error("Unhandled error."+(R?" ("+R.message+")":""));throw A.context=R,A}var M=O[w];if(M===void 0)return!1;if(typeof M=="function")e(M,this,S);else for(var q=M.length,$=g(M,q),x=0;x<q;++x)e($[x],this,S);return!0};function l(k,w,S,x){var I,O,R;if(a(S),O=k._events,O===void 0?(O=k._events=Object.create(null),k._eventsCount=0):(O.newListener!==void 0&&(k.emit("newListener",w,S.listener?S.listener:S),O=k._events),R=O[w]),R===void 0)R=O[w]=S,++k._eventsCount;else if(typeof R=="function"?R=O[w]=x?[S,R]:[R,S]:x?R.unshift(S):R.push(S),I=c(k),I>0&&R.length>I&&!R.warned){R.warned=!0;var A=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+String(w)+" listeners added. Use emitter.setMaxListeners() to increase limit");A.name="MaxListenersExceededWarning",A.emitter=k,A.type=w,A.count=R.length,i(A)}return k}s.prototype.addListener=function(w,S){return l(this,w,S,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(w,S){return l(this,w,S,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(k,w,S){var x={fired:!1,wrapFn:void 0,target:k,type:w,listener:S},I=d.bind(x);return I.listener=S,x.wrapFn=I,I}s.prototype.once=function(w,S){return a(S),this.on(w,u(this,w,S)),this},s.prototype.prependOnceListener=function(w,S){return a(S),this.prependListener(w,u(this,w,S)),this},s.prototype.removeListener=function(w,S){var x,I,O,R,A;if(a(S),I=this._events,I===void 0)return this;if(x=I[w],x===void 0)return this;if(x===S||x.listener===S)--this._eventsCount===0?this._events=Object.create(null):(delete I[w],I.removeListener&&this.emit("removeListener",w,x.listener||S));else if(typeof x!="function"){for(O=-1,R=x.length-1;R>=0;R--)if(x[R]===S||x[R].listener===S){A=x[R].listener,O=R;break}if(O<0)return this;O===0?x.shift():f(x,O),x.length===1&&(I[w]=x[0]),I.removeListener!==void 0&&this.emit("removeListener",w,A||S)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(w){var S,x,I;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[w]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[w]),this;if(arguments.length===0){var O=Object.keys(x),R;for(I=0;I<O.length;++I)R=O[I],R!=="removeListener"&&this.removeAllListeners(R);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(S=x[w],typeof S=="function")this.removeListener(w,S);else if(S!==void 0)for(I=S.length-1;I>=0;I--)this.removeListener(w,S[I]);return this};function h(k,w,S){var x=k._events;if(x===void 0)return[];var I=x[w];return I===void 0?[]:typeof I=="function"?S?[I.listener||I]:[I]:S?m(I):g(I,I.length)}s.prototype.listeners=function(w){return h(this,w,!0)},s.prototype.rawListeners=function(w){return h(this,w,!1)},s.listenerCount=function(k,w){return typeof k.listenerCount=="function"?k.listenerCount(w):p.call(k,w)},s.prototype.listenerCount=p;function p(k){var w=this._events;if(w!==void 0){var S=w[k];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function g(k,w){for(var S=new Array(w),x=0;x<w;++x)S[x]=k[x];return S}function f(k,w){for(;w+1<k.length;w++)k[w]=k[w+1];k.pop()}function m(k){for(var w=new Array(k.length),S=0;S<w.length;++S)w[S]=k[S].listener||k[S];return w}function v(k,w){return new Promise(function(S,x){function I(R){k.removeListener(w,O),x(R)}function O(){typeof k.removeListener=="function"&&k.removeListener("error",I),S([].slice.call(arguments))}_(k,w,O,{once:!0}),w!=="error"&&y(k,I,{once:!0})})}function y(k,w,S){typeof k.on=="function"&&_(k,"error",w,S)}function _(k,w,S,x){if(typeof k.on=="function")x.once?k.once(w,S):k.on(w,S);else if(typeof k.addEventListener=="function")k.addEventListener(w,function I(O){x.once&&k.removeEventListener(w,I),S(O)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof k)}return wr.exports}var _t=$g();let kd=!0,Cd=!0;function Oi(t,e,n){const i=t.match(e);return i&&i.length>=n&&parseFloat(i[n],10)}function Rn(t,e,n){if(!t.RTCPeerConnection)return;const i=t.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(o,a){if(o!==e)return r.apply(this,arguments);const c=l=>{const d=n(l);d&&(a.handleEvent?a.handleEvent(d):a(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),r.apply(this,[o,c])};const s=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function zg(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(kd=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function Wg(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(Cd=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function _d(){if(typeof window=="object"){if(kd)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function lo(t,e){Cd&&console.warn(t+" is deprecated, please use "+e+" instead.")}function Hg(t){const e={browser:null,version:null};if(typeof t>"u"||!t.navigator||!t.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:n}=t;if(n.userAgentData&&n.userAgentData.brands){const i=n.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(n.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Oi(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||t.isSecureContext===!1&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Oi(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(t.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Oi(n.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,e._safariVersion=Oi(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function wd(t){return Object.prototype.toString.call(t)==="[object Object]"}function Sd(t){return wd(t)?Object.keys(t).reduce(function(e,n){const i=wd(t[n]),r=i?Sd(t[n]):t[n],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[n]:r})},{}):t}function uo(t,e,n){!e||n.has(e.id)||(n.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?uo(t,t.get(e[i]),n):i.endsWith("Ids")&&e[i].forEach(r=>{uo(t,t.get(r),n)})}))}function Td(t,e,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return t.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{t.forEach(a=>{a.type===i&&a.trackId===o.id&&uo(t,a,r)})}),r}const xd=_d;function Ed(t,e){const n=t&&t.navigator;if(!n.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof a[l]=="object"?a[l]:{ideal:a[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},r=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return n.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let p=h.find(g=>u.some(f=>g.label.toLowerCase().includes(f)));return!p&&h.length&&u.includes("back")&&(p=h[h.length-1]),p&&(a.video.deviceId=l.exact?{exact:p.deviceId}:{ideal:p.deviceId}),a.video=i(a.video),xd("chrome: "+JSON.stringify(a)),c(a)})}a.video=i(a.video)}return xd("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){r(a,d=>{n.webkitGetUserMedia(d,c,u=>{l&&l(s(u))})})};if(n.getUserMedia=o.bind(n),n.mediaDevices.getUserMedia){const a=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(c){return r(c,l=>a(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(s(d))))}}}function Pd(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function Rd(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.track.id):s={track:r.track};const o=new Event("track");o.track=r.track,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(r=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.id):s={track:r};const o=new Event("track");o.track=r,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Rn(t,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Id(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(a,c){let l=r.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const s=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof t=="object"&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(t.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Od(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const n=t.RTCPeerConnection.prototype.getSenders;n&&(t.RTCPeerConnection.prototype.getSenders=function(){const s=n.apply(this,[]);return s.forEach(o=>o._pc=this),s});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),t.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(o=>Td(o,s.track,!0))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const n=t.RTCPeerConnection.prototype.getReceivers;n&&(t.RTCPeerConnection.prototype.getReceivers=function(){const r=n.apply(this,[]);return r.forEach(s=>s._pc=this),r}),Rn(t,"track",i=>(i.receiver._pc=i.srcElement,i)),t.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>Td(s,r.track,!1))}}if(!("getStats"in t.RTCRtpSender.prototype&&"getStats"in t.RTCRtpReceiver.prototype))return;const e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const i=arguments[0];let r,s,o;return this.getSenders().forEach(a=>{a.track===i&&(r?o=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(s?o=!0:s=a),a.track===i)),o||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Dd(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();n.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const r=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function Ad(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Dd(t);const n=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const d=n.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const i=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(p=>p.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new t.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}i.apply(this,[d])};const r=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},t.RTCPeerConnection.prototype.addTrack=function(d,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(f=>f===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(f=>f.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[u.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const f=new t.MediaStream([d]);this._streams[u.id]=f,this._reverseStreams[f.id]=u,this.addStream(f)}return this.getSenders().find(f=>f.track===d)};function s(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const p=l._reverseStreams[h],g=l._streams[p.id];u=u.replace(new RegExp(g.id,"g"),p.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function o(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const p=l._reverseStreams[h],g=l._streams[p.id];u=u.replace(new RegExp(p.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=t.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{const f=s(this,g);h[0].apply(null,[f])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>s(this,g))}};t.RTCPeerConnection.prototype[l]=u[l]});const a=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:s(this,l)}}),t.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(f=>d.track===f)&&(h=this._streams[p])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ho(t,e){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const i=t.RTCPeerConnection.prototype[n],r={[n](){return arguments[0]=new(n==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};t.RTCPeerConnection.prototype[n]=r[n]})}function Md(t,e){Rn(t,"negotiationneeded",n=>{const i=n.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return n})}var Nd=Object.freeze({__proto__:null,fixNegotiationNeeded:Md,shimAddTrackRemoveTrack:Ad,shimAddTrackRemoveTrackWithNative:Dd,shimGetSendersWithDtmf:Id,shimGetUserMedia:Ed,shimMediaStream:Pd,shimOnTrack:Rd,shimPeerConnection:ho,shimSenderReceiverGetStats:Od});function Ld(t,e){const n=t&&t.navigator,i=t&&t.MediaStreamTrack;if(n.getUserMedia=function(r,s,o){lo("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(r).then(s,o)},!(e.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const r=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const o=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function Gg(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,t.navigator.mediaDevices.getUserMedia(i)})}function Ud(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function fo(t,e){if(typeof t!="object"||!(t.RTCPeerConnection||t.mozRTCPeerConnection))return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=t.RTCPeerConnection.prototype[r],o={[r](){return arguments[0]=new(r==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};t.RTCPeerConnection.prototype[r]=o[r]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[s,o,a]=arguments;return i.apply(this,[s||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=n[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:n[d.type]||d.type}))})}return c}).then(o,a)}}function Fd(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const n=t.RTCPeerConnection.prototype.addTrack;n&&(t.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Bd(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),Rn(t,"track",n=>(n.receiver._pc=n.srcElement,n)),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function jd(t){!t.RTCPeerConnection||"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(n){lo("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&n.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Vd(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function qd(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.addTransceiver;e&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:o}=s,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return s})}function $d(t){if(!(typeof t=="object"&&t.RTCRtpSender))return;const e=t.RTCRtpSender.prototype.getParameters;e&&(t.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function zd(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Wd(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Hd=Object.freeze({__proto__:null,shimAddTransceiver:qd,shimCreateAnswer:Wd,shimCreateOffer:zd,shimGetDisplayMedia:Gg,shimGetParameters:$d,shimGetUserMedia:Ld,shimOnTrack:Ud,shimPeerConnection:fo,shimRTCDataChannel:Vd,shimReceiverGetStats:Bd,shimRemoveStream:jd,shimSenderGetStats:Fd});function Gd(t){if(!(typeof t!="object"||!t.RTCPeerConnection)){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},t.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s&&s.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(n){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(n);if(i===-1)return;this._localStreams.splice(i,1);const r=n.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function Kd(t){if(!(typeof t!="object"||!t.RTCPeerConnection)&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(n){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=n),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const o=new Event("addstream");o.stream=s,i.dispatchEvent(o)})}),e.apply(i,arguments)}}}function Jd(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype,n=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let a=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,l,d){const u=o.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=a}function Yd(t){const e=t&&t.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const n=e.mediaDevices,i=n.getUserMedia.bind(n);e.mediaDevices.getUserMedia=r=>i(Xd(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function Xd(t){return t&&t.video!==void 0?Object.assign({},t,{video:Sd(t.video)}):t}function Qd(t){if(!t.RTCPeerConnection)return;const e=t.RTCPeerConnection;t.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(lo("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(i.iceServers[o])}i.iceServers=s}return new e(i,r)},t.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Zd(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function eu(t){const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function tu(t){typeof t!="object"||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var nu=Object.freeze({__proto__:null,shimAudioContext:tu,shimCallbacksAPI:Jd,shimConstraints:Xd,shimCreateOfferLegacy:eu,shimGetUserMedia:Yd,shimLocalStreamsAPI:Gd,shimRTCIceServerUrls:Qd,shimRemoteStreamsAPI:Kd,shimTrackEventTransceiver:Zd}),po={exports:{}},iu;function Kg(){return iu||(iu=1,(function(t){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(n){return n.trim().split(`
1
+ (function(){"use strict";var vi,$,ec,tc,Sn,nc,ic,rc,sc,ms,gs,vs,oc,bi={},ac=[],Lp=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,yi=Array.isArray;function kt(t,e){for(var n in e)t[n]=e[n];return t}function bs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function fe(t,e,n){var i,r,s,o={};for(s in e)s=="key"?i=e[s]:s=="ref"?r=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?vi.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return ki(t,o,i,r,null)}function ki(t,e,n,i,r){var s={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r??++ec,__i:-1,__u:0};return r==null&&$.vnode!=null&&$.vnode(s),s}function cc(){return{current:null}}function ge(t){return t.children}function rt(t,e){this.props=t,this.context=e}function Fn(t,e){if(e==null)return t.__?Fn(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?Fn(t):null}function lc(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return lc(t)}}function ys(t){(!t.__d&&(t.__d=!0)&&Sn.push(t)&&!Ji.__r++||nc!=$.debounceRendering)&&((nc=$.debounceRendering)||ic)(Ji)}function Ji(){for(var t,e,n,i,r,s,o,a=1;Sn.length;)Sn.length>a&&Sn.sort(rc),t=Sn.shift(),a=Sn.length,t.__d&&(n=void 0,r=(i=(e=t).__v).__e,s=[],o=[],e.__P&&((n=kt({},i)).__v=i.__v+1,$.vnode&&$.vnode(n),ks(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??Fn(i),!!(32&i.__u),o),n.__v=i.__v,n.__.__k[n.__i]=n,pc(s,n,o),n.__e!=r&&lc(n)));Ji.__r=0}function dc(t,e,n,i,r,s,o,a,c,l,d){var u,h,f,v,p,g,b,k=i&&i.__k||ac,w=e.length;for(c=Up(n,e,k,c,w),u=0;u<w;u++)(f=n.__k[u])!=null&&(h=f.__i==-1?bi:k[f.__i]||bi,f.__i=u,g=ks(t,f,h,r,s,o,a,c,l,d),v=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&ws(h.ref,null,f),d.push(f.ref,f.__c||v,f)),p==null&&v!=null&&(p=v),(b=!!(4&f.__u))||h.__k===f.__k?c=uc(f,c,t,b):typeof f.type=="function"&&g!==void 0?c=g:v&&(c=v.nextSibling),f.__u&=-7);return n.__e=p,c}function Up(t,e,n,i,r){var s,o,a,c,l,d=n.length,u=d,h=0;for(t.__k=new Array(r),s=0;s<r;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(c=s+h,(o=t.__k[s]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?ki(null,o,null,null,null):yi(o)?ki(ge,{children:o},null,null,null):o.constructor==null&&o.__b>0?ki(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,a=null,(l=o.__i=Fp(o,n,c,u))!=-1&&(u--,(a=n[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(r>d?h--:r<d&&h++),typeof o.type!="function"&&(o.__u|=4)):l!=c&&(l==c-1?h--:l==c+1?h++:(l>c?h--:h++,o.__u|=4))):t.__k[s]=null;if(u)for(s=0;s<d;s++)(a=n[s])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=Fn(a)),gc(a,a));return i}function uc(t,e,n,i){var r,s;if(typeof t.type=="function"){for(r=t.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=t,e=uc(r[s],e,n,i));return e}t.__e!=e&&(i&&(e&&t.type&&!e.parentNode&&(e=Fn(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Ut(t,e){return e=e||[],t==null||typeof t=="boolean"||(yi(t)?t.some(function(n){Ut(n,e)}):e.push(t)),e}function Fp(t,e,n,i){var r,s,o,a=t.key,c=t.type,l=e[n],d=l!=null&&(2&l.__u)==0;if(l===null&&t.key==null||d&&a==l.key&&c==l.type)return n;if(i>(d?1:0)){for(r=n-1,s=n+1;r>=0||s<e.length;)if((l=e[o=r>=0?r--:s++])!=null&&(2&l.__u)==0&&a==l.key&&c==l.type)return o}return-1}function hc(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Lp.test(e)?n:n+"px"}function Yi(t,e,n,i,r){var s,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||hc(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||hc(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(sc,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?i?n.u=i.u:(n.u=ms,t.addEventListener(e,s?vs:gs,s)):t.removeEventListener(e,s?vs:gs,s);else{if(r=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function fc(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ms++;else if(e.t<n.u)return;return n($.event?$.event(e):e)}}}function ks(t,e,n,i,r,s,o,a,c,l){var d,u,h,f,v,p,g,b,k,w,y,_,S,x,I,R,A,M=e.type;if(e.constructor!=null)return null;128&n.__u&&(c=!!(32&n.__u),s=[a=e.__e=n.__e]),(d=$.__b)&&d(e);e:if(typeof M=="function")try{if(b=e.props,k="prototype"in M&&M.prototype.render,w=(d=M.contextType)&&i[d.__c],y=d?w?w.props.value:d.__:i,n.__c?g=(u=e.__c=n.__c).__=u.__E:(k?e.__c=u=new M(b,y):(e.__c=u=new rt(b,y),u.constructor=M,u.render=jp),w&&w.sub(u),u.props=b,u.state||(u.state={}),u.context=y,u.__n=i,h=u.__d=!0,u.__h=[],u._sb=[]),k&&u.__s==null&&(u.__s=u.state),k&&M.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=kt({},u.__s)),kt(u.__s,M.getDerivedStateFromProps(b,u.__s))),f=u.props,v=u.state,u.__v=e,h)k&&M.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),k&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(k&&M.getDerivedStateFromProps==null&&b!==f&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(b,y),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(b,u.__s,y)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(u.props=b,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(N){N&&(N.__=e)}),_=0;_<u._sb.length;_++)u.__h.push(u._sb[_]);u._sb=[],u.__h.length&&o.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(b,u.__s,y),k&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(f,v,p)})}if(u.context=y,u.props=b,u.__P=t,u.__e=!1,S=$.__r,x=0,k){for(u.state=u.__s,u.__d=!1,S&&S(e),d=u.render(u.props,u.state,u.context),I=0;I<u._sb.length;I++)u.__h.push(u._sb[I]);u._sb=[]}else do u.__d=!1,S&&S(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++x<25);u.state=u.__s,u.getChildContext!=null&&(i=kt(kt({},i),u.getChildContext())),k&&!h&&u.getSnapshotBeforeUpdate!=null&&(p=u.getSnapshotBeforeUpdate(f,v)),R=d,d!=null&&d.type===ge&&d.key==null&&(R=mc(d.props.children)),a=dc(t,yi(R)?R:[R],e,n,i,r,s,o,a,c,l),u.base=e.__e,e.__u&=-161,u.__h.length&&o.push(u),g&&(u.__E=u.__=null)}catch(N){if(e.__v=null,c||s!=null)if(N.then){for(e.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,e.__e=a}else{for(A=s.length;A--;)bs(s[A]);Cs(e)}else e.__e=n.__e,e.__k=n.__k,N.then||Cs(e);$.__e(N,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Bp(n.__e,e,n,i,r,s,o,c,l);return(d=$.diffed)&&d(e),128&e.__u?void 0:a}function Cs(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Cs)}function pc(t,e,n){for(var i=0;i<n.length;i++)ws(n[i],n[++i],n[++i]);$.__c&&$.__c(e,t),t.some(function(r){try{t=r.__h,r.__h=[],t.some(function(s){s.call(r)})}catch(s){$.__e(s,r.__v)}})}function mc(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:yi(t)?t.map(mc):kt({},t)}function Bp(t,e,n,i,r,s,o,a,c){var l,d,u,h,f,v,p,g=n.props,b=e.props,k=e.type;if(k=="svg"?r="http://www.w3.org/2000/svg":k=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((f=s[l])&&"setAttribute"in f==!!k&&(k?f.localName==k:f.nodeType==3)){t=f,s[l]=null;break}}if(t==null){if(k==null)return document.createTextNode(b);t=document.createElementNS(r,k,b.is&&b),a&&($.__m&&$.__m(e,s),a=!1),s=null}if(k==null)g===b||a&&t.data==b||(t.data=b);else{if(s=s&&vi.call(t.childNodes),g=n.props||bi,!a&&s!=null)for(g={},l=0;l<t.attributes.length;l++)g[(f=t.attributes[l]).name]=f.value;for(l in g)if(f=g[l],l!="children"){if(l=="dangerouslySetInnerHTML")u=f;else if(!(l in b)){if(l=="value"&&"defaultValue"in b||l=="checked"&&"defaultChecked"in b)continue;Yi(t,l,null,f,r)}}for(l in b)f=b[l],l=="children"?h=f:l=="dangerouslySetInnerHTML"?d=f:l=="value"?v=f:l=="checked"?p=f:a&&typeof f!="function"||g[l]===f||Yi(t,l,f,g[l],r);if(d)a||u&&(d.__html==u.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(u&&(t.innerHTML=""),dc(e.type=="template"?t.content:t,yi(h)?h:[h],e,n,i,k=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,o,s?s[0]:n.__k&&Fn(n,0),a,c),s!=null)for(l=s.length;l--;)bs(s[l]);a||(l="value",k=="progress"&&v==null?t.removeAttribute("value"):v!=null&&(v!==t[l]||k=="progress"&&!v||k=="option"&&v!=g[l])&&Yi(t,l,v,g[l],r),l="checked",p!=null&&p!=t[l]&&Yi(t,l,p,g[l],r))}return t}function ws(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(r){$.__e(r,n)}}function gc(t,e,n){var i,r;if($.unmount&&$.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||ws(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){$.__e(s,e)}i.base=i.__P=null}if(i=t.__k)for(r=0;r<i.length;r++)i[r]&&gc(i[r],e,n||typeof t.type!="function");n||bs(t.__e),t.__c=t.__=t.__e=void 0}function jp(t,e,n){return this.constructor(t,n)}function rn(t,e,n){var i,r,s,o;e==document&&(e=document.documentElement),$.__&&$.__(t,e),r=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],ks(e,t=(!i&&n||e).__k=fe(ge,null,[t]),r||bi,bi,e.namespaceURI,!i&&n?[n]:r?null:e.firstChild?vi.call(e.childNodes):null,s,!i&&n?n:r?r.__e:e.firstChild,i,o),pc(s,t,o)}function _s(t,e){rn(t,e,_s)}function Ss(t,e,n){var i,r,s,o,a=kt({},t.props);for(s in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)s=="key"?i=e[s]:s=="ref"?r=e[s]:a[s]=e[s]===void 0&&o!=null?o[s]:e[s];return arguments.length>2&&(a.children=arguments.length>3?vi.call(arguments,2):n),ki(t.type,a,i||t.key,r||t.ref,null)}function Re(t){function e(n){var i,r;return this.getChildContext||(i=new Set,(r={})[e.__c]=this,this.getChildContext=function(){return r},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&i.forEach(function(o){o.__e=!0,ys(o)})},this.sub=function(s){i.add(s);var o=s.componentWillUnmount;s.componentWillUnmount=function(){i&&i.delete(s),o&&o.call(s)}}),n.children}return e.__c="__cC"+oc++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}vi=ac.slice,$={__e:function(t,e,n,i){for(var r,s,o;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(t)),o=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(t,i||{}),o=r.__d),o)return r.__E=r}catch(a){t=a}throw t}},ec=0,tc=function(t){return t!=null&&t.constructor==null},rt.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=kt({},this.state),typeof t=="function"&&(t=t(kt({},n),this.props)),t&&kt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),ys(this))},rt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),ys(this))},rt.prototype.render=ge,Sn=[],ic=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,rc=function(t,e){return t.__v.__b-e.__v.__b},Ji.__r=0,sc=/(PointerCapture)$|Capture$/i,ms=0,gs=fc(!1),vs=fc(!0),oc=0;function Xi(){return Xi=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Xi.apply(this,arguments)}var Vp=["context","children"];function qp(t,e,n,i){function r(){var s=Reflect.construct(HTMLElement,[],r);return s._vdomComponent=t,s._root=i&&i.shadow?s.attachShadow({mode:i.mode||"open"}):s,s}return(r.prototype=Object.create(HTMLElement.prototype)).constructor=r,r.prototype.connectedCallback=zp,r.prototype.attributeChangedCallback=Wp,r.prototype.disconnectedCallback=Hp,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),r.observedAttributes=n,n.forEach(function(s){Object.defineProperty(r.prototype,s,{get:function(){return this._vdom.props[s]},set:function(o){this._vdom?this.attributeChangedCallback(s,null,o):(this._props||(this._props={}),this._props[s]=o,this.connectedCallback());var a=typeof o;o!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(s,o)}})}),customElements.define(e||t.tagName||t.displayName||t.name,r)}function $p(t){this.getChildContext=function(){return t.context};var e=t.children,n=(function(i,r){if(i==null)return{};var s,o,a={},c=Object.keys(i);for(o=0;o<c.length;o++)r.indexOf(s=c[o])>=0||(a[s]=i[s]);return a})(t,Vp);return Ss(e,n)}function zp(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=fe($p,Xi({},this._props,{context:t.detail.context}),yc(this,this._vdomComponent)),(this.hasAttribute("hydrate")?_s:rn)(this._vdom,this._root)}function vc(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Wp(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[vc(t)]=n,this._vdom=Ss(this._vdom,i),rn(this._vdom,this._root)}}function Hp(){rn(this._vdom=null,this._root)}function bc(t,e){var n=this;return fe("slot",Xi({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(r){r.stopPropagation(),r.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function yc(t,e){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var n=[],i={},r=0,s=t.attributes,o=t.childNodes;for(r=s.length;r--;)s[r].name!=="slot"&&(i[s[r].name]=s[r].value,i[vc(s[r].name)]=s[r].value);for(r=o.length;r--;){var a=yc(o[r],null),c=o[r].slot;c?i[c]=fe(bc,{name:c},a):n[r]=a}var l=e?fe(bc,null,n):n;return fe(e||t.nodeName.toLowerCase(),i,l)}var Gp=0;function m(t,e,n,i,r,s){e||(e={});var o,a,c=e;if("ref"in c)for(a in c={},e)a=="ref"?o=e[a]:c[a]=e[a];var l={type:t,props:c,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Gp,__i:-1,__u:0,__source:r,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(a in o)c[a]===void 0&&(c[a]=o[a]);return $.vnode&&$.vnode(l),l}var Ft,le,Ts,kc,Bn=0,Cc=[],ve=$,wc=ve.__b,_c=ve.__r,Sc=ve.diffed,Tc=ve.__c,xc=ve.unmount,Pc=ve.__;function Tn(t,e){ve.__h&&ve.__h(le,t,Bn||e),Bn=0;var n=le.__H||(le.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function V(t){return Bn=1,Qi(Rc,t)}function Qi(t,e,n){var i=Tn(Ft++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Rc(void 0,e),function(a){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,a);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=le,!le.__f)){var r=function(a,c,l){if(!i.__c.__H)return!0;var d=i.__c.__H.__.filter(function(h){return!!h.__c});if(d.every(function(h){return!h.__N}))return!s||s.call(this,a,c,l);var u=i.__c.props!==a;return d.forEach(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(u=!0)}}),s&&s.call(this,a,c,l)||u};le.__f=!0;var s=le.shouldComponentUpdate,o=le.componentWillUpdate;le.componentWillUpdate=function(a,c,l){if(this.__e){var d=s;s=void 0,r(a,c,l),s=d}o&&o.call(this,a,c,l)},le.shouldComponentUpdate=r}return i.__N||i.__}function G(t,e){var n=Tn(Ft++,3);!ve.__s&&Is(n.__H,e)&&(n.__=t,n.u=e,le.__H.__h.push(n))}function Bt(t,e){var n=Tn(Ft++,4);!ve.__s&&Is(n.__H,e)&&(n.__=t,n.u=e,le.__h.push(n))}function B(t){return Bn=5,oe(function(){return{current:t}},[])}function xs(t,e,n){Bn=6,Bt(function(){if(typeof t=="function"){var i=t(e());return function(){t(null),i&&typeof i=="function"&&i()}}if(t)return t.current=e(),function(){return t.current=null}},n==null?n:n.concat(t))}function oe(t,e){var n=Tn(Ft++,7);return Is(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function j(t,e){return Bn=8,oe(function(){return t},e)}function sn(t){var e=le.context[t.__c],n=Tn(Ft++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(le)),e.props.value):t.__}function Ps(t,e){ve.useDebugValue&&ve.useDebugValue(e?e(t):t)}function Kp(t){var e=Tn(Ft++,10),n=V();return e.__=t,le.componentDidCatch||(le.componentDidCatch=function(i,r){e.__&&e.__(i,r),n[1](i)}),[n[0],function(){n[1](void 0)}]}function Es(){var t=Tn(Ft++,11);if(!t.__){for(var e=le.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function Jp(){for(var t;t=Cc.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Zi),t.__H.__h.forEach(Rs),t.__H.__h=[]}catch(e){t.__H.__h=[],ve.__e(e,t.__v)}}ve.__b=function(t){le=null,wc&&wc(t)},ve.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Pc&&Pc(t,e)},ve.__r=function(t){_c&&_c(t),Ft=0;var e=(le=t.__c).__H;e&&(Ts===le?(e.__h=[],le.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Zi),e.__h.forEach(Rs),e.__h=[],Ft=0)),Ts=le},ve.diffed=function(t){Sc&&Sc(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Cc.push(e)!==1&&kc===ve.requestAnimationFrame||((kc=ve.requestAnimationFrame)||Yp)(Jp)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ts=le=null},ve.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Zi),n.__h=n.__h.filter(function(i){return!i.__||Rs(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],ve.__e(i,n.__v)}}),Tc&&Tc(t,e)},ve.unmount=function(t){xc&&xc(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{Zi(i)}catch(r){e=r}}),n.__H=void 0,e&&ve.__e(e,n.__v))};var Ec=typeof requestAnimationFrame=="function";function Yp(t){var e,n=function(){clearTimeout(i),Ec&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Ec&&(e=requestAnimationFrame(n))}function Zi(t){var e=le,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),le=e}function Rs(t){var e=le;t.__c=t.__(),le=e}function Is(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Rc(t,e){return typeof e=="function"?e(t):e}function Ic(t,e){for(var n in e)t[n]=e[n];return t}function Os(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var i in e)if(i!=="__source"&&t[i]!==e[i])return!0;return!1}function As(t,e){var n=e(),i=V({t:{__:n,u:e}}),r=i[0].t,s=i[1];return Bt(function(){r.__=n,r.u=e,Ds(r)&&s({t:r})},[t,n,e]),G(function(){return Ds(r)&&s({t:r}),t(function(){Ds(r)&&s({t:r})})},[t]),n}function Ds(t){var e,n,i=t.u,r=t.__;try{var s=i();return!((e=r)===(n=s)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function Ms(t){t()}function Ns(t){return t}function Ls(){return[!1,Ms]}var Us=Bt;function er(t,e){this.props=t,this.context=e}function tr(t,e){function n(r){var s=this.props.ref,o=s==r.ref;return!o&&s&&(s.call?s(null):s.current=null),e?!e(this.props,r)||!o:Os(this.props,r)}function i(r){return this.shouldComponentUpdate=n,fe(t,r)}return i.displayName="Memo("+(t.displayName||t.name)+")",i.prototype.isReactComponent=!0,i.__f=!0,i.type=t,i}(er.prototype=new rt).isPureReactComponent=!0,er.prototype.shouldComponentUpdate=function(t,e){return Os(this.props,t)||Os(this.state,e)};var Oc=$.__b;$.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Oc&&Oc(t)};var Xp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function X(t){function e(n){var i=Ic({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=Xp,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Ac=function(t,e){return t==null?null:Ut(Ut(t).map(e))},on={map:Ac,forEach:Ac,count:function(t){return t?Ut(t).length:0},only:function(t){var e=Ut(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Ut},Qp=$.__e;$.__e=function(t,e,n,i){if(t.then){for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),r.__c(t,e)}Qp(t,e,n,i)};var Dc=$.unmount;function Mc(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),t.__c.__H=null),(t=Ic({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(i){return Mc(i,e,n)})),t}function Nc(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return Nc(i,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function Ci(){this.__u=0,this.o=null,this.__b=null}function Lc(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Uc(t){var e,n,i;function r(s){if(e||(e=t()).then(function(o){n=o.default||o},function(o){i=o}),i)throw i;if(!n)throw e;return fe(n,s)}return r.displayName="Lazy",r.__f=!0,r}function jn(){this.i=null,this.l=null}$.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Dc&&Dc(t)},(Ci.prototype=new rt).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var r=Lc(i.__v),s=!1,o=function(){s||(s=!0,n.__R=null,r?r(a):a())};n.__R=o;var a=function(){if(!--i.__u){if(i.state.__a){var c=i.state.__a;i.__v.__k[0]=Nc(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(o,o)},Ci.prototype.componentWillUnmount=function(){this.o=[]},Ci.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Mc(this.__b,n,i.__O=i.__P)}this.__b=null}var r=e.__a&&fe(ge,null,t.fallback);return r&&(r.__u&=-33),[fe(ge,null,e.__a?null:t.children),r]};var Fc=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};function Zp(t){return this.getChildContext=function(){return t.context},t.children}function em(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){rn(null,e.v),e.v=null,e.h=null},e.h&&e.h!==n&&e.componentWillUnmount(),!e.v){for(var i=e.__v;i!==null&&!i.__m&&i.__!==null;)i=i.__;e.h=n,e.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:i.__m},contains:function(){return!0},insertBefore:function(r,s){this.childNodes.push(r),e.h.insertBefore(r,s)},removeChild:function(r){this.childNodes.splice(this.childNodes.indexOf(r)>>>1,1),e.h.removeChild(r)}}}rn(fe(Zp,{context:e.context},t.__v),e.v)}function nr(t,e){var n=fe(em,{__v:t,h:e});return n.containerInfo=e,n}(jn.prototype=new rt).__a=function(t){var e=this,n=Lc(e.__v),i=e.l.get(t);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Fc(e,t,i)):r()};n?n(s):s()}},jn.prototype.render=function(t){this.i=null,this.l=new Map;var e=Ut(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},jn.prototype.componentDidUpdate=jn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Fc(t,n,e)})};var Bc=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,tm=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,nm=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,im=/[A-Z0-9]/g,rm=typeof document<"u",sm=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function jc(t,e,n){return e.__k==null&&(e.textContent=""),rn(t,e),typeof n=="function"&&n(),t?t.__c:null}function Vc(t,e,n){return _s(t,e),typeof n=="function"&&n(),t?t.__c:null}rt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(rt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var qc=$.event;function om(){}function am(){return this.cancelBubble}function cm(){return this.defaultPrevented}$.event=function(t){return qc&&(t=qc(t)),t.persist=om,t.isPropagationStopped=am,t.isDefaultPrevented=cm,t.nativeEvent=t};var Fs,lm={enumerable:!1,configurable:!0,get:function(){return this.class}},$c=$.vnode;$.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,i=e.type,r={},s=i.indexOf("-")===-1;for(var o in n){var a=n[o];if(!(o==="value"&&"defaultValue"in n&&a==null||rm&&o==="children"&&i==="noscript"||o==="class"||o==="className")){var c=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?o="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||sm(n.type)?c==="onfocus"?o="onfocusin":c==="onblur"?o="onfocusout":nm.test(o)&&(o=c):c=o="oninput":s&&tm.test(o)?o=o.replace(im,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&r[o=c]&&(o="oninputCapture"),r[o]=a}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=Ut(n.children).forEach(function(l){l.props.selected=r.value.indexOf(l.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=Ut(n.children).forEach(function(l){l.props.selected=r.multiple?r.defaultValue.indexOf(l.props.value)!=-1:r.defaultValue==l.props.value})),n.class&&!n.className?(r.class=n.class,Object.defineProperty(r,"className",lm)):(n.className&&!n.class||n.class&&n.className)&&(r.class=r.className=n.className),e.props=r})(t),t.$$typeof=Bc,$c&&$c(t)};var zc=$.__r;$.__r=function(t){zc&&zc(t),Fs=t.__c};var Wc=$.diffed;$.diffed=function(t){Wc&&Wc(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value),Fs=null};var Hc={ReactCurrentDispatcher:{current:{readContext:function(t){return Fs.__n[t.__c].props.value},useCallback:j,useContext:sn,useDebugValue:Ps,useDeferredValue:Ns,useEffect:G,useId:Es,useImperativeHandle:xs,useInsertionEffect:Us,useLayoutEffect:Bt,useMemo:oe,useReducer:Qi,useRef:B,useState:V,useSyncExternalStore:As,useTransition:Ls}}},dm="18.3.1";function Gc(t){return fe.bind(null,t)}function jt(t){return!!t&&t.$$typeof===Bc}function Kc(t){return jt(t)&&t.type===ge}function Jc(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function wi(t){return jt(t)?Ss.apply(null,arguments):t}function Yc(t){return!!t.__k&&(rn(null,t),!0)}function Xc(t){return t&&(t.base||t.nodeType===1&&t)||null}var Qc=function(t,e){return t(e)},ir=function(t,e){return t(e)},Zc=ge,el=jt,Vt={useState:V,useId:Es,useReducer:Qi,useEffect:G,useLayoutEffect:Bt,useInsertionEffect:Us,useTransition:Ls,useDeferredValue:Ns,useSyncExternalStore:As,startTransition:Ms,useRef:B,useImperativeHandle:xs,useMemo:oe,useCallback:j,useContext:sn,useDebugValue:Ps,version:"18.3.1",Children:on,render:jc,hydrate:Vc,unmountComponentAtNode:Yc,createPortal:nr,createElement:fe,createContext:Re,createFactory:Gc,cloneElement:wi,createRef:cc,Fragment:ge,isValidElement:jt,isElement:el,isFragment:Kc,isMemo:Jc,findDOMNode:Xc,Component:rt,PureComponent:er,memo:tr,forwardRef:X,flushSync:ir,unstable_batchedUpdates:Qc,StrictMode:Zc,Suspense:Ci,SuspenseList:jn,lazy:Uc,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Hc};const tl=Object.freeze(Object.defineProperty({__proto__:null,Children:on,Component:rt,Fragment:ge,PureComponent:er,StrictMode:Zc,Suspense:Ci,SuspenseList:jn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Hc,cloneElement:wi,createContext:Re,createElement:fe,createFactory:Gc,createPortal:nr,createRef:cc,default:Vt,findDOMNode:Xc,flushSync:ir,forwardRef:X,hydrate:Vc,isElement:el,isFragment:Kc,isMemo:Jc,isValidElement:jt,lazy:Uc,memo:tr,render:jc,startTransition:Ms,unmountComponentAtNode:Yc,unstable_batchedUpdates:Qc,useCallback:j,useContext:sn,useDebugValue:Ps,useDeferredValue:Ns,useEffect:G,useErrorBoundary:Kp,useId:Es,useImperativeHandle:xs,useInsertionEffect:Us,useLayoutEffect:Bt,useMemo:oe,useReducer:Qi,useRef:B,useState:V,useSyncExternalStore:As,useTransition:Ls,version:dm},Symbol.toStringTag,{value:"Module"}));var um=Symbol.for("preact-signals");function rr(){if(an>1)an--;else{for(var t,e=!1;_i!==void 0;){var n=_i;for(_i=void 0,Bs++;n!==void 0;){var i=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&sl(n))try{n.c()}catch(r){e||(t=r,e=!0)}n=i}}if(Bs=0,an--,e)throw t}}function nl(t){if(an>0)return t();an++;try{return t()}finally{rr()}}var se=void 0;function il(t){var e=se;se=void 0;try{return t()}finally{se=e}}var _i=void 0,an=0,Bs=0,sr=0;function rl(t){if(se!==void 0){var e=t.n;if(e===void 0||e.t!==se)return e={i:0,S:t,p:se.s,n:void 0,t:se,e:void 0,x:void 0,r:e},se.s!==void 0&&(se.s.n=e),se.s=e,t.n=e,32&se.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=se.s,e.n=void 0,se.s.n=e,se.s=e),e}}function Le(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e==null?void 0:e.watched,this.Z=e==null?void 0:e.unwatched,this.name=e==null?void 0:e.name}Le.prototype.brand=um,Le.prototype.h=function(){return!0},Le.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:il(function(){var i;(i=e.W)==null||i.call(e)}))},Le.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,i=t.x;n!==void 0&&(n.x=i,t.e=void 0),i!==void 0&&(i.e=n,t.x=void 0),t===this.t&&(this.t=i,i===void 0&&il(function(){var r;(r=e.Z)==null||r.call(e)}))}},Le.prototype.subscribe=function(t){var e=this;return qn(function(){var n=e.value,i=se;se=void 0;try{t(n)}finally{se=i}},{name:"sub"})},Le.prototype.valueOf=function(){return this.value},Le.prototype.toString=function(){return this.value+""},Le.prototype.toJSON=function(){return this.value},Le.prototype.peek=function(){var t=se;se=void 0;try{return this.value}finally{se=t}},Object.defineProperty(Le.prototype,"value",{get:function(){var t=rl(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Bs>100)throw new Error("Cycle detected");this.v=t,this.i++,sr++,an++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{rr()}}}});function Je(t,e){return new Le(t,e)}function sl(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function ol(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function al(t){for(var e=t.s,n=void 0;e!==void 0;){var i=e.p;e.i===-1?(e.S.U(e),i!==void 0&&(i.n=e.n),e.n!==void 0&&(e.n.p=i)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=i}t.s=n}function xn(t,e){Le.call(this,void 0),this.x=t,this.s=void 0,this.g=sr-1,this.f=4,this.W=e==null?void 0:e.watched,this.Z=e==null?void 0:e.unwatched,this.name=e==null?void 0:e.name}xn.prototype=new Le,xn.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===sr))return!0;if(this.g=sr,this.f|=1,this.i>0&&!sl(this))return this.f&=-2,!0;var t=se;try{ol(this),se=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return se=t,al(this),this.f&=-2,!0},xn.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}Le.prototype.S.call(this,t)},xn.prototype.U=function(t){if(this.t!==void 0&&(Le.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},xn.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(xn.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=rl(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function Ye(t,e){return new xn(t,e)}function cl(t){var e=t.u;if(t.u=void 0,typeof e=="function"){an++;var n=se;se=void 0;try{e()}catch(i){throw t.f&=-2,t.f|=8,js(t),i}finally{se=n,rr()}}}function js(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,cl(t)}function hm(t){if(se!==this)throw new Error("Out-of-order effect");al(this),se=t,this.f&=-2,8&this.f&&js(this),rr()}function Vn(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e==null?void 0:e.name}Vn.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Vn.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,cl(this),ol(this),an++;var t=se;return se=this,hm.bind(this,t)},Vn.prototype.N=function(){2&this.f||(this.f|=2,this.o=_i,_i=this)},Vn.prototype.d=function(){this.f|=8,1&this.f||js(this)},Vn.prototype.dispose=function(){this.d()};function qn(t,e){var n=new Vn(t,e);try{n.c()}catch(r){throw n.d(),r}var i=n.d.bind(n);return i[Symbol.dispose]=i,i}var Vs,or,qs,ll=[],dl=[];qn(function(){Vs=this.N})();function $n(t,e){$[t]=e.bind(null,$[t]||function(){})}function ar(t){qs&&qs(),qs=t&&t.S()}function ul(t){var e=this,n=t.data,i=Ie(n);i.value=n;var r=oe(function(){for(var a=e,c=e.__v;c=c.__;)if(c.__c){c.__c.__$f|=4;break}var l=Ye(function(){var f=i.value.value;return f===0?0:f===!0?"":f||""}),d=Ye(function(){return!Array.isArray(l.value)&&!tc(l.value)}),u=qn(function(){if(this.N=hl,d.value){var f=l.value;a.__v&&a.__v.__e&&a.__v.__e.nodeType===3&&(a.__v.__e.data=f)}}),h=e.__$u.d;return e.__$u.d=function(){u(),h.call(this)},[d,l]},[]),s=r[0],o=r[1];return s.value?o.peek():o.value}ul.displayName="ReactiveTextNode",Object.defineProperties(Le.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:ul},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),$n("__b",function(t,e){if(typeof e.type=="function"&&typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent(),typeof e.type=="string"){var n,i=e.props;for(var r in i)if(r!=="children"){var s=i[r];s instanceof Le&&(n||(e.__np=n={}),n[r]=s,i[r]=s.peek())}}t(e)}),$n("__r",function(t,e){if(typeof e.type=="function"&&typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.enterComponent(e.type.displayName||e.type.name||"Unknown"),e.type!==ge){ar();var n,i=e.__c;i&&(i.__$f&=-2,(n=i.__$u)===void 0&&(i.__$u=n=(function(r){var s;return qn(function(){s=this}),s.c=function(){i.__$f|=1,i.setState({})},s})())),or=i,ar(n)}t(e)}),$n("__e",function(t,e,n,i){typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent(),ar(),or=void 0,t(e,n,i)}),$n("diffed",function(t,e){typeof e.type=="function"&&typeof window<"u"&&window.__PREACT_SIGNALS_DEVTOOLS__&&window.__PREACT_SIGNALS_DEVTOOLS__.exitComponent(),ar(),or=void 0;var n;if(typeof e.type=="string"&&(n=e.__e)){var i=e.__np,r=e.props;if(i){var s=n.U;if(s)for(var o in s){var a=s[o];a!==void 0&&!(o in i)&&(a.d(),s[o]=void 0)}else s={},n.U=s;for(var c in i){var l=s[c],d=i[c];l===void 0?(l=fm(n,c,d,r),s[c]=l):l.o(d,r)}}}t(e)});function fm(t,e,n,i){var r=e in t&&t.ownerSVGElement===void 0,s=Je(n);return{o:function(o,a){s.value=o,i=a},d:qn(function(){this.N=hl;var o=s.value.value;i[e]!==o&&(i[e]=o,r?t[e]=o:o?t.setAttribute(e,o):t.removeAttribute(e))})}}$n("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var i=n.U;if(i){n.U=void 0;for(var r in i){var s=i[r];s&&s.d()}}}}else{var o=e.__c;if(o){var a=o.__$u;a&&(o.__$u=void 0,a.d())}}t(e)}),$n("__h",function(t,e,n,i){(i<3||i===9)&&(e.__$f|=2),t(e,n,i)}),rt.prototype.shouldComponentUpdate=function(t,e){var n=this.__$u,i=n&&n.s!==void 0;for(var r in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(i||s||4&this.__$f)||1&this.__$f)return!0}else if(!(i||4&this.__$f)||3&this.__$f)return!0;for(var o in t)if(o!=="__source"&&t[o]!==this.props[o])return!0;for(var a in this.props)if(!(a in t))return!0;return!1};function Ie(t,e){return V(function(){return Je(t,e)})[0]}function ue(t,e){var n=B(t);return n.current=t,or.__$f|=4,oe(function(){return Ye(function(){return n.current()},e)},[])}var pm=typeof requestAnimationFrame>"u"?setTimeout:function(t){var e=function(){clearTimeout(n),cancelAnimationFrame(i),t()},n=setTimeout(e,35),i=requestAnimationFrame(e)},mm=function(t){queueMicrotask(function(){queueMicrotask(t)})};function gm(){nl(function(){for(var t;t=ll.shift();)Vs.call(t)})}function vm(){ll.push(this)===1&&($.requestAnimationFrame||pm)(gm)}function bm(){nl(function(){for(var t;t=dl.shift();)Vs.call(t)})}function hl(){dl.push(this)===1&&($.requestAnimationFrame||mm)(bm)}function Ct(t,e){var n=B(t);n.current=t,G(function(){return qn(function(){return this.N=vm,n.current()},e)},[])}function ym(t,e){return e.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(i){if(i!=="default"&&!(i in t)){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}})}),Object.freeze(t)}var km=Object.defineProperty,Cm=(t,e,n)=>e in t?km(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fl=(t,e,n)=>Cm(t,typeof e!="symbol"?e+"":e,n);let qe=class{constructor(){fl(this,"_locking"),fl(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const n=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>n),i}};function ye(t,e){if(!t)throw new Error(e)}const wm=34028234663852886e22,_m=-34028234663852886e22,Sm=4294967295,Tm=2147483647,xm=-2147483648;function cr(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>Tm||t<xm)throw new Error("invalid int 32: "+t)}function $s(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>Sm||t<0)throw new Error("invalid uint 32: "+t)}function pl(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>wm||t<_m))throw new Error("invalid float 32: "+t)}const ml=Symbol("@bufbuild/protobuf/enum-type");function Pm(t){const e=t[ml];return ye(e,"missing enum type on enum object"),e}function gl(t,e,n,i){t[ml]=vl(e,n.map(r=>({no:r.no,name:r.name,localName:t[r.no]})))}function vl(t,e,n){const i=Object.create(null),r=Object.create(null),s=[];for(const o of e){const a=bl(o);s.push(a),i[o.name]=a,r[o.no]=a}return{typeName:t,values:s,findName(o){return i[o]},findNumber(o){return r[o]}}}function Em(t,e,n){const i={};for(const r of e){const s=bl(r);i[s.localName]=s.no,i[s.no]=s.localName}return gl(i,t,e),i}function bl(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class zs{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,n){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(n);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,n){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(n);return r.readMessage(i,e,s,this),this}fromJsonString(e,n){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,n)}toBinary(e){const n=this.getType(),i=n.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const n=this.getType(),i=n.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var n;const i=this.toJson(e);return JSON.stringify(i,null,(n=e==null?void 0:e.prettySpaces)!==null&&n!==void 0?n:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Rm(t,e,n,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),o={[s]:function(a){t.util.initFields(this),t.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new zs),Object.assign(o,{runtime:t,typeName:e,fields:t.util.newFieldList(n),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return t.util.equals(o,a,c)}}),o}function Im(){let t=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function Ws(t,e,n){for(let s=0;s<28;s=s+7){const o=t>>>s,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(n.push(c),!a)return}const i=t>>>28&15|(e&7)<<4,r=e>>3!=0;if(n.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const o=e>>>s,a=!!(o>>>7),c=(a?o|128:o)&255;if(n.push(c),!a)return}n.push(e>>>31&1)}}const lr=4294967296;function yl(t){const e=t[0]==="-";e&&(t=t.slice(1));const n=1e6;let i=0,r=0;function s(o,a){const c=Number(t.slice(o,a));r*=n,i=i*n+c,i>=lr&&(r=r+(i/lr|0),i=i%lr)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Cl(i,r):Hs(i,r)}function Om(t,e){let n=Hs(t,e);const i=n.hi&2147483648;i&&(n=Cl(n.lo,n.hi));const r=kl(n.lo,n.hi);return i?"-"+r:r}function kl(t,e){if({lo:t,hi:e}=Am(t,e),e<=2097151)return String(lr*e+t);const n=t&16777215,i=(t>>>24|e<<8)&16777215,r=e>>16&65535;let s=n+i*6777216+r*6710656,o=i+r*8147497,a=r*2;const c=1e7;return s>=c&&(o+=Math.floor(s/c),s%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+wl(o)+wl(s)}function Am(t,e){return{lo:t>>>0,hi:e>>>0}}function Hs(t,e){return{lo:t|0,hi:e|0}}function Cl(t,e){return e=~e,t?t=~t+1:e+=1,Hs(t,e)}const wl=t=>{const e=String(t);return"0000000".slice(e.length)+e};function _l(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function Dm(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Mm(){const t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>s||l<r)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return t.setBigInt64(0,this.parse(c),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(c){return t.setBigInt64(0,this.uParse(c),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(c,l){return t.setInt32(0,c,!0),t.setInt32(4,l,!0),t.getBigInt64(0,!0)},uDec(c,l){return t.setInt32(0,c,!0),t.setInt32(4,l,!0),t.getBigUint64(0,!0)}}}const n=r=>ye(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>ye(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),n(r),yl(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),yl(r)},dec(r,s){return Om(r,s)},uDec(r,s){return kl(r,s)}}}const pe=Mm();var E;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(E||(E={}));var cn;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"})(cn||(cn={}));function ln(t,e,n){if(e===n)return!0;if(t==E.BYTES){if(!(e instanceof Uint8Array)||!(n instanceof Uint8Array)||e.length!==n.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==n[i])return!1;return!0}switch(t){case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==n}return!1}function zn(t,e){switch(t){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==0?pe.zero:"0";case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function Sl(t,e){switch(t){case E.BOOL:return e===!1;case E.STRING:return e==="";case E.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var we;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(we||(we={}));class Nm{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let n=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)n.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for($s(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return cr(e),_l(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.textEncoder.encode(e);return this.uint32(n.byteLength),this.raw(n)}float(e){pl(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){$s(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){cr(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return cr(e),e=(e<<1^e>>31)>>>0,_l(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),r=pe.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),r=pe.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}int64(e){let n=pe.enc(e);return Ws(n.lo,n.hi,this.buf),this}sint64(e){let n=pe.enc(e),i=n.hi>>31,r=n.lo<<1^i,s=(n.hi<<1|n.lo>>>31)^i;return Ws(r,s,this.buf),this}uint64(e){let n=pe.uEnc(e);return Ws(n.lo,n.hi,this.buf),this}}class Lm{constructor(e,n){this.varint64=Im,this.uint32=Dm,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=n??new TextDecoder}tag(){let e=this.uint32(),n=e>>>3,i=e&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(e,n){let i=this.pos;switch(e){case we.Varint:for(;this.buf[this.pos++]&128;);break;case we.Bit64:this.pos+=4;case we.Bit32:this.pos+=4;break;case we.LengthDelimited:let r=this.uint32();this.pos+=r;break;case we.StartGroup:for(;;){const[s,o]=this.tag();if(o===we.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return pe.dec(...this.varint64())}uint64(){return pe.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),i=-(e&1);return e=(e>>>1|(n&1)<<31)^i,n=n>>>1^i,pe.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return pe.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return pe.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(){return this.textDecoder.decode(this.bytes())}}function Um(t,e,n,i){let r;return{typeName:e,extendee:n,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=t.util.newFieldList([s]).list()[0]}return r},runtime:t}}function Tl(t){const e=t.field.localName,n=Object.create(null);return n[e]=Fm(t),[n,()=>n[e]]}function Fm(t){const e=t.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return zn(e.T,e.L);case"message":const n=e.T,i=new n;return n.fieldWrapper?n.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function Bm(t,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let n=t.length-1;n>=0;--n)if(t[n].no==e.no)return[t[n]];return[]}return t.filter(n=>n.no===e.no)}let qt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),dr=[];for(let t=0;t<qt.length;t++)dr[qt[t].charCodeAt(0)]=t;dr[45]=qt.indexOf("+"),dr[95]=qt.indexOf("/");const xl={dec(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let n=new Uint8Array(e),i=0,r=0,s,o=0;for(let a=0;a<t.length;a++){if(s=dr[t.charCodeAt(a)],s===void 0)switch(t[a]){case"=":r=0;case`
2
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:n[i++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:n[i++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:n[i++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return n.subarray(0,i)},enc(t){let e="",n=0,i,r=0;for(let s=0;s<t.length;s++)switch(i=t[s],n){case 0:e+=qt[i>>2],r=(i&3)<<4,n=1;break;case 1:e+=qt[r|i>>4],r=(i&15)<<2,n=2;break;case 2:e+=qt[r|i>>6],e+=qt[i&63],n=0;break}return n&&(e+=qt[r],e+="=",n==1&&(e+="=")),e}};function jm(t,e,n){El(e,t);const i=e.runtime.bin.makeReadOptions(n),r=Bm(t.getType().runtime.bin.listUnknownFields(t),e.field),[s,o]=Tl(e);for(const a of r)e.runtime.bin.readField(s,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function Vm(t,e,n,i){El(e,t);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(Pl(t,e)){const l=t.getType().runtime.bin.listUnknownFields(t).filter(d=>d.no!=e.field.no);t.getType().runtime.bin.discardUnknownFields(t);for(const d of l)t.getType().runtime.bin.onUnknownField(t,d.no,d.wireType,d.data)}const o=s.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,n,o,s);const c=r.readerFactory(o.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);t.getType().runtime.bin.onUnknownField(t,l,d,u)}}function Pl(t,e){const n=t.getType();return e.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(t).find(i=>i.no==e.field.no)}function El(t,e){ye(t.extendee.typeName==e.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function Rl(t,e){const n=t.localName;if(t.repeated)return e[n].length>0;if(t.oneof)return e[t.oneof.localName].case===n;switch(t.kind){case"enum":case"scalar":return t.opt||t.req?e[n]!==void 0:t.kind=="enum"?e[n]!==t.T.values[0].no:!Sl(t.T,e[n]);case"message":return e[n]!==void 0;case"map":return Object.keys(e[n]).length>0}}function Il(t,e){const n=t.localName,i=!t.opt&&!t.req;if(t.repeated)e[n]=[];else if(t.oneof)e[t.oneof.localName]={case:void 0};else switch(t.kind){case"map":e[n]={};break;case"enum":e[n]=i?t.T.values[0].no:void 0;break;case"scalar":e[n]=i?zn(t.T,t.L):void 0;break;case"message":e[n]=void 0;break}}function $t(t,e){if(t===null||typeof t!="object"||!Object.getOwnPropertyNames(zs.prototype).every(i=>i in t&&typeof t[i]=="function"))return!1;const n=t.getType();return n===null||typeof n!="function"||!("typeName"in n)||typeof n.typeName!="string"?!1:e===void 0?!0:n.typeName==e.typeName}function Ol(t,e){return $t(e)||!t.fieldWrapper?e:t.fieldWrapper.wrapField(e)}E.DOUBLE,E.FLOAT,E.INT64,E.UINT64,E.INT32,E.UINT32,E.BOOL,E.STRING,E.BYTES;const Al={ignoreUnknownFields:!1},Dl={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function qm(t){return t?Object.assign(Object.assign({},Al),t):Al}function $m(t){return t?Object.assign(Object.assign({},Dl),t):Dl}const ur=Symbol(),hr=Symbol();function zm(){return{makeReadOptions:qm,makeWriteOptions:$m,readMessage(t,e,n,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(wt(e)));i=i??new t;const r=new Map,s=n.typeRegistry;for(const[o,a]of Object.entries(e)){const c=t.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=r.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));r.set(c.oneof,o)}Ml(i,a,c,n,t)}else{let l=!1;if(s!=null&&s.findExtension&&o.startsWith("[")&&o.endsWith("]")){const d=s.findExtension(o.substring(1,o.length-1));if(d&&d.extendee.typeName==t.typeName){l=!0;const[u,h]=Tl(d);Ml(u,a,d.field,n,d),Vm(i,d,h(),n)}}if(!l&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(t,e){const n=t.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!Rl(r,t)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Hm(r))continue}const o=r.oneof?t[r.oneof.localName].value:t[r.localName],a=Nl(r,o,e);a!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=a)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const o of n.runtime.bin.listUnknownFields(t)){const a=s.findExtensionFor(n.typeName,o.no);if(a&&Pl(t,a)){const c=jm(t,a,e),l=Nl(a.field,c,e);l!==void 0&&(i[a.field.jsonName]=l)}}}catch(s){const o=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?": ".concat(a):""))}return i},readScalar(t,e,n){return Si(t,e,n??cn.BIGINT,!0)},writeScalar(t,e,n){if(e!==void 0&&(n||Sl(t,e)))return fr(t,e)},debug:wt}}function wt(t){if(t===null)return"null";switch(typeof t){case"object":return Array.isArray(t)?"array":"object";case"string":return t.length>100?"string":'"'.concat(t.split('"').join('\\"'),'"');default:return String(t)}}function Ml(t,e,n,i,r){let s=n.localName;if(n.repeated){if(ye(n.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e)));const o=t[s];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(a)));switch(n.kind){case"message":o.push(n.T.fromJson(a,i));break;case"enum":const c=Gs(n.T,a,i.ignoreUnknownFields,!0);c!==hr&&o.push(c);break;case"scalar":try{o.push(Si(n.T,a,n.L,!0))}catch(l){let d="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(a));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}}else if(n.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e)));const o=t[s];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let l;try{l=Wm(n.K,a)}catch(d){let u="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(n.V.kind){case"message":o[l]=n.V.T.fromJson(c,i);break;case"enum":const d=Gs(n.V.T,c,i.ignoreUnknownFields,!0);d!==hr&&(o[l]=d);break;case"scalar":try{o[l]=Si(n.V.T,c,cn.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(n.oneof&&(t=t[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const o=n.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=t[s];$t(a)?a.fromJson(e,i):(t[s]=a=o.fromJson(e,i),o.fieldWrapper&&!n.oneof&&(t[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Gs(n.T,e,i.ignoreUnknownFields,!1);switch(c){case ur:Il(n,t);break;case hr:break;default:t[s]=c;break}break;case"scalar":try{const l=Si(n.T,e,n.L,!1);switch(l){case ur:Il(n,t);break;default:t[s]=l;break}}catch(l){let d="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Wm(t,e){if(t===E.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Si(t,e,cn.BIGINT,!0).toString()}function Si(t,e,n,i){if(e===null)return i?zn(t,n):ur;switch(t){case E.DOUBLE:case E.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return t==E.FLOAT&&pl(r),r;case E.INT32:case E.FIXED32:case E.SFIXED32:case E.SINT32:case E.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return t==E.UINT32||t==E.FIXED32?$s(s):cr(s),s;case E.INT64:case E.SFIXED64:case E.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=pe.parse(e);return n?o.toString():o;case E.FIXED64:case E.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=pe.uParse(e);return n?a.toString():a;case E.BOOL:if(typeof e!="boolean")break;return e;case E.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case E.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return xl.dec(e)}throw new Error}function Gs(t,e,n,i){if(e===null)return t.typeName=="google.protobuf.NullValue"?0:i?t.values[0].no:ur;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=t.findName(e);if(r!==void 0)return r.no;if(n)return hr;break}throw new Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(wt(e)))}function Hm(t){return t.repeated||t.kind=="map"?!0:!(t.oneof||t.kind=="message"||t.opt||t.req)}function Nl(t,e,n){if(t.kind=="map"){ye(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(t.V.kind){case"scalar":for(const[o,a]of r)i[o.toString()]=fr(t.V.T,a);break;case"message":for(const[o,a]of r)i[o.toString()]=a.toJson(n);break;case"enum":const s=t.V.T;for(const[o,a]of r)i[o.toString()]=Ks(s,a,n.enumAsInteger);break}return n.emitDefaultValues||r.length>0?i:void 0}if(t.repeated){ye(Array.isArray(e));const i=[];switch(t.kind){case"scalar":for(let r=0;r<e.length;r++)i.push(fr(t.T,e[r]));break;case"enum":for(let r=0;r<e.length;r++)i.push(Ks(t.T,e[r],n.enumAsInteger));break;case"message":for(let r=0;r<e.length;r++)i.push(e[r].toJson(n));break}return n.emitDefaultValues||i.length>0?i:void 0}switch(t.kind){case"scalar":return fr(t.T,e);case"enum":return Ks(t.T,e,n.enumAsInteger);case"message":return Ol(t.T,e).toJson(n)}}function Ks(t,e,n){var i;if(ye(typeof e=="number"),t.typeName=="google.protobuf.NullValue")return null;if(n)return e;const r=t.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function fr(t,e){switch(t){case E.INT32:case E.SFIXED32:case E.SINT32:case E.FIXED32:case E.UINT32:return ye(typeof e=="number"),e;case E.FLOAT:case E.DOUBLE:return ye(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case E.STRING:return ye(typeof e=="string"),e;case E.BOOL:return ye(typeof e=="boolean"),e;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return ye(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case E.BYTES:return ye(e instanceof Uint8Array),xl.enc(e)}}const Wn=Symbol("@bufbuild/protobuf/unknown-fields"),Ll={readUnknownFields:!0,readerFactory:t=>new Lm(t)},Ul={writeUnknownFields:!0,writerFactory:()=>new Nm};function Gm(t){return t?Object.assign(Object.assign({},Ll),t):Ll}function Km(t){return t?Object.assign(Object.assign({},Ul),t):Ul}function Jm(){return{makeReadOptions:Gm,makeWriteOptions:Km,listUnknownFields(t){var e;return(e=t[Wn])!==null&&e!==void 0?e:[]},discardUnknownFields(t){delete t[Wn]},writeUnknownFields(t,e){const i=t[Wn];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(t,e,n,i){const r=t;Array.isArray(r[Wn])||(r[Wn]=[]),r[Wn].push({no:e,wireType:n,data:i})},readMessage(t,e,n,i,r){const s=t.getType(),o=r?e.len:e.pos+n;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(r===!0&&c==we.EndGroup));){const l=s.fields.find(a);if(!l){const d=e.skip(c,a);i.readUnknownFields&&this.onUnknownField(t,a,c,d);continue}Fl(t,e,l,c,i)}if(r&&(c!=we.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:Fl,writeMessage(t,e,n){const i=t.getType();for(const r of i.fields.byNumber()){if(!Rl(r,t)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?t[r.oneof.localName].value:t[r.localName];Bl(r,s,e,n)}return n.writeUnknownFields&&this.writeUnknownFields(t,e),e},writeField(t,e,n,i){e!==void 0&&Bl(t,e,n,i)}}}function Fl(t,e,n,i,r){let{repeated:s,localName:o}=n;switch(n.oneof&&(t=t[n.oneof.localName],t.case!=o&&delete t.value,t.case=o,o="value"),n.kind){case"scalar":case"enum":const a=n.kind=="enum"?E.INT32:n.T;let c=mr;if(n.kind=="scalar"&&n.L>0&&(c=Xm),s){let h=t[o];if(i==we.LengthDelimited&&a!=E.STRING&&a!=E.BYTES){let v=e.uint32()+e.pos;for(;e.pos<v;)h.push(c(e,a))}else h.push(c(e,a))}else t[o]=c(e,a);break;case"message":const l=n.T;s?t[o].push(pr(e,new l,r,n)):$t(t[o])?pr(e,t[o],r,n):(t[o]=pr(e,new l,r,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(t[o]=l.fieldWrapper.unwrapField(t[o])));break;case"map":let[d,u]=Ym(n,e,r);t[o][d]=u;break}}function pr(t,e,n,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,t,s?i.no:t.uint32(),n,s),e}function Ym(t,e,n){const i=e.uint32(),r=e.pos+i;let s,o;for(;e.pos<r;){const[a]=e.tag();switch(a){case 1:s=mr(e,t.K);break;case 2:switch(t.V.kind){case"scalar":o=mr(e,t.V.T);break;case"enum":o=e.int32();break;case"message":o=pr(e,new t.V.T,n,void 0);break}break}}if(s===void 0&&(s=zn(t.K,cn.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),o===void 0)switch(t.V.kind){case"scalar":o=zn(t.V.T,cn.BIGINT);break;case"enum":o=t.V.T.values[0].no;break;case"message":o=new t.V.T;break}return[s,o]}function Xm(t,e){const n=mr(t,e);return typeof n=="bigint"?n.toString():n}function mr(t,e){switch(e){case E.STRING:return t.string();case E.BOOL:return t.bool();case E.DOUBLE:return t.double();case E.FLOAT:return t.float();case E.INT32:return t.int32();case E.INT64:return t.int64();case E.UINT64:return t.uint64();case E.FIXED64:return t.fixed64();case E.BYTES:return t.bytes();case E.FIXED32:return t.fixed32();case E.SFIXED32:return t.sfixed32();case E.SFIXED64:return t.sfixed64();case E.SINT64:return t.sint64();case E.UINT32:return t.uint32();case E.SINT32:return t.sint32()}}function Bl(t,e,n,i){ye(e!==void 0);const r=t.repeated;switch(t.kind){case"scalar":case"enum":let s=t.kind=="enum"?E.INT32:t.T;if(r)if(ye(Array.isArray(e)),t.packed)Zm(n,s,t.no,e);else for(const o of e)Ti(n,s,t.no,o);else Ti(n,s,t.no,e);break;case"message":if(r){ye(Array.isArray(e));for(const o of e)jl(n,i,t,o)}else jl(n,i,t,e);break;case"map":ye(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))Qm(n,i,t,o,a);break}}function Qm(t,e,n,i,r){t.tag(n.no,we.LengthDelimited),t.fork();let s=i;switch(n.K){case E.INT32:case E.FIXED32:case E.UINT32:case E.SFIXED32:case E.SINT32:s=Number.parseInt(i);break;case E.BOOL:ye(i=="true"||i=="false"),s=i=="true";break}switch(Ti(t,n.K,1,s),n.V.kind){case"scalar":Ti(t,n.V.T,2,r);break;case"enum":Ti(t,E.INT32,2,r);break;case"message":ye(r!==void 0),t.tag(2,we.LengthDelimited).bytes(r.toBinary(e));break}t.join()}function jl(t,e,n,i){const r=Ol(n.T,i);n.delimited?t.tag(n.no,we.StartGroup).raw(r.toBinary(e)).tag(n.no,we.EndGroup):t.tag(n.no,we.LengthDelimited).bytes(r.toBinary(e))}function Ti(t,e,n,i){ye(i!==void 0);let[r,s]=Vl(e);t.tag(n,r)[s](i)}function Zm(t,e,n,i){if(!i.length)return;t.tag(n,we.LengthDelimited).fork();let[,r]=Vl(e);for(let s=0;s<i.length;s++)t[r](i[s]);t.join()}function Vl(t){let e=we.Varint;switch(t){case E.BYTES:case E.STRING:e=we.LengthDelimited;break;case E.DOUBLE:case E.FIXED64:case E.SFIXED64:e=we.Bit64;break;case E.FIXED32:case E.SFIXED32:case E.FLOAT:e=we.Bit32;break}const n=E[t].toLowerCase();return[e,n]}function eg(){return{setEnumType:gl,initPartial(t,e){if(t===void 0)return;const n=e.getType();for(const i of n.fields.byMember()){const r=i.localName,s=e,o=t;if(o[r]!=null)switch(i.kind){case"oneof":const a=o[r].case;if(a===void 0)continue;const c=i.findField(a);let l=o[r].value;c&&c.kind=="message"&&!$t(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===E.BYTES&&(l=xi(l)),s[r]={case:a,value:l};break;case"scalar":case"enum":let d=o[r];i.T===E.BYTES&&(d=i.repeated?d.map(xi):xi(d)),s[r]=d;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===E.BYTES)for(const[f,v]of Object.entries(o[r]))s[r][f]=xi(v);else Object.assign(s[r],o[r]);break;case"message":const h=i.V.T;for(const f of Object.keys(o[r])){let v=o[r][f];h.fieldWrapper||(v=new h(v)),s[r][f]=v}break}break;case"message":const u=i.T;if(i.repeated)s[r]=o[r].map(h=>$t(h,u)?h:new u(h));else{const h=o[r];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?s[r]=xi(h):s[r]=h:s[r]=$t(h,u)?h:new u(h)}break}}},equals(t,e,n){return e===n?!0:!e||!n?!1:t.fields.byMember().every(i=>{const r=e[i.localName],s=n[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((o,a)=>i.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>ln(i.T,o,s[a]));case"enum":return r.every((o,a)=>ln(E.INT32,o,s[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=r,a=s;return i.T.fieldWrapper&&(o!==void 0&&!$t(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!$t(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return ln(E.INT32,r,s);case"scalar":return ln(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=i.findField(r.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(r.value,s.value);case"enum":return ln(E.INT32,r.value,s.value);case"scalar":return ln(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const d=i.V.T;return l.every(h=>d.equals(r[h],s[h]));case"enum":return l.every(h=>ln(E.INT32,r[h],s[h]));case"scalar":const u=i.V.T;return l.every(h=>ln(u,r[h],s[h]))}break}})},clone(t){const e=t.getType(),n=new e,i=n;for(const r of e.fields.byMember()){const s=t[r.localName];let o;if(r.repeated)o=s.map(gr);else if(r.kind=="map"){o=i[r.localName];for(const[a,c]of Object.entries(s))o[a]=gr(c)}else r.kind=="oneof"?o=r.findField(s.case)?{case:s.case,value:gr(s.value)}:{case:void 0}:o=gr(s);i[r.localName]=o}for(const r of e.runtime.bin.listUnknownFields(t))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return n}}}function gr(t){if(t===void 0)return t;if($t(t))return t.clone();if(t instanceof Uint8Array){const e=new Uint8Array(t.byteLength);return e.set(t),e}return t}function xi(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function tg(t,e,n){return{syntax:t,json:zm(),bin:Jm(),util:Object.assign(Object.assign({},eg()),{newFieldList:e,initFields:n}),makeMessageType(i,r,s){return Rm(this,i,r,s)},makeEnum:Em,makeEnumType:vl,getEnumType:Pm,makeExtension(i,r,s){return Um(this,i,r,s)}}}class ng{constructor(e,n){this._fields=e,this._normalizer=n}findJsonName(e){if(!this.jsonNames){const n={};for(const i of this.list())n[i.jsonName]=n[i.name]=i;this.jsonNames=n}return this.jsonNames[e]}find(e){if(!this.numbers){const n={};for(const i of this.list())n[i.no]=i;this.numbers=n}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,n)=>e.no-n.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let n;for(const i of this.list())i.oneof?i.oneof!==n&&(n=i.oneof,e.push(n)):e.push(i)}return this.members}}function ql(t,e){const n=$l(t);return e?n:cg(ag(n))}function ig(t){return ql(t,!1)}const rg=$l;function $l(t){let e=!1;const n=[];for(let i=0;i<t.length;i++){let r=t.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),n.push(r);break}}return n.join("")}const sg=new Set(["constructor","toString","toJSON","valueOf"]),og=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),zl=t=>"".concat(t,"$"),ag=t=>og.has(t)?zl(t):t,cg=t=>sg.has(t)?zl(t):t;class lg{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ig(e)}addField(e){ye(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let n=0;n<this.fields.length;n++)this._lookup[this.fields[n].localName]=this.fields[n]}return this._lookup[e]}}function dg(t,e){var n,i,r,s,o,a;const c=[];let l;for(const d of typeof t=="function"?t():t){const u=d;if(u.localName=ql(d.name,d.oneof!==void 0),u.jsonName=(n=d.jsonName)!==null&&n!==void 0?n:rg(d.name),u.repeated=(i=d.repeated)!==null&&i!==void 0?i:!1,d.kind=="scalar"&&(u.L=(r=d.L)!==null&&r!==void 0?r:cn.BIGINT),u.delimited=(s=d.delimited)!==null&&s!==void 0?s:!1,u.req=(o=d.req)!==null&&o!==void 0?o:!1,u.opt=(a=d.opt)!==null&&a!==void 0?a:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=E.BYTES&&d.T!=E.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new lg(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const T=tg("proto3",t=>new ng(t,e=>dg(e)),t=>{for(const e of t.getType().fields.byMember()){if(e.opt)continue;const n=e.localName,i=t;if(e.repeated){i[n]=[];continue}switch(e.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=zn(e.T,e.L);break}}});class $e extends zs{constructor(e){super(),this.seconds=pe.zero,this.nanos=0,T.util.initPartial(e,this)}fromJson(e,n){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(T.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=pe.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const n=Number(this.seconds)*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(n).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return $e.fromDate(new Date)}static fromDate(e){const n=e.getTime();return new $e({seconds:pe.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(e,n){return new $e().fromBinary(e,n)}static fromJson(e,n){return new $e().fromJson(e,n)}static fromJsonString(e,n){return new $e().fromJsonString(e,n)}static equals(e,n){return T.util.equals($e,e,n)}}$e.runtime=T,$e.typeName="google.protobuf.Timestamp",$e.fields=T.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const ug=T.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:$e},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:hg,repeated:!0},{no:5,name:"events",kind:"message",T:pg,repeated:!0}]),hg=T.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:fg,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),fg=T.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:$e},{no:3,name:"value",kind:"scalar",T:2}]),pg=T.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:$e},{no:7,name:"normalized_end_timestamp",kind:"message",T:$e,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Wl=T.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),ot=T.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Te=T.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Js=T.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Pi=T.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ei=T.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),at=T.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),Hn=T.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),mg=T.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),De=T.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),vr=T.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:br,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:sd}]),br=T.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),gg=T.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:T.getEnumType(Te),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),Pn=T.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:T.getEnumType(Gn)},{no:4,name:"tracks",kind:"message",T:Kn,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:gg},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:T.getEnumType(Ri)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:T.getEnumType(at)},{no:18,name:"kind_details",kind:"enum",T:T.getEnumType(vg),repeated:!0}]),Gn=T.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ri=T.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),vg=T.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Xe=T.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),bg=T.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:En,repeated:!0}]),Kn=T.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:T.getEnumType(ot)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:T.getEnumType(Te)},{no:10,name:"layers",kind:"message",T:En,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:bg,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:T.getEnumType(Xe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:sd},{no:19,name:"audio_features",kind:"enum",T:T.getEnumType(De),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(Wl)}]),En=T.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(Js)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),ze=T.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:T.getEnumType(K)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Gl,oneof:"value"},{no:3,name:"speaker",kind:"message",T:yg,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Kl,oneof:"value"},{no:7,name:"transcription",kind:"message",T:kg,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ug,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Ys,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Jl,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Yl,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Xl,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Qs,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Zs,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:eo,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),K=T.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),yg=T.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Hl,repeated:!0}]),Hl=T.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),Gl=T.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Kl=T.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),kg=T.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Cg,repeated:!0}]),Cg=T.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),Ys=T.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),Jl=T.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),Yl=T.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Xl=T.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Ql,oneof:"value"}]),Ql=T.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),Zl=T.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),ed=T.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:T.getEnumType(td)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),td=T.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),wg=T.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:T.getEnumType(nd)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),nd=T.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),id=T.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:rd},{no:2,name:"screen",kind:"message",T:rd},{no:3,name:"resume_connection",kind:"enum",T:T.getEnumType(Ei)},{no:4,name:"disabled_codecs",kind:"message",T:_g},{no:5,name:"force_relay",kind:"enum",T:T.getEnumType(Ei)}]),rd=T.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:T.getEnumType(Ei)}]),_g=T.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:br,repeated:!0},{no:2,name:"publish",kind:"message",T:br,repeated:!0}]),sd=T.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Xs=T.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),od=T.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:T.getEnumType(Xs)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),ad=T.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Qs=T.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:T.getEnumType(Xe)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:od,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:ad,oneof:"content_header"}],{localName:"DataStream_Header"}),Zs=T.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),eo=T.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),ct=T.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),to=T.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Sg=T.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Tg=T.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Rn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Rn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ro,oneof:"message"},{no:4,name:"add_track",kind:"message",T:io,oneof:"message"},{no:5,name:"mute",kind:"message",T:so,oneof:"message"},{no:6,name:"subscription",kind:"message",T:yr,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ld,oneof:"message"},{no:8,name:"leave",kind:"message",T:kr,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ud,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:md,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:gd,oneof:"message"},{no:13,name:"simulate",kind:"message",T:_t,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:hd,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:yd,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:dd,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ig,oneof:"message"}]),cd=T.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:xg,oneof:"message"},{no:2,name:"answer",kind:"message",T:Rn,oneof:"message"},{no:3,name:"offer",kind:"message",T:Rn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ro,oneof:"message"},{no:5,name:"update",kind:"message",T:Rg,oneof:"message"},{no:6,name:"track_published",kind:"message",T:oo,oneof:"message"},{no:8,name:"leave",kind:"message",T:kr,oneof:"message"},{no:9,name:"mute",kind:"message",T:so,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Og,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Ag,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Mg,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Lg,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Fg,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Bg,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Eg,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Pg,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Vg,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:zg,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Wg,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Hg,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:jg,oneof:"message"}]),no=T.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),io=T.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:T.getEnumType(ot)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:T.getEnumType(Te)},{no:9,name:"layers",kind:"message",T:En,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:no,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:T.getEnumType(Xe)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(Wl)},{no:17,name:"audio_features",kind:"enum",T:T.getEnumType(De),repeated:!0}]),ro=T.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:T.getEnumType(ct)},{no:3,name:"final",kind:"scalar",T:8}]),so=T.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),xg=T.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:vr},{no:2,name:"participant",kind:"message",T:Pn},{no:3,name:"other_participants",kind:"message",T:Pn,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:fd,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:id},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:ed},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:br,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Pg=T.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:fd,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:id},{no:3,name:"server_info",kind:"message",T:ed},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),oo=T.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Kn}]),Eg=T.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Rn=T.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),Rg=T.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Pn,repeated:!0}]),yr=T.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Zl,repeated:!0}]),ld=T.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:T.getEnumType(Js)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),dd=T.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:T.getEnumType(De),repeated:!0}]),Ig=T.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),kr=T.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:T.getEnumType(at)},{no:3,name:"action",kind:"enum",T:T.getEnumType(Jn)},{no:4,name:"regions",kind:"message",T:qg}]),Jn=T.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ud=T.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:En,repeated:!0}]),hd=T.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),fd=T.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Og=T.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Hl,repeated:!0}]),Ag=T.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:vr}]),Dg=T.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:T.getEnumType(Pi)},{no:3,name:"score",kind:"scalar",T:2}]),Mg=T.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Dg,repeated:!0}]),Ng=T.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:T.getEnumType(to)}]),Lg=T.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Ng,repeated:!0}]),ao=T.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(Js)},{no:2,name:"enabled",kind:"scalar",T:8}]),Ug=T.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ao,repeated:!0}]),Fg=T.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ao,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Ug,repeated:!0}]),pd=T.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),md=T.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:pd,repeated:!0}]),Bg=T.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),jg=T.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:vr},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Pn},{no:4,name:"other_participants",kind:"message",T:Pn,repeated:!0}]),gd=T.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Rn},{no:2,name:"subscription",kind:"message",T:yr},{no:3,name:"publish_tracks",kind:"message",T:oo,repeated:!0},{no:4,name:"data_channels",kind:"message",T:bd,repeated:!0},{no:5,name:"offer",kind:"message",T:Rn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:vd,repeated:!0}]),vd=T.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),bd=T.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:T.getEnumType(ct)}]),_t=T.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:T.getEnumType(Sg),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),yd=T.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Vg=T.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),qg=T.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:$g,repeated:!0}]),$g=T.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),zg=T.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:T.getEnumType(mg)}]),Wg=T.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:T.getEnumType(co)},{no:3,name:"message",kind:"scalar",T:9}]),co=T.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Hg=T.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Gg(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Cr={exports:{}},Kg=Cr.exports,kd;function Jg(){return kd||(kd=1,(function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(Kg,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(p,g){var b=p[g];if(typeof b.bind=="function")return b.bind(p);try{return Function.prototype.bind.call(b,p)}catch{return function(){return Function.prototype.apply.apply(b,[p,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(p){return p==="debug"&&(p="log"),typeof console===n?!1:p==="trace"&&i?c:console[p]!==void 0?a(console,p):console.log!==void 0?a(console,"log"):e}function d(){for(var p=this.getLevel(),g=0;g<r.length;g++){var b=r[g];this[b]=g<p?e:this.methodFactory(b,p,this.name)}if(this.log=this.debug,typeof console===n&&p<this.levels.SILENT)return"No console available for logging"}function u(p){return function(){typeof console!==n&&(d.call(this),this[p].apply(this,arguments))}}function h(p,g,b){return l(p)||u.apply(this,arguments)}function f(p,g){var b=this,k,w,y,_="loglevel";typeof p=="string"?_+=":"+p:typeof p=="symbol"&&(_=void 0);function S(M){var N=(r[M]||"silent").toUpperCase();if(!(typeof window===n||!_)){try{window.localStorage[_]=N;return}catch{}try{window.document.cookie=encodeURIComponent(_)+"="+N+";"}catch{}}}function x(){var M;if(!(typeof window===n||!_)){try{M=window.localStorage[_]}catch{}if(typeof M===n)try{var N=window.document.cookie,q=encodeURIComponent(_),F=N.indexOf(q+"=");F!==-1&&(M=/^([^;]+)/.exec(N.slice(F+q.length+1))[1])}catch{}return b.levels[M]===void 0&&(M=void 0),M}}function I(){if(!(typeof window===n||!_)){try{window.localStorage.removeItem(_)}catch{}try{window.document.cookie=encodeURIComponent(_)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function R(M){var N=M;if(typeof N=="string"&&b.levels[N.toUpperCase()]!==void 0&&(N=b.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=b.levels.SILENT)return N;throw new TypeError("log.setLevel() called with invalid level: "+M)}b.name=p,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=g||h,b.getLevel=function(){return y??w??k},b.setLevel=function(M,N){return y=R(M),N!==!1&&S(y),d.call(b)},b.setDefaultLevel=function(M){w=R(M),x()||b.setLevel(M,!1)},b.resetLevel=function(){y=null,I(),d.call(b)},b.enableAll=function(M){b.setLevel(b.levels.TRACE,M)},b.disableAll=function(M){b.setLevel(b.levels.SILENT,M)},b.rebuild=function(){if(o!==b&&(k=R(o.getLevel())),d.call(b),o===b)for(var M in s)s[M].rebuild()},k=R(o?o.getLevel():"WARN");var A=x();A!=null&&(y=R(A)),d.call(b)}o=new f,o.getLogger=function(g){if(typeof g!="symbol"&&typeof g!="string"||g==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[g];return b||(b=s[g]=new f(g,o.methodFactory)),b};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})})(Cr)),Cr.exports}var wr=Jg(),lo;(function(t){t[t.trace=0]="trace",t[t.debug=1]="debug",t[t.info=2]="info",t[t.warn=3]="warn",t[t.error=4]="error",t[t.silent=5]="silent"})(lo||(lo={}));var lt;(function(t){t.Default="livekit",t.Room="livekit-room",t.Participant="livekit-participant",t.Track="livekit-track",t.Publication="livekit-track-publication",t.Engine="livekit-engine",t.Signal="livekit-signal",t.PCManager="livekit-pc-manager",t.PCTransport="livekit-pc-transport",t.E2EE="lk-e2ee"})(lt||(lt={}));let Q=wr.getLogger("livekit");Object.values(lt).map(t=>wr.getLogger(t)),Q.setDefaultLevel(lo.info);function zt(t){const e=wr.getLogger(t);return e.setDefaultLevel(Q.getLevel()),e}const Yg=wr.getLogger("lk-e2ee"),Ii=7e3,Xg=[0,300,4*300,9*300,16*300,Ii,Ii,Ii,Ii,Ii];class Qg{constructor(e){this._retryDelays=e!==void 0?[...e]:Xg}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const n=this._retryDelays[e.retryCount];return e.retryCount<=1?n:n+Math.random()*1e3}}function Zg(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function C(t,e,n,i){function r(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(d){try{l(i.next(d))}catch(u){o(u)}}function c(d){try{l(i.throw(d))}catch(u){o(u)}}function l(d){d.done?s(d.value):r(d.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function Cd(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Wt(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Cd=="function"?Cd(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var _r={exports:{}},wd;function ev(){if(wd)return _r.exports;wd=1;var t=typeof Reflect=="object"?Reflect:null,e=t&&typeof t.apply=="function"?t.apply:function(_,S,x){return Function.prototype.apply.call(_,S,x)},n;t&&typeof t.ownKeys=="function"?n=t.ownKeys:Object.getOwnPropertySymbols?n=function(_){return Object.getOwnPropertyNames(_).concat(Object.getOwnPropertySymbols(_))}:n=function(_){return Object.getOwnPropertyNames(_)};function i(y){console&&console.warn&&console.warn(y)}var r=Number.isNaN||function(_){return _!==_};function s(){s.init.call(this)}_r.exports=s,_r.exports.once=b,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(y){if(typeof y!="number"||y<0||r(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");o=y}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(_){if(typeof _!="number"||_<0||r(_))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+_+".");return this._maxListeners=_,this};function c(y){return y._maxListeners===void 0?s.defaultMaxListeners:y._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(_){for(var S=[],x=1;x<arguments.length;x++)S.push(arguments[x]);var I=_==="error",R=this._events;if(R!==void 0)I=I&&R.error===void 0;else if(!I)return!1;if(I){var A;if(S.length>0&&(A=S[0]),A instanceof Error)throw A;var M=new Error("Unhandled error."+(A?" ("+A.message+")":""));throw M.context=A,M}var N=R[_];if(N===void 0)return!1;if(typeof N=="function")e(N,this,S);else for(var q=N.length,F=v(N,q),x=0;x<q;++x)e(F[x],this,S);return!0};function l(y,_,S,x){var I,R,A;if(a(S),R=y._events,R===void 0?(R=y._events=Object.create(null),y._eventsCount=0):(R.newListener!==void 0&&(y.emit("newListener",_,S.listener?S.listener:S),R=y._events),A=R[_]),A===void 0)A=R[_]=S,++y._eventsCount;else if(typeof A=="function"?A=R[_]=x?[S,A]:[A,S]:x?A.unshift(S):A.push(S),I=c(y),I>0&&A.length>I&&!A.warned){A.warned=!0;var M=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+String(_)+" listeners added. Use emitter.setMaxListeners() to increase limit");M.name="MaxListenersExceededWarning",M.emitter=y,M.type=_,M.count=A.length,i(M)}return y}s.prototype.addListener=function(_,S){return l(this,_,S,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(_,S){return l(this,_,S,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(y,_,S){var x={fired:!1,wrapFn:void 0,target:y,type:_,listener:S},I=d.bind(x);return I.listener=S,x.wrapFn=I,I}s.prototype.once=function(_,S){return a(S),this.on(_,u(this,_,S)),this},s.prototype.prependOnceListener=function(_,S){return a(S),this.prependListener(_,u(this,_,S)),this},s.prototype.removeListener=function(_,S){var x,I,R,A,M;if(a(S),I=this._events,I===void 0)return this;if(x=I[_],x===void 0)return this;if(x===S||x.listener===S)--this._eventsCount===0?this._events=Object.create(null):(delete I[_],I.removeListener&&this.emit("removeListener",_,x.listener||S));else if(typeof x!="function"){for(R=-1,A=x.length-1;A>=0;A--)if(x[A]===S||x[A].listener===S){M=x[A].listener,R=A;break}if(R<0)return this;R===0?x.shift():p(x,R),x.length===1&&(I[_]=x[0]),I.removeListener!==void 0&&this.emit("removeListener",_,M||S)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(_){var S,x,I;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[_]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[_]),this;if(arguments.length===0){var R=Object.keys(x),A;for(I=0;I<R.length;++I)A=R[I],A!=="removeListener"&&this.removeAllListeners(A);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(S=x[_],typeof S=="function")this.removeListener(_,S);else if(S!==void 0)for(I=S.length-1;I>=0;I--)this.removeListener(_,S[I]);return this};function h(y,_,S){var x=y._events;if(x===void 0)return[];var I=x[_];return I===void 0?[]:typeof I=="function"?S?[I.listener||I]:[I]:S?g(I):v(I,I.length)}s.prototype.listeners=function(_){return h(this,_,!0)},s.prototype.rawListeners=function(_){return h(this,_,!1)},s.listenerCount=function(y,_){return typeof y.listenerCount=="function"?y.listenerCount(_):f.call(y,_)},s.prototype.listenerCount=f;function f(y){var _=this._events;if(_!==void 0){var S=_[y];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function v(y,_){for(var S=new Array(_),x=0;x<_;++x)S[x]=y[x];return S}function p(y,_){for(;_+1<y.length;_++)y[_]=y[_+1];y.pop()}function g(y){for(var _=new Array(y.length),S=0;S<_.length;++S)_[S]=y[S].listener||y[S];return _}function b(y,_){return new Promise(function(S,x){function I(A){y.removeListener(_,R),x(A)}function R(){typeof y.removeListener=="function"&&y.removeListener("error",I),S([].slice.call(arguments))}w(y,_,R,{once:!0}),_!=="error"&&k(y,I,{once:!0})})}function k(y,_,S){typeof y.on=="function"&&w(y,"error",_,S)}function w(y,_,S,x){if(typeof y.on=="function")x.once?y.once(_,S):y.on(_,S);else if(typeof y.addEventListener=="function")y.addEventListener(_,function I(R){x.once&&y.removeEventListener(_,I),S(R)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return _r.exports}var St=ev();let _d=!0,Sd=!0;function Oi(t,e,n){const i=t.match(e);return i&&i.length>=n&&parseFloat(i[n],10)}function In(t,e,n){if(!t.RTCPeerConnection)return;const i=t.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(o,a){if(o!==e)return r.apply(this,arguments);const c=l=>{const d=n(l);d&&(a.handleEvent?a.handleEvent(d):a(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),r.apply(this,[o,c])};const s=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function tv(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(_d=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function nv(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(Sd=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function Td(){if(typeof window=="object"){if(_d)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function uo(t,e){Sd&&console.warn(t+" is deprecated, please use "+e+" instead.")}function iv(t){const e={browser:null,version:null};if(typeof t>"u"||!t.navigator||!t.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:n}=t;if(n.userAgentData&&n.userAgentData.brands){const i=n.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(n.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Oi(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||t.isSecureContext===!1&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Oi(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(t.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Oi(n.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,e._safariVersion=Oi(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function xd(t){return Object.prototype.toString.call(t)==="[object Object]"}function Pd(t){return xd(t)?Object.keys(t).reduce(function(e,n){const i=xd(t[n]),r=i?Pd(t[n]):t[n],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[n]:r})},{}):t}function ho(t,e,n){!e||n.has(e.id)||(n.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?ho(t,t.get(e[i]),n):i.endsWith("Ids")&&e[i].forEach(r=>{ho(t,t.get(r),n)})}))}function Ed(t,e,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return t.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{t.forEach(a=>{a.type===i&&a.trackId===o.id&&ho(t,a,r)})}),r}const Rd=Td;function Id(t,e){const n=t&&t.navigator;if(!n.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof a[l]=="object"?a[l]:{ideal:a[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},r=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return n.mediaDevices.enumerateDevices().then(h=>{h=h.filter(v=>v.kind==="videoinput");let f=h.find(v=>u.some(p=>v.label.toLowerCase().includes(p)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=i(a.video),Rd("chrome: "+JSON.stringify(a)),c(a)})}a.video=i(a.video)}return Rd("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){r(a,d=>{n.webkitGetUserMedia(d,c,u=>{l&&l(s(u))})})};if(n.getUserMedia=o.bind(n),n.mediaDevices.getUserMedia){const a=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(c){return r(c,l=>a(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(s(d))))}}}function Od(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function Ad(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.track.id):s={track:r.track};const o=new Event("track");o.track=r.track,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(r=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.id):s={track:r};const o=new Event("track");o.track=r,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else In(t,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Dd(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(a,c){let l=r.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const s=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof t=="object"&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(t.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Md(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const n=t.RTCPeerConnection.prototype.getSenders;n&&(t.RTCPeerConnection.prototype.getSenders=function(){const s=n.apply(this,[]);return s.forEach(o=>o._pc=this),s});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),t.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(o=>Ed(o,s.track,!0))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const n=t.RTCPeerConnection.prototype.getReceivers;n&&(t.RTCPeerConnection.prototype.getReceivers=function(){const r=n.apply(this,[]);return r.forEach(s=>s._pc=this),r}),In(t,"track",i=>(i.receiver._pc=i.srcElement,i)),t.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>Ed(s,r.track,!1))}}if(!("getStats"in t.RTCRtpSender.prototype&&"getStats"in t.RTCRtpReceiver.prototype))return;const e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const i=arguments[0];let r,s,o;return this.getSenders().forEach(a=>{a.track===i&&(r?o=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(s?o=!0:s=a),a.track===i)),o||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Nd(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();n.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const r=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function Ld(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Nd(t);const n=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const d=n.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const i=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new t.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}i.apply(this,[d])};const r=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},t.RTCPeerConnection.prototype.addTrack=function(d,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(p=>p===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(p=>p.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const v=this._streams[u.id];if(v)v.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const p=new t.MediaStream([d]);this._streams[u.id]=p,this._reverseStreams[p.id]=u,this.addStream(p)}return this.getSenders().find(p=>p.track===d)};function s(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],v=l._streams[f.id];u=u.replace(new RegExp(v.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function o(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],v=l._streams[f.id];u=u.replace(new RegExp(f.id,"g"),v.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=t.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[v=>{const p=s(this,v);h[0].apply(null,[p])},v=>{h[1]&&h[1].apply(null,v)},arguments[2]]):d.apply(this,arguments).then(v=>s(this,v))}};t.RTCPeerConnection.prototype[l]=u[l]});const a=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:s(this,l)}}),t.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(p=>d.track===p)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function fo(t,e){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const i=t.RTCPeerConnection.prototype[n],r={[n](){return arguments[0]=new(n==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};t.RTCPeerConnection.prototype[n]=r[n]})}function Ud(t,e){In(t,"negotiationneeded",n=>{const i=n.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return n})}var Fd=Object.freeze({__proto__:null,fixNegotiationNeeded:Ud,shimAddTrackRemoveTrack:Ld,shimAddTrackRemoveTrackWithNative:Nd,shimGetSendersWithDtmf:Dd,shimGetUserMedia:Id,shimMediaStream:Od,shimOnTrack:Ad,shimPeerConnection:fo,shimSenderReceiverGetStats:Md});function Bd(t,e){const n=t&&t.navigator,i=t&&t.MediaStreamTrack;if(n.getUserMedia=function(r,s,o){uo("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(r).then(s,o)},!(e.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const r=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const o=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function rv(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,t.navigator.mediaDevices.getUserMedia(i)})}function jd(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function po(t,e){if(typeof t!="object"||!(t.RTCPeerConnection||t.mozRTCPeerConnection))return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=t.RTCPeerConnection.prototype[r],o={[r](){return arguments[0]=new(r==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};t.RTCPeerConnection.prototype[r]=o[r]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[s,o,a]=arguments;return i.apply(this,[s||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=n[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:n[d.type]||d.type}))})}return c}).then(o,a)}}function Vd(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const n=t.RTCPeerConnection.prototype.addTrack;n&&(t.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function qd(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),In(t,"track",n=>(n.receiver._pc=n.srcElement,n)),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function $d(t){!t.RTCPeerConnection||"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(n){uo("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&n.getTracks().includes(i.track)&&this.removeTrack(i)})})}function zd(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function Wd(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.addTransceiver;e&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:o}=s,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return s})}function Hd(t){if(!(typeof t=="object"&&t.RTCRtpSender))return;const e=t.RTCRtpSender.prototype.getParameters;e&&(t.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Gd(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Kd(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Jd=Object.freeze({__proto__:null,shimAddTransceiver:Wd,shimCreateAnswer:Kd,shimCreateOffer:Gd,shimGetDisplayMedia:rv,shimGetParameters:Hd,shimGetUserMedia:Bd,shimOnTrack:jd,shimPeerConnection:po,shimRTCDataChannel:zd,shimReceiverGetStats:qd,shimRemoveStream:$d,shimSenderGetStats:Vd});function Yd(t){if(!(typeof t!="object"||!t.RTCPeerConnection)){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},t.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s&&s.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(n){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(n);if(i===-1)return;this._localStreams.splice(i,1);const r=n.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function Xd(t){if(!(typeof t!="object"||!t.RTCPeerConnection)&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(n){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=n),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const o=new Event("addstream");o.stream=s,i.dispatchEvent(o)})}),e.apply(i,arguments)}}}function Qd(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype,n=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let a=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,l,d){const u=o.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=a}function Zd(t){const e=t&&t.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const n=e.mediaDevices,i=n.getUserMedia.bind(n);e.mediaDevices.getUserMedia=r=>i(eu(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function eu(t){return t&&t.video!==void 0?Object.assign({},t,{video:Pd(t.video)}):t}function tu(t){if(!t.RTCPeerConnection)return;const e=t.RTCPeerConnection;t.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(uo("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(i.iceServers[o])}i.iceServers=s}return new e(i,r)},t.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function nu(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function iu(t){const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function ru(t){typeof t!="object"||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var su=Object.freeze({__proto__:null,shimAudioContext:ru,shimCallbacksAPI:Qd,shimConstraints:eu,shimCreateOfferLegacy:iu,shimGetUserMedia:Zd,shimLocalStreamsAPI:Yd,shimRTCIceServerUrls:tu,shimRemoteStreamsAPI:Xd,shimTrackEventTransceiver:nu}),mo={exports:{}},ou;function sv(){return ou||(ou=1,(function(t){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(n){return n.trim().split(`
3
3
  `).map(i=>i.trim())},e.splitSections=function(n){return n.split(`
4
4
  m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
5
5
  `)},e.getDescription=function(n){const i=e.splitSections(n);return i&&i[0]},e.getMediaSections=function(n){const i=e.splitSections(n);return i.shift(),i},e.matchPrefix=function(n,i){return e.splitLines(n).filter(r=>r.indexOf(i)===0)},e.parseCandidate=function(n){let i;n.indexOf("a=candidate:")===0?i=n.substring(12).split(" "):i=n.substring(10).split(" ");const r={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let s=8;s<i.length;s+=2)switch(i[s]){case"raddr":r.relatedAddress=i[s+1];break;case"rport":r.relatedPort=parseInt(i[s+1],10);break;case"tcptype":r.tcpType=i[s+1];break;case"ufrag":r.ufrag=i[s+1],r.usernameFragment=i[s+1];break;default:r[i[s]]===void 0&&(r[i[s]]=i[s+1]);break}return r},e.writeCandidate=function(n){const i=[];i.push(n.foundation);const r=n.component;r==="rtp"?i.push(1):r==="rtcp"?i.push(2):i.push(r),i.push(n.protocol.toUpperCase()),i.push(n.priority),i.push(n.address||n.ip),i.push(n.port);const s=n.type;return i.push("typ"),i.push(s),s!=="host"&&n.relatedAddress&&n.relatedPort&&(i.push("raddr"),i.push(n.relatedAddress),i.push("rport"),i.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(i.push("ufrag"),i.push(n.usernameFragment||n.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(n){return n.substring(14).split(" ")},e.parseRtpMap=function(n){let i=n.substring(9).split(" ");const r={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),r.name=i[0],r.clockRate=parseInt(i[1],10),r.channels=i.length===3?parseInt(i[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(n){let i=n.payloadType;n.preferredPayloadType!==void 0&&(i=n.preferredPayloadType);const r=n.channels||n.numChannels||1;return"a=rtpmap:"+i+" "+n.name+"/"+n.clockRate+(r!==1?"/"+r:"")+`\r
@@ -16,7 +16,7 @@ a=ice-pwd:`+n.password+`\r
16
16
  `,r+=`c=IN IP4 0.0.0.0\r
17
17
  `,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
18
18
  `,i.codecs.forEach(o=>{r+=e.writeRtpMap(o),r+=e.writeFmtp(o),r+=e.writeRtcpFb(o)});let s=0;return i.codecs.forEach(o=>{o.maxptime>s&&(s=o.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r
19
- `),i.headerExtensions&&i.headerExtensions.forEach(o=>{r+=e.writeExtmap(o)}),r},e.parseRtpEncodingParameters=function(n){const i=[],r=e.parseRtpParameters(n),s=r.fecMechanisms.indexOf("RED")!==-1,o=r.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(n,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),c=a.length>0&&a[0].ssrc;let l;const d=e.matchPrefix(n,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(g=>parseInt(g,10)));d.length>0&&d[0].length>1&&d[0][0]===c&&(l=d[0][1]),r.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:c,codecPayloadType:parseInt(h.parameters.apt,10)};c&&l&&(p.rtx={ssrc:l}),i.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&c&&i.push({ssrc:c});let u=e.matchPrefix(n,"b=");return u.length&&(u[0].indexOf("b=TIAS:")===0?u=parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?u=parseInt(u[0].substring(5),10)*1e3*.95-2e3*8:u=void 0,i.forEach(h=>{h.maxBitrate=u})),i},e.parseRtcpParameters=function(n){const i={},r=e.matchPrefix(n,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const s=e.matchPrefix(n,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=s.length===0;const o=e.matchPrefix(n,"a=rtcp-mux");return i.mux=o.length>0,i},e.writeRtcpParameters=function(n){let i="";return n.reducedSize&&(i+=`a=rtcp-rsize\r
19
+ `),i.headerExtensions&&i.headerExtensions.forEach(o=>{r+=e.writeExtmap(o)}),r},e.parseRtpEncodingParameters=function(n){const i=[],r=e.parseRtpParameters(n),s=r.fecMechanisms.indexOf("RED")!==-1,o=r.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(n,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),c=a.length>0&&a[0].ssrc;let l;const d=e.matchPrefix(n,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(v=>parseInt(v,10)));d.length>0&&d[0].length>1&&d[0][0]===c&&(l=d[0][1]),r.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let f={ssrc:c,codecPayloadType:parseInt(h.parameters.apt,10)};c&&l&&(f.rtx={ssrc:l}),i.push(f),s&&(f=JSON.parse(JSON.stringify(f)),f.fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},i.push(f))}}),i.length===0&&c&&i.push({ssrc:c});let u=e.matchPrefix(n,"b=");return u.length&&(u[0].indexOf("b=TIAS:")===0?u=parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?u=parseInt(u[0].substring(5),10)*1e3*.95-2e3*8:u=void 0,i.forEach(h=>{h.maxBitrate=u})),i},e.parseRtcpParameters=function(n){const i={},r=e.matchPrefix(n,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const s=e.matchPrefix(n,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=s.length===0;const o=e.matchPrefix(n,"a=rtcp-mux");return i.mux=o.length>0,i},e.writeRtcpParameters=function(n){let i="";return n.reducedSize&&(i+=`a=rtcp-rsize\r
20
20
  `),n.mux&&(i+=`a=rtcp-mux\r
21
21
  `),n.ssrc!==void 0&&n.cname&&(i+="a=ssrc:"+n.ssrc+" cname:"+n.cname+`\r
22
22
  `),i},e.parseMsid=function(n){let i;const r=e.matchPrefix(n,"a=msid:");if(r.length===1)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(n,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");if(s.length>0)return i=s[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(n){const i=e.parseMLine(n),r=e.matchPrefix(n,"a=max-message-size:");let s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);const o=e.matchPrefix(n,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const a=e.matchPrefix(n,"a=sctpmap:");if(a.length>0){const c=a[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:s}}},e.writeSctpDescription=function(n,i){let r=[];return n.protocol!=="DTLS/SCTP"?r=["m="+n.kind+" 9 "+n.protocol+" "+i.protocol+`\r
@@ -30,12 +30,17 @@ a=ice-pwd:`+n.password+`\r
30
30
  o=`+(r||"thisisadapterortc")+" "+s+" "+o+` IN IP4 127.0.0.1\r
31
31
  s=-\r
32
32
  t=0 0\r
33
- `},e.getDirection=function(n,i){const r=e.splitLines(n);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(n){return e.splitLines(n)[0].split(" ")[0].substring(2)},e.isRejected=function(n){return n.split(" ",2)[1]==="0"},e.parseMLine=function(n){const r=e.splitLines(n)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(n){const r=e.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const i=e.splitLines(n);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},t.exports=e})(po)),po.exports}var ru=Kg(),Yn=Lg(ru),Jg=cm({__proto__:null,default:Yn},[ru]);function Sr(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new e(i),s=Yn.parseCandidate(i.candidate);for(const o in s)o in r||Object.defineProperty(r,o,{value:s[o]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(i)},t.RTCIceCandidate.prototype=e.prototype,Rn(t,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new t.RTCIceCandidate(n.candidate),writable:"false"}),n))}function mo(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||Rn(t,"icecandidate",e=>{if(e.candidate){const n=Yn.parseCandidate(e.candidate.candidate);n.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[n.priority>>24])}return e})}function Tr(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const n=function(a){if(!a||!a.sdp)return!1;const c=Yn.splitSections(a.sdp);return c.shift(),c.some(l=>{const d=Yn.parseMLine(l);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},i=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},r=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const d=Yn.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?l=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const c=i(arguments[0]),l=r(c),d=s(arguments[0],c);let u;l===0&&d===0?u=Number.POSITIVE_INFINITY:l===0||d===0?u=Math.max(l,d):u=Math.min(l,d);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function xr(t){if(!(t.RTCPeerConnection&&"createDataChannel"in t.RTCPeerConnection.prototype))return;function e(i,r){const s=i.send;i.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(i.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}const n=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const r=n.apply(this,arguments);return e(r,this),r},Rn(t,"datachannel",i=>(e(i.channel,i.target),i))}function go(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(n){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),n&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=n)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(n=>{const i=e[n];e[n]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",r);s.dispatchEvent(o)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function vo(t,e){if(!t.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const n=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
33
+ `},e.getDirection=function(n,i){const r=e.splitLines(n);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(n){return e.splitLines(n)[0].split(" ")[0].substring(2)},e.isRejected=function(n){return n.split(" ",2)[1]==="0"},e.parseMLine=function(n){const r=e.splitLines(n)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(n){const r=e.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const i=e.splitLines(n);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},t.exports=e})(mo)),mo.exports}var au=sv(),Yn=Gg(au),ov=ym({__proto__:null,default:Yn},[au]);function Sr(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new e(i),s=Yn.parseCandidate(i.candidate);for(const o in s)o in r||Object.defineProperty(r,o,{value:s[o]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(i)},t.RTCIceCandidate.prototype=e.prototype,In(t,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new t.RTCIceCandidate(n.candidate),writable:"false"}),n))}function go(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||In(t,"icecandidate",e=>{if(e.candidate){const n=Yn.parseCandidate(e.candidate.candidate);n.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[n.priority>>24])}return e})}function Tr(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const n=function(a){if(!a||!a.sdp)return!1;const c=Yn.splitSections(a.sdp);return c.shift(),c.some(l=>{const d=Yn.parseMLine(l);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},i=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},r=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const d=Yn.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?l=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const c=i(arguments[0]),l=r(c),d=s(arguments[0],c);let u;l===0&&d===0?u=Number.POSITIVE_INFINITY:l===0||d===0?u=Math.max(l,d):u=Math.min(l,d);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function xr(t){if(!(t.RTCPeerConnection&&"createDataChannel"in t.RTCPeerConnection.prototype))return;function e(i,r){const s=i.send;i.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(i.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}const n=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const r=n.apply(this,arguments);return e(r,this),r},In(t,"datachannel",i=>(e(i.channel,i.target),i))}function vo(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(n){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),n&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=n)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(n=>{const i=e[n];e[n]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",r);s.dispatchEvent(o)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function bo(t,e){if(!t.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const n=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
34
34
  a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
35
35
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
36
- `);t.RTCSessionDescription&&r instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function Er(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Pr(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var Yg=Object.freeze({__proto__:null,removeExtmapAllowMixed:vo,shimAddIceCandidateNullOrEmpty:Er,shimConnectionState:go,shimMaxMessageSize:Tr,shimParameterlessSetLocalDescription:Pr,shimRTCIceCandidate:Sr,shimRTCIceCandidateRelayProtocol:mo,shimSendThrowTypeError:xr});function Xg(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=_d,i=Hg(t),r={browserDetails:i,commonShim:Yg,extractVersion:Oi,disableLog:zg,disableWarnings:Wg,sdp:Jg};switch(i.browser){case"chrome":if(!Nd||!ho||!e.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Nd,Er(t,i),Pr(t),Ed(t,i),Pd(t),ho(t,i),Rd(t),Ad(t,i),Id(t),Od(t),Md(t,i),Sr(t),mo(t),go(t),Tr(t,i),xr(t),vo(t,i);break;case"firefox":if(!Hd||!fo||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Hd,Er(t,i),Pr(t),Ld(t,i),fo(t,i),Ud(t),jd(t),Fd(t),Bd(t),Vd(t),qd(t),$d(t),zd(t),Wd(t),Sr(t),go(t),Tr(t,i),xr(t);break;case"safari":if(!nu||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=nu,Er(t,i),Pr(t),Qd(t),eu(t),Jd(t),Gd(t),Kd(t),Zd(t),Yd(t),tu(t),Sr(t),mo(t),Tr(t,i),xr(t),vo(t,i);break;default:n("Unsupported browser!");break}return r}Xg({window:typeof window>"u"?void 0:window});const Qg=10,Di="lk_e2ee",Zg={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Qg,keyringSize:16};var an;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(an||(an={}));var su;(function(t){t.KeyRatcheted="keyRatcheted"})(su||(su={}));var cn;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(cn||(cn={}));var ou;(function(t){t.Error="cryptorError"})(ou||(ou={}));function ev(){return tv()||bo()}function bo(){return typeof window.RTCRtpScriptTransform<"u"}function tv(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class J_ extends _t.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{X.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Zg),e),this.on(an.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,n,i){const r={key:e,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(an.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(an.RatchetRequest,e,n)}}class zt extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var Q;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout"})(Q||(Q={}));class le extends zt{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=Q[n]}}class yo extends zt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Wt extends zt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class nv extends zt{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Pe extends zt{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class ko extends zt{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class au extends zt{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class cu extends zt{constructor(e,n){super(15,e),this.reason=n,this.reasonName=typeof n=="string"?n:ao[n]}}var lt;(function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered"})(lt||(lt={}));class ln extends zt{constructor(e,n){super(16,e),this.name="DataStreamError",this.reason=n,this.reasonName=lt[n]}}var Rr;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(Rr||(Rr={})),(function(t){function e(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?t.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?t.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e})(Rr||(Rr={}));var lu;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(lu||(lu={}));var D;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(D||(D={}));var U;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(U||(U={}));var L;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(L||(L={}));var N;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(N||(N={}));function iv(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}const rv=/version\/(\d+(\.?_?\d+)+)/i;let Co;function Xe(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(Co===void 0||e){const i=sv.find(r=>{let{test:s}=r;return s.test(n)});Co=i==null?void 0:i.describe(n)}return Co}const sv=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:Ir(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:_o(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:Ir(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:_o(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:Ir(rv,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:_o(t)}}}];function Ir(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(t);return i&&i.length>=n&&i[n]||""}function _o(t){return t.includes("mac os")?Ir(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var ov="2.15.5";const av=ov,cv=16;class Ne{}Ne.setTimeout=function(){return setTimeout(...arguments)},Ne.setInterval=function(){return setInterval(...arguments)},Ne.clearTimeout=function(){return clearTimeout(...arguments)},Ne.clearInterval=function(){return clearInterval(...arguments)};const lv=5e3,Ai=[];var Qe;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(Qe||(Qe={}));class E extends _t.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=E.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=X,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),lv):this.handleAppVisibilityChanged()},this.log=qt((r=i.loggerName)!==null&&r!==void 0?r:ct.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=E.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let n="audio";this.kind===E.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===E.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(Ai.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Ai.splice(Ai.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),Xn(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?N.AudioPlaybackStarted:N.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?N.AudioPlaybackFailed:N.VideoPlaybackFailed,s):s.name==="AbortError"?X.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):X.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(N.ElementAttached,e),e}detach(e){try{if(e){Qn(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(N.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{Qn(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(N.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=qt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),Ai.forEach(i=>{i.parentElement||(n=!1)}),n&&Ai.push(e)}}handleAppVisibilityChanged(){return C(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===E.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){qe()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){qe()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Xn(t,e){let n;e.srcObject instanceof MediaStream?n=e.srcObject:n=new MediaStream;let i;t.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(t)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(t)),(!In()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,(In()||Zn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function Qn(t,e){if(e.srcObject instanceof MediaStream){const n=e.srcObject;n.removeTrack(t),n.getTracks().length>0?e.srcObject=n:e.srcObject=null}}(function(t){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=t.Source||(t.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=t.StreamState||(t.StreamState={}));function r(l){switch(l){case e.Audio:return st.AUDIO;case e.Video:return st.VIDEO;default:return st.DATA}}t.kindToProto=r;function s(l){switch(l){case st.AUDIO:return e.Audio;case st.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=s;function o(l){switch(l){case n.Camera:return Te.CAMERA;case n.Microphone:return Te.MICROPHONE;case n.ScreenShare:return Te.SCREEN_SHARE;case n.ScreenShareAudio:return Te.SCREEN_SHARE_AUDIO;default:return Te.UNKNOWN}}t.sourceToProto=o;function a(l){switch(l){case Te.CAMERA:return n.Camera;case Te.MICROPHONE:return n.Microphone;case Te.SCREEN_SHARE:return n.ScreenShare;case Te.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=a;function c(l){switch(l){case eo.ACTIVE:return i.Active;case eo.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=c})(E||(E={}));class se{constructor(e,n,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(n!==void 0&&i!==void 0)this.width=e,this.height=n,this.aspectRatio=e/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const dv=["vp8","h264"],uv=["vp8","h264","vp9","av1","h265"];function hv(t){return!!dv.find(e=>e===t)}var du;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(du||(du={}));var wo;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(wo||(wo={}));const Mi={h90:new se(160,90,9e4,20),h180:new se(320,180,16e4,20),h216:new se(384,216,18e4,20),h360:new se(640,360,45e4,20),h540:new se(960,540,8e5,25),h720:new se(1280,720,17e5,30),h1080:new se(1920,1080,3e6,30),h1440:new se(2560,1440,5e6,30),h2160:new se(3840,2160,8e6,30)},So={h120:new se(160,120,7e4,20),h180:new se(240,180,125e3,20),h240:new se(320,240,14e4,20),h360:new se(480,360,33e4,20),h480:new se(640,480,5e5,20),h540:new se(720,540,6e5,25),h720:new se(960,720,13e5,30),h1080:new se(1440,1080,23e5,30),h1440:new se(1920,1440,38e5,30)},To={h360fps3:new se(640,360,2e5,3,"medium"),h360fps15:new se(640,360,4e5,15,"medium"),h720fps5:new se(1280,720,8e5,5,"medium"),h720fps15:new se(1280,720,15e5,15,"medium"),h720fps30:new se(1280,720,2e6,30,"medium"),h1080fps15:new se(1920,1080,25e5,15,"medium"),h1080fps30:new se(1920,1080,5e6,30,"medium"),original:new se(0,0,7e6,30,"medium")},fv="|",uu="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function pv(t){const e=t.split(fv);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function Ve(t){return C(this,void 0,void 0,function*(){return new Promise(e=>Ne.setTimeout(e,t))})}function xo(){return"addTransceiver"in RTCPeerConnection.prototype}function Eo(){return"addTrack"in RTCPeerConnection.prototype}function mv(){if(!("getCapabilities"in RTCRtpSender)||In())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/AV1"){e=!0;break}}return e}function gv(){if(!("getCapabilities"in RTCRtpSender)||Zn())return!1;if(In()){const n=Xe();if(n!=null&&n.version&&Tt(n.version,"16")<0||(n==null?void 0:n.os)==="iOS"&&(n!=null&&n.osVersion)&&Tt(n.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/VP9"){e=!0;break}}return e}function wt(t){return t==="av1"||t==="vp9"}function Po(t){return!document||Or()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function vv(){return typeof RTCPeerConnection>"u"?!1:xo()||Eo()}function Zn(){var t;return((t=Xe())===null||t===void 0?void 0:t.name)==="Firefox"}function In(){var t;return((t=Xe())===null||t===void 0?void 0:t.name)==="Safari"}function Or(){const t=Xe();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function bv(){const t=Xe();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Tt(t.osVersion,"17")>=0}function yv(t){return t||(t=Xe()),(t==null?void 0:t.name)==="Safari"&&Tt(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Tt(t.osVersion,"18.3")>0}function hu(){var t,e;return qe()?(e=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function kv(){const t=Xe(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&Tt(e,t.osVersion)>=0?!0:t.name==="Safari"&&Tt(e,t.version)>=0}function qe(){return typeof document<"u"}function St(){return navigator.product=="ReactNative"}function Ro(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function fu(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function pu(){if(!St())return;let t=fu();if(t)return t.platform}function mu(){if(qe())return window.devicePixelRatio;if(St()){let t=fu();if(t)return t.devicePixelRatio}return 1}function Tt(t,e){const n=t.split("."),i=e.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const o=parseInt(n[s],10),a=parseInt(i[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return t===""&&e!==""?-1:e===""?1:n.length==i.length?0:n.length<i.length?-1:1}function Cv(t){for(const e of t)e.target.handleResize(e)}function _v(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Io=null;const gu=()=>(Io||(Io=new ResizeObserver(Cv)),Io);let Oo=null;const vu=()=>(Oo||(Oo=new IntersectionObserver(_v,{root:null,rootMargin:"0px"})),Oo);function wv(){var t;const e=new ug({sdk:Zl.JS,protocol:cv,version:av});return St()&&(e.os=(t=pu())!==null&&t!==void 0?t:""),e}function bu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=t,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(t/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let Ni;function Do(){if(!Ni){const t=new AudioContext,e=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const i=t.createMediaStreamDestination();if(e.connect(n),n.connect(i),e.start(),[Ni]=i.stream.getAudioTracks(),!Ni)throw Error("Could not get empty media stream audio track");Ni.enabled=!1}return Ni.clone()}class xt{get isResolved(){return this._isResolved}constructor(e,n){this._isResolved=!1,this.onFinally=n,this.promise=new Promise((i,r)=>C(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function Sv(t){return uv.includes(t)}function dn(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact!==void 0)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal!==void 0)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function Tv(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function Ao(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function xv(t,e){return t.segments.map(n=>{let{id:i,text:r,language:s,startTime:o,endTime:a,final:c}=n;var l;const d=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,d),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:s,firstReceivedTime:d,lastReceivedTime:u}})}function Ev(t){const{id:e,timestamp:n,message:i,editTimestamp:r}=t;return{id:e,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function yu(t){switch(t.reason){case Q.LeaveRequest:return t.context;case Q.Cancelled:return ot.CLIENT_INITIATED;case Q.NotAllowed:return ot.USER_REJECTED;case Q.ServerUnreachable:return ot.JOIN_FAILURE;default:return ot.UNKNOWN_REASON}}function Dr(t){return t!==void 0?Number(t):void 0}function On(t){return t!==void 0?BigInt(t):void 0}function ei(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Et(t){return!!t&&t.kind==E.Kind.Audio}function Dn(t){return!!t&&t.kind==E.Kind.Video}function un(t){return ei(t)&&Dn(t)}function Ht(t){return ei(t)&&Et(t)}function Mo(t){return!!t&&!t.isLocal}function Pv(t){return!!t&&!t.isLocal}function No(t){return Mo(t)&&Dn(t)}function Rv(t){return t.isLocal}function Iv(t,e){const n=[];let i=new TextEncoder().encode(t);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function ku(t,e,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=wu(t??{}),d=e==null?void 0:e.processor,u=n==null?void 0:n.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Lo(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(Lo(h.video,n),(r=(o=h.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function Lo(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function Uo(t){var e,n,i,r;const s={};if(t.video)if(typeof t.video=="object"){const o={},a=o,c=t.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":Lo(a,c.resolution);break;default:a[l]=c[l]}}),s.video=o,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=t.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return t.audio?typeof t.audio=="object"?(s.audio=t.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Cu(t){return C(this,arguments,void 0,function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=_u();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Ve(n),r.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return i.close(),!c}return!1})()})}function _u(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const n=new e({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const i=()=>C(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return n}}function Ov(t){return t==="audioinput"?E.Source.Microphone:t==="videoinput"?E.Source.Camera:E.Source.Unknown}function Fo(t){return t===E.Source.Microphone?"audioinput":t===E.Source.Camera?"videoinput":void 0}function Dv(t){var e,n;let i=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(i=typeof i=="boolean"?{}:i,In()?i=Object.assign(Object.assign({},i),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(n=t.audio)!==null&&n!==void 0?n:!1,video:i,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function Ar(t){return t.split("/")[1].toLowerCase()}function Av(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new so({cid:n.track.mediaStreamID,track:n.trackInfo}))}),e}function K(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?K(t.track):{})}}function Mv(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Nv(t,e){var n;t===void 0&&(t={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(t)],r={};for(const s of i)t[s]!==e[s]&&(r[s]=(n=e[s])!==null&&n!==void 0?n:"");return r}function wu(t){const e=Object.assign({},t);let n,i;return typeof e.audio=="object"&&e.audio.processor&&(n=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:iv(e)}}function Lv(t){switch(t){case Te.CAMERA:return E.Source.Camera;case Te.MICROPHONE:return E.Source.Microphone;case Te.SCREEN_SHARE:return E.Source.ScreenShare;case Te.SCREEN_SHARE_AUDIO:return E.Source.ScreenShareAudio;default:return E.Source.Unknown}}function Su(t,e){return t.width*t.height<e.width*e.height}function Uv(t,e){var n;return(n=t.layers)===null||n===void 0?void 0:n.find(i=>i.quality===e)}class Fv extends _t.EventEmitter{constructor(e){super(),this.onWorkerMessage=n=>{var i,r;const{kind:s,data:o}=n.data;switch(s){case"error":X.error(o.error.message),this.emit(cn.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(cn.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(cn.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(an.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break}},this.onWorkerError=n=>{X.error("e2ee worker encountered an error:",{error:n.error}),this.emit(cn.EncryptionError,n.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!ev())throw new yo("tried to setup end-to-end encryption on an unsupported browser");if(X.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Bg.getLevel()}};this.worker&&(X.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(e,n){X.debug("set e2ee to ".concat(e," for participant ").concat(n)),this.postEnable(e,n)}setSifTrailer(e){!e||e.length===0?X.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(L.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(D.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Ye.NONE,r.identity)),e.on(D.ConnectionStateChanged,i=>{i===ee.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Ye.NONE,r.identity)})})}).on(D.TrackUnsubscribed,(i,r,s)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(D.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(D.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(U.LocalSenderCreated,(i,r)=>C(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),n.on(an.SetKey,i=>this.postKey(i)).on(an.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(e,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:n}};this.worker.postMessage(i)}postKey(e){let{key:n,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(e,n){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(n)}setupE2EEReceiver(e,n,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,n,e.kind==="video"?Ar(i.mimeType):void 0)}}setupE2EESender(e,n){if(!ei(e)||!n){n||X.warn("early return because sender is not ready");return}this.handleSender(n,e.mediaStreamID,void 0)}handleReceiver(e,n,i,r){return C(this,void 0,void 0,function*(){if(this.worker){if(bo()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Di in e&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,o=e.readableStream;if(!s||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:Di in e}};this.worker.postMessage(a,[o,s])}e[Di]=!0}})}handleSender(e,n,i){var r;if(!(Di in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(bo()){X.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{X.info("initialize encoded streams");const s=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[s.readable,s.writable])}e[Di]=!0}}}const Bo="default";class Ie{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Ie),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=Ie.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){X.debug("awaiting getUserMedia promise");try{n?yield Ie.userMediaPromiseMap.get(n):yield Promise.all(Ie.userMediaPromiseMap.values())}catch{X.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(In()&&i.hasDeviceInUse(n))&&(o.filter(c=>c.kind===n).length===0||o.some(c=>{const l=c.label==="",d=n?c.kind===n:!0;return l&&d}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return i._previousDevices=o,n&&(o=o.filter(a=>a.kind===n)),o})()})}normalizeDeviceId(e,n,i){return C(this,void 0,void 0,function*(){if(n!==Bo)return n;const r=yield this.getDevices(e),s=r.find(a=>a.deviceId===Bo);if(!s){X.warn("could not reliably determine default device");return}const o=r.find(a=>a.deviceId!==Bo&&a.groupId===(i??s.groupId));if(!o){X.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?Ie.userMediaPromiseMap.has(e):Ie.userMediaPromiseMap.size>0}}Ie.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Ie.userMediaPromiseMap=new Map;var Li;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(Li||(Li={}));class Bv{constructor(){this.pendingTasks=new Map,this.taskMutex=new Fe,this.nextTaskIndex=0}run(e){return C(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Li.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=Li.RUNNING,yield e()}finally{n.status=Li.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return C(this,void 0,void 0,function*(){return this.run(()=>C(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function jv(t,e){const n=new URL(Tv(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),Tu(n,"rtc")}function Vv(t){const e=new URL(Ao(t));return Tu(e,"validate")}function qv(t){return t.endsWith("/")?t:"".concat(t,"/")}function Tu(t,e){return t.pathname="".concat(qv(t.pathname)).concat(e),t.toString()}const $v=["syncState","trickle","offer","answer","simulate","leave"];function zv(t){const e=$v.indexOf(t.case)>=0;return X.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var ue;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(ue||(ue={}));class jo{get currentState(){return this.state}get isDisconnected(){return this.state===ue.DISCONNECTING||this.state===ue.DISCONNECTED}get isEstablishingConnection(){return this.state===ue.CONNECTING||this.state===ue.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=ue.DISCONNECTED,this.log=X,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=qt((i=n.loggerName)!==null&&i!==void 0?i:ct.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new Bv,this.queuedRequests=[],this.closingLock=new Fe,this.connectionLock=new Fe,this.state=ue.DISCONNECTED}get logContext(){var e,n;return(n=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&n!==void 0?n:{}}join(e,n,i,r){return C(this,void 0,void 0,function*(){return this.state=ue.CONNECTING,this.options=i,yield this.connect(e,n,i,r)})}reconnect(e,n,i,r){return C(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=ue.RECONNECTING,this.clearPingInterval(),yield this.connect(e,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,n,i,r){this.connectOptions=i;const s=wv(),o=Wv(n,s,i),a=jv(e,o),c=Vv(a);return new Promise((l,d)=>C(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const h=()=>C(this,void 0,void 0,function*(){this.close(),clearTimeout(p),d(new le("room connection has been cancelled (signal)",Q.Cancelled))}),p=setTimeout(()=>{this.close(),d(new le("room connection has timed out (signal)",Q.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const g=new URL(a);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(p)},this.ws.onerror=f=>C(this,void 0,void 0,function*(){if(this.state!==ue.CONNECTED){this.state=ue.DISCONNECTED,clearTimeout(p);try{const m=yield fetch(c);if(m.status.toFixed(0).startsWith("4")){const v=yield m.text();d(new le(v,Q.NotAllowed,m.status))}else d(new le("Encountered unknown websocket error during connection: ".concat(f.toString()),Q.InternalError,m.status))}catch(m){d(new le(m instanceof Error?m.message:"server was not reachable",Q.ServerUnreachable))}return}this.handleWSError(f)}),this.ws.onmessage=f=>C(this,void 0,void 0,function*(){var m,v,y;let _;if(typeof f.data=="string"){const k=JSON.parse(f.data);_=sd.fromJson(k,{ignoreUnknownFields:!0})}else if(f.data instanceof ArrayBuffer)_=sd.fromBinary(new Uint8Array(f.data));else{this.log.error("could not decode websocket message: ".concat(typeof f.data),this.logContext);return}if(this.state!==ue.CONNECTED){let k=!1;if(((m=_.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=ue.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=_.message.value.pingTimeout,this.pingIntervalDuration=_.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(_.message.value)):this.state===ue.RECONNECTING&&_.message.case!=="leave"?(this.state=ue.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((v=_.message)===null||v===void 0?void 0:v.case)==="reconnect"?l(_.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),k=!0)):this.isEstablishingConnection&&_.message.case==="leave"?d(new le("Received leave request while trying to (re)connect",Q.LeaveRequest,void 0,_.message.value.reason)):i.reconnect||d(new le("did not receive join response, got ".concat((y=_.message)===null||y===void 0?void 0:y.case," instead"),Q.InternalError)),!k)return}this.signalLatency&&(yield Ve(this.signalLatency)),this.handleSignalResponse(_)}),this.ws.onclose=f=>{this.isEstablishingConnection&&d(new le("Websocket got closed during a (re)connection attempt",Q.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:f.reason,code:f.code,wasClean:f.wasClean,state:this.state})),this.handleOnClose(f.reason)}}finally{u()}}))}close(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),n&&(e.state=ue.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,Ve(250)])),e.ws=void 0}}finally{n&&(e.state=ue.DISCONNECTED),i()}})()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Mr(e,n)})}sendAnswer(e,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Mr(e,n)})}sendIceCandidate(e,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new io({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new ro({sid:e,muted:n})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new ld({requestId:a,metadata:i,name:r,attributes:o})}),a})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,n){return this.sendRequest({case:"updateLayers",value:new cd({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new hd({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:pe.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new gd({timestamp:pe.parse(Date.now()),rtt:pe.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new ad({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new kr({reason:ot.CLIENT_INITIATED,action:Jn.DISCONNECT})})}sendRequest(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!zv(n)&&i.state===ue.RECONNECTING){i.queuedRequests.push(()=>C(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield Ve(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(n.case,") - SignalClient disconnected"));return}if(!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new pg({message:n});try{i.useJSON?i.ws.send(o.toJsonString()):i.ws.send(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}})()})}handleSignalResponse(e){var n,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const o=xu(r.value);this.onAnswer&&this.onAnswer(o,r.value.id)}else if(r.case==="offer"){const o=xu(r.value);this.onOffer&&this.onOffer(o,r.value.id)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return C(this,void 0,void 0,function*(){if(this.state===ue.DISCONNECTED)return;const n=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),n&&n(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Ne.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Ne.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Ne.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ne.clearInterval(this.pingInterval)}}function xu(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type;break}return e}function Mr(t,e){return new Pn({sdp:t.sdp,type:t.type,id:e})}function Wv(t,e,n){var i;const r=new URLSearchParams;return r.set("access_token",t),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",St()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}class Eu{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Hv{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:n,expiresAt:r}),this}get(e){const n=this._map.get(e);if(n){if(n.expiresAt<Date.now()){this._map.delete(e);return}return n.value}}has(e){const n=this._map.get(e);return n?n.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<e&&this._map.delete(n);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,n,this.asValueMap())}map(e){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(e(s,r,i));return n}asValueMap(){const e=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(n,i.value);return e}}var dt={},Vo={},qo={exports:{}},Pu;function $o(){if(Pu)return qo.exports;Pu=1;var t=qo.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 e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(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 e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var n="candidate:%s %d %s %d %s %d typ %s";return n+=e.raddr!=null?" raddr %s rport %d":"%v%v",n+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(n+=" generation %d"),n+=e["network-id"]!=null?" network-id %d":"%v",n+=e["network-cost"]!=null?" network-cost %d":"%v",n}},{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 n="ssrc:%d";return e.attribute!=null&&(n+=" %s",e.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(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"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var n="mediaclk:";return n+=e.id!=null?"id=%s %s":"%v%s",n+=e.mediaClockValue!=null?"=%s":"",n+=e.rateNumerator!=null?" rate=%s":"",n+=e.rateDenominator!=null?"/%s":"",n}},{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"]}]};return Object.keys(t).forEach(function(e){var n=t[e];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),qo.exports}var Ru;function Gv(){return Ru||(Ru=1,(function(t){var e=function(a){return String(Number(a))===a?Number(a):a},n=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},i=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;n(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},r=$o(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],p=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(r[h]||[]).length;g+=1){var f=r[h][g];if(f.reg.test(p))return i(f,d,p)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},t.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}})(Vo)),Vo}var zo,Iu;function Kv(){if(Iu)return zo;Iu=1;var t=$o(),e=/%[sdv%]/g,n=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?d.push(c[a.name][h]):d.push(c[a.names[u]])}else d.push(c[a.name]);return n.apply(null,d)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return zo=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||r,l=a.innerOrder||s,d=[];return c.forEach(function(u){t[u].forEach(function(h){h.name in o&&o[h.name]!=null?d.push(i(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(p){d.push(i(u,h,p))})})}),o.media.forEach(function(u){d.push(i("m",t.m[0],u)),l.forEach(function(h){t[h].forEach(function(p){p.name in u&&u[p.name]!=null?d.push(i(h,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(g){d.push(i(h,p,g))})})})}),d.join(`\r
36
+ `);t.RTCSessionDescription&&r instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function Pr(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Er(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var av=Object.freeze({__proto__:null,removeExtmapAllowMixed:bo,shimAddIceCandidateNullOrEmpty:Pr,shimConnectionState:vo,shimMaxMessageSize:Tr,shimParameterlessSetLocalDescription:Er,shimRTCIceCandidate:Sr,shimRTCIceCandidateRelayProtocol:go,shimSendThrowTypeError:xr});function cv(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Td,i=iv(t),r={browserDetails:i,commonShim:av,extractVersion:Oi,disableLog:tv,disableWarnings:nv,sdp:ov};switch(i.browser){case"chrome":if(!Fd||!fo||!e.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Fd,Pr(t,i),Er(t),Id(t,i),Od(t),fo(t,i),Ad(t),Ld(t,i),Dd(t),Md(t),Ud(t,i),Sr(t),go(t),vo(t),Tr(t,i),xr(t),bo(t,i);break;case"firefox":if(!Jd||!po||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Jd,Pr(t,i),Er(t),Bd(t,i),po(t,i),jd(t),$d(t),Vd(t),qd(t),zd(t),Wd(t),Hd(t),Gd(t),Kd(t),Sr(t),vo(t),Tr(t,i),xr(t);break;case"safari":if(!su||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=su,Pr(t,i),Er(t),tu(t),iu(t),Qd(t),Yd(t),Xd(t),nu(t),Zd(t),ru(t),Sr(t),go(t),Tr(t,i),xr(t),bo(t,i);break;default:n("Unsupported browser!");break}return r}cv({window:typeof window>"u"?void 0:window});const lv=10,Ai="lk_e2ee",dv={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:lv,keyringSize:16};var dn;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(dn||(dn={}));var cu;(function(t){t.KeyRatcheted="keyRatcheted"})(cu||(cu={}));var un;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(un||(un={}));var lu;(function(t){t.Error="cryptorError"})(lu||(lu={}));function uv(){return hv()||yo()}function yo(){return typeof window.RTCRtpScriptTransform<"u"}function hv(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class w_ extends St.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{Q.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},dv),e),this.on(dn.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,n,i){const r={key:e,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(dn.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(dn.RatchetRequest,e,n)}}class Ht extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var ee;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout"})(ee||(ee={}));class de extends Ht{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=ee[n]}}class ko extends Ht{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Gt extends Ht{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class fv extends Ht{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Oe extends Ht{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Co extends Ht{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class du extends Ht{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class uu extends Ht{constructor(e,n){super(15,e),this.reason=n,this.reasonName=typeof n=="string"?n:co[n]}}var dt;(function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered"})(dt||(dt={}));class hn extends Ht{constructor(e,n){super(16,e),this.name="DataStreamError",this.reason=n,this.reasonName=dt[n]}}var Rr;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(Rr||(Rr={})),(function(t){function e(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?t.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?t.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e})(Rr||(Rr={}));var hu;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(hu||(hu={}));var O;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(O||(O={}));var U;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(U||(U={}));var L;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(L||(L={}));var D;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(D||(D={}));function pv(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}const mv=/version\/(\d+(\.?_?\d+)+)/i;let wo;function Qe(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(wo===void 0||e){const i=gv.find(r=>{let{test:s}=r;return s.test(n)});wo=i==null?void 0:i.describe(n)}return wo}const gv=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:Ir(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:_o(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:Ir(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:_o(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:Ir(mv,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:_o(t)}}}];function Ir(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(t);return i&&i.length>=n&&i[n]||""}function _o(t){return t.includes("mac os")?Ir(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var vv="2.15.5";const bv=vv,yv=16;class Ue{}Ue.setTimeout=function(){return setTimeout(...arguments)},Ue.setInterval=function(){return setInterval(...arguments)},Ue.clearTimeout=function(){return clearTimeout(...arguments)},Ue.clearInterval=function(){return clearInterval(...arguments)};const kv=5e3,Di=[];var Ze;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(Ze||(Ze={}));class P extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=P.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Q,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),kv):this.handleAppVisibilityChanged()},this.log=zt((r=i.loggerName)!==null&&r!==void 0?r:lt.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=P.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Y(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let n="audio";this.kind===P.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===P.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(Di.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Di.splice(Di.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),Xn(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?D.AudioPlaybackStarted:D.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?D.AudioPlaybackFailed:D.VideoPlaybackFailed,s):s.name==="AbortError"?Q.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Q.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(D.ElementAttached,e),e}detach(e){try{if(e){Qn(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(D.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{Qn(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(D.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=zt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),Di.forEach(i=>{i.parentElement||(n=!1)}),n&&Di.push(e)}}handleAppVisibilityChanged(){return C(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===P.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){He()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){He()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Xn(t,e){let n;e.srcObject instanceof MediaStream?n=e.srcObject:n=new MediaStream;let i;t.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(t)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(t)),(!On()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,(On()||Zn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function Qn(t,e){if(e.srcObject instanceof MediaStream){const n=e.srcObject;n.removeTrack(t),n.getTracks().length>0?e.srcObject=n:e.srcObject=null}}(function(t){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=t.Source||(t.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=t.StreamState||(t.StreamState={}));function r(l){switch(l){case e.Audio:return ot.AUDIO;case e.Video:return ot.VIDEO;default:return ot.DATA}}t.kindToProto=r;function s(l){switch(l){case ot.AUDIO:return e.Audio;case ot.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=s;function o(l){switch(l){case n.Camera:return Te.CAMERA;case n.Microphone:return Te.MICROPHONE;case n.ScreenShare:return Te.SCREEN_SHARE;case n.ScreenShareAudio:return Te.SCREEN_SHARE_AUDIO;default:return Te.UNKNOWN}}t.sourceToProto=o;function a(l){switch(l){case Te.CAMERA:return n.Camera;case Te.MICROPHONE:return n.Microphone;case Te.SCREEN_SHARE:return n.ScreenShare;case Te.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=a;function c(l){switch(l){case to.ACTIVE:return i.Active;case to.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=c})(P||(P={}));class ce{constructor(e,n,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(n!==void 0&&i!==void 0)this.width=e,this.height=n,this.aspectRatio=e/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Cv=["vp8","h264"],wv=["vp8","h264","vp9","av1","h265"];function _v(t){return!!Cv.find(e=>e===t)}var fu;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(fu||(fu={}));var So;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(So||(So={}));const Mi={h90:new ce(160,90,9e4,20),h180:new ce(320,180,16e4,20),h216:new ce(384,216,18e4,20),h360:new ce(640,360,45e4,20),h540:new ce(960,540,8e5,25),h720:new ce(1280,720,17e5,30),h1080:new ce(1920,1080,3e6,30),h1440:new ce(2560,1440,5e6,30),h2160:new ce(3840,2160,8e6,30)},To={h120:new ce(160,120,7e4,20),h180:new ce(240,180,125e3,20),h240:new ce(320,240,14e4,20),h360:new ce(480,360,33e4,20),h480:new ce(640,480,5e5,20),h540:new ce(720,540,6e5,25),h720:new ce(960,720,13e5,30),h1080:new ce(1440,1080,23e5,30),h1440:new ce(1920,1440,38e5,30)},xo={h360fps3:new ce(640,360,2e5,3,"medium"),h360fps15:new ce(640,360,4e5,15,"medium"),h720fps5:new ce(1280,720,8e5,5,"medium"),h720fps15:new ce(1280,720,15e5,15,"medium"),h720fps30:new ce(1280,720,2e6,30,"medium"),h1080fps15:new ce(1920,1080,25e5,15,"medium"),h1080fps30:new ce(1920,1080,5e6,30,"medium"),original:new ce(0,0,7e6,30,"medium")},Sv="|",pu="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Tv(t){const e=t.split(Sv);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function We(t){return C(this,void 0,void 0,function*(){return new Promise(e=>Ue.setTimeout(e,t))})}function Po(){return"addTransceiver"in RTCPeerConnection.prototype}function Eo(){return"addTrack"in RTCPeerConnection.prototype}function xv(){if(!("getCapabilities"in RTCRtpSender)||On())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/AV1"){e=!0;break}}return e}function Pv(){if(!("getCapabilities"in RTCRtpSender)||Zn())return!1;if(On()){const n=Qe();if(n!=null&&n.version&&Pt(n.version,"16")<0||(n==null?void 0:n.os)==="iOS"&&(n!=null&&n.osVersion)&&Pt(n.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/VP9"){e=!0;break}}return e}function Tt(t){return t==="av1"||t==="vp9"}function Ro(t){return!document||Or()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function Ev(){return typeof RTCPeerConnection>"u"?!1:Po()||Eo()}function Zn(){var t;return((t=Qe())===null||t===void 0?void 0:t.name)==="Firefox"}function On(){var t;return((t=Qe())===null||t===void 0?void 0:t.name)==="Safari"}function Or(){const t=Qe();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function Rv(){const t=Qe();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Pt(t.osVersion,"17")>=0}function Iv(t){return t||(t=Qe()),(t==null?void 0:t.name)==="Safari"&&Pt(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Pt(t.osVersion,"18.3")>0}function mu(){var t,e;return He()?(e=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Ov(){const t=Qe(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&Pt(e,t.osVersion)>=0?!0:t.name==="Safari"&&Pt(e,t.version)>=0}function He(){return typeof document<"u"}function xt(){return navigator.product=="ReactNative"}function Io(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function gu(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function vu(){if(!xt())return;let t=gu();if(t)return t.platform}function bu(){if(He())return window.devicePixelRatio;if(xt()){let t=gu();if(t)return t.devicePixelRatio}return 1}function Pt(t,e){const n=t.split("."),i=e.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const o=parseInt(n[s],10),a=parseInt(i[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return t===""&&e!==""?-1:e===""?1:n.length==i.length?0:n.length<i.length?-1:1}function Av(t){for(const e of t)e.target.handleResize(e)}function Dv(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Oo=null;const yu=()=>(Oo||(Oo=new ResizeObserver(Av)),Oo);let Ao=null;const ku=()=>(Ao||(Ao=new IntersectionObserver(Dv,{root:null,rootMargin:"0px"})),Ao);function Mv(){var t;const e=new wg({sdk:nd.JS,protocol:yv,version:bv});return xt()&&(e.os=(t=vu())!==null&&t!==void 0?t:""),e}function Cu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=t,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(t/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let Ni;function Do(){if(!Ni){const t=new AudioContext,e=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const i=t.createMediaStreamDestination();if(e.connect(n),n.connect(i),e.start(),[Ni]=i.stream.getAudioTracks(),!Ni)throw Error("Could not get empty media stream audio track");Ni.enabled=!1}return Ni.clone()}class Et{get isResolved(){return this._isResolved}constructor(e,n){this._isResolved=!1,this.onFinally=n,this.promise=new Promise((i,r)=>C(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function Nv(t){return wv.includes(t)}function fn(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact!==void 0)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal!==void 0)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function Lv(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function Mo(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function Uv(t,e){return t.segments.map(n=>{let{id:i,text:r,language:s,startTime:o,endTime:a,final:c}=n;var l;const d=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,d),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:s,firstReceivedTime:d,lastReceivedTime:u}})}function Fv(t){const{id:e,timestamp:n,message:i,editTimestamp:r}=t;return{id:e,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function wu(t){switch(t.reason){case ee.LeaveRequest:return t.context;case ee.Cancelled:return at.CLIENT_INITIATED;case ee.NotAllowed:return at.USER_REJECTED;case ee.ServerUnreachable:return at.JOIN_FAILURE;default:return at.UNKNOWN_REASON}}function Ar(t){return t!==void 0?Number(t):void 0}function An(t){return t!==void 0?BigInt(t):void 0}function ei(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Rt(t){return!!t&&t.kind==P.Kind.Audio}function Dn(t){return!!t&&t.kind==P.Kind.Video}function pn(t){return ei(t)&&Dn(t)}function Kt(t){return ei(t)&&Rt(t)}function No(t){return!!t&&!t.isLocal}function Bv(t){return!!t&&!t.isLocal}function Lo(t){return No(t)&&Dn(t)}function jv(t){return t.isLocal}function Vv(t,e){const n=[];let i=new TextEncoder().encode(t);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function _u(t,e,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=xu(t??{}),d=e==null?void 0:e.processor,u=n==null?void 0:n.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Uo(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(Uo(h.video,n),(r=(o=h.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function Uo(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function Fo(t){var e,n,i,r;const s={};if(t.video)if(typeof t.video=="object"){const o={},a=o,c=t.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":Uo(a,c.resolution);break;default:a[l]=c[l]}}),s.video=o,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=t.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return t.audio?typeof t.audio=="object"?(s.audio=t.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Su(t){return C(this,arguments,void 0,function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Tu();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield We(n),r.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return i.close(),!c}return!1})()})}function Tu(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const n=new e({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const i=()=>C(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return n}}function qv(t){return t==="audioinput"?P.Source.Microphone:t==="videoinput"?P.Source.Camera:P.Source.Unknown}function Bo(t){return t===P.Source.Microphone?"audioinput":t===P.Source.Camera?"videoinput":void 0}function $v(t){var e,n;let i=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(i=typeof i=="boolean"?{}:i,On()?i=Object.assign(Object.assign({},i),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(n=t.audio)!==null&&n!==void 0?n:!1,video:i,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function Dr(t){return t.split("/")[1].toLowerCase()}function zv(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new oo({cid:n.track.mediaStreamID,track:n.trackInfo}))}),e}function Y(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?Y(t.track):{})}}function Wv(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Hv(t,e){var n;t===void 0&&(t={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(t)],r={};for(const s of i)t[s]!==e[s]&&(r[s]=(n=e[s])!==null&&n!==void 0?n:"");return r}function xu(t){const e=Object.assign({},t);let n,i;return typeof e.audio=="object"&&e.audio.processor&&(n=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:pv(e)}}function Gv(t){switch(t){case Te.CAMERA:return P.Source.Camera;case Te.MICROPHONE:return P.Source.Microphone;case Te.SCREEN_SHARE:return P.Source.ScreenShare;case Te.SCREEN_SHARE_AUDIO:return P.Source.ScreenShareAudio;default:return P.Source.Unknown}}function Pu(t,e){return t.width*t.height<e.width*e.height}function Kv(t,e){var n;return(n=t.layers)===null||n===void 0?void 0:n.find(i=>i.quality===e)}class Jv extends St.EventEmitter{constructor(e){super(),this.onWorkerMessage=n=>{var i,r;const{kind:s,data:o}=n.data;switch(s){case"error":Q.error(o.error.message),this.emit(un.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(un.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(un.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(dn.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break}},this.onWorkerError=n=>{Q.error("e2ee worker encountered an error:",{error:n.error}),this.emit(un.EncryptionError,n.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!uv())throw new ko("tried to setup end-to-end encryption on an unsupported browser");if(Q.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Yg.getLevel()}};this.worker&&(Q.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(e,n){Q.debug("set e2ee to ".concat(e," for participant ").concat(n)),this.postEnable(e,n)}setSifTrailer(e){!e||e.length===0?Q.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(L.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(O.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Xe.NONE,r.identity)),e.on(O.ConnectionStateChanged,i=>{i===ne.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Xe.NONE,r.identity)})})}).on(O.TrackUnsubscribed,(i,r,s)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(O.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(O.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(U.LocalSenderCreated,(i,r)=>C(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),n.on(dn.SetKey,i=>this.postKey(i)).on(dn.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(e,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:n}};this.worker.postMessage(i)}postKey(e){let{key:n,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(e,n){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(n)}setupE2EEReceiver(e,n,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,n,e.kind==="video"?Dr(i.mimeType):void 0)}}setupE2EESender(e,n){if(!ei(e)||!n){n||Q.warn("early return because sender is not ready");return}this.handleSender(n,e.mediaStreamID,void 0)}handleReceiver(e,n,i,r){return C(this,void 0,void 0,function*(){if(this.worker){if(yo()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Ai in e&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,o=e.readableStream;if(!s||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:Ai in e}};this.worker.postMessage(a,[o,s])}e[Ai]=!0}})}handleSender(e,n,i){var r;if(!(Ai in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(yo()){Q.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{Q.info("initialize encoded streams");const s=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[s.readable,s.writable])}e[Ai]=!0}}}const jo="default";class Me{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Me),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=Me.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){Q.debug("awaiting getUserMedia promise");try{n?yield Me.userMediaPromiseMap.get(n):yield Promise.all(Me.userMediaPromiseMap.values())}catch{Q.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(On()&&i.hasDeviceInUse(n))&&(o.filter(c=>c.kind===n).length===0||o.some(c=>{const l=c.label==="",d=n?c.kind===n:!0;return l&&d}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return i._previousDevices=o,n&&(o=o.filter(a=>a.kind===n)),o})()})}normalizeDeviceId(e,n,i){return C(this,void 0,void 0,function*(){if(n!==jo)return n;const r=yield this.getDevices(e),s=r.find(a=>a.deviceId===jo);if(!s){Q.warn("could not reliably determine default device");return}const o=r.find(a=>a.deviceId!==jo&&a.groupId===(i??s.groupId));if(!o){Q.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?Me.userMediaPromiseMap.has(e):Me.userMediaPromiseMap.size>0}}Me.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Me.userMediaPromiseMap=new Map;var Li;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(Li||(Li={}));class Yv{constructor(){this.pendingTasks=new Map,this.taskMutex=new qe,this.nextTaskIndex=0}run(e){return C(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Li.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=Li.RUNNING,yield e()}finally{n.status=Li.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return C(this,void 0,void 0,function*(){return this.run(()=>C(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function Xv(t,e){const n=new URL(Lv(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),Eu(n,"rtc")}function Qv(t){const e=new URL(Mo(t));return Eu(e,"validate")}function Zv(t){return t.endsWith("/")?t:"".concat(t,"/")}function Eu(t,e){return t.pathname="".concat(Zv(t.pathname)).concat(e),t.toString()}const e0=["syncState","trickle","offer","answer","simulate","leave"];function t0(t){const e=e0.indexOf(t.case)>=0;return Q.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var he;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(he||(he={}));class Vo{get currentState(){return this.state}get isDisconnected(){return this.state===he.DISCONNECTING||this.state===he.DISCONNECTED}get isEstablishingConnection(){return this.state===he.CONNECTING||this.state===he.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=he.DISCONNECTED,this.log=Q,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=zt((i=n.loggerName)!==null&&i!==void 0?i:lt.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new Yv,this.queuedRequests=[],this.closingLock=new qe,this.connectionLock=new qe,this.state=he.DISCONNECTED}get logContext(){var e,n;return(n=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&n!==void 0?n:{}}join(e,n,i,r){return C(this,void 0,void 0,function*(){return this.state=he.CONNECTING,this.options=i,yield this.connect(e,n,i,r)})}reconnect(e,n,i,r){return C(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=he.RECONNECTING,this.clearPingInterval(),yield this.connect(e,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,n,i,r){this.connectOptions=i;const s=Mv(),o=n0(n,s,i),a=Xv(e,o),c=Qv(a);return new Promise((l,d)=>C(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const h=()=>C(this,void 0,void 0,function*(){this.close(),clearTimeout(f),d(new de("room connection has been cancelled (signal)",ee.Cancelled))}),f=setTimeout(()=>{this.close(),d(new de("room connection has timed out (signal)",ee.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const v=new URL(a);v.searchParams.has("access_token")&&v.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(v),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=p=>C(this,void 0,void 0,function*(){if(this.state!==he.CONNECTED){this.state=he.DISCONNECTED,clearTimeout(f);try{const g=yield fetch(c);if(g.status.toFixed(0).startsWith("4")){const b=yield g.text();d(new de(b,ee.NotAllowed,g.status))}else d(new de("Encountered unknown websocket error during connection: ".concat(p.toString()),ee.InternalError,g.status))}catch(g){d(new de(g instanceof Error?g.message:"server was not reachable",ee.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>C(this,void 0,void 0,function*(){var g,b,k;let w;if(typeof p.data=="string"){const y=JSON.parse(p.data);w=cd.fromJson(y,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)w=cd.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==he.CONNECTED){let y=!1;if(((g=w.message)===null||g===void 0?void 0:g.case)==="join"?(this.state=he.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=w.message.value.pingTimeout,this.pingIntervalDuration=w.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(w.message.value)):this.state===he.RECONNECTING&&w.message.case!=="leave"?(this.state=he.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((b=w.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(w.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),y=!0)):this.isEstablishingConnection&&w.message.case==="leave"?d(new de("Received leave request while trying to (re)connect",ee.LeaveRequest,void 0,w.message.value.reason)):i.reconnect||d(new de("did not receive join response, got ".concat((k=w.message)===null||k===void 0?void 0:k.case," instead"),ee.InternalError)),!y)return}this.signalLatency&&(yield We(this.signalLatency)),this.handleSignalResponse(w)}),this.ws.onclose=p=>{this.isEstablishingConnection&&d(new de("Websocket got closed during a (re)connection attempt",ee.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{u()}}))}close(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),n&&(e.state=he.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,We(250)])),e.ws=void 0}}finally{n&&(e.state=he.DISCONNECTED),i()}})()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Mr(e,n)})}sendAnswer(e,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Mr(e,n)})}sendIceCandidate(e,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ro({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new so({sid:e,muted:n})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new hd({requestId:a,metadata:i,name:r,attributes:o})}),a})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,n){return this.sendRequest({case:"updateLayers",value:new ud({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new md({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:pe.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new yd({timestamp:pe.parse(Date.now()),rtt:pe.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new dd({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new kr({reason:at.CLIENT_INITIATED,action:Jn.DISCONNECT})})}sendRequest(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!t0(n)&&i.state===he.RECONNECTING){i.queuedRequests.push(()=>C(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield We(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(n.case,") - SignalClient disconnected"));return}if(!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new Tg({message:n});try{i.useJSON?i.ws.send(o.toJsonString()):i.ws.send(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}})()})}handleSignalResponse(e){var n,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const o=Ru(r.value);this.onAnswer&&this.onAnswer(o,r.value.id)}else if(r.case==="offer"){const o=Ru(r.value);this.onOffer&&this.onOffer(o,r.value.id)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return C(this,void 0,void 0,function*(){if(this.state===he.DISCONNECTED)return;const n=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),n&&n(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Ue.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Ue.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Ue.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ue.clearInterval(this.pingInterval)}}function Ru(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type;break}return e}function Mr(t,e){return new Rn({sdp:t.sdp,type:t.type,id:e})}function n0(t,e,n){var i;const r=new URLSearchParams;return r.set("access_token",t),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",xt()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}class Iu{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class i0{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:n,expiresAt:r}),this}get(e){const n=this._map.get(e);if(n){if(n.expiresAt<Date.now()){this._map.delete(e);return}return n.value}}has(e){const n=this._map.get(e);return n?n.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<e&&this._map.delete(n);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,n,this.asValueMap())}map(e){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(e(s,r,i));return n}asValueMap(){const e=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(n,i.value);return e}}var ut={},qo={},$o={exports:{}},Ou;function zo(){if(Ou)return $o.exports;Ou=1;var t=$o.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 e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(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 e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var n="candidate:%s %d %s %d %s %d typ %s";return n+=e.raddr!=null?" raddr %s rport %d":"%v%v",n+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(n+=" generation %d"),n+=e["network-id"]!=null?" network-id %d":"%v",n+=e["network-cost"]!=null?" network-cost %d":"%v",n}},{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 n="ssrc:%d";return e.attribute!=null&&(n+=" %s",e.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(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"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var n="mediaclk:";return n+=e.id!=null?"id=%s %s":"%v%s",n+=e.mediaClockValue!=null?"=%s":"",n+=e.rateNumerator!=null?" rate=%s":"",n+=e.rateDenominator!=null?"/%s":"",n}},{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"]}]};return Object.keys(t).forEach(function(e){var n=t[e];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),$o.exports}var Au;function r0(){return Au||(Au=1,(function(t){var e=function(a){return String(Number(a))===a?Number(a):a},n=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},i=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;n(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},r=zo(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var v=0;v<(r[h]||[]).length;v+=1){var p=r[h][v];if(p.reg.test(f))return i(p,d,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},t.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}})(qo)),qo}var Wo,Du;function s0(){if(Du)return Wo;Du=1;var t=zo(),e=/%[sdv%]/g,n=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?d.push(c[a.name][h]):d.push(c[a.names[u]])}else d.push(c[a.name]);return n.apply(null,d)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Wo=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||r,l=a.innerOrder||s,d=[];return c.forEach(function(u){t[u].forEach(function(h){h.name in o&&o[h.name]!=null?d.push(i(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){d.push(i(u,h,f))})})}),o.media.forEach(function(u){d.push(i("m",t.m[0],u)),l.forEach(function(h){t[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(v){d.push(i(h,f,v))})})})}),d.join(`\r
37
37
  `)+`\r
38
- `},zo}var Ou;function Jv(){if(Ou)return dt;Ou=1;var t=Gv(),e=Kv(),n=$o();return dt.grammar=n,dt.write=e,dt.parse=t.parse,dt.parseParams=t.parseParams,dt.parseFmtpConfig=t.parseFmtpConfig,dt.parsePayloads=t.parsePayloads,dt.parseRemoteCandidates=t.parseRemoteCandidates,dt.parseImageAttributes=t.parseImageAttributes,dt.parseSimulcastStreamList=t.parseSimulcastStreamList,dt}var hn=Jv();function Wo(t,e,n){var i,r,s;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var p=Date.now()-l;if(p+e>=c)return c-p}return e}var h=function(){var p=[].slice.call(arguments),g=this;return new Promise(function(f,m){var v=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var _=t.apply(g,p);a&&a(_),d.forEach(function(k){return(0,k.resolve)(_)}),d=[]}},u()),v){var y=t.apply(g,p);return a&&a(y),f(y)}d.push({resolve:f,reject:m})})};return h.cancel=function(p){s!==void 0&&clearTimeout(s),d.forEach(function(g){return(0,g.reject)(p)}),d=[]},h}const Yv=.7,Xv=20,ti={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Du extends _t.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=X,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Wo(r=>C(this,void 0,void 0,function*(){this.emit(ti.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),Xv),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=qt((i=n.loggerName)!==null&&i!==void 0?i:ct.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new Fe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return C(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return C(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:s,nackMids:o}=Qv(e);this.remoteStereoMids=s,this.remoteNackMids=o}else if(e.type==="answer"){const s=hn.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=hn.write(s)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(ti.NegotiationComplete),e.sdp&&hn.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(ti.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const o=hn.parse((n=s.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(a=>{Mu(a),a.type==="audio"?Au(a,[],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(wt(c.codec)&&!In()&&this.ensureVideoDDExtensionForSVC(a,o),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*Yv);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,hn.write(o)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=hn.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Mu(r),r.type==="audio"&&Au(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,hn.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new Pe("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new Pe("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return C(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return C(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new ko(s)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===uu))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:uu})}}}function Au(t,e,n){let i=0;t.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(t.mid)&&!t.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&t.rtcpFb.push({payload:i,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Qv(t){var e;const n=[],i=[],r=hn.parse((e=t.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function Mu(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const Ho="vp8",Zv={audioPreset:wo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:To.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ho,backupCodec:!0,preConnectBuffer:!1},Nu={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Lu={deviceId:{ideal:"default"},resolution:Mi.h720.resolution},e0={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Vg,disconnectOnPageLeave:!0,webAudioMix:!1},Go={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ke;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(ke||(ke={}));class t0{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Go.peerConnectionTimeout,this.log=X,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=ke.CONNECTED:a.some(c=>c==="failed")?this.state=ke.FAILED:a.some(c=>c==="connecting")?this.state=ke.CONNECTING:a.every(c=>c==="closed")?this.state=ke.CLOSED:a.some(c=>c==="closed")?this.state=ke.CLOSING:a.every(c=>c==="new")&&(this.state=ke.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(ke[o]," to ").concat(ke[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=qt((r=i.loggerName)!==null&&r!==void 0?r:ct.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new Du(e,i),this.subscriber=new Du(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,at.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,at.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=ke.NEW,this.connectionLock=new Fe,this.remoteOfferLock=new Fe}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return C(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const n of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return C(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return C(this,void 0,void 0,function*(){n===at.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return C(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(e,n){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return C(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,n)))}finally{r()}})}negotiate(e){return C(this,void 0,void 0,function*(){return new Promise((n,i)=>C(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(ti.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(ti.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===at.PUBLISHER?this.publisher.getConnectedAddress():e===at.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>C(s,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Ne.clearTimeout(u),l(new le("room connection has been cancelled",Q.Cancelled))};r!=null&&r.signal.aborted&&d(),r==null||r.signal.addEventListener("abort",d);const u=Ne.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",d),l(new le("could not establish pc connection",Q.InternalError))},o);for(;this.state!==ke.CONNECTED;)if(yield Ve(50),r!=null&&r.signal.aborted){l(new le("room connection has been cancelled",Q.Cancelled));return}Ne.clearTimeout(u),r==null||r.signal.removeEventListener("abort",d),c()}))})()})}}class Ce extends Error{constructor(e,n,i){super(n),this.code=e,this.message=Fu(n,Ce.MAX_MESSAGE_BYTES),this.data=i?Fu(i,Ce.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ce(e.code,e.message,e.data)}toProto(){return new Jl({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Ce(Ce.ErrorCode[e],Ce.ErrorMessage[e],n)}}Ce.MAX_MESSAGE_BYTES=256,Ce.MAX_DATA_BYTES=15360,Ce.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ce.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Uu=15360;function Ko(t){return new TextEncoder().encode(t).length}function Fu(t,e){if(Ko(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(t.slice(0,s)).length<=e?n=s:i=s-1}return t.slice(0,n)}const Jo=2e3;function Nr(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const Yo=typeof MediaRecorder<"u";class n0{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const i0=Yo?MediaRecorder:n0;class r0 extends i0{constructor(e,n){if(!Yo)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>C(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");s()||c.enqueue(d)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function s0(){return Yo}const o0=1e3,a0=1e4;class Bu extends E{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,n,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Wo(()=>C(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>C(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(N.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Fe,this.pauseUpstreamLock=new Fe,this.trackChangeLock=new Fe,this.trackChangeLock.lock().then(o=>C(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==E.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return C(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Qn(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Xn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Xn(r??e,s)}))})}waitForDimensions(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o0;return(function*(){var i;if(e.kind===E.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Xe())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Ve(10));const r=Date.now();for(;Date.now()-r<n;){const s=e.dimensions;if(s)return s;yield Ve(50)}throw new Wt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return C(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===dn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),dn(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===E.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===E.Kind.Audio?"audioinput":"videoinput";return n?Ie.getInstance().normalizeDeviceId(s,i,r):i})()})}mute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return C(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Wt("unable to replace an unpublished track");let r,s;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,s=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return C(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=qg(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===E.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Qn(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(N.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?N.Muted:N.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),hu()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(N.UpstreamPaused,this);const i=Xe();if((i==null?void 0:i.name)==="Safari"&&Tt(i.version,"12.0")<0)throw new yo("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(N.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Xn(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:d}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))}),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Qn(i._mediaStreamTrack,l),Xn(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(N.TrackProcessorUpdate,i.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}})()})}internalStopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(N.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!s0()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new r0(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},a0)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Lr extends Bu{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,E.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(N.AudioTrackFeatureUpdate,this,Re.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(N.AudioTrackFeatureUpdate,this,Re.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==dn(this._constraints.deviceId);return this.source===E.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return C(this,void 0,void 0,function*(){let n;if(e){const i=Uo({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return C(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){qe()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Jo)))}setProcessor(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!St()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(N.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return C(this,void 0,void 0,function*(){const e=yield Cu(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(N.AudioSilenceDetected)),e})}}function c0(t,e,n){switch(t.kind){case"audio":return new Lr(t,e,!1,void 0,n);case"video":return new Ur(t,e,!1,n);default:throw new Wt("unsupported track type: ".concat(t.kind))}}const l0=Object.values(Mi),d0=Object.values(So),u0=Object.values(To),h0=[Mi.h180,Mi.h360],f0=[So.h180,So.h360],p0=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new se(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),Xo=["q","h","f"];function Qo(t,e,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!n)return[{}];o||(o=g0(t,e,n,l),X.debug("using video encoding",o));const d=o.maxFramerate,u=new se(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&wt(l)){const g=new qu(c),f=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=Xe();if(Or()||St()||(m==null?void 0:m.name)==="Chrome"&&Tt(m==null?void 0:m.version,"113")<0){const v=g.suffix=="h"?2:3,y=yv(m);for(let _=0;_<g.spatial;_+=1)f.push({rid:Xo[2-_],maxBitrate:o.maxBitrate/Math.pow(v,_),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,_):void 0});f[0].scalabilityMode=c}else f.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(f[0].priority=u.encoding.priority,f[0].networkPriority=u.encoding.priority),X.debug("using svc encoding",{encodings:f}),f}if(!a)return[o];let h=[];t?h=(r=Vu(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:ju(t,u):h=(s=Vu(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:ju(t,u);let p;if(h.length>0){const g=h[0];h.length>1&&([,p]=h);const f=Math.max(e,n);if(f>=960&&p)return Zo(e,n,[g,p,u],d);if(f>=480)return Zo(e,n,[g,u],d)}return Zo(e,n,[u])}function m0(t,e,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&X.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===E.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Qo(t.source===E.Source.ScreenShare,c,l,n)}function g0(t,e,n,i){const r=v0(t,e,n);let{encoding:s}=r[0];const o=Math.max(e,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function v0(t,e,n){if(t)return u0;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?l0:d0}function ju(t,e){if(t)return p0(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?h0:f0}function Zo(t,e,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=Xo.length)return;const a=Math.min(t,e),l={rid:Xo[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},d=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=Zn()||o===0;s.encoding.priority&&u&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),St()&&pu()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,X.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),X.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function Vu(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class qu{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function b0(t){return t.source===E.Source.ScreenShare||t.constraints.height&&dn(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const y0=5e3;class Ur extends Bu{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,E.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(s.map(c=>[c.rid,c])),a=s.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(N.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=Nr(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new Fe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!qe())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Jo))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=$t(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=$t(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const d=s;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(e){const n=[];for(let i=Qe.LOW;i<=Qe.HIGH;i+=1)n.push(new oo({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(wt(this.codec),n)}restartTrack(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(e){const u=Uo({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=$t(this.simulcastCodecs.values()),d;d=yield l.next(),n=d.done,!n;c=!0){s=d.value,c=!1;const u=s;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return C(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield n.setProcessor.call(r,i,s),!((d=r.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,p=$t(r.simulcastCodecs.values()),g;g=yield p.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(f){a={error:f}}finally{try{!h&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return C(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},y0))}setPublishingCodecs(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(wt(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(n=!0,i=$t(e);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(wt(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield $u(u.sender,u.encodings,d.qualities,this.senderLock,wt(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,n){return C(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield $u(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return C(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&wt(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),hu()&&this.isInBackground&&this.source===E.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function $u(t,e,n,i,r,s,o){return C(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const c=t.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(r&&n.some(p=>p.enabled)&&n.forEach(p=>p.enabled=!0),l.forEach((h,p)=>{var g;let f=(g=h.rid)!==null&&g!==void 0?g:"";f===""&&(f="q");const m=zu(f),v=n.find(y=>y.quality===m);v&&h.active!==v.enabled&&(d=!0,h.active=v.enabled,s.debug("setting layer ".concat(v.quality," to ").concat(h.active?"enabled":"disabled"),o),Zn()&&(v.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield t.setParameters(c))}finally{a()}})}function zu(t){switch(t){case"f":return Qe.HIGH;case"h":return Qe.MEDIUM;case"q":return Qe.LOW;default:return Qe.HIGH}}function Wu(t,e,n,i){if(!n)return[new En({quality:Qe.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new qu(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new En({quality:Math.min(Qe.HIGH,s.spatial-1)-l,width:Math.ceil(t/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=zu((o=r.rid)!==null&&o!==void 0?o:"");return new En({quality:l,width:Math.ceil(t/c),height:Math.ceil(e/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Hu="_lossy",Gu="_reliable",k0=2*1e3,ea="leave-reconnect",C0=3e4;var ut;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(ut||(ut={}));class _0 extends _t.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Go.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ut.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=X,this.reliableDataSequence=1,this.reliableMessageBuffer=new Eu,this.reliableReceivedState=new Hv(C0),this.handleDataChannel=i=>C(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return(function*(){if(o){if(o.label===Gu)s.reliableDCSub=o;else if(o.label===Hu)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}})()}),this.handleDataMessage=i=>C(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=je.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(L.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&S0(c,c.value.value),this.emit(L.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?G.LOSSY:G.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(L.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===ea&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ne.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ut.Connected&&i();const s=()=>{this.off(L.Disconnected,o),i()},o=()=>{this.off(L.Restarted,s),r()};this.once(L.Restarted,s),this.once(L.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(L.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===G.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ue.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Hn.RR_SIGNAL_DISCONNECTED))},this.log=qt((n=e.loggerName)!==null&&n!==void 0?n:ct.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Fe,this.dataProcessLock=new Fe,this.dcBufferStatus=new Map([[G.LOSSY,!0],[G.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(L.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(L.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(L.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(L.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(L.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(L.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(L.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(L.SignalRequestResponse,i)}get logContext(){var e,n,i,r,s,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return C(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(L.SignalConnected,s),s}catch(s){if(s instanceof le&&s.reason===Q.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,n,i,r);throw s}})}close(){return C(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(L.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return C(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Eu,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return C(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Wt("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new le("publication of local track timed out, no response from server",Q.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return C(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return C(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==ke.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new t0(r,e.subscriberPrimary,this.loggerOptions),this.emit(L.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>C(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===ke.CONNECTED){const d=this.pcState===ut.New;this.pcState=ut.Connected,d&&this.emit(L.Connected,e)}else s===ke.FAILED&&this.pcState===ut.Connected&&(this.pcState=ut.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Hn.RR_SUBSCRIBER_FAILED:Hn.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===ue.RECONNECTING,l=[ke.FAILED,ke.CLOSING,ke.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(L.Offline)}),this.pcManager.onTrack=s=>{this.emit(L.MediaTrackAdded,s.track,s.streams[0],s.receiver)},w0((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n)=>C(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n)=>C(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(L.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(L.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(L.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(L.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(L.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Hn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Jn.DISCONNECT:this.emit(L.Disconnected,e==null?void 0:e.reason),this.close();break;case Jn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ea);break;case Jn.RESUME:this.handleDisconnect(ea)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Pi.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Hu,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Gu,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,n,i){return C(this,void 0,void 0,function*(){if(xo())return yield this.createTransceiverRTCRtpSender(e,n,i);if(Eo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Pe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(xo())return this.createSimulcastTransceiverSender(e,n,i,r);if(Eo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Pe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Dn(e)&&(e.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return C(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){X.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===Pi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:ke.NEW)===ke.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof Pe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof ni||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Hn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(L.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return C(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new Pe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(L.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ni;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof le&&o.reason===Q.NotAllowed?new Pe("could not reconnect, token might be expired"):new ni}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(L.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ue.CONNECTED)throw new ni("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(L.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return C(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new Pe("could not reconnect, url or token not saved");if(!this.pcManager)throw new Pe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(L.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof le&&r.reason===Q.NotAllowed?new Pe("could not reconnect, token might be expired"):r instanceof le&&r.reason===Q.LeaveRequest?r:new ni(s)}if(this.emit(L.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==ue.CONNECTED)throw new ni("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(L.Resumed)})}waitForPCInitialConnection(e,n){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return C(this,void 0,void 0,function*(){this.pcState=ut.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ve(k0),!this.pcManager)throw new Pe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ut.Connected}catch(e){throw this.pcState=ut.Disconnected,new le("could not establish PC connection, ".concat(e.message),Q.InternalError)}})}publishRpcResponse(e,n,i,r){return C(this,void 0,void 0,function*(){const s=new je({destinationIdentities:[e],kind:G.RELIABLE,value:{case:"rpcResponse",value:new Kl({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,G.RELIABLE)})}publishRpcAck(e,n){return C(this,void 0,void 0,function*(){const i=new je({destinationIdentities:[e],kind:G.RELIABLE,value:{case:"rpcAck",value:new Gl({requestId:n})}});yield this.sendDataPacket(i,G.RELIABLE)})}sendDataPacket(e,n){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===G.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===G.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(G.RELIABLE);const n=this.dataChannelForKind(G.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(G.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>C(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(L.Closing,r);!this.dcBufferStatus.get(e);)yield Ve(10);this.off(L.Closing,r),n()}}))}ensureDataTransportConnected(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new Pe("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new le("".concat(a," connection not set"),Q.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Ve(50)}throw new le("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),Q.InternalError)})()})}ensurePublisherConnected(e){return C(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ke.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return C(this,void 0,void 0,function*(){return new Promise((e,n)=>C(this,void 0,void 0,function*(){if(!this.pcManager){n(new ko("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(L.Closing,r),this.pcManager.publisher.once(ti.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();Sv(c)&&o.set(a.payload,c)}),this.emit(L.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof ko&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Hn.RR_UNKNOWN),n(s)}finally{this.off(L.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===G.LOSSY)return this.lossyDCSub;if(e===G.RELIABLE)return this.reliableDCSub}else{if(e===G.LOSSY)return this.lossyDC;if(e===G.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==a&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new fd({answer:s?Mr({sdp:s.sdp,type:s.type}):void 0,offer:o?Mr({sdp:o.sdp,type:o.type}):void 0,subscription:new yr({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:Av(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new pd({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new md({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(G.LOSSY),at.PUBLISHER),n(this.dataChannelForKind(G.RELIABLE),at.PUBLISHER),n(this.dataChannelForKind(G.LOSSY,!0),at.SUBSCRIBER),n(this.dataChannelForKind(G.RELIABLE,!0),at.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ne.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){qe()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){qe()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ni extends Error{}function w0(t){return t!==void 0&&t>13}function S0(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class ta{constructor(e,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return Ro(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return C(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),X.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return C(this,void 0,void 0,function*(){const n=yield fetch("".concat(T0(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new le("Could not fetch region settings: ".concat(n.statusText),n.status===401?Q.NotAllowed:Q.InternalError,n.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function T0(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class Ku{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new ln("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),lt.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ln("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),lt.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class x0 extends Ku{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new xt,i=null,r=null;if(this.signal){const o=this.signal;r=()=>{var a;(a=n.reject)===null||a===void 0||a.call(n,o.reason)},o.addEventListener("abort",r),i=o}const s=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),n.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw s(),c}}),return(){return C(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a=new Set;const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=$t(c),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return Array.from(a)})()})}}class E0 extends Ku{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=Dr(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new xt,r=null,s=null;if(this.signal){const a=this.signal;s=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,a.reason)},a.addEventListener("abort",s),r=a}const o=()=>{e.releaseLock(),r&&s&&r.removeEventListener("abort",s),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),i.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=n.decode(d.content)}catch(h){throw new ln("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),lt.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return C(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a="";const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=$t(c),u;u=yield d.next(),i=u.done,!i;l=!0)o=u.value,l=!1,a+=o}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return a})()})}}class P0{constructor(){this.log=X,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new ln('A text stream handler for topic "'.concat(e,'" has already been set.'),lt.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new ln('A byte stream handler for topic "'.concat(e,'" has already been set.'),lt.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,s;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new ln("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),lt.AbnormalEnd);for(const[l,d]of a)(i=(n=d.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(s=(r=d.outOfBandFailureRejectingFuture).reject)===null||s===void 0||s.call(r,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e){return C(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n){return C(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const o=new xt,a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Dr(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new ln("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),lt.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new x0(a,c,Dr(e.totalLength),o),{identity:n})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const o=new xt,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new ln("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),lt.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new E0(a,c,Dr(e.totalLength),o),{identity:n})}})}handleStreamChunk(e){const n=this.byteStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class Ju{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return C(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class R0 extends Ju{}class I0 extends Ju{}const Yu=15e3;class O0{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return C(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var p;c[h]=u;const g=c.reduce((f,m)=>f+m,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,g)},d=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield d.write(e),l(1,0),yield d.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((u,h)=>C(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:n.topic,mimeType:u.type,onProgress:p=>{l(p,h+1)}})})))),d.info})}streamText(e){return C(this,void 0,void 0,function*(){var n,i;const r=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},o=new Xs({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:On(s.timestamp),totalLength:On(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new id({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Ys.UPDATE:Ys.CREATE})}}),a=e==null?void 0:e.destinationIdentities,c=new je({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,G.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(g){return C(this,void 0,void 0,function*(){for(const f of Iv(g,Yu)){yield d.waitForBufferStatusLow(G.RELIABLE);const m=new Qs({content:f,streamId:r,chunkIndex:On(l)}),v=new je({destinationIdentities:a,value:{case:"streamChunk",value:m}});yield d.sendDataPacket(v,G.RELIABLE),l+=1}})},close(){return C(this,void 0,void 0,function*(){const g=new Zs({streamId:r}),f=new je({destinationIdentities:a,value:{case:"streamTrailer",value:g}});yield d.sendDataPacket(f,G.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>C(this,void 0,void 0,function*(){yield p.close()});d.once(L.Closing,h);const p=new R0(u,s,()=>this.engine.off(L.Closing,h));return p})}sendFile(e,n){return C(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return C(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:a,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},d=new Xs({totalLength:On((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:On(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new rd({name:l.name})}}),u=new je({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,G.RELIABLE);let h=0;const p=new Fe,g=this.engine,f=this.log,m=new WritableStream({write(y){return C(this,void 0,void 0,function*(){const _=yield p.lock();let k=0;try{for(;k<y.byteLength;){const w=y.slice(k,k+Yu);yield g.waitForBufferStatusLow(G.RELIABLE);const S=new je({destinationIdentities:c,value:{case:"streamChunk",value:new Qs({content:w,streamId:a,chunkIndex:On(h)})}});yield g.sendDataPacket(S,G.RELIABLE),h+=1,k+=w.byteLength}}finally{_()}})},close(){return C(this,void 0,void 0,function*(){const y=new Zs({streamId:a}),_=new je({destinationIdentities:c,value:{case:"streamTrailer",value:y}});yield g.sendDataPacket(_,G.RELIABLE)})},abort(y){f.error("Sink error:",y)}});return new I0(m,l)})}}class Xu extends E{constructor(e,n,i,r,s){super(e,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?N.Muted:N.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(N.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Jo)),Mv()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(N.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class D0 extends Xu{constructor(e,n,i,r,s,o){super(e,n,E.Kind.Audio,i,o),this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;St()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(St())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return C(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(Po(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Po(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(N.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(N.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const na=100;class A0 extends Xu{constructor(e,n,i,r,s){super(e,n,E.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Wo(()=>{this.updateDimensions()},na),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Qn(this._mediaStreamTrack,n):Xn(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new M0(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<na){Ne.setTimeout(()=>{this.updateVisibility()},na);return}this.lastVisible=o,this.emit(N.VisibilityChanged,o,this)}}updateDimensions(){var e,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(N.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?mu():n||(mu()>2?2:1)}}class M0{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=Ui(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ui(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ui(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??ia(e),this.isPiP=qe()&&Ui(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=ia(this.element),this.isPiP=Ui(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,vu().observe(this.element),gu().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,s;(e=vu())===null||e===void 0||e.unobserve(this.element),(n=gu())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ui(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ia(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function ia(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const s=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class Gt extends _t.EventEmitter{constructor(e,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Ye.NONE,this.log=X,this.handleMuted=()=>{this.emit(N.Muted)},this.handleUnmuted=()=>{this.emit(N.Unmuted)},this.log=qt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:ct.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=E.Source.Unknown}setTrack(e){this.track&&(this.track.off(N.Muted,this.handleMuted),this.track.off(N.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(N.Muted,this.handleMuted),e.on(N.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ye.NONE}get audioTrack(){if(Et(this.track))return this.track}get videoTrack(){if(Dn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=E.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===E.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(t.PermissionStatus||(t.PermissionStatus={}))})(Gt||(Gt={}));class ra extends Gt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(N.Ended)},this.handleCpuConstrained=()=>{this.track&&Dn(this.track)&&this.emit(N.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(N.Ended,this.handleTrackEnded),this.track.off(N.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(N.Ended,this.handleTrackEnded),e.on(N.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Et(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(Re.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(Re.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(Re.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(Re.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Re.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Re.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Fr(t,e){return C(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=wu(t);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),t.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const u=s.audio.deviceId;s.audio.deviceId={exact:u},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:u}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const u=s.video.deviceId;s.video.deviceId={exact:u},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:u}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=ku(s,Nu,Lu),l=Uo(c),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(Ie.userMediaPromiseMap.set("audioinput",d),d.catch(()=>Ie.userMediaPromiseMap.delete("audioinput"))),s.video&&(Ie.userMediaPromiseMap.set("videoinput",d),d.catch(()=>Ie.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>C(this,void 0,void 0,function*(){const p=h.kind==="audio";let g=p?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let f;const m=p?l.audio:l.video;typeof m!="boolean"&&(f=m);const v=h.getSettings().deviceId;f!=null&&f.deviceId&&dn(f.deviceId)!==v?f.deviceId=v:f||(f={deviceId:v});const y=c0(h,f,e);return y.kind===E.Kind.Video?y.source=E.Source.Camera:y.kind===E.Kind.Audio&&(y.source=E.Source.Microphone),y.mediaStream=u,Et(y)&&i?yield y.setProcessor(i):Dn(y)&&r&&(yield y.setProcessor(r)),y})))}catch(u){if(!n)throw u;return Fr(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}})}function N0(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:!1,video:!0}))[0]})}function Qu(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:t??!0,video:!1}))[0]})}var fn;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(fn||(fn={}));function L0(t){switch(t){case Ei.EXCELLENT:return fn.Excellent;case Ei.GOOD:return fn.Good;case Ei.POOR:return fn.Poor;case Ei.LOST:return fn.Lost;default:return fn.Unknown}}class Zu extends _t.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ri.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Gn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ri.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=fn.Unknown,this.log=X,this.log=qt((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:ct.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new xt,this.once(U.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(E.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(E.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(E.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Gn.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Gn.ACTIVE&&this.emit(U.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(U.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(U.ParticipantNameChanged,e)}_setAttributes(e){const n=Nv(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(U.AttributesChanged,n)}setPermissions(e){var n,i,r,s,o,a;const c=this.permissions,l=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(U.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(U.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=L0(e),n!==this._connectionQuality&&this.emit(U.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Et(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(N.Muted,()=>{this.emit(U.TrackMuted,e)}),e.on(N.Unmuted,()=>{this.emit(U.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case E.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case E.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function U0(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new ud({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class F0 extends Zu{constructor(e,n,i,r,s,o){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Ye.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new xt)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(p=>this.log.warn(p.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new xt),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==ao.OK&&u.reject(new cu(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=Ce.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>U0(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),K(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),K(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),K(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),K(c))),this.emit(U.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>C(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const p=this.videoTrackPublications.get(a.trackSid);if(!p){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!p.videoTrack)return;const g=yield p.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var f=!0,m=$t(g),v;v=yield m.next(),c=v.done,!c;f=!0){u=v.value,f=!1;const y=u;hv(y)&&(this.log.debug("publish ".concat(y," for ").concat(p.videoTrack.sid),Object.assign(Object.assign({},this.logContext),K(p))),yield this.publishAdditionalCodecForTrack(p.videoTrack,y,p.options))}}catch(y){l={error:y}}finally{try{!f&&!c&&(d=m.return)&&(yield d.call(m))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>C(this,void 0,void 0,function*(){if(a.source===E.Source.ScreenShare||a.source===E.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),K(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Ht(a)||un(a))try{if(qe())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===E.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),K(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),K(a))),Ht(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),K(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ye.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(L.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(L.Connected,this.handleReconnected).on(L.SignalConnected,this.handleSignalConnected).on(L.SignalRestarted,this.handleReconnected).on(L.SignalResumed,this.handleReconnected).on(L.Restarting,this.handleReconnecting).on(L.Resuming,this.handleReconnecting).on(L.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(L.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(L.Closing,this.handleClosing).on(L.SignalRequestResponse,this.handleSignalRequestResponse).on(L.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return C(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return(function*(){return new Promise((a,c)=>C(i,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(d=s??this.name)!==null&&d!==void 0?d:"",o),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-p<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(g=>{let[f,m]=g;return this.attributes[f]===m||m===""&&!this.attributes[f]}))){this.pendingSignalRequests.delete(h),a();return}yield Ve(50)}c(new cu("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))})()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(E.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(E.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(E.Source.ScreenShare,e,n,i)}setPermissions(e){const n=this.permissions,i=super.setPermissions(e);return i&&n&&this.emit(U.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){this.encryptionType=e?Ye.GCM:Ye.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return C(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case E.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case E.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case E.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Wt(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(U.MediaDevicesError,l,Fo(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===E.Source.Microphone&&Et(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),K(u))),l.push(this.publishTrack(u,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===E.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(E.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return C(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(E.Source.Camera)||this.pendingPublishing.has(E.Source.Microphone))){this.pendingPublishing.add(E.Source.Camera),this.pendingPublishing.add(E.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(E.Source.Camera),this.pendingPublishing.delete(E.Source.Microphone)}}})}createTracks(e){return C(this,void 0,void 0,function*(){var n,i;e??(e={});const r=ku(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Fr(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Et(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=E.Source.Microphone,this.emit(U.AudioStreamAcquired)),Dn(a)&&(this.cameraError=void 0,a.source=E.Source.Camera),a))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return C(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new yo("getDisplayMedia not supported");e.resolution===void 0&&!bv()&&(e.resolution=To.h1080fps30.resolution);const n=Dv(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Wt("no video track found");const s=new Ur(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=E.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(U.AudioStreamAcquired);const a=new Lr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=E.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,n){return C(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;Ht(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),ei(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let v;switch(i.source){case E.Source.Microphone:v="audioinput";break;case E.Source.Camera:v="videoinput"}v&&s.activeDeviceMap.has(v)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(v)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Lr(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ur(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Wt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(v=>{v.track&&v.track===i&&(h=v)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),K(h))),h;const p="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:p;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),K(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(d=r.red)!==null&&d!==void 0||(r.red=!1));const f=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!kv()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const m=new Promise((v,y)=>C(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ue.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:K(i)}));const _=setTimeout(()=>{y(new au("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(_);const k=yield this.publish(i,f,g);v(k)}else try{const _=yield this.publish(i,f,g);v(_)}catch(_){y(_)}}catch(_){y(_)}}));s.pendingPublishPromises.set(i,m);try{return yield m}catch(v){throw v}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new xt),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),K(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>Lv(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),K(e))),!1)}publish(e,n,i){return C(this,void 0,void 0,function*(){var r,s,o,a,c,l,d,u,h,p;if(!this.hasPermissionsToPublish(e))throw new au("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(O=>ei(e)&&O.source===e.source)&&e.source!==E.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),K(e))),n.stopMicTrackOnMute&&Et(e)&&(e.stopOnMute=!0),e.source===E.Source.ScreenShare&&Zn()&&(n.simulcast=!1),n.videoCodec==="av1"&&!mv()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!gv()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=Ho),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(O=>n.videoCodec===Ar(O.mime))||(n.videoCodec=Ar(this.enabledPublishVideoCodecs[0].mime)));const f=n.videoCodec;e.on(N.Muted,this.onTrackMuted),e.on(N.Unmuted,this.onTrackUnmuted),e.on(N.Ended,this.handleTrackEnded),e.on(N.UpstreamPaused,this.onTrackUpstreamPaused),e.on(N.UpstreamResumed,this.onTrackUpstreamResumed),e.on(N.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],v=!(!((r=n.dtx)!==null&&r!==void 0)||r),y=e.getSourceTrackSettings();y.autoGainControl&&m.push(Re.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&m.push(Re.TF_ECHO_CANCELLATION),y.noiseSuppression&&m.push(Re.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&m.push(Re.TF_STEREO),v&&m.push(Re.TF_NO_DTX),Ht(e)&&e.hasPreConnectBuffer&&m.push(Re.TF_PRECONNECT_BUFFER);const _=new no({cid:e.mediaStreamTrack.id,name:n.name,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:m});let k;if(e.kind===E.Kind.Video){let O={width:0,height:0};try{O=yield e.waitForDimensions()}catch{const A=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Mi.h720.resolution;O={width:A.width,height:A.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{dims:O}))}_.width=O.width,_.height=O.height,un(e)&&(wt(f)&&(e.source===E.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),K(e))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),_.simulcastCodecs=[new to({codec:f,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:Ho}),n.backupCodec&&f!==n.backupCodec.codec&&_.encryption===Ye.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),_.simulcastCodecs.push(new to({codec:n.backupCodec.codec,cid:""})))),k=Qo(e.source===E.Source.ScreenShare,_.width,_.height,n),_.layers=Wu(_.width,_.height,k,wt(n.videoCodec))}else e.kind===E.Kind.Audio&&(k=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=n.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(p=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new Pe("cannot publish track when not connected");const w=()=>C(this,void 0,void 0,function*(){var O,R,A;if(!this.engine.pcManager)throw new Pe("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,k),this.emit(U.LocalSenderCreated,e.sender,e),un(e)&&((O=n.degradationPreference)!==null&&O!==void 0||(n.degradationPreference=b0(e)),e.setDegradationPreference(n.degradationPreference)),k)if(Zn()&&e.kind===E.Kind.Audio){let M;for(const q of this.engine.pcManager.publisher.getTransceivers())if(q.sender===e.sender){M=q;break}M&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:M,codec:"opus",maxbr:!((R=k[0])===null||R===void 0)&&R.maxBitrate?k[0].maxBitrate/1e3:0})}else e.codec&&wt(e.codec)&&(!((A=k[0])===null||A===void 0)&&A.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:_.cid,codec:e.codec,maxbr:k[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const x=new Promise((O,R)=>C(this,void 0,void 0,function*(){var A;try{S=yield this.engine.addTrack(_),O(S)}catch(M){e.sender&&(!((A=this.engine.pcManager)===null||A===void 0)&&A.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(q=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:q}))})),R(M)}}));if(this.enabledPublishVideoCodecs.length>0)S=(yield Promise.all([x,w()]))[0];else{S=yield x;let O;if(S.codecs.forEach(R=>{O===void 0&&(O=R.mimeType)}),O&&e.kind===E.Kind.Video){const R=Ar(O);R!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{codec:R})),n.videoCodec=R,k=Qo(e.source===E.Source.ScreenShare,_.width,_.height,n))}yield w()}const I=new ra(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(I.on(N.CpuConstrained,O=>this.onTrackCpuConstrained(O,I)),I.options=n,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:k,trackInfo:S})),un(e)?e.startMonitor(this.engine.client):Ht(e)&&e.startMonitor(),this.addTrackPublication(I),this.emit(U.LocalTrackPublished,I),Ht(e)&&S.audioFeatures.includes(Re.TF_PRECONNECT_BUFFER)){const O=e.getPreConnectBuffer(),R=e.getPreConnectBufferMimeType();this.on(U.LocalTrackSubscribed,A=>{if(A.trackSid===S.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e))),e.stopPreConnectBuffer()}}),O&&new Promise((M,q)=>C(this,void 0,void 0,function*(){var $,oe,J,Z,W,te;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),K(e)));const rt=setTimeout(()=>{q(new Error("agent not active within 10 seconds"))},1e4),Ue=yield this.waitUntilActiveAgentPresent();clearTimeout(rt),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e)));const At=yield this.streamBytes({name:"preconnect-buffer",mimeType:R,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ue.identity],attributes:{trackId:I.trackSid,sampleRate:String((W=y.sampleRate)!==null&&W!==void 0?W:"48000"),channels:String((te=y.channelCount)!==null&&te!==void 0?te:"1")}});try{for(var De=!0,vt=$t(O),Zt;Zt=yield vt.next(),$=Zt.done,!$;De=!0){Z=Zt.value,De=!1;const bt=Z;yield At.write(bt)}}catch(bt){oe={error:bt}}finally{try{!De&&!$&&(J=vt.return)&&(yield J.call(vt))}finally{if(oe)throw oe.error}}yield At.close(),M()}catch(rt){q(rt)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),K(e)))}).catch(M=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:M}))})}return I})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return C(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Ye.NONE)return;let s;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(s=p)}),!s)throw new Wt("track is not published");if(!un(e))throw new Wt("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=m0(e,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),K(e)));return}const c=e.addSimulcastTrack(n,a);if(!c)return;const l=new no({cid:c.mediaStreamTrack.id,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Wu(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new Pe("cannot publish track when not connected");const d=()=>C(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,n){return C(this,void 0,void 0,function*(){var i,r;if(ei(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),K(e))),yield l)}const s=this.getPublicationForTrack(e),o=s?K(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=s.track,e.off(N.Muted,this.onTrackMuted),e.off(N.Unmuted,this.onTrackUnmuted),e.off(N.Ended,this.handleTrackEnded),e.off(N.UpstreamPaused,this.onTrackUpstreamPaused),e.off(N.UpstreamResumed,this.onTrackUpstreamResumed),e.off(N.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ke.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),un(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case E.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case E.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(U.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return C(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>C(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>C(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==E.Source.ScreenShare&&l.source!==E.Source.ScreenShareAudio&&(Ht(l)||un(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?G.RELIABLE:G.LOSSY,o=r.destinationIdentities,a=r.topic,c=new je({kind:s,value:{case:"user",value:new zl({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)})()})}publishDtmf(e,n){return C(this,void 0,void 0,function*(){const i=new je({kind:G.RELIABLE,value:{case:"sipDtmf",value:new Wl({code:e,digit:n})}});yield this.engine.sendDataPacket(i,G.RELIABLE)})}sendChatMessage(e,n){return C(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new je({value:{case:"chatMessage",value:new Js(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,G.RELIABLE),this.emit(U.ChatMessage,i),i})}editChatMessage(e,n){return C(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new je({value:{case:"chatMessage",value:new Js(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp),editTimestamp:pe.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,G.RELIABLE),this.emit(U.ChatMessage,i),i})}sendText(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return C(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return(function*(){return new Promise((l,d)=>C(i,void 0,void 0,function*(){var u,h,p,g;if(Ko(o)>Uu){d(Ce.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Tt((g=(p=this.engine.latestJoinResponse)===null||p===void 0?void 0:p.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){d(Ce.builtIn("UNSUPPORTED_SERVER"));return}const f=crypto.randomUUID();yield this.publishRpcRequest(r,f,s,o,a-2e3);const m=setTimeout(()=>{this.pendingAcks.delete(f),d(Ce.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(f),clearTimeout(v)},2e3);this.pendingAcks.set(f,{resolve:()=>{clearTimeout(m)},participantIdentity:r});const v=setTimeout(()=>{this.pendingResponses.delete(f),d(Ce.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(f,{resolve:(y,_)=>{clearTimeout(v),this.pendingAcks.has(f)&&(console.warn("RPC response received before ack",f),this.pendingAcks.delete(f),clearTimeout(m)),_?d(_):l(y??"")},participantIdentity:r})}))})()})}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,s){return C(this,void 0,void 0,function*(){const o=new je({destinationIdentities:[e],kind:G.RELIABLE,value:{case:"rpcRequest",value:new Hl({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,G.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Ce.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),K(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new xt),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Ht(r)||un(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return C(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===e});if(r)return r[1];yield Ve(20)}})}}class B0 extends Gt{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(N.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new yr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Yl({participantSid:"",trackSids:[this.trackSid]})]});this.emit(N.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Gt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Gt.SubscriptionStatus.Subscribed:Gt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Gt.PermissionStatus.Allowed:Gt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(No(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&No(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Qe.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(N.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(N.VisibilityChanged,this.handleVisibilityChange),r.off(N.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(N.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(N.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(N.VisibilityChanged,this.handleVisibilityChange),e.on(N.Ended,this.handleEnded),this.emit(N.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(N.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?N.Muted:N.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(N.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(N.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return No(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new od({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===E.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)Su(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Uv(this.trackInfo,this.requestedMaxQuality);i&&Su(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Qe.HIGH})),e.quality=Qe.HIGH)}this.emit(N.UpdateSettings,e)}}class Br extends Zu{static fromParticipantInfo(e,n,i){return new Br(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ri.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(N.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(N.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(N.SubscriptionPermissionChanged,n=>{this.emit(U.TrackSubscriptionPermissionChanged,e,n)}),e.on(N.SubscriptionStatusChanged,n=>{this.emit(U.TrackSubscriptionStatusChanged,e,n)}),e.on(N.Subscribed,n=>{this.emit(U.TrackSubscribed,n,e)}),e.on(N.Unsubscribed,n=>{this.emit(U.TrackUnsubscribed,n,e)}),e.on(N.SubscriptionFailed,n=>{this.emit(U.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:E.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(U.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,s,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),K(a))),this.emit(U.TrackSubscriptionFailed,n);return}const c=e.kind==="video";let l;return c?l=new A0(e,n,r,s):l=new D0(e,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&Mo(l)&&Et(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=E.kindFromProto(r.type);if(!c)return;a=new B0(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==E.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:K(l),newTrack:K(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),K(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(U.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case E.Kind.Audio:this.audioTrackPublications.delete(e);break;case E.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(U.TrackUnpublished,i)}setAudioOutput(e){return C(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Et(i.track)&&Mo(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ee;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(ee||(ee={}));const j0=4*1e3;class ii extends _t.EventEmitter{constructor(e){var n,i,r,s;if(super(),n=this,this.state=ee.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=X,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,a,c)=>C(this,void 0,void 0,function*(){var l;if(!vv())throw St()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===ee.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ee.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ro(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new ta(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(p=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const u=(p,g,f)=>C(this,void 0,void 0,function*(){var m,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,d==null||d();try{yield this.attemptConnection(f??o,a,c,y),this.abortController=void 0,p()}catch(_){if(this.regionUrlProvider&&_ instanceof le&&_.reason!==Q.Cancelled&&_.reason!==Q.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((m=this.abortController)===null||m===void 0?void 0:m.signal)}catch(w){if(w instanceof le&&(w.status===401||w.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(w);return}}k&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield u(p,g,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,yu(_)),g(_))}else{let k=ot.UNKNOWN_REASON;_ instanceof le&&(k=yu(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),g(_)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new xt((p,g)=>{u(p,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,d,u)=>C(this,void 0,void 0,function*(){var h,p,g;const f=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let m=f.serverInfo;if(m||(m={version:f.serverVersion,region:f.serverRegion}),this.serverInfo=m,this.log.debug("connected to Livekit Server ".concat(Object.entries(m).map(v=>{let[y,_]=v;return"".concat(y,": ").concat(_)}).join(", ")),{room:(h=f.room)===null||h===void 0?void 0:h.name,roomSid:(p=f.room)===null||p===void 0?void 0:p.sid,identity:(g=f.participant)===null||g===void 0?void 0:g.identity}),!m.version)throw new nv("unknown server version");return m.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),f}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>C(this,void 0,void 0,function*(){var d,u;this.state===ee.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Go),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(D.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const p=new le("could not establish signal connection",Q.ServerUnreachable);throw h instanceof Error&&(p.message="".concat(p.message,": ").concat(h.message)),h instanceof le&&(p.reason=h.reason,p.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),p}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new le("Connection attempt aborted",Q.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}qe()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),qe()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ee.Connected),this.emit(D.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return C(n,[...a],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var u,h,p,g;const f=yield l.disconnectLock.lock();try{if(l.state===ee.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ee.Connecting||l.state===ee.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(p=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,new le("Client initiated disconnect",Q.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,ot.CLIENT_INITIATED),l.engine=void 0}finally{f()}})()})},this.onPageLeave=()=>C(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>C(this,void 0,void 0,function*(){const o=[],a=Xe();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Do();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(D.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{o.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>C(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{o.includes(d)||o.push(d)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(ee.Reconnecting)&&this.emit(D.Reconnecting)},this.handleSignalRestarted=o=>C(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(ee.Connected),this.emit(D.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===Gn.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),a.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(D.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?a.set(l.sid,d):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(D.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const d=E.streamStateFromProto(a.state);d!==l.track.streamState&&(l.track.streamState=d,c.emit(U.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(D.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(D.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(U.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(D.SipDTMFReceived,a,o),o==null||o.emit(U.SipDTMFReceived,a)},this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),d=xv(a,this.transcriptionReceivedTimes);l==null||l.emit(N.TranscriptionReceived,d),c==null||c.emit(U.TranscriptionReceived,d,l),this.emit(D.TranscriptionReceived,d,c,l)},this.handleChatMessage=(o,a)=>{const c=Ev(a);this.emit(D.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(D.MetricsReceived,o,a)},this.handleDataStream=o=>{this.incomingDataStreamManager.handleDataStreamPacket(o)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(D.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(D.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(D.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(D.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>C(this,void 0,void 0,function*(){var o;((o=Xe())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(D.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(D.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(D.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(D.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(D.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(D.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(D.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(D.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>C(this,void 0,void 0,function*(){var a,c,l,d,u,h;(a=o.track)===null||a===void 0||a.on(N.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(N.Restarted,this.onLocalTrackRestarted),(u=(d=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(D.LocalTrackPublished,o,this.localParticipant),Ht(o.track)&&(yield o.track.checkForSilence())&&this.emit(D.LocalAudioSilenceDetected,o);const p=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Fo(o.source);g&&p&&p!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,p),this.emit(D.ActiveDeviceChanged,g,p))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(N.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(N.Restarted,this.onLocalTrackRestarted),this.emit(D.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>C(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=Fo(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(D.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(D.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(D.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(D.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(D.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},e0),e),this.log=qt((i=this.options.loggerName)!==null&&i!==void 0?i:ct.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Nu),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Lu),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Zv),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new P0,this.outgoingDataStreamManager=new O0(this.engine,this.log),this.disconnectLock=new Fe,this.localParticipant=new F0("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",dn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",dn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",dn(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),qe()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),ii.cleanupRegistry&&ii.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Fv(this.options.e2ee),this.e2eeManager.on(cn.ParticipantEncryptionStatusChanged,(n,i)=>{Rv(i)&&(this.isE2EEEnabled=n),this.emit(D.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(cn.EncryptionError,n=>this.emit(D.EncryptionError,n)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return C(this,void 0,void 0,function*(){return this.state===ee.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(L.RoomUpdate,i),e(r.sid))};this.engine.on(L.RoomUpdate,i),this.once(D.Disconnected,()=>{this.engine.off(L.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new _0(this.options),this.engine.on(L.ParticipantUpdate,this.handleParticipantUpdates).on(L.RoomUpdate,this.handleRoomUpdate).on(L.SpeakersChanged,this.handleSpeakersChanged).on(L.StreamStateChanged,this.handleStreamStateUpdate).on(L.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(L.SubscriptionError,this.handleSubscriptionError).on(L.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(L.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(L.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(L.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(L.DataPacketReceived,this.handleDataPacket).on(L.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ee.SignalReconnecting)&&this.emit(D.SignalReconnecting)}).on(L.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ee.Connected)&&this.emit(D.Reconnected)}).on(L.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ee.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(L.Restarting,this.handleRestarting).on(L.SignalRestarted,this.handleSignalRestarted).on(L.Offline,()=>{this.setAndEmitConnectionState(ee.Reconnecting)&&this.emit(D.Reconnecting)}).on(L.DCBufferStatusChanged,(e,n)=>{this.emit(D.DCBufferStatusChanged,e,n)}).on(L.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(U.LocalTrackSubscribed,n),this.emitWhenConnected(D.LocalTrackSubscribed,n,this.localParticipant)}).on(L.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(D.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ie.getInstance().getDevices(e,n)}prepareConnection(e,n){return C(this,void 0,void 0,function*(){if(this.state===ee.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ro(new URL(e))&&n){this.regionUrlProvider=new ta(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ee.Disconnected&&(this.regionUrl=i,yield fetch(Ao(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ao(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return C(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Ct({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Ct({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Ct({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Ct({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Ct({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Ct({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new Ct({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>C(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new kr({reason:ot.CLIENT_INITIATED,action:Jn.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Ct({scenario:{case:"subscriberBandwidth",value:On(n)}});break;case"leave-full-reconnect":r=new Ct({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,p;let g=!0,f=!1;const m=o?{exact:r}:r;if(i==="audioinput"){f=s.localParticipant.audioTrackPublications.size===0;const v=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=m;const y=Array.from(s.localParticipant.audioTrackPublications.values()).filter(k=>k.source===E.Source.Microphone);try{g=(yield Promise.all(y.map(k=>{var w;return(w=k.audioTrack)===null||w===void 0?void 0:w.setDeviceId(m)}))).every(k=>k===!0)}catch(k){throw s.options.audioCaptureDefaults.deviceId=v,k}const _=y.some(k=>{var w,S;return(S=(w=k.track)===null||w===void 0?void 0:w.isMuted)!==null&&S!==void 0?S:!1});g&&_&&(f=!0)}else if(i==="videoinput"){f=s.localParticipant.videoTrackPublications.size===0;const v=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=m;const y=Array.from(s.localParticipant.videoTrackPublications.values()).filter(k=>k.source===E.Source.Camera);try{g=(yield Promise.all(y.map(k=>{var w;return(w=k.videoTrack)===null||w===void 0?void 0:w.setDeviceId(m)}))).every(k=>k===!0)}catch(k){throw s.options.videoCaptureDefaults.deviceId=v,k}const _=y.some(k=>{var w,S;return(S=(w=k.track)===null||w===void 0?void 0:w.isMuted)!==null&&S!==void 0?S:!1});g&&_&&(f=!0)}else if(i==="audiooutput"){if(f=!0,!Po()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(l=yield Ie.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(d=(p=s.options).audioOutput)!==null&&d!==void 0||(p.audioOutput={});const v=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(y=>y.setAudioOutput({deviceId:r})))}catch(y){throw s.options.audioOutput.deviceId=v,y}}return f&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(D.ActiveDeviceChanged,i,r)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(U.AttributesChanged,this.onLocalAttributesChanged).on(U.TrackMuted,this.onLocalTrackMuted).on(U.TrackUnmuted,this.onLocalTrackUnmuted).on(U.LocalTrackPublished,this.onLocalTrackPublished).on(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(U.MediaDevicesError,this.onMediaDevicesError).on(U.AudioStreamAcquired,this.startAudio).on(U.ChatMessage,this.onLocalChatMessageSent).on(U.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===ee.Connecting||this.state===ee.Reconnecting){const d=()=>{this.onTrackAdded(e,n,i),u()},u=()=>{this.off(D.Reconnected,d),this.off(D.Connected,d),this.off(D.Disconnected,u)};this.once(D.Reconnected,d),this.once(D.Connected,d),this.once(D.Disconnected,u);return}if(this.state===ee.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=pv(n.id),s=r[0];let o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,a,n,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==ee.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(U.AttributesChanged,this.onLocalAttributesChanged).off(U.TrackMuted,this.onLocalTrackMuted).off(U.TrackUnmuted,this.onLocalTrackUnmuted).off(U.LocalTrackPublished,this.onLocalTrackPublished).off(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(U.MediaDevicesError,this.onMediaDevicesError).off(U.AudioStreamAcquired,this.startAudio).off(U.ChatMessage,this.onLocalChatMessageSent).off(U.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),qe()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ee.Disconnected),this.emit(D.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(D.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,s,o){return C(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:n,callerIdentity:e,payload:r,responseTimeout:s});Ko(d)>Uu?(c=Ce.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=d}catch(d){d instanceof Ce?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),c=Ce.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,l,c)})}selectDefaultDevices(){return C(this,void 0,void 0,function*(){var e,n,i;const r=Ie.getInstance().previousDevices,s=yield Ie.getInstance().getDevices(void 0,!1),o=Xe();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(D.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=Ov(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(p=>p.kind===c),h=this.getActiveDevice(c);if(h===((n=r.filter(p=>p.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Or()||c==="videoinput"||u.length>0&&!u.find(p=>p.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Or())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return C(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=_u())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ve(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(D.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Br.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Br(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(D.ParticipantConnected,i),i.on(U.TrackPublished,r=>{this.emitWhenConnected(D.TrackPublished,r,i)}).on(U.TrackSubscribed,(r,s)=>{r.kind===E.Kind.Audio?(r.on(N.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(N.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===E.Kind.Video&&(r.on(N.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(N.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(D.TrackSubscribed,r,s,i)}).on(U.TrackUnpublished,r=>{this.emit(D.TrackUnpublished,r,i)}).on(U.TrackUnsubscribed,(r,s)=>{this.emit(D.TrackUnsubscribed,r,s,i)}).on(U.TrackMuted,r=>{this.emitWhenConnected(D.TrackMuted,r,i)}).on(U.TrackUnmuted,r=>{this.emitWhenConnected(D.TrackUnmuted,r,i)}).on(U.ParticipantMetadataChanged,r=>{this.emitWhenConnected(D.ParticipantMetadataChanged,r,i)}).on(U.ParticipantNameChanged,r=>{this.emitWhenConnected(D.ParticipantNameChanged,r,i)}).on(U.AttributesChanged,r=>{this.emitWhenConnected(D.ParticipantAttributesChanged,r,i)}).on(U.ConnectionQualityChanged,r=>{this.emitWhenConnected(D.ConnectionQualityChanged,r,i)}).on(U.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(D.ParticipantPermissionsChanged,r,i)}).on(U.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(D.TrackSubscriptionStatusChanged,r,s,i)}).on(U.TrackSubscriptionFailed,(r,s)=>{this.emit(D.TrackSubscriptionFailed,r,i,s)}).on(U.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(D.TrackSubscriptionPermissionChanged,r,s,i)}).on(U.Active,()=>{this.emitWhenConnected(D.ParticipantActive,i),i.kind===Ri.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&Pv(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ne.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ot.STATE_MISMATCH))):e=0},j0)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ne.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(D.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===ee.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ee.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return C(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new vr({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:pe.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new xn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(D.SignalConnected),this.emit(D.Connected),this.setAndEmitConnectionState(ee.Connected),r.video){const o=new ra(E.Kind.Video,new Kn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:st.AUDIO,name:"video-dummy"}),new Ur(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:bu(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(U.LocalTrackPublished,o)}if(r.audio){const o=new ra(E.Kind.Audio,new Kn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:st.AUDIO}),new Lr(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Do(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(U.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new xn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Gn.ACTIVE,tracks:[],joinedAt:pe.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=bu(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),d=new Kn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:st.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}if(s.audio){const l=Do(),d=new Kn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:st.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}c.updateInfo(a)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==D.ActiveSpeakersChanged&&e!==D.TranscriptionReceived){const s=eh(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}ii.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function eh(t){return t.map(e=>{if(e)return Array.isArray(e)?eh(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var ht;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(ht||(ht={}));class pn extends _t.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=ht.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new ii(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return C(this,void 0,void 0,function*(){if(this.status!==ht.IDLE)throw Error("check is running already");this.setStatus(ht.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==ht.SKIPPED&&this.setStatus(this.isSuccess()?ht.SUCCESS:ht.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return C(this,void 0,void 0,function*(){return this.room.state===ee.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return C(this,void 0,void 0,function*(){this.room&&this.room.state!==ee.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(ht.SKIPPED)}switchProtocol(e){return C(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(D.Reconnecting,()=>{n=!0}),this.room.once(D.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Ve(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class V0 extends pn{get description(){return"Cloud regions"}perform(){return C(this,void 0,void 0,function*(){const e=new ta(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return C(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield s.write(l);yield s.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(p.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const sa=1e4;class q0 extends pn{get description(){return"Connection via UDP vs TCP"}perform(){return C(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(sa/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(sa/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return C(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>C(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(d.packetsSent=p.packetsSent,d.qualityLimitationDurations=p.qualityLimitationDurations,d.bitrateTotal+=p.targetBitrate,d.count++):p.type==="remote-inbound-rtp"&&(d.packetsLost=p.packetsLost,d.rttTotal+=p.roundTripTime,d.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,sa)),clearInterval(u),a.stop(),n.remove(),yield this.disconnect(),d})}}class $0 extends pn{get description(){return"Can publish audio"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield Qu();if(yield Cu(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class z0 extends pn{get description(){return"Can publish video"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield N0();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return C(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(s=d.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const p=l.getContext("2d");p.drawImage(i,0,0);const f=p.getImageData(0,0,l.width,l.height).data;let m=!0;for(let v=0;v<f.length;v+=4)if(f[v]!==0||f[v+1]!==0||f[v+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class W0 extends pn{get description(){return"Resuming connection after interruption"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(D.SignalReconnecting,a).on(D.Reconnecting,a).on(D.Reconnected,()=>{r=!0,s(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==ee.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class H0 extends pn{get description(){return"Can connect via TURN"}perform(){return C(this,void 0,void 0,function*(){var e,n;const i=new jo,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class G0 extends pn{get description(){return"Establishing WebRTC connection"}perform(){return C(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(D.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(K0(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),X.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function K0(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class J0 extends pn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return C(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new jo;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===Ql.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class Y_ extends _t.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:ht.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==ht.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return C(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(J0)})}checkWebRTC(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(G0)})}checkTURN(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(H0)})}checkReconnect(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(W0)})}checkPublishAudio(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck($0)})}checkPublishVideo(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(z0)})}checkConnectionProtocol(){return C(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(q0);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(V0)})}}function Kt(){return Kt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Kt.apply(null,arguments)}const th=new Uint8Array(0);let Fi=class{static getFullOptions(e){return Kt({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,n){var i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(r){i.status!=="connected"&&i.status!=="connecting"||(i.updateStatus("disconnecting"),await i.handleEndSession(),i.updateStatus("disconnected"),i.options.onDisconnect&&i.options.onDisconnect(r))},this.onMessage=async function(r){switch(r.type){case"interruption":return void i.handleInterruption(r);case"agent_response":return void i.handleAgentResponse(r);case"user_transcript":return void i.handleUserTranscript(r);case"internal_tentative_agent_response":return void i.handleTentativeAgentResponse(r);case"client_tool_call":try{await i.handleClientToolCall(r)}catch(s){i.onError(`Unexpected error in client tool call handling: ${s instanceof Error?s.message:String(s)}`,{clientToolName:r.client_tool_call.tool_name,toolCallId:r.client_tool_call.tool_call_id})}return;case"audio":return void i.handleAudio(r);case"vad_score":return void i.handleVadScore(r);case"ping":return void i.connection.sendMessage({type:"pong",event_id:r.ping_event.event_id});case"mcp_tool_call":return void i.handleMCPToolCall(r);case"mcp_connection_status":return void i.handleMCPConnectionStatus(r);case"agent_tool_response":return void i.handleAgentToolResponse(r);case"conversation_initiation_metadata":return void i.handleConversationMetadata(r);case"asr_initiation_metadata":return void i.handleAsrInitiationMetadata(r);default:return void(i.options.onDebug&&i.options.onDebug(r))}},this.setVolume=({volume:r})=>{this.volume=r},this.options=e,this.connection=n,this.options.onConnect&&this.options.onConnect({conversationId:n.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(r=>this.updateMode(r)),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){const e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:"ai",message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:"user",message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{var n;const i=(n=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters))!=null?n:"Client tool execution successful.",r=typeof i=="object"?JSON.stringify(i):String(i);this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:r,is_error:!1})}catch(i){this.onError(`Client tool execution failed with following error: ${i==null?void 0:i.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${i==null?void 0:i.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolResponse(e){this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}onError(e,n){console.error(e,n),this.options.onError&&this.options.onError(e,n)}getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return th}getOutputByteFrequencyData(){return th}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:e?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(e){this.connection.sendMessage({type:"contextual_update",text:e})}sendUserMessage(e){this.connection.sendMessage({type:"user_message",text:e})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(e,n){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:n})}};class nh{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;const n=this.queue;this.queue=[],n.length>0&&queueMicrotask(()=>{n.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;const n=this.disconnectionDetails;n&&queueMicrotask(()=>{e(n)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var n;(n=this.onModeChangeCallback)==null||n.call(this,e)}disconnect(e){var n;this.disconnectionDetails||(this.disconnectionDetails=e,(n=this.onDisconnectCallback)==null||n.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}}function jr(t){const[e,n]=t.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${t}`);const i=Number.parseInt(n);if(Number.isNaN(i))throw new Error(`Invalid sample rate: ${n}`);return{format:e,sampleRate:i}}const ih="0.6.2";function oa(t){return!!t.type}const rh="conversation_initiation_client_data";function sh(t){var e;const n={type:rh};var i,r,s,o,a;return t.overrides&&(n.conversation_config_override={agent:{prompt:(i=t.overrides.agent)==null?void 0:i.prompt,first_message:(r=t.overrides.agent)==null?void 0:r.firstMessage,language:(s=t.overrides.agent)==null?void 0:s.language},tts:{voice_id:(o=t.overrides.tts)==null?void 0:o.voiceId},conversation:{text_only:(a=t.overrides.conversation)==null?void 0:a.textOnly}}),t.customLlmExtraBody&&(n.custom_llm_extra_body=t.customLlmExtraBody),t.dynamicVariables&&(n.dynamic_variables=t.dynamicVariables),t.userId&&(n.user_id=t.userId),(e=t.overrides)!=null&&e.client&&(n.source_info={source:t.overrides.client.source,version:t.overrides.client.version}),n}class Bi extends nh{constructor(e,n,i,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=n,this.inputFormat=i,this.outputFormat=r,this.socket.addEventListener("error",s=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:s}),0)}),this.socket.addEventListener("close",s=>{this.disconnect(s.code===1e3?{reason:"agent",context:s}:{reason:"error",message:s.reason||"The connection was closed by the server.",context:s})}),this.socket.addEventListener("message",s=>{try{const o=JSON.parse(s.data);if(!oa(o))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:s.data});this.handleMessage(o)}catch(o){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:o instanceof Error?o.message:String(o),data:s.data})}})}static async create(e){let n=null;try{var i,r,s;const a=(i=e.origin)!=null?i:"wss://api.elevenlabs.io";let c;const l=((r=e.overrides)==null||(r=r.client)==null?void 0:r.version)||ih,d=((s=e.overrides)==null||(s=s.client)==null?void 0:s.source)||"js_sdk";if(e.signedUrl){const y=e.signedUrl.includes("?")?"&":"?";c=`${e.signedUrl}${y}source=${d}&version=${l}`}else c=`${a}/v1/convai/conversation?agent_id=${e.agentId}&source=${d}&version=${l}`;const u=["convai"];e.authorization&&u.push(`bearer.${e.authorization}`),n=new WebSocket(c,u);const h=await new Promise((y,_)=>{n.addEventListener("open",()=>{var k;const w=sh(e);(k=n)==null||k.send(JSON.stringify(w))},{once:!0}),n.addEventListener("error",k=>{setTimeout(()=>_(k),0)}),n.addEventListener("close",_),n.addEventListener("message",k=>{const w=JSON.parse(k.data);oa(w)&&(w.type==="conversation_initiation_metadata"?y(w.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:p,agent_output_audio_format:g,user_input_audio_format:f}=h,m=jr(f??"pcm_16000"),v=jr(g);return new Bi(n,p,m,v)}catch(a){var o;throw(o=n)==null||o.close(),a}}close(){this.socket.close()}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}}function oh(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function Y0(t){const e=window.atob(t),n=e.length,i=new Uint8Array(n);for(let r=0;r<n;r++)i[r]=e.charCodeAt(r);return i.buffer}const aa=new Map;function ah(t,e){return async n=>{const i=aa.get(t);if(i)return n.addModule(i);const r=new Blob([e],{type:"application/javascript"}),s=URL.createObjectURL(r);try{return await n.addModule(s),void aa.set(t,s)}catch{URL.revokeObjectURL(s)}try{const o=`data:application/javascript;base64,${btoa(e)}`;await n.addModule(o),aa.set(t,o)}catch{throw new Error(`Failed to load the ${t} worklet module. Make sure the browser supports AudioWorklets.`)}}}const ch=ah("raw-audio-processor",`
38
+ `},Wo}var Mu;function o0(){if(Mu)return ut;Mu=1;var t=r0(),e=s0(),n=zo();return ut.grammar=n,ut.write=e,ut.parse=t.parse,ut.parseParams=t.parseParams,ut.parseFmtpConfig=t.parseFmtpConfig,ut.parsePayloads=t.parsePayloads,ut.parseRemoteCandidates=t.parseRemoteCandidates,ut.parseImageAttributes=t.parseImageAttributes,ut.parseSimulcastStreamList=t.parseSimulcastStreamList,ut}var mn=o0();function Ho(t,e,n){var i,r,s;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),v=this;return new Promise(function(p,g){var b=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var w=t.apply(v,f);a&&a(w),d.forEach(function(y){return(0,y.resolve)(w)}),d=[]}},u()),b){var k=t.apply(v,f);return a&&a(k),p(k)}d.push({resolve:p,reject:g})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),d.forEach(function(v){return(0,v.reject)(f)}),d=[]},h}const a0=.7,c0=20,ti={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Nu extends St.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Q,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ho(r=>C(this,void 0,void 0,function*(){this.emit(ti.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),c0),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=zt((i=n.loggerName)!==null&&i!==void 0?i:lt.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new qe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return C(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return C(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:s,nackMids:o}=l0(e);this.remoteStereoMids=s,this.remoteNackMids=o}else if(e.type==="answer"){const s=mn.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=mn.write(s)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(ti.NegotiationComplete),e.sdp&&mn.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(ti.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const o=mn.parse((n=s.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(a=>{Uu(a),a.type==="audio"?Lu(a,[],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Tt(c.codec)&&!On()&&this.ensureVideoDDExtensionForSVC(a,o),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*a0);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,mn.write(o)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=mn.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Uu(r),r.type==="audio"&&Lu(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,mn.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new Oe("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new Oe("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return C(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return C(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Co(s)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===pu))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:pu})}}}function Lu(t,e,n){let i=0;t.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(t.mid)&&!t.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&t.rtcpFb.push({payload:i,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function l0(t){var e;const n=[],i=[],r=mn.parse((e=t.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function Uu(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const Go="vp8",d0={audioPreset:So.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:xo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Go,backupCodec:!0,preConnectBuffer:!1},Fu={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Bu={deviceId:{ideal:"default"},resolution:Mi.h720.resolution},u0={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Qg,disconnectOnPageLeave:!0,webAudioMix:!1},Ko={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ke;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(ke||(ke={}));class h0{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Ko.peerConnectionTimeout,this.log=Q,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=ke.CONNECTED:a.some(c=>c==="failed")?this.state=ke.FAILED:a.some(c=>c==="connecting")?this.state=ke.CONNECTING:a.every(c=>c==="closed")?this.state=ke.CLOSED:a.some(c=>c==="closed")?this.state=ke.CLOSING:a.every(c=>c==="new")&&(this.state=ke.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(ke[o]," to ").concat(ke[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=zt((r=i.loggerName)!==null&&r!==void 0?r:lt.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new Nu(e,i),this.subscriber=new Nu(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ct.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ct.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=ke.NEW,this.connectionLock=new qe,this.remoteOfferLock=new qe}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return C(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const n of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return C(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return C(this,void 0,void 0,function*(){n===ct.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return C(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(e,n){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return C(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,n)))}finally{r()}})}negotiate(e){return C(this,void 0,void 0,function*(){return new Promise((n,i)=>C(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(ti.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(ti.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===ct.PUBLISHER?this.publisher.getConnectedAddress():e===ct.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>C(s,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Ue.clearTimeout(u),l(new de("room connection has been cancelled",ee.Cancelled))};r!=null&&r.signal.aborted&&d(),r==null||r.signal.addEventListener("abort",d);const u=Ue.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",d),l(new de("could not establish pc connection",ee.InternalError))},o);for(;this.state!==ke.CONNECTED;)if(yield We(50),r!=null&&r.signal.aborted){l(new de("room connection has been cancelled",ee.Cancelled));return}Ue.clearTimeout(u),r==null||r.signal.removeEventListener("abort",d),c()}))})()})}}class Ce extends Error{constructor(e,n,i){super(n),this.code=e,this.message=Vu(n,Ce.MAX_MESSAGE_BYTES),this.data=i?Vu(i,Ce.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ce(e.code,e.message,e.data)}toProto(){return new Ql({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Ce(Ce.ErrorCode[e],Ce.ErrorMessage[e],n)}}Ce.MAX_MESSAGE_BYTES=256,Ce.MAX_DATA_BYTES=15360,Ce.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ce.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ju=15360;function Jo(t){return new TextEncoder().encode(t).length}function Vu(t,e){if(Jo(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(t.slice(0,s)).length<=e?n=s:i=s-1}return t.slice(0,n)}const Yo=2e3;function Nr(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const Xo=typeof MediaRecorder<"u";class f0{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const p0=Xo?MediaRecorder:f0;class m0 extends p0{constructor(e,n){if(!Xo)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>C(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");s()||c.enqueue(d)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function g0(){return Xo}const v0=1e3,b0=1e4;class qu extends P{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,n,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Ho(()=>C(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>C(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(D.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new qe,this.pauseUpstreamLock=new qe,this.trackChangeLock=new qe,this.trackChangeLock.lock().then(o=>C(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==P.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return C(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Qn(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Xn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Xn(r??e,s)}))})}waitForDimensions(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:v0;return(function*(){var i;if(e.kind===P.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Qe())===null||i===void 0?void 0:i.os)==="iOS"&&(yield We(10));const r=Date.now();for(;Date.now()-r<n;){const s=e.dimensions;if(s)return s;yield We(50)}throw new Gt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return C(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fn(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===P.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===P.Kind.Audio?"audioinput":"videoinput";return n?Me.getInstance().normalizeDeviceId(s,i,r):i})()})}mute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return C(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return C(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Gt("unable to replace an unpublished track");let r,s;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,s=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return C(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=Zg(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===P.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Qn(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(D.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?D.Muted:D.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),mu()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(D.UpstreamPaused,this);const i=Qe();if((i==null?void 0:i.name)==="Safari"&&Pt(i.version,"12.0")<0)throw new ko("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(D.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Xn(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:d}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))}),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Qn(i._mediaStreamTrack,l),Xn(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(D.TrackProcessorUpdate,i.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}})()})}internalStopProcessor(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(D.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!g0()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new m0(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},b0)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Lr extends qu{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,P.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,De.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,De.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===P.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fn(this._constraints.deviceId);return this.source===P.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return C(this,void 0,void 0,function*(){let n;if(e){const i=Fo({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return C(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){He()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Yo)))}setProcessor(e){return C(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(D.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return C(this,void 0,void 0,function*(){const e=yield Su(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(D.AudioSilenceDetected)),e})}}function y0(t,e,n){switch(t.kind){case"audio":return new Lr(t,e,!1,void 0,n);case"video":return new Ur(t,e,!1,n);default:throw new Gt("unsupported track type: ".concat(t.kind))}}const k0=Object.values(Mi),C0=Object.values(To),w0=Object.values(xo),_0=[Mi.h180,Mi.h360],S0=[To.h180,To.h360],T0=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new ce(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),Qo=["q","h","f"];function Zo(t,e,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!n)return[{}];o||(o=P0(t,e,n,l),Q.debug("using video encoding",o));const d=o.maxFramerate,u=new ce(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Tt(l)){const v=new Wu(c),p=[];if(v.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const g=Qe();if(Or()||xt()||(g==null?void 0:g.name)==="Chrome"&&Pt(g==null?void 0:g.version,"113")<0){const b=v.suffix=="h"?2:3,k=Iv(g);for(let w=0;w<v.spatial;w+=1)p.push({rid:Qo[2-w],maxBitrate:o.maxBitrate/Math.pow(b,w),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:k?Math.pow(2,w):void 0});p[0].scalabilityMode=c}else p.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(p[0].priority=u.encoding.priority,p[0].networkPriority=u.encoding.priority),Q.debug("using svc encoding",{encodings:p}),p}if(!a)return[o];let h=[];t?h=(r=zu(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:$u(t,u):h=(s=zu(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:$u(t,u);let f;if(h.length>0){const v=h[0];h.length>1&&([,f]=h);const p=Math.max(e,n);if(p>=960&&f)return ea(e,n,[v,f,u],d);if(p>=480)return ea(e,n,[v,u],d)}return ea(e,n,[u])}function x0(t,e,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Q.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===P.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Zo(t.source===P.Source.ScreenShare,c,l,n)}function P0(t,e,n,i){const r=E0(t,e,n);let{encoding:s}=r[0];const o=Math.max(e,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function E0(t,e,n){if(t)return w0;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?k0:C0}function $u(t,e){if(t)return T0(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?_0:S0}function ea(t,e,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=Qo.length)return;const a=Math.min(t,e),l={rid:Qo[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},d=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=Zn()||o===0;s.encoding.priority&&u&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),xt()&&vu()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,Q.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Q.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function zu(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class Wu{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function R0(t){return t.source===P.Source.ScreenShare||t.constraints.height&&fn(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const I0=5e3;class Ur extends qu{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,P.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>C(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(s.map(c=>[c.rid,c])),a=s.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(D.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=Nr(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new qe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!He())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Yo))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=Wt(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return C(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=Wt(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const d=s;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===P.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return C(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===P.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return C(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(e){const n=[];for(let i=Ze.LOW;i<=Ze.HIGH;i+=1)n.push(new ao({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Tt(this.codec),n)}restartTrack(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(e){const u=Fo({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=Wt(this.simulcastCodecs.values()),d;d=yield l.next(),n=d.done,!n;c=!0){s=d.value,c=!1;const u=s;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return C(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield n.setProcessor.call(r,i,s),!((d=r.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=Wt(r.simulcastCodecs.values()),v;v=yield f.next(),o=v.done,!o;h=!0)l=v.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(p){a={error:p}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return C(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},I0))}setPublishingCodecs(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Tt(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(n=!0,i=Wt(e);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Tt(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield Hu(u.sender,u.encodings,d.qualities,this.senderLock,Tt(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,n){return C(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield Hu(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return C(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&Tt(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),mu()&&this.isInBackground&&this.source===P.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Hu(t,e,n,i,r,s,o){return C(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const c=t.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(r&&n.some(f=>f.enabled)&&n.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var v;let p=(v=h.rid)!==null&&v!==void 0?v:"";p===""&&(p="q");const g=Gu(p),b=n.find(k=>k.quality===g);b&&h.active!==b.enabled&&(d=!0,h.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),o),Zn()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield t.setParameters(c))}finally{a()}})}function Gu(t){switch(t){case"f":return Ze.HIGH;case"h":return Ze.MEDIUM;case"q":return Ze.LOW;default:return Ze.HIGH}}function Ku(t,e,n,i){if(!n)return[new En({quality:Ze.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new Wu(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new En({quality:Math.min(Ze.HIGH,s.spatial-1)-l,width:Math.ceil(t/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Gu((o=r.rid)!==null&&o!==void 0?o:"");return new En({quality:l,width:Math.ceil(t/c),height:Math.ceil(e/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Ju="_lossy",Yu="_reliable",O0=2*1e3,ta="leave-reconnect",A0=3e4;var ht;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(ht||(ht={}));class D0 extends St.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ko.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ht.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Q,this.reliableDataSequence=1,this.reliableMessageBuffer=new Iu,this.reliableReceivedState=new i0(A0),this.handleDataChannel=i=>C(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return(function*(){if(o){if(o.label===Yu)s.reliableDCSub=o;else if(o.label===Ju)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}})()}),this.handleDataMessage=i=>C(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=ze.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(L.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&N0(c,c.value.value),this.emit(L.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?K.LOSSY:K.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(L.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===ta&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ue.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ht.Connected&&i();const s=()=>{this.off(L.Disconnected,o),i()},o=()=>{this.off(L.Restarted,s),r()};this.once(L.Restarted,s),this.once(L.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(L.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===K.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===he.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Hn.RR_SIGNAL_DISCONNECTED))},this.log=zt((n=e.loggerName)!==null&&n!==void 0?n:lt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Vo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new qe,this.dataProcessLock=new qe,this.dcBufferStatus=new Map([[K.LOSSY,!0],[K.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(L.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(L.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(L.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(L.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(L.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(L.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(L.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(L.SignalRequestResponse,i)}get logContext(){var e,n,i,r,s,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return C(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(L.SignalConnected,s),s}catch(s){if(s instanceof de&&s.reason===ee.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,n,i,r);throw s}})}close(){return C(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(L.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return C(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Iu,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return C(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Gt("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new de("publication of local track timed out, no response from server",ee.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return C(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return C(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==ke.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new h0(r,e.subscriberPrimary,this.loggerOptions),this.emit(L.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>C(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===ke.CONNECTED){const d=this.pcState===ht.New;this.pcState=ht.Connected,d&&this.emit(L.Connected,e)}else s===ke.FAILED&&this.pcState===ht.Connected&&(this.pcState=ht.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Hn.RR_SUBSCRIBER_FAILED:Hn.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===he.RECONNECTING,l=[ke.FAILED,ke.CLOSING,ke.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(L.Offline)}),this.pcManager.onTrack=s=>{this.emit(L.MediaTrackAdded,s.track,s.streams[0],s.receiver)},M0((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n)=>C(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n)=>C(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(L.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(L.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(L.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(L.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(L.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Hn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Jn.DISCONNECT:this.emit(L.Disconnected,e==null?void 0:e.reason),this.close();break;case Jn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ta);break;case Jn.RESUME:this.handleDisconnect(ta)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ei.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ju,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Yu,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,n,i){return C(this,void 0,void 0,function*(){if(Po())return yield this.createTransceiverRTCRtpSender(e,n,i);if(Eo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Oe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(Po())return this.createSimulcastTransceiverSender(e,n,i,r);if(Eo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Oe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Oe("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Dn(e)&&(e.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,n,i,r){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Oe("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Oe("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return C(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Q.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===Ei.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:ke.NEW)===ke.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof Oe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof ni||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Hn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(L.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return C(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new Oe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(L.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ni;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof de&&o.reason===ee.NotAllowed?new Oe("could not reconnect, token might be expired"):new ni}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(L.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==he.CONNECTED)throw new ni("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(L.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return C(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new Oe("could not reconnect, url or token not saved");if(!this.pcManager)throw new Oe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(L.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof de&&r.reason===ee.NotAllowed?new Oe("could not reconnect, token might be expired"):r instanceof de&&r.reason===ee.LeaveRequest?r:new ni(s)}if(this.emit(L.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==he.CONNECTED)throw new ni("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(L.Resumed)})}waitForPCInitialConnection(e,n){return C(this,void 0,void 0,function*(){if(!this.pcManager)throw new Oe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return C(this,void 0,void 0,function*(){this.pcState=ht.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield We(O0),!this.pcManager)throw new Oe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ht.Connected}catch(e){throw this.pcState=ht.Disconnected,new de("could not establish PC connection, ".concat(e.message),ee.InternalError)}})}publishRpcResponse(e,n,i,r){return C(this,void 0,void 0,function*(){const s=new ze({destinationIdentities:[e],kind:K.RELIABLE,value:{case:"rpcResponse",value:new Xl({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,K.RELIABLE)})}publishRpcAck(e,n){return C(this,void 0,void 0,function*(){const i=new ze({destinationIdentities:[e],kind:K.RELIABLE,value:{case:"rpcAck",value:new Yl({requestId:n})}});yield this.sendDataPacket(i,K.RELIABLE)})}sendDataPacket(e,n){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===K.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===K.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return C(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(K.RELIABLE);const n=this.dataChannelForKind(K.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(K.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>C(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(L.Closing,r);!this.dcBufferStatus.get(e);)yield We(10);this.off(L.Closing,r),n()}}))}ensureDataTransportConnected(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new Oe("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new de("".concat(a," connection not set"),ee.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield We(50)}throw new de("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),ee.InternalError)})()})}ensurePublisherConnected(e){return C(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ke.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return C(this,void 0,void 0,function*(){return new Promise((e,n)=>C(this,void 0,void 0,function*(){if(!this.pcManager){n(new Co("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(L.Closing,r),this.pcManager.publisher.once(ti.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();Nv(c)&&o.set(a.payload,c)}),this.emit(L.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Co&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Hn.RR_UNKNOWN),n(s)}finally{this.off(L.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===K.LOSSY)return this.lossyDCSub;if(e===K.RELIABLE)return this.reliableDCSub}else{if(e===K.LOSSY)return this.lossyDC;if(e===K.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==a&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new gd({answer:s?Mr({sdp:s.sdp,type:s.type}):void 0,offer:o?Mr({sdp:o.sdp,type:o.type}):void 0,subscription:new yr({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:zv(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new vd({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new bd({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(K.LOSSY),ct.PUBLISHER),n(this.dataChannelForKind(K.RELIABLE),ct.PUBLISHER),n(this.dataChannelForKind(K.LOSSY,!0),ct.SUBSCRIBER),n(this.dataChannelForKind(K.RELIABLE,!0),ct.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ue.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){He()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){He()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ni extends Error{}function M0(t){return t!==void 0&&t>13}function N0(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class na{constructor(e,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return Io(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return C(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),Q.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return C(this,void 0,void 0,function*(){const n=yield fetch("".concat(L0(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new de("Could not fetch region settings: ".concat(n.statusText),n.status===401?ee.NotAllowed:ee.InternalError,n.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function L0(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class Xu{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new hn("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),dt.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new hn("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),dt.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class U0 extends Xu{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new Et,i=null,r=null;if(this.signal){const o=this.signal;r=()=>{var a;(a=n.reject)===null||a===void 0||a.call(n,o.reason)},o.addEventListener("abort",r),i=o}const s=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),n.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw s(),c}}),return(){return C(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a=new Set;const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=Wt(c),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return Array.from(a)})()})}}class F0 extends Xu{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=Ar(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new Et,r=null,s=null;if(this.signal){const a=this.signal;s=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,a.reason)},a.addEventListener("abort",s),r=a}const o=()=>{e.releaseLock(),r&&s&&r.removeEventListener("abort",s),this.signal=void 0};return{next:()=>C(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),i.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=n.decode(d.content)}catch(h){throw new hn("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),dt.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return C(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return C(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,o;let a="";const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,d=Wt(c),u;u=yield d.next(),i=u.done,!i;l=!0)o=u.value,l=!1,a+=o}catch(h){r={error:h}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}return a})()})}}class B0{constructor(){this.log=Q,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new hn('A text stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new hn('A byte stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,s;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new hn("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),dt.AbnormalEnd);for(const[l,d]of a)(i=(n=d.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(s=(r=d.outOfBandFailureRejectingFuture).reject)===null||s===void 0||s.call(r,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e){return C(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n){return C(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const o=new Et,a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ar(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new hn("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new U0(a,c,Ar(e.totalLength),o),{identity:n})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const o=new Et,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(s=l,this.textStreamControllers.has(e.streamId))throw new hn("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});r(new F0(a,c,Ar(e.totalLength),o),{identity:n})}})}handleStreamChunk(e){const n=this.byteStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class Qu{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return C(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class j0 extends Qu{}class V0 extends Qu{}const Zu=15e3;class q0{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return C(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const v=c.reduce((p,g)=>p+g,0);(f=n==null?void 0:n.onProgress)===null||f===void 0||f.call(n,v)},d=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield d.write(e),l(1,0),yield d.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((u,h)=>C(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:n.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return C(this,void 0,void 0,function*(){var n,i;const r=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},o=new Qs({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:An(s.timestamp),totalLength:An(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new od({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Xs.UPDATE:Xs.CREATE})}}),a=e==null?void 0:e.destinationIdentities,c=new ze({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,K.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(v){return C(this,void 0,void 0,function*(){for(const p of Vv(v,Zu)){yield d.waitForBufferStatusLow(K.RELIABLE);const g=new Zs({content:p,streamId:r,chunkIndex:An(l)}),b=new ze({destinationIdentities:a,value:{case:"streamChunk",value:g}});yield d.sendDataPacket(b,K.RELIABLE),l+=1}})},close(){return C(this,void 0,void 0,function*(){const v=new eo({streamId:r}),p=new ze({destinationIdentities:a,value:{case:"streamTrailer",value:v}});yield d.sendDataPacket(p,K.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let h=()=>C(this,void 0,void 0,function*(){yield f.close()});d.once(L.Closing,h);const f=new j0(u,s,()=>this.engine.off(L.Closing,h));return f})}sendFile(e,n){return C(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return C(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return C(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:a,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},d=new Qs({totalLength:An((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:An(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new ad({name:l.name})}}),u=new ze({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,K.RELIABLE);let h=0;const f=new qe,v=this.engine,p=this.log,g=new WritableStream({write(k){return C(this,void 0,void 0,function*(){const w=yield f.lock();let y=0;try{for(;y<k.byteLength;){const _=k.slice(y,y+Zu);yield v.waitForBufferStatusLow(K.RELIABLE);const S=new ze({destinationIdentities:c,value:{case:"streamChunk",value:new Zs({content:_,streamId:a,chunkIndex:An(h)})}});yield v.sendDataPacket(S,K.RELIABLE),h+=1,y+=_.byteLength}}finally{w()}})},close(){return C(this,void 0,void 0,function*(){const k=new eo({streamId:a}),w=new ze({destinationIdentities:c,value:{case:"streamTrailer",value:k}});yield v.sendDataPacket(w,K.RELIABLE)})},abort(k){p.error("Sink error:",k)}});return new V0(g,l)})}}class eh extends P{constructor(e,n,i,r,s){super(e,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?D.Muted:D.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(D.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return C(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Yo)),Wv()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(D.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class $0 extends eh{constructor(e,n,i,r,s,o){super(e,n,P.Kind.Audio,i,o),this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(xt())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return C(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(Ro(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ro(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(D.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(D.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const ia=100;class z0 extends eh{constructor(e,n,i,r,s){super(e,n,P.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>C(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Nr(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Ho(()=>{this.updateDimensions()},ia),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Qn(this._mediaStreamTrack,n):Xn(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new W0(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return C(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return C(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<ia){Ue.setTimeout(()=>{this.updateVisibility()},ia);return}this.lastVisible=o,this.emit(D.VisibilityChanged,o,this)}}updateDimensions(){var e,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(D.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?bu():n||(bu()>2?2:1)}}class W0{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=Ui(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ui(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ui(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??ra(e),this.isPiP=He()&&Ui(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=ra(this.element),this.isPiP=Ui(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ku().observe(this.element),yu().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,s;(e=ku())===null||e===void 0||e.unobserve(this.element),(n=yu())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ui(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ra(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function ra(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const s=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class Jt extends St.EventEmitter{constructor(e,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Xe.NONE,this.log=Q,this.handleMuted=()=>{this.emit(D.Muted)},this.handleUnmuted=()=>{this.emit(D.Unmuted)},this.log=zt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:lt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=P.Source.Unknown}setTrack(e){this.track&&(this.track.off(D.Muted,this.handleMuted),this.track.off(D.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(D.Muted,this.handleMuted),e.on(D.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Y(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Xe.NONE}get audioTrack(){if(Rt(this.track))return this.track}get videoTrack(){if(Dn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=P.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===P.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(t.PermissionStatus||(t.PermissionStatus={}))})(Jt||(Jt={}));class sa extends Jt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(D.Ended)},this.handleCpuConstrained=()=>{this.track&&Dn(this.track)&&this.emit(D.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(D.Ended,this.handleTrackEnded),this.track.off(D.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(D.Ended,this.handleTrackEnded),e.on(D.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return C(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return C(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Rt(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(De.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(De.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(De.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(De.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(De.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(De.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Fr(t,e){return C(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=xu(t);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),t.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const u=s.audio.deviceId;s.audio.deviceId={exact:u},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:u}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const u=s.video.deviceId;s.video.deviceId={exact:u},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:u}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=_u(s,Fu,Bu),l=Fo(c),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(Me.userMediaPromiseMap.set("audioinput",d),d.catch(()=>Me.userMediaPromiseMap.delete("audioinput"))),s.video&&(Me.userMediaPromiseMap.set("videoinput",d),d.catch(()=>Me.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>C(this,void 0,void 0,function*(){const f=h.kind==="audio";let v=f?c.audio:c.video;(typeof v=="boolean"||!v)&&(v={});let p;const g=f?l.audio:l.video;typeof g!="boolean"&&(p=g);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&fn(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const k=y0(h,p,e);return k.kind===P.Kind.Video?k.source=P.Source.Camera:k.kind===P.Kind.Audio&&(k.source=P.Source.Microphone),k.mediaStream=u,Rt(k)&&i?yield k.setProcessor(i):Dn(k)&&r&&(yield k.setProcessor(r)),k})))}catch(u){if(!n)throw u;return Fr(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}})}function H0(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:!1,video:!0}))[0]})}function th(t){return C(this,void 0,void 0,function*(){return(yield Fr({audio:t??!0,video:!1}))[0]})}var gn;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(gn||(gn={}));function G0(t){switch(t){case Pi.EXCELLENT:return gn.Excellent;case Pi.GOOD:return gn.Good;case Pi.POOR:return gn.Poor;case Pi.LOST:return gn.Lost;default:return gn.Unknown}}class nh extends St.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ri.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Gn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ri.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=gn.Unknown,this.log=Q,this.log=zt((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:lt.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Et,this.once(U.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(P.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(P.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(P.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Gn.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Gn.ACTIVE&&this.emit(U.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(U.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(U.ParticipantNameChanged,e)}_setAttributes(e){const n=Hv(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(U.AttributesChanged,n)}setPermissions(e){var n,i,r,s,o,a;const c=this.permissions,l=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(U.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(U.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=G0(e),n!==this._connectionQuality&&this.emit(U.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Rt(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(D.Muted,()=>{this.emit(U.TrackMuted,e)}),e.on(D.Unmuted,()=>{this.emit(U.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case P.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case P.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function K0(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new pd({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class J0 extends nh{constructor(e,n,i,r,s,o){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Xe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Et)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Et),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==co.OK&&u.reject(new uu(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=Ce.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>K0(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Y(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Y(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Y(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Y(c))),this.emit(U.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>C(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const v=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var p=!0,g=Wt(v),b;b=yield g.next(),c=b.done,!c;p=!0){u=b.value,p=!1;const k=u;_v(k)&&(this.log.debug("publish ".concat(k," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Y(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,k,f.options))}}catch(k){l={error:k}}finally{try{!p&&!c&&(d=g.return)&&(yield d.call(g))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>C(this,void 0,void 0,function*(){if(a.source===P.Source.ScreenShare||a.source===P.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Y(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Kt(a)||pn(a))try{if(He())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===P.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),Y(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Y(a))),Kt(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Y(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Xe.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(L.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(L.Connected,this.handleReconnected).on(L.SignalConnected,this.handleSignalConnected).on(L.SignalRestarted,this.handleReconnected).on(L.SignalResumed,this.handleReconnected).on(L.Restarting,this.handleReconnecting).on(L.Resuming,this.handleReconnecting).on(L.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(L.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(L.Closing,this.handleClosing).on(L.SignalRequestResponse,this.handleSignalRequestResponse).on(L.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return C(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return C(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return(function*(){return new Promise((a,c)=>C(i,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(d=s??this.name)!==null&&d!==void 0?d:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:v=>{c(v),u=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-f<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(v=>{let[p,g]=v;return this.attributes[p]===g||g===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),a();return}yield We(50)}c(new uu("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))})()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(P.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(P.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(P.Source.ScreenShare,e,n,i)}setPermissions(e){const n=this.permissions,i=super.setPermissions(e);return i&&n&&this.emit(U.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){this.encryptionType=e?Xe.GCM:Xe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return C(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case P.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case P.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case P.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Gt(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(U.MediaDevicesError,l,Bo(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===P.Source.Microphone&&Rt(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Y(u))),l.push(this.publishTrack(u,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===P.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(P.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return C(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(P.Source.Camera)||this.pendingPublishing.has(P.Source.Microphone))){this.pendingPublishing.add(P.Source.Camera),this.pendingPublishing.add(P.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(P.Source.Camera),this.pendingPublishing.delete(P.Source.Microphone)}}})}createTracks(e){return C(this,void 0,void 0,function*(){var n,i;e??(e={});const r=_u(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Fr(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Rt(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=P.Source.Microphone,this.emit(U.AudioStreamAcquired)),Dn(a)&&(this.cameraError=void 0,a.source=P.Source.Camera),a))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return C(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new ko("getDisplayMedia not supported");e.resolution===void 0&&!Rv()&&(e.resolution=xo.h1080fps30.resolution);const n=$v(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Gt("no video track found");const s=new Ur(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=P.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(U.AudioStreamAcquired);const a=new Lr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=P.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,n){return C(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;Kt(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),ei(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let b;switch(i.source){case P.Source.Microphone:b="audioinput";break;case P.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Lr(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ur(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Gt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),Y(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;v&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),Y(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(d=r.red)!==null&&d!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!Ov()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const g=new Promise((b,k)=>C(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==he.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Y(i)}));const w=setTimeout(()=>{k(new du("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(w);const y=yield this.publish(i,p,v);b(y)}else try{const w=yield this.publish(i,p,v);b(w)}catch(w){k(w)}}catch(w){k(w)}}));s.pendingPublishPromises.set(i,g);try{return yield g}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Et),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Y(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>Gv(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Y(e))),!1)}publish(e,n,i){return C(this,void 0,void 0,function*(){var r,s,o,a,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new du("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(R=>ei(e)&&R.source===e.source)&&e.source!==P.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Y(e))),n.stopMicTrackOnMute&&Rt(e)&&(e.stopOnMute=!0),e.source===P.Source.ScreenShare&&Zn()&&(n.simulcast=!1),n.videoCodec==="av1"&&!xv()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!Pv()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=Go),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(R=>n.videoCodec===Dr(R.mime))||(n.videoCodec=Dr(this.enabledPublishVideoCodecs[0].mime)));const p=n.videoCodec;e.on(D.Muted,this.onTrackMuted),e.on(D.Unmuted,this.onTrackUnmuted),e.on(D.Ended,this.handleTrackEnded),e.on(D.UpstreamPaused,this.onTrackUpstreamPaused),e.on(D.UpstreamResumed,this.onTrackUpstreamResumed),e.on(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),k=e.getSourceTrackSettings();k.autoGainControl&&g.push(De.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&g.push(De.TF_ECHO_CANCELLATION),k.noiseSuppression&&g.push(De.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>1&&g.push(De.TF_STEREO),b&&g.push(De.TF_NO_DTX),Kt(e)&&e.hasPreConnectBuffer&&g.push(De.TF_PRECONNECT_BUFFER);const w=new io({cid:e.mediaStreamTrack.id,name:n.name,type:P.kindToProto(e.kind),muted:e.isMuted,source:P.sourceToProto(e.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:g});let y;if(e.kind===P.Kind.Video){let R={width:0,height:0};try{R=yield e.waitForDimensions()}catch{const M=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Mi.h720.resolution;R={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Y(e)),{dims:R}))}w.width=R.width,w.height=R.height,pn(e)&&(Tt(p)&&(e.source===P.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Y(e))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),w.simulcastCodecs=[new no({codec:p,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:Go}),n.backupCodec&&p!==n.backupCodec.codec&&w.encryption===Xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),w.simulcastCodecs.push(new no({codec:n.backupCodec.codec,cid:""})))),y=Zo(e.source===P.Source.ScreenShare,w.width,w.height,n),w.layers=Ku(w.width,w.height,y,Tt(n.videoCodec))}else e.kind===P.Kind.Audio&&(y=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=n.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Oe("cannot publish track when not connected");const _=()=>C(this,void 0,void 0,function*(){var R,A,M;if(!this.engine.pcManager)throw new Oe("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,y),this.emit(U.LocalSenderCreated,e.sender,e),pn(e)&&((R=n.degradationPreference)!==null&&R!==void 0||(n.degradationPreference=R0(e)),e.setDegradationPreference(n.degradationPreference)),y)if(Zn()&&e.kind===P.Kind.Audio){let N;for(const q of this.engine.pcManager.publisher.getTransceivers())if(q.sender===e.sender){N=q;break}N&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:N,codec:"opus",maxbr:!((A=y[0])===null||A===void 0)&&A.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Tt(e.codec)&&(!((M=y[0])===null||M===void 0)&&M.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:w.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const x=new Promise((R,A)=>C(this,void 0,void 0,function*(){var M;try{S=yield this.engine.addTrack(w),R(S)}catch(N){e.sender&&(!((M=this.engine.pcManager)===null||M===void 0)&&M.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(q=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Y(e)),{error:q}))})),A(N)}}));if(this.enabledPublishVideoCodecs.length>0)S=(yield Promise.all([x,_()]))[0];else{S=yield x;let R;if(S.codecs.forEach(A=>{R===void 0&&(R=A.mimeType)}),R&&e.kind===P.Kind.Video){const A=Dr(R);A!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Y(e)),{codec:A})),n.videoCodec=A,y=Zo(e.source===P.Source.ScreenShare,w.width,w.height,n))}yield _()}const I=new sa(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(I.on(D.CpuConstrained,R=>this.onTrackCpuConstrained(R,I)),I.options=n,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:S})),pn(e)?e.startMonitor(this.engine.client):Kt(e)&&e.startMonitor(),this.addTrackPublication(I),this.emit(U.LocalTrackPublished,I),Kt(e)&&S.audioFeatures.includes(De.TF_PRECONNECT_BUFFER)){const R=e.getPreConnectBuffer(),A=e.getPreConnectBufferMimeType();this.on(U.LocalTrackSubscribed,M=>{if(M.trackSid===S.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Y(e))),e.stopPreConnectBuffer()}}),R&&new Promise((N,q)=>C(this,void 0,void 0,function*(){var F,te,H,J,W,Z;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Y(e)));const st=setTimeout(()=>{q(new Error("agent not active within 10 seconds"))},1e4),Ve=yield this.waitUntilActiveAgentPresent();clearTimeout(st),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Y(e)));const Lt=yield this.streamBytes({name:"preconnect-buffer",mimeType:A,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ve.identity],attributes:{trackId:I.trackSid,sampleRate:String((W=k.sampleRate)!==null&&W!==void 0?W:"48000"),channels:String((Z=k.channelCount)!==null&&Z!==void 0?Z:"1")}});try{for(var Ne=!0,bt=Wt(R),nn;nn=yield bt.next(),F=nn.done,!F;Ne=!0){J=nn.value,Ne=!1;const yt=J;yield Lt.write(yt)}}catch(yt){te={error:yt}}finally{try{!Ne&&!F&&(H=bt.return)&&(yield H.call(bt))}finally{if(te)throw te.error}}yield Lt.close(),N()}catch(st){q(st)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Y(e)))}).catch(N=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Y(e)),{error:N}))})}return I})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return C(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Xe.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new Gt("track is not published");if(!pn(e))throw new Gt("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=x0(e,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Y(e)));return}const c=e.addSimulcastTrack(n,a);if(!c)return;const l=new io({cid:c.mediaStreamTrack.id,type:P.kindToProto(e.kind),muted:e.isMuted,source:P.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Ku(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new Oe("cannot publish track when not connected");const d=()=>C(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,n){return C(this,void 0,void 0,function*(){var i,r;if(ei(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Y(e))),yield l)}const s=this.getPublicationForTrack(e),o=s?Y(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=s.track,e.off(D.Muted,this.onTrackMuted),e.off(D.Unmuted,this.onTrackUnmuted),e.off(D.Ended,this.handleTrackEnded),e.off(D.UpstreamPaused,this.onTrackUpstreamPaused),e.off(D.UpstreamResumed,this.onTrackUpstreamResumed),e.off(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ke.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),pn(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case P.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case P.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(U.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return C(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>C(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>C(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==P.Source.ScreenShare&&l.source!==P.Source.ScreenShareAudio&&(Kt(l)||pn(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return C(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?K.RELIABLE:K.LOSSY,o=r.destinationIdentities,a=r.topic,c=new ze({kind:s,value:{case:"user",value:new Gl({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)})()})}publishDtmf(e,n){return C(this,void 0,void 0,function*(){const i=new ze({kind:K.RELIABLE,value:{case:"sipDtmf",value:new Kl({code:e,digit:n})}});yield this.engine.sendDataPacket(i,K.RELIABLE)})}sendChatMessage(e,n){return C(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new ze({value:{case:"chatMessage",value:new Ys(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(U.ChatMessage,i),i})}editChatMessage(e,n){return C(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new ze({value:{case:"chatMessage",value:new Ys(Object.assign(Object.assign({},i),{timestamp:pe.parse(i.timestamp),editTimestamp:pe.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(U.ChatMessage,i),i})}sendText(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return C(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return C(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return(function*(){return new Promise((l,d)=>C(i,void 0,void 0,function*(){var u,h,f,v;if(Jo(o)>ju){d(Ce.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Pt((v=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||v===void 0?void 0:v.version,"1.8.0")<0){d(Ce.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,o,a-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),d(Ce.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(g)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),d(Ce.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(p,{resolve:(k,w)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),w?d(w):l(k??"")},participantIdentity:r})}))})()})}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,s){return C(this,void 0,void 0,function*(){const o=new ze({destinationIdentities:[e],kind:K.RELIABLE,value:{case:"rpcRequest",value:new Jl({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,K.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Ce.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Y(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Et),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Kt(r)||pn(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return C(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===e});if(r)return r[1];yield We(20)}})}}class Y0 extends Jt{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(D.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new yr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Zl({participantSid:"",trackSids:[this.trackSid]})]});this.emit(D.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Jt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Jt.SubscriptionStatus.Subscribed:Jt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Jt.PermissionStatus.Allowed:Jt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Lo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Lo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ze.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(D.VisibilityChanged,this.handleVisibilityChange),r.off(D.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(D.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(D.VisibilityChanged,this.handleVisibilityChange),e.on(D.Ended,this.handleEnded),this.emit(D.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(D.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?D.Muted:D.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(D.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(D.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Lo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ld({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===P.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)Pu(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Kv(this.trackInfo,this.requestedMaxQuality);i&&Pu(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Ze.HIGH})),e.quality=Ze.HIGH)}this.emit(D.UpdateSettings,e)}}class Br extends nh{static fromParticipantInfo(e,n,i){return new Br(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ri.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(D.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Y(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(D.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(D.SubscriptionPermissionChanged,n=>{this.emit(U.TrackSubscriptionPermissionChanged,e,n)}),e.on(D.SubscriptionStatusChanged,n=>{this.emit(U.TrackSubscriptionStatusChanged,e,n)}),e.on(D.Subscribed,n=>{this.emit(U.TrackSubscribed,n,e)}),e.on(D.Unsubscribed,n=>{this.emit(U.TrackUnsubscribed,n,e)}),e.on(D.SubscriptionFailed,n=>{this.emit(U.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:P.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:P.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(U.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,s,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Y(a))),this.emit(U.TrackSubscriptionFailed,n);return}const c=e.kind==="video";let l;return c?l=new z0(e,n,r,s):l=new $0(e,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&No(l)&&Rt(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=P.kindFromProto(r.type);if(!c)return;a=new Y0(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==P.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Y(l),newTrack:Y(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Y(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(U.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case P.Kind.Audio:this.audioTrackPublications.delete(e);break;case P.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(U.TrackUnpublished,i)}setAudioOutput(e){return C(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Rt(i.track)&&No(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ne;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(ne||(ne={}));const X0=4*1e3;class ii extends St.EventEmitter{constructor(e){var n,i,r,s;if(super(),n=this,this.state=ne.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Q,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,a,c)=>C(this,void 0,void 0,function*(){var l;if(!Ev())throw xt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===ne.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ne.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Io(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new na(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(f=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const u=(f,v,p)=>C(this,void 0,void 0,function*(){var g,b;this.abortController&&this.abortController.abort();const k=new AbortController;this.abortController=k,d==null||d();try{yield this.attemptConnection(p??o,a,c,k),this.abortController=void 0,f()}catch(w){if(this.regionUrlProvider&&w instanceof de&&w.reason!==ee.Cancelled&&w.reason!==ee.NotAllowed){let y=null;try{y=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(_){if(_ instanceof de&&(_.status===401||_.reason===ee.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(_);return}}y&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield u(f,v,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,wu(w)),v(w))}else{let y=at.UNKNOWN_REASON;w instanceof de&&(y=wu(w)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),v(w)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Et((f,v)=>{u(f,v,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,d,u)=>C(this,void 0,void 0,function*(){var h,f,v;const p=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let g=p.serverInfo;if(g||(g={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=g,this.log.debug("connected to Livekit Server ".concat(Object.entries(g).map(b=>{let[k,w]=b;return"".concat(k,": ").concat(w)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(v=p.participant)===null||v===void 0?void 0:v.identity}),!g.version)throw new fv("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),p}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>C(this,void 0,void 0,function*(){var d,u;this.state===ne.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ko),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new de("could not establish signal connection",ee.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof de&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new de("Connection attempt aborted",ee.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}He()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),He()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ne.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return C(n,[...a],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var u,h,f,v;const p=yield l.disconnectLock.lock();try{if(l.state===ne.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ne.Connecting||l.state===ne.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new de("Client initiated disconnect",ee.Cancelled)),l.connectFuture=void 0),!((v=l.engine)===null||v===void 0)&&v.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,at.CLIENT_INITIATED),l.engine=void 0}finally{p()}})()})},this.onPageLeave=()=>C(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>C(this,void 0,void 0,function*(){const o=[],a=Qe();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Do();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(O.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{o.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>C(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{o.includes(d)||o.push(d)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(ne.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=o=>C(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(ne.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===Gn.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),a.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(O.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?a.set(l.sid,d):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(O.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const d=P.streamStateFromProto(a.state);d!==l.track.streamState&&(l.track.streamState=d,c.emit(U.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(O.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(U.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(O.SipDTMFReceived,a,o),o==null||o.emit(U.SipDTMFReceived,a)},this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),d=Uv(a,this.transcriptionReceivedTimes);l==null||l.emit(D.TranscriptionReceived,d),c==null||c.emit(U.TranscriptionReceived,d,l),this.emit(O.TranscriptionReceived,d,c,l)},this.handleChatMessage=(o,a)=>{const c=Fv(a);this.emit(O.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(O.MetricsReceived,o,a)},this.handleDataStream=o=>{this.incomingDataStreamManager.handleDataStreamPacket(o)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>C(this,void 0,void 0,function*(){var o;((o=Qe())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(O.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(O.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(O.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(O.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(O.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>C(this,void 0,void 0,function*(){var a,c,l,d,u,h;(a=o.track)===null||a===void 0||a.on(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(D.Restarted,this.onLocalTrackRestarted),(u=(d=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(O.LocalTrackPublished,o,this.localParticipant),Kt(o.track)&&(yield o.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,o);const f=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),v=Bo(o.source);v&&f&&f!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,f),this.emit(O.ActiveDeviceChanged,v,f))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(D.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>C(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=Bo(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(O.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(O.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(O.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(O.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(O.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},u0),e),this.log=zt((i=this.options.loggerName)!==null&&i!==void 0?i:lt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Fu),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Bu),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},d0),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new B0,this.outgoingDataStreamManager=new q0(this.engine,this.log),this.disconnectLock=new qe,this.localParticipant=new J0("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",fn(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),He()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),ii.cleanupRegistry&&ii.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return C(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Jv(this.options.e2ee),this.e2eeManager.on(un.ParticipantEncryptionStatusChanged,(n,i)=>{jv(i)&&(this.isE2EEEnabled=n),this.emit(O.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(un.EncryptionError,n=>this.emit(O.EncryptionError,n)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return C(this,void 0,void 0,function*(){return this.state===ne.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(L.RoomUpdate,i),e(r.sid))};this.engine.on(L.RoomUpdate,i),this.once(O.Disconnected,()=>{this.engine.off(L.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new D0(this.options),this.engine.on(L.ParticipantUpdate,this.handleParticipantUpdates).on(L.RoomUpdate,this.handleRoomUpdate).on(L.SpeakersChanged,this.handleSpeakersChanged).on(L.StreamStateChanged,this.handleStreamStateUpdate).on(L.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(L.SubscriptionError,this.handleSubscriptionError).on(L.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(L.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(L.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(L.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(L.DataPacketReceived,this.handleDataPacket).on(L.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ne.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(L.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ne.Connected)&&this.emit(O.Reconnected)}).on(L.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ne.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(L.Restarting,this.handleRestarting).on(L.SignalRestarted,this.handleSignalRestarted).on(L.Offline,()=>{this.setAndEmitConnectionState(ne.Reconnecting)&&this.emit(O.Reconnecting)}).on(L.DCBufferStatusChanged,(e,n)=>{this.emit(O.DCBufferStatusChanged,e,n)}).on(L.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(U.LocalTrackSubscribed,n),this.emitWhenConnected(O.LocalTrackSubscribed,n,this.localParticipant)}).on(L.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(O.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Me.getInstance().getDevices(e,n)}prepareConnection(e,n){return C(this,void 0,void 0,function*(){if(this.state===ne.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Io(new URL(e))&&n){this.regionUrlProvider=new na(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ne.Disconnected&&(this.regionUrl=i,yield fetch(Mo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Mo(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return C(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new _t({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new _t({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new _t({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new _t({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new _t({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>C(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new _t({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new _t({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>C(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new kr({reason:at.CLIENT_INITIATED,action:Jn.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new _t({scenario:{case:"subscriberBandwidth",value:An(n)}});break;case"leave-full-reconnect":r=new _t({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return C(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,f;let v=!0,p=!1;const g=o?{exact:r}:r;if(i==="audioinput"){p=s.localParticipant.audioTrackPublications.size===0;const b=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=g;const k=Array.from(s.localParticipant.audioTrackPublications.values()).filter(y=>y.source===P.Source.Microphone);try{v=(yield Promise.all(k.map(y=>{var _;return(_=y.audioTrack)===null||_===void 0?void 0:_.setDeviceId(g)}))).every(y=>y===!0)}catch(y){throw s.options.audioCaptureDefaults.deviceId=b,y}const w=k.some(y=>{var _,S;return(S=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&S!==void 0?S:!1});v&&w&&(p=!0)}else if(i==="videoinput"){p=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=g;const k=Array.from(s.localParticipant.videoTrackPublications.values()).filter(y=>y.source===P.Source.Camera);try{v=(yield Promise.all(k.map(y=>{var _;return(_=y.videoTrack)===null||_===void 0?void 0:_.setDeviceId(g)}))).every(y=>y===!0)}catch(y){throw s.options.videoCaptureDefaults.deviceId=b,y}const w=k.some(y=>{var _,S;return(S=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&S!==void 0?S:!1});v&&w&&(p=!0)}else if(i==="audiooutput"){if(p=!0,!Ro()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(l=yield Me.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(d=(f=s.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const b=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(k=>k.setAudioOutput({deviceId:r})))}catch(k){throw s.options.audioOutput.deviceId=b,k}}return p&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(O.ActiveDeviceChanged,i,r)),v})()})}setupLocalParticipantEvents(){this.localParticipant.on(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(U.AttributesChanged,this.onLocalAttributesChanged).on(U.TrackMuted,this.onLocalTrackMuted).on(U.TrackUnmuted,this.onLocalTrackUnmuted).on(U.LocalTrackPublished,this.onLocalTrackPublished).on(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(U.MediaDevicesError,this.onMediaDevicesError).on(U.AudioStreamAcquired,this.startAudio).on(U.ChatMessage,this.onLocalChatMessageSent).on(U.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===ne.Connecting||this.state===ne.Reconnecting){const d=()=>{this.onTrackAdded(e,n,i),u()},u=()=>{this.off(O.Reconnected,d),this.off(O.Connected,d),this.off(O.Disconnected,u)};this.once(O.Reconnected,d),this.once(O.Connected,d),this.once(O.Disconnected,u);return}if(this.state===ne.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=Tv(n.id),s=r[0];let o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,a,n,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==ne.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(U.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(U.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(U.AttributesChanged,this.onLocalAttributesChanged).off(U.TrackMuted,this.onLocalTrackMuted).off(U.TrackUnmuted,this.onLocalTrackUnmuted).off(U.LocalTrackPublished,this.onLocalTrackPublished).off(U.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(U.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(U.MediaDevicesError,this.onMediaDevicesError).off(U.AudioStreamAcquired,this.startAudio).off(U.ChatMessage,this.onLocalChatMessageSent).off(U.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),He()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ne.Disconnected),this.emit(O.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(O.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,s,o){return C(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,n,null,Ce.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:n,callerIdentity:e,payload:r,responseTimeout:s});Jo(d)>ju?(c=Ce.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=d}catch(d){d instanceof Ce?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),c=Ce.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,l,c)})}selectDefaultDevices(){return C(this,void 0,void 0,function*(){var e,n,i;const r=Me.getInstance().previousDevices,s=yield Me.getInstance().getDevices(void 0,!1),o=Qe();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(O.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=qv(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((n=r.filter(f=>f.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Or()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Or())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return C(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Tu())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),We(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(O.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Br.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Br(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(O.ParticipantConnected,i),i.on(U.TrackPublished,r=>{this.emitWhenConnected(O.TrackPublished,r,i)}).on(U.TrackSubscribed,(r,s)=>{r.kind===P.Kind.Audio?(r.on(D.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(D.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===P.Kind.Video&&(r.on(D.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(D.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,r,s,i)}).on(U.TrackUnpublished,r=>{this.emit(O.TrackUnpublished,r,i)}).on(U.TrackUnsubscribed,(r,s)=>{this.emit(O.TrackUnsubscribed,r,s,i)}).on(U.TrackMuted,r=>{this.emitWhenConnected(O.TrackMuted,r,i)}).on(U.TrackUnmuted,r=>{this.emitWhenConnected(O.TrackUnmuted,r,i)}).on(U.ParticipantMetadataChanged,r=>{this.emitWhenConnected(O.ParticipantMetadataChanged,r,i)}).on(U.ParticipantNameChanged,r=>{this.emitWhenConnected(O.ParticipantNameChanged,r,i)}).on(U.AttributesChanged,r=>{this.emitWhenConnected(O.ParticipantAttributesChanged,r,i)}).on(U.ConnectionQualityChanged,r=>{this.emitWhenConnected(O.ConnectionQualityChanged,r,i)}).on(U.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,r,i)}).on(U.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,r,s,i)}).on(U.TrackSubscriptionFailed,(r,s)=>{this.emit(O.TrackSubscriptionFailed,r,i,s)}).on(U.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,r,s,i)}).on(U.Active,()=>{this.emitWhenConnected(O.ParticipantActive,i),i.kind===Ri.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&Bv(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ue.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,at.STATE_MISMATCH))):e=0},X0)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ue.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===ne.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ne.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return C(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new vr({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:pe.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Pn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(ne.Connected),r.video){const o=new sa(P.Kind.Video,new Kn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO,name:"video-dummy"}),new Ur(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Cu(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(U.LocalTrackPublished,o)}if(r.audio){const o=new sa(P.Kind.Audio,new Kn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO}),new Lr(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Do(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(U.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new Pn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Gn.ACTIVE,tracks:[],joinedAt:pe.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=Cu(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),d=new Kn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}if(s.audio){const l=Do(),d=new Kn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}c.updateInfo(a)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const s=ih(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}ii.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function ih(t){return t.map(e=>{if(e)return Array.isArray(e)?ih(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var ft;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(ft||(ft={}));class vn extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=ft.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new ii(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return C(this,void 0,void 0,function*(){if(this.status!==ft.IDLE)throw Error("check is running already");this.setStatus(ft.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==ft.SKIPPED&&this.setStatus(this.isSuccess()?ft.SUCCESS:ft.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return C(this,void 0,void 0,function*(){return this.room.state===ne.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return C(this,void 0,void 0,function*(){this.room&&this.room.state!==ne.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(ft.SKIPPED)}switchProtocol(e){return C(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(O.Reconnecting,()=>{n=!0}),this.room.once(O.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield We(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Q0 extends vn{get description(){return"Cloud regions"}perform(){return C(this,void 0,void 0,function*(){const e=new na(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return C(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let v=0;v<c;v++)yield s.write(l);yield s.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:u-d};return h==null||h.forEach(v=>{v.type==="candidate-pair"&&v.nominated&&(f.rtt=v.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const oa=1e4;class Z0 extends vn{get description(){return"Connection via UDP vs TCP"}perform(){return C(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(oa/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(oa/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return C(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>C(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,oa)),clearInterval(u),a.stop(),n.remove(),yield this.disconnect(),d})}}class eb extends vn{get description(){return"Can publish audio"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield th();if(yield Su(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class tb extends vn{get description(){return"Can publish video"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield H0();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return C(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(s=d.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let g=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class nb extends vn{get description(){return"Resuming connection after interruption"}perform(){return C(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(O.SignalReconnecting,a).on(O.Reconnecting,a).on(O.Reconnected,()=>{r=!0,s(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==ne.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class ib extends vn{get description(){return"Can connect via TURN"}perform(){return C(this,void 0,void 0,function*(){var e,n;const i=new Vo,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class rb extends vn{get description(){return"Establishing WebRTC connection"}perform(){return C(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(O.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(sb(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),Q.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function sb(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class ob extends vn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return C(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Vo;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===td.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class __ extends St.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:ft.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==ft.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return C(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ob)})}checkWebRTC(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(rb)})}checkTURN(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(ib)})}checkReconnect(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(nb)})}checkPublishAudio(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(eb)})}checkPublishVideo(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(tb)})}checkConnectionProtocol(){return C(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Z0);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return C(this,void 0,void 0,function*(){return this.createAndRunCheck(Q0)})}}function Yt(){return Yt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Yt.apply(null,arguments)}const rh=new Uint8Array(0);let Fi=class{static getFullOptions(e){return Yt({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,n){var i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(r){i.status!=="connected"&&i.status!=="connecting"||(i.updateStatus("disconnecting"),await i.handleEndSession(),i.updateStatus("disconnected"),i.options.onDisconnect&&i.options.onDisconnect(r))},this.onMessage=async function(r){switch(r.type){case"interruption":return void i.handleInterruption(r);case"agent_response":return void i.handleAgentResponse(r);case"user_transcript":return void i.handleUserTranscript(r);case"internal_tentative_agent_response":return void i.handleTentativeAgentResponse(r);case"client_tool_call":try{await i.handleClientToolCall(r)}catch(s){i.onError(`Unexpected error in client tool call handling: ${s instanceof Error?s.message:String(s)}`,{clientToolName:r.client_tool_call.tool_name,toolCallId:r.client_tool_call.tool_call_id})}return;case"audio":return void i.handleAudio(r);case"vad_score":return void i.handleVadScore(r);case"ping":return void i.connection.sendMessage({type:"pong",event_id:r.ping_event.event_id});case"mcp_tool_call":return void i.handleMCPToolCall(r);case"mcp_connection_status":return void i.handleMCPConnectionStatus(r);case"agent_tool_response":return void i.handleAgentToolResponse(r);case"conversation_initiation_metadata":return void i.handleConversationMetadata(r);case"asr_initiation_metadata":return void i.handleAsrInitiationMetadata(r);case"agent_chat_response_part":return void i.handleAgentChatResponsePart(r);case"error":return void i.handleErrorEvent(r);default:return void(i.options.onDebug&&i.options.onDebug(r))}},this.setVolume=({volume:r})=>{this.volume=r},this.options=e,this.connection=n,this.options.onConnect&&this.options.onConnect({conversationId:n.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(r=>this.updateMode(r)),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){const e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:"ai",message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:"user",message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{var n;const i=(n=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters))!=null?n:"Client tool execution successful.",r=typeof i=="object"?JSON.stringify(i):String(i);this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:r,is_error:!1})}catch(i){this.onError(`Client tool execution failed with following error: ${i==null?void 0:i.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${i==null?void 0:i.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolResponse(e){e.agent_tool_response.tool_name==="end_call"&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){const n=e.error_event.error_type,i=e.error_event.message||e.error_event.reason||"Unknown error";n!=="max_duration_exceeded"?this.onError(`Server error: ${i}`,{errorType:n,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details}):this.endSessionWithDetails({reason:"error",message:i,context:new Event("max_duration_exceeded")})}onError(e,n){console.error(e,n),this.options.onError&&this.options.onError(e,n)}getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return rh}getOutputByteFrequencyData(){return rh}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:e?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(e){this.connection.sendMessage({type:"contextual_update",text:e})}sendUserMessage(e){this.connection.sendMessage({type:"user_message",text:e})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(e,n){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:n})}};class sh{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;const n=this.queue;this.queue=[],n.length>0&&queueMicrotask(()=>{n.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;const n=this.disconnectionDetails;n&&queueMicrotask(()=>{e(n)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var n;(n=this.onModeChangeCallback)==null||n.call(this,e)}disconnect(e){var n;this.disconnectionDetails||(this.disconnectionDetails=e,(n=this.onDisconnectCallback)==null||n.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}}function jr(t){const[e,n]=t.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${t}`);const i=Number.parseInt(n);if(Number.isNaN(i))throw new Error(`Invalid sample rate: ${n}`);return{format:e,sampleRate:i}}const oh="0.9.2";function aa(t){return!!t.type}const ah="conversation_initiation_client_data";function ch(t){var e;const n={type:ah};var i,r,s,o,a;return t.overrides&&(n.conversation_config_override={agent:{prompt:(i=t.overrides.agent)==null?void 0:i.prompt,first_message:(r=t.overrides.agent)==null?void 0:r.firstMessage,language:(s=t.overrides.agent)==null?void 0:s.language},tts:{voice_id:(o=t.overrides.tts)==null?void 0:o.voiceId},conversation:{text_only:(a=t.overrides.conversation)==null?void 0:a.textOnly}}),t.customLlmExtraBody&&(n.custom_llm_extra_body=t.customLlmExtraBody),t.dynamicVariables&&(n.dynamic_variables=t.dynamicVariables),t.userId&&(n.user_id=t.userId),(e=t.overrides)!=null&&e.client&&(n.source_info={source:t.overrides.client.source,version:t.overrides.client.version}),n}class Bi extends sh{constructor(e,n,i,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=n,this.inputFormat=i,this.outputFormat=r,this.socket.addEventListener("error",s=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:s}),0)}),this.socket.addEventListener("close",s=>{this.disconnect(s.code===1e3?{reason:"agent",context:s}:{reason:"error",message:s.reason||"The connection was closed by the server.",context:s})}),this.socket.addEventListener("message",s=>{try{const o=JSON.parse(s.data);if(!aa(o))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:s.data});this.handleMessage(o)}catch(o){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:o instanceof Error?o.message:String(o),data:s.data})}})}static async create(e){let n=null;try{var i,r,s;const a=(i=e.origin)!=null?i:"wss://api.elevenlabs.io";let c;const l=((r=e.overrides)==null||(r=r.client)==null?void 0:r.version)||oh,d=((s=e.overrides)==null||(s=s.client)==null?void 0:s.source)||"js_sdk";if(e.signedUrl){const k=e.signedUrl.includes("?")?"&":"?";c=`${e.signedUrl}${k}source=${d}&version=${l}`}else c=`${a}/v1/convai/conversation?agent_id=${e.agentId}&source=${d}&version=${l}`;const u=["convai"];e.authorization&&u.push(`bearer.${e.authorization}`),n=new WebSocket(c,u);const h=await new Promise((k,w)=>{n.addEventListener("open",()=>{var y;const _=ch(e);(y=n)==null||y.send(JSON.stringify(_))},{once:!0}),n.addEventListener("error",y=>{setTimeout(()=>w(y),0)}),n.addEventListener("close",w),n.addEventListener("message",y=>{const _=JSON.parse(y.data);aa(_)&&(_.type==="conversation_initiation_metadata"?k(_.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:f,agent_output_audio_format:v,user_input_audio_format:p}=h,g=jr(p??"pcm_16000"),b=jr(v);return new Bi(n,f,g,b)}catch(a){var o;throw(o=n)==null||o.close(),a}}close(){this.socket.close()}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}}function lh(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function ab(t){const e=window.atob(t),n=e.length,i=new Uint8Array(n);for(let r=0;r<n;r++)i[r]=e.charCodeAt(r);return i.buffer}const Vr=new Map;function dh(t,e){return async(n,i)=>{const r=Vr.get(t);if(r)return n.addModule(r);if(i)try{return await n.addModule(i),void Vr.set(t,i)}catch(a){throw new Error(`Failed to load the ${t} worklet module from path: ${i}. Error: ${a}`)}const s=new Blob([e],{type:"application/javascript"}),o=URL.createObjectURL(s);try{return await n.addModule(o),void Vr.set(t,o)}catch{URL.revokeObjectURL(o)}try{const a=`data:application/javascript;base64,${btoa(e)}`;await n.addModule(a),Vr.set(t,a)}catch{throw new Error(`Failed to load the ${t} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}const uh=dh("rawAudioProcessor",`/*
39
+ * ulaw encoding logic taken from the wavefile library
40
+ * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
41
+ * USED BY @elevenlabs/client
42
+ */
43
+
39
44
  const BIAS = 0x84;
40
45
  const CLIP = 32635;
41
46
  const encodeTable = [
@@ -153,11 +158,16 @@ class RawAudioProcessor extends AudioWorkletProcessor {
153
158
  return true; // Continue processing
154
159
  }
155
160
  }
156
- registerProcessor("raw-audio-processor", RawAudioProcessor);
157
- `);class Jt extends nh{constructor(e,n,i,r,s={}){super(s),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=n,this.inputFormat=i,this.outputFormat=r,this.setupRoomEventListeners()}static async create(e){let n;if("conversationToken"in e&&e.conversationToken)n=e.conversationToken;else{if(!("agentId"in e)||!e.agentId)throw new Error("Either conversationToken or agentId is required for WebRTC connection");try{var i,r,s;const l=((i=e.overrides)==null||(i=i.client)==null?void 0:i.version)||ih,d=((r=e.overrides)==null||(r=r.client)==null?void 0:r.source)||"js_sdk",u=`${o=(s=e.origin)!=null?s:"https://api.elevenlabs.io",o.replace(/^wss:\/\//,"https://")}/v1/convai/conversation/token?agent_id=${e.agentId}&source=${d}&version=${l}`,h=await fetch(u);if(!h.ok)throw new Error(`ElevenLabs API returned ${h.status} ${h.statusText}`);if(n=(await h.json()).token,!n)throw new Error("No conversation token received from API")}catch(l){let d=l instanceof Error?l.message:String(l);throw l instanceof Error&&l.message.includes("401")&&(d="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${e.agentId}: ${d}`)}}var o;const a=new ii;try{const l=`room_${Date.now()}`,d=jr("pcm_48000"),u=jr("pcm_48000"),h=new Jt(a,l,d,u,e),p=e.livekitUrl||"wss://livekit.rtc.elevenlabs.io";var c;await a.connect(p,n),await new Promise(f=>{if(h.isConnected)f();else{const m=()=>{a.off(D.Connected,m),f()};a.on(D.Connected,m)}}),a.name&&(h.conversationId=((c=a.name.match(/(conv_[a-zA-Z0-9]+)/))==null?void 0:c[0])||a.name),await a.localParticipant.setMicrophoneEnabled(!0);const g=sh(e);return h.debug({type:rh,message:g}),await h.sendMessage(g),h}catch(l){throw await a.disconnect(),l}}setupRoomEventListeners(){var e=this;this.room.on(D.Connected,async function(){e.isConnected=!0,console.info("WebRTC room connected")}),this.room.on(D.Disconnected,n=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:n==null?void 0:n.toString()})})}),this.room.on(D.ConnectionStateChanged,n=>{n===ee.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${n}`,context:new Event("connection_state_changed")}))}),this.room.on(D.DataReceived,(n,i)=>{try{const r=JSON.parse(new TextDecoder().decode(n));if(r.type==="audio")return;oa(r)?this.handleMessage(r):console.warn("Invalid socket event received:",r)}catch(r){console.warn("Failed to parse incoming data message:",r),console.warn("Raw payload:",new TextDecoder().decode(n))}}),this.room.on(D.TrackSubscribed,async function(n,i,r){if(n.kind===E.Kind.Audio&&r.identity.includes("agent")){const s=n,o=s.attach();if(o.autoplay=!0,o.controls=!1,e.outputDeviceId&&o.setSinkId)try{await o.setSinkId(e.outputDeviceId)}catch(a){console.warn("Failed to set output device for new audio element:",a)}o.style.display="none",document.body.appendChild(o),e.audioElements.push(o),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:"audio_element_ready"})),await e.setupAudioCapture(s)}}),this.room.on(D.ActiveSpeakersChanged,async function(n){e.updateMode(n.length>0&&n[0].identity.startsWith("agent")?"speaking":"listening")})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch(e=>{console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!("user_audio_chunk"in e))try{const n=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(n,{reliable:!0})}catch(n){this.debug({type:"send_message_error",message:{message:e,error:n}}),console.error("Failed to send message via WebRTC:",n)}}else console.warn("Cannot send message: room not connected or no local participant")}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn("Cannot set microphone muted: room not connected or no local participant");const n=this.room.localParticipant.getTrackPublication(E.Source.Microphone);if(n!=null&&n.track)try{e?await n.track.mute():await n.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{const n=new AudioContext;this.audioCaptureContext=n,this.outputAnalyser=n.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;const i=new MediaStream([e.mediaStreamTrack]),r=n.createMediaStreamSource(i);r.connect(this.outputAnalyser),await ch(n.audioWorklet);const s=new AudioWorkletNode(n,"raw-audio-processor");this.outputAnalyser.connect(s),s.port.postMessage({type:"setFormat",format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),s.port.onmessage=o=>{const[a,c]=o.data;if(c>.01){const l=oh(a.buffer),d=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:l,event_id:d}})}},r.connect(s)}catch(n){console.warn("Failed to set up audio capture:",n)}}setAudioVolume(e){this.audioElements.forEach(n=>{n.volume=e})}async setAudioOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");const n=this.audioElements.map(async function(i){try{await i.setSinkId(e)}catch(r){throw console.error("Failed to set sink ID for audio element:",r),r}});await Promise.all(n),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");try{const n=this.room.localParticipant.getTrackPublication(E.Source.Microphone);n!=null&&n.track&&(await n.track.stop(),await this.room.localParticipant.unpublishTrack(n.track));const i={deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},r=await Qu(i);await this.room.localParticipant.publishTrack(r,{name:"microphone",source:E.Source.Microphone})}catch(n){console.error("Failed to change input device:",n);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(i){console.error("Failed to recover microphone after device switch error:",i)}throw n}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}}async function lh(t){const e=(function(n){return n.connectionType?n.connectionType:"conversationToken"in n&&n.conversationToken?"webrtc":"websocket"})(t);switch(e){case"websocket":return Bi.create(t);case"webrtc":return Jt.create(t);default:throw new Error(`Unknown connection type: ${e}`)}}function dh(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function uh(t={default:0,android:3e3}){let e=t.default;var n;if(/android/i.test(navigator.userAgent))e=(n=t.android)!=null?n:e;else if(dh()){var i;e=(i=t.ios)!=null?i:e}e>0&&await new Promise(r=>setTimeout(r,e))}class ca extends Fi{static async startSession(e){const n=Fi.getFullOptions(e);n.onStatusChange&&n.onStatusChange({status:"connecting"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:"listening"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let i=null;try{return await uh(n.connectionDelay),i=await lh(e),new ca(n,i)}catch(s){var r;throw n.onStatusChange&&n.onStatusChange({status:"disconnected"}),(r=i)==null||r.close(),s}}}const hh={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class Vr{static async create({sampleRate:e,format:n,preferHeadphonesForIosDevices:i,inputDeviceId:r}){let s=null,o=null;try{const l=Kt({sampleRate:{ideal:e}},hh);if(dh()&&i){const f=(await window.navigator.mediaDevices.enumerateDevices()).find(m=>m.kind==="audioinput"&&["airpod","headphone","earphone"].find(v=>m.label.toLowerCase().includes(v)));f&&(l.deviceId={ideal:f.deviceId})}r&&(l.deviceId={exact:r});const d=navigator.mediaDevices.getSupportedConstraints().sampleRate;s=new window.AudioContext(d?{sampleRate:e}:{});const u=s.createAnalyser();d||await s.audioWorklet.addModule("https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js"),await ch(s.audioWorklet);const h=Kt({voiceIsolation:!0},l);o=await navigator.mediaDevices.getUserMedia({audio:h});const p=s.createMediaStreamSource(o),g=new AudioWorkletNode(s,"raw-audio-processor");return g.port.postMessage({type:"setFormat",format:n,sampleRate:e}),p.connect(u),u.connect(g),await s.resume(),new Vr(s,u,g,o,p)}catch(l){var a,c;throw(a=o)==null||a.getTracks().forEach(d=>{d.stop()}),(c=s)==null||c.close(),l}}constructor(e,n,i,r,s){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=n,this.worklet=i,this.inputStream=r,this.mediaStreamSource=s}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:"setMuted",isMuted:e})}async setInputDevice(e){if(!e)throw new Error("Input device ID is required");try{const n=Kt({deviceId:{exact:e}},hh),i=Kt({voiceIsolation:!0},n),r=await navigator.mediaDevices.getUserMedia({audio:i});this.inputStream.getTracks().forEach(s=>{s.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=r,this.mediaStreamSource=this.context.createMediaStreamSource(r),this.mediaStreamSource.connect(this.analyser)}catch(n){throw console.error("Failed to switch input device:",n),n}}}const X0=ah("audio-concat-processor",`
161
+ registerProcessor("rawAudioProcessor", RawAudioProcessor);
162
+ `);class Xt extends sh{constructor(e,n,i,r,s={}){super(s),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=n,this.inputFormat=i,this.outputFormat=r,this.setupRoomEventListeners()}static async create(e){let n;if("conversationToken"in e&&e.conversationToken)n=e.conversationToken;else{if(!("agentId"in e)||!e.agentId)throw new Error("Either conversationToken or agentId is required for WebRTC connection");try{var i,r,s;const l=((i=e.overrides)==null||(i=i.client)==null?void 0:i.version)||oh,d=((r=e.overrides)==null||(r=r.client)==null?void 0:r.source)||"js_sdk",u=`${o=(s=e.origin)!=null?s:"https://api.elevenlabs.io",o.replace(/^wss:\/\//,"https://")}/v1/convai/conversation/token?agent_id=${e.agentId}&source=${d}&version=${l}`,h=await fetch(u);if(!h.ok)throw new Error(`ElevenLabs API returned ${h.status} ${h.statusText}`);if(n=(await h.json()).token,!n)throw new Error("No conversation token received from API")}catch(l){let d=l instanceof Error?l.message:String(l);throw l instanceof Error&&l.message.includes("401")&&(d="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${e.agentId}: ${d}`)}}var o;const a=new ii;try{const l=`room_${Date.now()}`,d=jr("pcm_48000"),u=jr("pcm_48000"),h=new Xt(a,l,d,u,e),f=e.livekitUrl||"wss://livekit.rtc.elevenlabs.io";var c;await a.connect(f,n),await new Promise(p=>{if(h.isConnected)p();else{const g=()=>{a.off(O.Connected,g),p()};a.on(O.Connected,g)}}),a.name&&(h.conversationId=((c=a.name.match(/(conv_[a-zA-Z0-9]+)/))==null?void 0:c[0])||a.name),await a.localParticipant.setMicrophoneEnabled(!0);const v=ch(e);return h.debug({type:ah,message:v}),await h.sendMessage(v),h}catch(l){throw await a.disconnect(),l}}setupRoomEventListeners(){var e=this;this.room.on(O.Connected,async function(){e.isConnected=!0,console.info("WebRTC room connected")}),this.room.on(O.Disconnected,n=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:n==null?void 0:n.toString()})})}),this.room.on(O.ConnectionStateChanged,n=>{n===ne.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${n}`,context:new Event("connection_state_changed")}))}),this.room.on(O.DataReceived,(n,i)=>{try{const r=JSON.parse(new TextDecoder().decode(n));if(r.type==="audio")return;aa(r)?this.handleMessage(r):console.warn("Invalid socket event received:",r)}catch(r){console.warn("Failed to parse incoming data message:",r),console.warn("Raw payload:",new TextDecoder().decode(n))}}),this.room.on(O.TrackSubscribed,async function(n,i,r){if(n.kind===P.Kind.Audio&&r.identity.includes("agent")){const s=n,o=s.attach();if(o.autoplay=!0,o.controls=!1,e.outputDeviceId&&o.setSinkId)try{await o.setSinkId(e.outputDeviceId)}catch(a){console.warn("Failed to set output device for new audio element:",a)}o.style.display="none",document.body.appendChild(o),e.audioElements.push(o),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:"audio_element_ready"})),await e.setupAudioCapture(s)}}),this.room.on(O.ActiveSpeakersChanged,async function(n){e.updateMode(n.length>0&&n[0].identity.startsWith("agent")?"speaking":"listening")})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch(e=>{console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!("user_audio_chunk"in e))try{const n=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(n,{reliable:!0})}catch(n){this.debug({type:"send_message_error",message:{message:e,error:n}}),console.error("Failed to send message via WebRTC:",n)}}else console.warn("Cannot send message: room not connected or no local participant")}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn("Cannot set microphone muted: room not connected or no local participant");const n=this.room.localParticipant.getTrackPublication(P.Source.Microphone);if(n!=null&&n.track)try{e?await n.track.mute():await n.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{const n=new AudioContext;this.audioCaptureContext=n,this.outputAnalyser=n.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;const i=new MediaStream([e.mediaStreamTrack]),r=n.createMediaStreamSource(i);r.connect(this.outputAnalyser),await uh(n.audioWorklet);const s=new AudioWorkletNode(n,"rawAudioProcessor");this.outputAnalyser.connect(s),s.port.postMessage({type:"setFormat",format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),s.port.onmessage=o=>{const[a,c]=o.data;if(c>.01){const l=lh(a.buffer),d=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:l,event_id:d}})}},r.connect(s)}catch(n){console.warn("Failed to set up audio capture:",n)}}setAudioVolume(e){this.audioElements.forEach(n=>{n.volume=e})}async setAudioOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");const n=this.audioElements.map(async function(i){try{await i.setSinkId(e)}catch(r){throw console.error("Failed to set sink ID for audio element:",r),r}});await Promise.all(n),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");try{const n=this.room.localParticipant.getTrackPublication(P.Source.Microphone);n!=null&&n.track&&(await n.track.stop(),await this.room.localParticipant.unpublishTrack(n.track));const i={deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},r=await th(i);await this.room.localParticipant.publishTrack(r,{name:"microphone",source:P.Source.Microphone})}catch(n){console.error("Failed to change input device:",n);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(i){console.error("Failed to recover microphone after device switch error:",i)}throw n}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}}async function hh(t){const e=(function(n){return n.connectionType?n.connectionType:"conversationToken"in n&&n.conversationToken?"webrtc":"websocket"})(t);switch(e){case"websocket":return Bi.create(t);case"webrtc":return Xt.create(t);default:throw new Error(`Unknown connection type: ${e}`)}}function fh(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function ph(t={default:0,android:3e3}){let e=t.default;var n;if(/android/i.test(navigator.userAgent))e=(n=t.android)!=null?n:e;else if(fh()){var i;e=(i=t.ios)!=null?i:e}e>0&&await new Promise(r=>setTimeout(r,e))}class ca extends Fi{static async startSession(e){const n=Fi.getFullOptions(e);n.onStatusChange&&n.onStatusChange({status:"connecting"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:"listening"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let i=null;try{return await ph(n.connectionDelay),i=await hh(e),new ca(n,i)}catch(s){var r;throw n.onStatusChange&&n.onStatusChange({status:"disconnected"}),(r=i)==null||r.close(),s}}}const mh={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class qr{static async create({sampleRate:e,format:n,preferHeadphonesForIosDevices:i,inputDeviceId:r,workletPaths:s,libsampleratePath:o}){let a=null,c=null;try{const u=Yt({sampleRate:{ideal:e}},mh);if(fh()&&i){const b=(await window.navigator.mediaDevices.enumerateDevices()).find(k=>k.kind==="audioinput"&&["airpod","headphone","earphone"].find(w=>k.label.toLowerCase().includes(w)));b&&(u.deviceId={ideal:b.deviceId})}r&&(u.deviceId={exact:r});const h=navigator.mediaDevices.getSupportedConstraints().sampleRate;a=new window.AudioContext(h?{sampleRate:e}:{});const f=a.createAnalyser();if(!h){const b=o||"https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js";await a.audioWorklet.addModule(b)}await uh(a.audioWorklet,s==null?void 0:s.rawAudioProcessor);const v=Yt({voiceIsolation:!0},u);c=await navigator.mediaDevices.getUserMedia({audio:v});const p=a.createMediaStreamSource(c),g=new AudioWorkletNode(a,"rawAudioProcessor");return g.port.postMessage({type:"setFormat",format:n,sampleRate:e}),p.connect(f),f.connect(g),await a.resume(),new qr(a,f,g,c,p)}catch(u){var l,d;throw(l=c)==null||l.getTracks().forEach(h=>{h.stop()}),(d=a)==null||d.close(),u}}constructor(e,n,i,r,s){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=n,this.worklet=i,this.inputStream=r,this.mediaStreamSource=s}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:"setMuted",isMuted:e})}async setInputDevice(e){try{const n=Yt({},mh);e&&(n.deviceId={exact:e});const i=Yt({voiceIsolation:!0},n),r=await navigator.mediaDevices.getUserMedia({audio:i});this.inputStream.getTracks().forEach(s=>{s.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=r,this.mediaStreamSource=this.context.createMediaStreamSource(r),this.mediaStreamSource.connect(this.analyser)}catch(n){throw console.error("Failed to switch input device:",n),n}}}const cb=dh("audioConcatProcessor",`/*
163
+ * ulaw decoding logic taken from the wavefile library
164
+ * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
165
+ * USED BY @elevenlabs/client
166
+ */
167
+
158
168
  const decodeTable = [0,132,396,924,1980,4092,8316,16764];
159
169
 
160
- export function decodeSample(muLawSample) {
170
+ function decodeSample(muLawSample) {
161
171
  let sign;
162
172
  let exponent;
163
173
  let mantissa;
@@ -240,11 +250,11 @@ class AudioConcatProcessor extends AudioWorkletProcessor {
240
250
  }
241
251
  }
242
252
 
243
- registerProcessor("audio-concat-processor", AudioConcatProcessor);
244
- `);class qr{static async create({sampleRate:e,format:n,outputDeviceId:i}){let r=null,s=null;try{r=new AudioContext({sampleRate:e});const c=r.createAnalyser(),l=r.createGain();s=new Audio,s.src="",s.load(),s.autoplay=!0,s.style.display="none",document.body.appendChild(s);const d=r.createMediaStreamDestination();s.srcObject=d.stream,l.connect(c),c.connect(d),await X0(r.audioWorklet);const u=new AudioWorkletNode(r,"audio-concat-processor");return u.port.postMessage({type:"setFormat",format:n}),u.connect(l),await r.resume(),i&&s.setSinkId&&await s.setSinkId(i),new qr(r,c,l,u,s)}catch(c){var o,a;throw(o=s)!=null&&o.parentNode&&s.parentNode.removeChild(s),(a=s)==null||a.pause(),r&&r.state!=="closed"&&await r.close(),c}}constructor(e,n,i,r,s){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=n,this.gain=i,this.worklet=r,this.audioElement=s}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(e)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class la extends Fi{static async startSession(e){var n;const i=Fi.getFullOptions(e);i.onStatusChange&&i.onStatusChange({status:"connecting"}),i.onCanSendFeedbackChange&&i.onCanSendFeedbackChange({canSendFeedback:!1});let r=null,s=null,o=null,a=null,c=null;if((n=e.useWakeLock)==null||n)try{c=await navigator.wakeLock.request("screen")}catch{}try{var l;return a=await navigator.mediaDevices.getUserMedia({audio:!0}),await uh(i.connectionDelay),s=await lh(e),[r,o]=await Promise.all([Vr.create(Kt({},s.inputFormat,{preferHeadphonesForIosDevices:e.preferHeadphonesForIosDevices,inputDeviceId:e.inputDeviceId})),qr.create(Kt({},s.outputFormat,{outputDeviceId:e.outputDeviceId}))]),(l=a)==null||l.getTracks().forEach(f=>{f.stop()}),a=null,new la(i,s,r,o,c)}catch(f){var d,u,h,p;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),(d=a)==null||d.getTracks().forEach(m=>{m.stop()}),(u=s)==null||u.close(),await((h=r)==null?void 0:h.close()),await((p=o)==null?void 0:p.close());try{var g;await((g=c)==null?void 0:g.release()),c=null}catch{}throw f}}constructor(e,n,i,r,s){super(e,n),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=o=>{this.status==="connected"&&this.connection.sendMessage({user_audio_chunk:oh(o.data[0].buffer)})},this.onOutputWorkletMessage=({data:o})=>{o.type==="process"&&this.updateMode(o.finished?"listening":"speaking")},this.addAudioBase64Chunk=o=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:Y0(o)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},this.calculateVolume=o=>{if(o.length===0)return 0;let a=0;for(let c=0;c<o.length;c++)a+=o[c]/255;return a/=o.length,a<0?0:a>1?1:a},this.setVolume=({volume:o})=>{const a=Number.isFinite(o)?Math.min(1,Math.max(0,o)):1;this.volume=a,this.connection instanceof Jt?this.connection.setAudioVolume(a):this.output.gain.gain.value=a},this.input=i,this.output=r,this.wakeLock=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{var e;await((e=this.wakeLock)==null?void 0:e.release()),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var n,i;this.lastInterruptTimestamp<=e.audio_event.event_id&&((n=(i=this.options).onAudio)==null||n.call(i,e.audio_event.audio_base_64),this.connection instanceof Jt||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(e){this.connection instanceof Jt?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData!=null||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Jt?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:n,preferHeadphonesForIosDevices:i,inputDeviceId:r}){try{if(this.connection instanceof Bi&&r)try{return await this.input.setInputDevice(r),this.input}catch(o){console.warn("Failed to change device on existing input, recreating:",o)}this.connection instanceof Jt&&r&&await this.connection.setAudioInputDevice(r),await this.input.close();const s=await Vr.create({sampleRate:e,format:n,preferHeadphonesForIosDevices:i,inputDeviceId:r});return this.input=s,this.input}catch(s){throw console.error("Error changing input device",s),s}}async changeOutputDevice({sampleRate:e,format:n,outputDeviceId:i}){try{if(this.connection instanceof Bi&&i)try{return await this.output.setOutputDevice(i),this.output}catch(s){console.warn("Failed to change device on existing output, recreating:",s)}this.connection instanceof Jt&&i&&await this.connection.setAudioOutputDevice(i),await this.output.close();const r=await qr.create({sampleRate:e,format:n,outputDeviceId:i});return this.output=r,this.output}catch(r){throw console.error("Error changing output device",r),r}}}class Q0 extends Fi{static startSession(e){return e.textOnly?ca.startSession(e):la.startSession(e)}}function fh(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var r=t.length;for(e=0;e<r;e++)t[e]&&(n=fh(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function he(){for(var t,e,n=0,i="",r=arguments.length;n<r;n++)(t=arguments[n])&&(e=fh(t))&&(i&&(i+=" "),i+=e);return i}var Z0=Object.defineProperty,eb=(t,e,n)=>e in t?Z0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$e=(t,e,n)=>eb(t,typeof e!="symbol"?e+"":e,n);function mn(t){return t?t==="true"?!0:t==="false"?!1:null:null}const da=["variant","placement","override-config","avatar-image-url","avatar-orb-color-1","avatar-orb-color-2","agent-id","signed-url","terms-key","server-location","language","dynamic-variables","show-avatar-when-collapsed","override-prompt","override-first-message","override-language","override-voice-id","override-text-only","mic-muting","transcript","text-input","text-contents","default-expanded","always-expanded","user-id"],tb='@import"https://fonts.googleapis.com/css2?family=Inter:wght@400,500&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:currentColor}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.pointer-events-auto{pointer-events:auto}.\\!visible{visibility:visible!important}.visible{visibility:visible}.collapse{visibility:collapse}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-3{bottom:-12px}.bottom-0{bottom:0}.bottom-1{bottom:4px}.bottom-20{bottom:80px}.left-0{left:0}.left-1\\/2{left:50%}.left-4{left:16px}.right-0{right:0}.right-1{right:4px}.top-0{top:0}.top-1\\/2{top:50%}.top-20{top:80px}.top-4{top:16px}.z-1{z-index:1}.z-10{z-index:10}.m-1{margin:4px}.-mx-0\\.5{margin-left:-2px;margin-right:-2px}.mx-1{margin-left:4px;margin-right:4px}.-mr-1\\.5{margin-right:-6px}.ml-auto{margin-left:auto}.mt-2{margin-top:8px}.block{display:block}.inline{display:inline}.\\!flex{display:flex!important}.flex{display:flex}.inline-flex{display:inline-flex}.contents{display:contents}.hidden{display:none}.h-11{height:44px}.h-16{height:64px}.h-4{height:16px}.h-48{height:192px}.h-5{height:20px}.h-6{height:24px}.h-7{height:28px}.h-9{height:36px}.h-\\[calc\\(100\\%-80px\\)\\]{height:calc(100% - 80px)}.h-full{height:100%}.h-screen{height:100vh}.max-h-\\[550px\\]{max-height:550px}.max-h-\\[8lh\\]{max-height:8lh}.max-h-\\[min\\(384px\\,var\\(--radix-select-content-available-height\\)\\)\\]{max-height:min(384px,var(--radix-select-content-available-height))}.min-h-min{min-height:-moz-min-content;min-height:min-content}.w-16{width:64px}.w-4{width:16px}.w-48{width:192px}.w-5{width:20px}.w-6{width:24px}.w-64{width:256px}.w-7{width:28px}.w-9{width:36px}.w-full{width:100%}.w-screen{width:100vw}.\\!min-w-60{min-width:240px!important}.min-w-0{min-width:0px}.min-w-60{min-width:240px}.min-w-9{min-width:36px}.min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.min-w-max{min-width:-moz-max-content;min-width:max-content}.min-w-min{min-width:-moz-min-content;min-width:min-content}.max-w-64{max-width:256px}.max-w-\\[400px\\]{max-width:400px}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-bottom{transform-origin:bottom}.origin-bottom-left{transform-origin:bottom left}.origin-bottom-right{transform-origin:bottom right}.origin-top{transform-origin:top}.origin-top-left{transform-origin:top left}.origin-top-right{transform-origin:top right}.-translate-x-1\\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(calc(var(--el-overlay-padding)) * -1);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-1\\/2{--tw-translate-y: 50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(var(--el-overlay-padding));transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-full{--tw-translate-y: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-180{--tw-rotate: -180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-150{--tw-scale-x: 1.5;--tw-scale-y: 1.5;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-75{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-90{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\\[0\\.333\\]{--tw-scale-x: .333;--tw-scale-y: .333;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.gap-1{gap:4px}.gap-2{gap:8px}.gap-2\\.5{gap:10px}.gap-3{gap:12px}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-all{word-break:break-all}.rounded-\\[calc\\(var\\(--el-button-radius\\)\\+4px\\)\\]{border-radius:calc(var(--el-button-radius) + 4px)}.rounded-bubble{border-radius:var(--el-bubble-radius)}.rounded-button{border-radius:var(--el-button-radius)}.rounded-compact-sheet{border-radius:var(--el-compact-sheet-radius)}.rounded-dropdown-sheet{border-radius:var(--el-dropdown-sheet-radius)}.rounded-full{border-radius:9999px}.rounded-input{border-radius:var(--el-input-radius)}.rounded-sheet{border-radius:var(--el-sheet-radius)}.rounded-bl-\\[calc\\(var\\(--el-bubble-radius\\)\\/3\\)\\]{border-bottom-left-radius:calc(var(--el-bubble-radius) / 3)}.border{border-width:1px}.border-accent{border-color:var(--el-accent)}.border-base-border{border-color:var(--el-base-border)}.bg-accent{background-color:var(--el-accent)}.bg-base{background-color:var(--el-base)}.bg-base-active{background-color:var(--el-base-active)}.bg-base-border{background-color:var(--el-base-border)}.bg-base-hover{background-color:var(--el-base-hover)}.bg-cover{background-size:cover}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:4px}.p-1\\.5{padding:6px}.p-2{padding:8px}.p-3{padding:12px}.p-4{padding:16px}.px-1{padding-left:4px;padding-right:4px}.px-1\\.5{padding-left:6px;padding-right:6px}.px-2{padding-left:8px;padding-right:8px}.px-2\\.5{padding-left:10px;padding-right:10px}.px-3{padding-left:12px;padding-right:12px}.px-4{padding-left:16px;padding-right:16px}.px-8{padding-left:32px;padding-right:32px}.py-1\\.5{padding-top:6px;padding-bottom:6px}.py-2\\.5{padding-top:10px;padding-bottom:10px}.py-\\[calc\\(theme\\(spacing\\.2\\)-1px\\)\\]{padding-top:7px;padding-bottom:7px}.pb-1{padding-bottom:4px}.pb-3{padding-bottom:12px}.pl-16{padding-left:64px}.pr-16{padding-right:64px}.pr-3{padding-right:12px}.pr-9{padding-right:36px}.pt-1{padding-top:4px}.text-center{text-align:center}.text-\\[10px\\]{font-size:10px}.text-lg{font-size:18px;line-height:26px}.text-md{font-size:16px;line-height:24px}.text-sm{font-size:14px;line-height:20px}.text-xs{font-size:12px;line-height:16px}.font-medium{font-weight:500}.text-accent-primary{color:var(--el-accent-primary)}.text-base-error{color:var(--el-base-error)}.text-base-primary{color:var(--el-base-primary)}.text-base-subtle{color:var(--el-base-subtle)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-30{opacity:.3}.shadow-lg{--tw-shadow: 0 2px 40px 1px rgba(0, 0, 0, .12);--tw-shadow-colored: 0 2px 40px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 2px 24px 1px rgba(0, 0, 0, .16);--tw-shadow-colored: 0 2px 24px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[border-radius\\]{transition-property:border-radius;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[margin\\]{transition-property:margin;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,width\\,height\\,transform\\,flex-grow\\]{transition-property:opacity,width,height,transform,flex-grow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,left\\,top\\]{transition-property:transform,left,top;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,opacity\\]{transition-property:transform,opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.overlay{position:absolute;inset:var(--el-overlay-padding);right:calc(var(--el-overlay-padding) + var(--removed-body-scroll-bar-size, 0px))}.focus-ring{--tw-ring-color: var(--el-accent);--tw-ring-offset-width: 2px;--tw-ring-offset-color: var(--el-base)}.focus-ring:focus-visible{outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.animate-text{background-image:linear-gradient(75deg,var(--el-base-primary),var(--el-base-subtle),var(--el-base-primary),var(--el-base-subtle));background-size:300% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:TextAnimation 2s linear infinite}@keyframes TextAnimation{0%{background-position:0 0}to{background-position:100% 0}}.\\!terms h6,.terms h6{font-size:12px;line-height:16px;font-weight:500;color:var(--el-base-primary)}.\\!terms h5,.terms h5{font-size:14px;line-height:20px;font-weight:500;color:var(--el-base-primary)}.\\!terms h4,.terms h4{font-size:16px;line-height:24px;font-weight:500;color:var(--el-base-primary)}.\\!terms h3,.terms h3{font-size:18px;line-height:26px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:20px;line-height:28px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:24px;line-height:30px;font-weight:500;color:var(--el-base-primary)}.\\[field-sizing\\:content\\]{field-sizing:content}.\\[line-height\\:var\\(--el-overlay-padding\\)\\]{line-height:var(--el-overlay-padding)}.\\[overflow-wrap\\:break-word\\]{overflow-wrap:break-word}.dev-host,:host{pointer-events:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1000;font-size:16px;line-height:24px;color:var(--el-base-primary);font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;scrollbar-color:#e5e7eb transparent}.placeholder\\:text-base-subtle::-moz-placeholder{color:var(--el-base-subtle)}.placeholder\\:text-base-subtle::placeholder{color:var(--el-base-subtle)}.hover\\:border-accent-hover:hover{border-color:var(--el-accent-hover)}.hover\\:bg-accent-hover:hover{background-color:var(--el-accent-hover)}.hover\\:bg-base-hover:hover{background-color:var(--el-base-hover)}.hover\\:opacity-50:hover{opacity:.5}.focus-visible\\:underline-offset-2:focus-visible{text-underline-offset:2px}.focus-visible\\:opacity-100:focus-visible{opacity:1}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.active\\:border-accent-active:active{border-color:var(--el-accent-active)}.active\\:bg-accent-active:active{background-color:var(--el-accent-active)}.active\\:bg-base-active:active{background-color:var(--el-base-active)}.data-hidden\\:-translate-y-4[data-shown=false]{--tw-translate-y: -16px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:translate-y-2[data-shown=false]{--tw-translate-y: 8px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-100[data-shown=false]{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-75[data-shown=false]{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-90[data-shown=false]{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:opacity-0[data-shown=false]{opacity:0}.data-\\[highlighted\\]\\:bg-base-active[data-highlighted]{background-color:var(--el-base-active)}',ph=["tiny","compact","full"];function nb(t){return ph.includes(t)?t:ph[0]}const ib=["top-left","top","top-right","bottom-left","bottom","bottom-right"];function rb(t){return ib.includes(t)?t:"bottom-right"}const mh={main_label:"Need help?",start_call:"Start a call",start_chat:"Start a chat",send_message:"Send",new_call:"New call",end_call:"End",mute_microphone:"Mute microphone",change_language:"Change language",collapse:"Collapse",expand:"Expand",copied:"Copied!",accept_terms:"Accept",dismiss_terms:"Cancel",listening_status:"Listening",speaking_status:"Talk to interrupt",connecting_status:"Connecting",chatting_status:"Chatting with AI Agent",input_label:"Text message input",input_placeholder:"Send a message",input_placeholder_text_only:"Send a message",input_placeholder_new_conversation:"Start a new conversation",user_ended_conversation:"You ended the conversation",agent_ended_conversation:"The agent ended the conversation",conversation_id:"ID",error_occurred:"An error occurred",copy_id:"Copy ID"},sb=Object.keys(mh),gh={base:"#ffffff",base_hover:"#f9fafb",base_active:"#f3f4f6",base_border:"#e5e7eb",base_subtle:"#6b7280",base_primary:"#000000",base_error:"#ef4444",accent:"#000000",accent_hover:"#1f2937",accent_active:"#374151",accent_border:"#4b5563",accent_subtle:"#6b7280",accent_primary:"#ffffff",overlay_padding:32,button_radius:18,input_radius:10,bubble_radius:15,sheet_radius:"calc(var(--el-button-radius) + 6px)",compact_sheet_radius:"calc(var(--el-button-radius) + 12px)",dropdown_sheet_radius:"calc(var(--el-input-radius) + 6px)"},ob=Object.keys(gh);function ab(t="us"){switch(t){case"eu-residency":case"in-residency":case"us":case"global":return t;default:return console.warn(`[ConversationalAI] Invalid server-location: ${t}. Defaulting to "us"`),"us"}}function ft(t){const e=tn(t);if(e==null)throw new Error(`${t.displayName} cannot be used outside of provider`);return e}const vh=Ae(null);function cb({value:t,children:e}){const n=ce(()=>Object.fromEntries(da.map(i=>[i,Ge(t[i])])),[]);return da.forEach(i=>{n[i].value=t[i]}),b(vh.Provider,{value:n,children:e})}function lb(){return ft(vh)}function re(t){return lb()[t]}const bh=Ae(null);function db({children:t}){const e=re("server-location"),n=ce(()=>{const i=Ke(()=>ab(e.value)),r={us:"https://api.us.elevenlabs.io","eu-residency":"https://api.eu.residency.elevenlabs.io","in-residency":"https://api.in.residency.elevenlabs.io",global:"https://api.elevenlabs.io"},s={us:"wss://api.us.elevenlabs.io","eu-residency":"wss://api.eu.residency.elevenlabs.io","in-residency":"wss://api.in.residency.elevenlabs.io",global:"wss://api.elevenlabs.io"};return{location:i,serverUrl:Ke(()=>r[i.value]),webSocketUrl:Ke(()=>s[i.value])}},[]);return b(bh.Provider,{value:n,children:t})}function yh(){return ft(bh)}const ji={en:{name:"English",flagCode:"us",languageCode:"en"},zh:{name:"中文",flagCode:"cn",languageCode:"zh"},es:{name:"Español",flagCode:"es",languageCode:"es"},hi:{name:"हिन्दी",flagCode:"in",languageCode:"hi"},pt:{name:"Português (Portugal)",flagCode:"pt",languageCode:"pt"},"pt-br":{name:"Português (Brasil)",flagCode:"br",languageCode:"pt-br"},fr:{name:"Français",flagCode:"fr",languageCode:"fr"},de:{name:"Deutsch",flagCode:"de",languageCode:"de"},ja:{name:"日本語",flagCode:"jp",languageCode:"ja"},ar:{name:"العربية",flagCode:"ae",languageCode:"ar"},ru:{name:"Русский",flagCode:"ru",languageCode:"ru"},ko:{name:"한국어",flagCode:"kr",languageCode:"ko"},id:{name:"Bahasa Indonesia",flagCode:"id",languageCode:"id"},it:{name:"Italiano",flagCode:"it",languageCode:"it"},nl:{name:"Nederlands",flagCode:"nl",languageCode:"nl"},tr:{name:"Türkçe",flagCode:"tr",languageCode:"tr"},pl:{name:"Polski",flagCode:"pl",languageCode:"pl"},sv:{name:"Svenska",flagCode:"se",languageCode:"sv"},ms:{name:"Bahasa Melayu",flagCode:"my",languageCode:"ms"},ro:{name:"Română",flagCode:"ro",languageCode:"ro"},uk:{name:"Українська",flagCode:"ua",languageCode:"uk"},el:{name:"Ελληνικά",flagCode:"gr",languageCode:"el"},cs:{name:"Čeština",flagCode:"cz",languageCode:"cs"},da:{name:"Dansk",flagCode:"dk",languageCode:"da"},fi:{name:"Suomi",flagCode:"fi",languageCode:"fi"},bg:{name:"Български",flagCode:"bg",languageCode:"bg"},hr:{name:"Hrvatski",flagCode:"hr",languageCode:"hr"},sk:{name:"Slovenčina",flagCode:"sk",languageCode:"sk"},ta:{name:"தமிழ்",flagCode:"in",languageCode:"ta"},hu:{name:"Magyar",flagCode:"hu",languageCode:"hu"},no:{name:"Norsk",flagCode:"no",languageCode:"no"},vi:{name:"Tiếng Việt",flagCode:"vn",languageCode:"vi"},tl:{name:"Filipino",flagCode:"ph",languageCode:"tl"}};function ua(t){return Object.keys(ji).includes(t??"")}const kh=Ae(null);function ub({children:t}){const e=Oe(),n=re("language"),i=re("override-language"),r=Je(n.peek()??e.peek().language),s=de(()=>(e.value.supported_language_overrides??[]).filter(ua)),o=de(()=>s.value.map(c=>ji[c]).sort((c,l)=>c.name.localeCompare(l.name))),a=ce(()=>({language:Ke(()=>ua(i.value)?ji[i.value]:ua(r.value)&&s.value.includes(r.value)?ji[r.value]:ji[e.value.language]),setLanguage:c=>{r.value=c},options:o,showPicker:Ke(()=>o.value.length>0)}),[]);return b(kh.Provider,{value:a,children:t})}function ri(){return ft(kh)}const hb="0.3.0",Ch=Ae(null);function fb({children:t}){const e=Oe(),n=de(()=>e.value.mic_muting_enabled??!1),i=Je(!1),r=ce(()=>({isMuted:Ke(()=>n.value?i.value:!1),setIsMuted:s=>{i.value=s},isMutingEnabled:n}),[]);return b(Ch.Provider,{value:r,children:t})}function _h(){return ft(Ch)}const wh=Ae(null);function pb({children:t}){const{language:e}=ri(),n=re("override-prompt"),i=re("override-first-message"),r=re("override-voice-id"),s=re("override-text-only"),o=re("user-id"),a=de(()=>({agent:{prompt:{prompt:n.value},firstMessage:i.value,language:e.value.languageCode},tts:{voiceId:r.value},conversation:{textOnly:mn(s.value)??void 0}})),c=re("dynamic-variables"),l=de(()=>{if(c.value)try{return JSON.parse(c.value)}catch(m){console.error(`[ConversationalAI] Cannot parse dynamic-variables: ${m==null?void 0:m.message}`)}}),{webSocketUrl:d}=yh(),u=re("agent-id"),h=re("signed-url"),p=ha(),g=Cb(),f=de(()=>{const m=g.value,v={dynamicVariables:l.value,overrides:a.value,connectionDelay:{default:300},textOnly:p.value,userId:o.value||void 0};return u.value?m?{agentId:u.value,origin:d.value,connectionType:"webrtc",...v}:{agentId:u.value,origin:d.value,connectionType:"websocket",...v}:h.value?{signedUrl:h.value,connectionType:"websocket",...v}:(console.error("[ConversationalAI] Either agent-id or signed-url is required"),null)});return f.value?b(wh.Provider,{value:f,children:t}):null}function mb(){return ft(wh)}const Sh=Ae(null);function gb({children:t}){const e=Oe(),n=ce(()=>{const i=e.peek().terms_key,r=i?!!localStorage.getItem(i):!1,s=Ge(!1),o=Ge(r),a=Ke(()=>!e.value.terms_html||o.value);let c=[];return{termsShown:s,termsAccepted:a,dismissTerms:()=>{s.value=!1,c.forEach(l=>l.reject()),c=[]},acceptTerms:()=>{o.value=!0,s.value=!1;const l=e.peek().terms_key;l&&localStorage.setItem(l,"true"),c.forEach(d=>d.resolve()),c=[]},requestTerms:async()=>{a.peek()||(s.value=!0,await new Promise((l,d)=>{c.push({resolve:l,reject:d})}))}}},[]);return b(Sh.Provider,{value:n,children:t})}function $r(){return ft(Sh)}const Th=Ae(null);function vb({children:t}){const e=bb();return Bt(()=>{if(e.conversationTextOnly.value===!0){e.transcript.value;const n=setTimeout(()=>{e.endSession()},600*1e3);return()=>{clearTimeout(n)}}}),b(Th.Provider,{value:e,children:t})}function ze(){return ft(Th)}function bb(){const t=B(null),e=B(null),n=Oe(),i=Eh(),r=$r(),s=mb(),{isMuted:o}=_h();return Bt(()=>{var a;const c=o.value;(a=t==null?void 0:t.current)==null||a.setMicMuted(c)}),H(()=>()=>{var a;(a=t.current)==null||a.endSession()},[]),ce(()=>{const a=Ge("disconnected"),c=Ke(()=>a.value==="disconnected"),l=Ge("listening"),d=Ke(()=>l.value==="speaking"),u=Ge(null),h=Ge(null),p=Ge(!1),g=Ge([]),f=Ge(0),m=Ge(null);return{status:a,isSpeaking:d,mode:l,isDisconnected:c,lastId:h,error:u,canSendFeedback:p,conversationIndex:f,conversationTextOnly:m,transcript:g,startSession:async(v,y)=>{var _,k,w,S,x,I,O;if(await r.requestTerms(),(_=t.current)!=null&&_.isOpen())return t.current.getId();if(e.current)return(await e.current).getId();let R=structuredClone(s.peek());y&&n.value.supports_text_only&&(R.textOnly=!0,n.value.text_only||(R.overrides??(R.overrides={}),(k=R.overrides).conversation??(k.conversation={}),R.overrides.conversation.textOnly=!0));try{R=yb(v,R)}catch(A){console.error("[ConversationalAI] Error triggering call event:",A)}m.value=R.textOnly??!1,g.value=y?[{type:"message",role:"user",message:y,isText:!0,conversationIndex:f.peek()}]:[];try{if(e.current=Q0.startSession({...R,overrides:{...R.overrides,client:{...(w=R.overrides)==null?void 0:w.client,source:((x=(S=R.overrides)==null?void 0:S.client)==null?void 0:x.source)||"widget",version:((O=(I=R.overrides)==null?void 0:I.client)==null?void 0:O.version)||hb}},onModeChange:M=>{l.value=M.mode},onStatusChange:M=>{a.value=M.status},onCanSendFeedbackChange:M=>{p.value=M.canSendFeedback},onMessage:({source:M,message:q})=>{m.peek()===!0&&M==="ai"&&q===i.peek()||(g.value=[...g.value,{type:"message",role:M,message:q,isText:!1,conversationIndex:f.peek()}])},onDisconnect:M=>{m.value=null,g.value=[...g.value,M.reason==="error"?{type:"error",message:M.message,conversationIndex:f.peek()}:{type:"disconnection",role:M.reason==="user"?"user":"ai",conversationIndex:f.peek()}],f.value++,M.reason==="error"&&(u.value=M.message,console.error("[ConversationalAI] Disconnected due to an error:",M.message))}}),t.current=await e.current,t.current.setMicMuted(o.peek()),y){const M=t.current;setTimeout(()=>M.sendUserMessage(y),100)}const A=t.current.getId();return h.value=A,u.value=null,A}catch(A){let M="Could not start a conversation.";A instanceof CloseEvent?M=A.reason||M:A instanceof Error&&(M=A.message||M),u.value=M,g.value=[...g.value,{type:"error",message:M,conversationIndex:f.peek()}]}finally{e.current=null}},endSession:async()=>{const v=t.current;t.current=null,await(v==null?void 0:v.endSession())},getInputVolume:()=>{var v;return((v=t.current)==null?void 0:v.getInputVolume())??0},getOutputVolume:()=>{var v;return((v=t.current)==null?void 0:v.getOutputVolume())??0},sendFeedback:v=>{var y;(y=t.current)==null||y.sendFeedback(v)},sendUserMessage:v=>{var y;(y=t.current)==null||y.sendUserMessage(v),g.value=[...g.value,{type:"message",role:"user",message:v,isText:!0,conversationIndex:f.peek()}]},sendUserActivity:()=>{var v;(v=t.current)==null||v.sendUserActivity()}}},[s,o])}function yb(t,e){try{const n=new CustomEvent("elevenlabs-convai:call",{bubbles:!0,composed:!0,detail:{config:e}});return t.dispatchEvent(n),n.detail.config}catch(n){return console.error("[ConversationalAI] Could not trigger call event:",n),e}}const xh=Ae(null);function kb({children:t}){const{serverUrl:e}=yh(),n=re("agent-id"),i=re("override-config"),r=re("signed-url"),s=Je(null);Bt(()=>{if(i.value)try{const _=JSON.parse(i.value);if(_){s.value=_;return}}catch(_){console.error(`[ConversationalAI] Cannot parse override-config: ${_==null?void 0:_.message}`)}let m=n.value,v;if(r.value){const _=new URL(r.value).searchParams;m=_.get("agent_id")??n.value,v=_.get("conversation_signature")??void 0}if(!m){s.value=null;return}const y=new AbortController;return _b(m,e.value,y.signal,v).then(_=>{y.signal.aborted||(s.value=_)}).catch(_=>{console.error(`[ConversationalAI] Cannot fetch config for agent ${n.value}: ${_==null?void 0:_.message}`),y.signal.aborted||(s.value=null)}),()=>{y.abort()}});const o=re("variant"),a=re("placement"),c=re("terms-key"),l=re("mic-muting"),d=re("transcript"),u=re("text-input"),h=re("default-expanded"),p=re("always-expanded"),g=re("override-text-only"),f=de(()=>{if(!s.value)return null;const m=o.value??s.value.variant,v=a.value??s.value.placement,y=c.value??s.value.terms_key,_=mn(g.value)??s.value.text_only??!1,k=mn(l.value)??s.value.mic_muting_enabled,w=mn(d.value)??s.value.transcript_enabled,S=mn(u.value)??s.value.text_input_enabled,x=mn(p.value)??s.value.always_expanded??!1,I=mn(h.value)??s.value.default_expanded??!1;return{...s.value,variant:nb(m),placement:rb(v),terms_key:y,mic_muting_enabled:!_&&k,transcript_enabled:_||w,text_input_enabled:_||S,always_expanded:x,default_expanded:I}});return f.value?b(xh.Provider,{value:f,children:t}):null}function Oe(){return ft(xh)}function ha(){const t=re("override-text-only"),e=Oe();return de(()=>mn(t.value)??e.value.text_only??!1)}function zr(){const t=ha(),{conversationTextOnly:e}=ze();return de(()=>e.value??t.value)}function Eh(){const t=re("override-first-message"),e=Oe(),{language:n}=ri();return de(()=>{var i,r;return t.value??((r=(i=e.value.language_presets)==null?void 0:i[n.value.languageCode])==null?void 0:r.first_message)??e.value.first_message??null})}function Cb(){const t=Oe();return de(()=>t.value.use_rtc??!1)}async function _b(t,e,n,i){const r=await(await fetch(`${e}/v1/convai/agents/${t}/widget${i?`?conversation_signature=${encodeURIComponent(i)}`:""}`,{signal:n})).json();if(!r.widget_config)throw new Error("Response does not contain widget_config");return r.widget_config}const wb=tr(function(){const t=Oe(),e=de(()=>{const n=t.value.styles;return`:host, :root {
245
- ${ob.map(i=>`${Sb(i)}: ${Tb((n==null?void 0:n[i])??gh[i])};`).join(`
253
+ registerProcessor("audioConcatProcessor", AudioConcatProcessor);
254
+ `);class $r{static async create({sampleRate:e,format:n,outputDeviceId:i,workletPaths:r}){let s=null,o=null;try{s=new AudioContext({sampleRate:e});const l=s.createAnalyser(),d=s.createGain();o=new Audio,o.src="",o.load(),o.autoplay=!0,o.style.display="none",document.body.appendChild(o);const u=s.createMediaStreamDestination();o.srcObject=u.stream,d.connect(l),l.connect(u),await cb(s.audioWorklet,r==null?void 0:r.audioConcatProcessor);const h=new AudioWorkletNode(s,"audioConcatProcessor");return h.port.postMessage({type:"setFormat",format:n}),h.connect(d),await s.resume(),i&&o.setSinkId&&await o.setSinkId(i),new $r(s,l,d,h,o)}catch(l){var a,c;throw(a=o)!=null&&a.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),s&&s.state!=="closed"&&await s.close(),l}}constructor(e,n,i,r,s){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=n,this.gain=i,this.worklet=r,this.audioElement=s}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(e||"")}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class la extends Fi{static async startSession(e){var n;const i=Fi.getFullOptions(e);i.onStatusChange&&i.onStatusChange({status:"connecting"}),i.onCanSendFeedbackChange&&i.onCanSendFeedbackChange({canSendFeedback:!1});let r=null,s=null,o=null,a=null,c=null;if((n=e.useWakeLock)==null||n)try{c=await navigator.wakeLock.request("screen")}catch{}try{var l;return a=await navigator.mediaDevices.getUserMedia({audio:!0}),await ph(i.connectionDelay),s=await hh(e),[r,o]=await Promise.all([qr.create(Yt({},s.inputFormat,{preferHeadphonesForIosDevices:e.preferHeadphonesForIosDevices,inputDeviceId:e.inputDeviceId,workletPaths:e.workletPaths,libsampleratePath:e.libsampleratePath})),$r.create(Yt({},s.outputFormat,{outputDeviceId:e.outputDeviceId,workletPaths:e.workletPaths}))]),(l=a)==null||l.getTracks().forEach(p=>{p.stop()}),a=null,new la(i,s,r,o,c)}catch(p){var d,u,h,f;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),(d=a)==null||d.getTracks().forEach(g=>{g.stop()}),(u=s)==null||u.close(),await((h=r)==null?void 0:h.close()),await((f=o)==null?void 0:f.close());try{var v;await((v=c)==null?void 0:v.release()),c=null}catch{}throw p}}constructor(e,n,i,r,s){super(e,n),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=o=>{this.status==="connected"&&this.connection.sendMessage({user_audio_chunk:lh(o.data[0].buffer)})},this.onOutputWorkletMessage=({data:o})=>{o.type==="process"&&this.updateMode(o.finished?"listening":"speaking")},this.addAudioBase64Chunk=o=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:ab(o)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},this.calculateVolume=o=>{if(o.length===0)return 0;let a=0;for(let c=0;c<o.length;c++)a+=o[c]/255;return a/=o.length,a<0?0:a>1?1:a},this.setVolume=({volume:o})=>{const a=Number.isFinite(o)?Math.min(1,Math.max(0,o)):1;this.volume=a,this.connection instanceof Xt?this.connection.setAudioVolume(a):this.output.gain.gain.value=a},this.input=i,this.output=r,this.wakeLock=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{var e;await((e=this.wakeLock)==null?void 0:e.release()),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var n,i;this.lastInterruptTimestamp<=e.audio_event.event_id&&((n=(i=this.options).onAudio)==null||n.call(i,e.audio_event.audio_base_64),this.connection instanceof Xt||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(e){this.connection instanceof Xt?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData!=null||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Xt?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:n,preferHeadphonesForIosDevices:i,inputDeviceId:r}){try{if(this.connection instanceof Bi)try{return await this.input.setInputDevice(r),this.input}catch(o){console.warn("Failed to change device on existing input, recreating:",o)}this.connection instanceof Xt&&await this.connection.setAudioInputDevice(r||""),await this.input.close();const s=await qr.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:n??this.connection.inputFormat.format,preferHeadphonesForIosDevices:i,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath});return this.input=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(s){throw console.error("Error changing input device",s),s}}async changeOutputDevice({sampleRate:e,format:n,outputDeviceId:i}){try{if(this.connection instanceof Bi)try{return await this.output.setOutputDevice(i),this.output}catch(s){console.warn("Failed to change device on existing output, recreating:",s)}this.connection instanceof Xt&&await this.connection.setAudioOutputDevice(i||""),await this.output.close();const r=await $r.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:n??this.connection.outputFormat.format,outputDeviceId:i,workletPaths:this.options.workletPaths});return this.output=r,this.output}catch(r){throw console.error("Error changing output device",r),r}}}function gh(t,e,n="https://api.elevenlabs.io"){const i={};return typeof e=="boolean"?i.feedback=e?"like":"dislike":(i.rating=e.rating,i.comment=e.comment),fetch(`${n}/v1/convai/conversations/${t}/feedback`,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json"}})}var vh;(function(t){t.SESSION_STARTED="session_started",t.PARTIAL_TRANSCRIPT="partial_transcript",t.FINAL_TRANSCRIPT="final_transcript",t.FINAL_TRANSCRIPT_WITH_TIMESTAMPS="final_transcript_with_timestamps",t.AUTH_ERROR="auth_error",t.ERROR="error",t.OPEN="open",t.CLOSE="close"})(vh||(vh={}));var bh,yh;(function(t){t.PCM_8000="pcm_8000",t.PCM_16000="pcm_16000",t.PCM_22050="pcm_22050",t.PCM_24000="pcm_24000",t.PCM_44100="pcm_44100",t.PCM_48000="pcm_48000",t.ULAW_8000="ulaw_8000"})(bh||(bh={})),(function(t){t.MANUAL="manual",t.VAD="vad"})(yh||(yh={}));class lb extends Fi{static startSession(e){return e.textOnly?ca.startSession(e):la.startSession(e)}}function kh(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var r=t.length;for(e=0;e<r;e++)t[e]&&(n=kh(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function ae(){for(var t,e,n=0,i="",r=arguments.length;n<r;n++)(t=arguments[n])&&(e=kh(t))&&(i&&(i+=" "),i+=e);return i}var db=Object.defineProperty,ub=(t,e,n)=>e in t?db(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ge=(t,e,n)=>ub(t,typeof e!="symbol"?e+"":e,n);function Qt(t){return t?t==="true"?!0:t==="false"?!1:null:null}const da=["variant","placement","override-config","avatar-image-url","avatar-orb-color-1","avatar-orb-color-2","agent-id","signed-url","terms-key","server-location","language","dynamic-variables","show-avatar-when-collapsed","override-prompt","override-first-message","override-language","override-voice-id","override-text-only","mic-muting","transcript","text-input","text-contents","default-expanded","always-expanded","user-id","use-rtc","collect-feedback"],hb='@import"https://fonts.googleapis.com/css2?family=Inter:wght@400,500&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:currentColor}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\\!container{width:100%!important}.container{width:100%}@media (min-width: 640px){.\\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width: 768px){.\\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width: 1024px){.\\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width: 1280px){.\\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width: 1536px){.\\!container{max-width:1536px!important}.container{max-width:1536px}}.pointer-events-auto{pointer-events:auto}.\\!visible{visibility:visible!important}.visible{visibility:visible}.collapse{visibility:collapse}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-3{bottom:-12px}.bottom-0{bottom:0}.bottom-1{bottom:4px}.bottom-20{bottom:80px}.left-0{left:0}.left-1\\/2{left:50%}.left-4{left:16px}.right-0{right:0}.right-1{right:4px}.top-0{top:0}.top-1\\/2{top:50%}.top-20{top:80px}.top-4{top:16px}.top-\\[88px\\]{top:88px}.z-1{z-index:1}.z-10{z-index:10}.m-1{margin:4px}.-mx-0\\.5{margin-left:-2px;margin-right:-2px}.mx-1{margin-left:4px;margin-right:4px}.-mr-1\\.5{margin-right:-6px}.mb-4{margin-bottom:16px}.ml-auto{margin-left:auto}.mt-2{margin-top:8px}.mt-3{margin-top:12px}.block{display:block}.inline{display:inline}.\\!flex{display:flex!important}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.contents{display:contents}.hidden{display:none}.\\!h-8{height:32px!important}.h-11{height:44px}.h-4{height:16px}.h-48{height:192px}.h-5{height:20px}.h-6{height:24px}.h-7{height:28px}.h-8{height:32px}.h-9{height:36px}.h-\\[calc\\(100\\%-80px\\)\\]{height:calc(100% - 80px)}.h-full{height:100%}.h-screen{height:100vh}.max-h-\\[550px\\]{max-height:550px}.max-h-\\[8lh\\]{max-height:8lh}.max-h-\\[min\\(384px\\,var\\(--radix-select-content-available-height\\)\\)\\]{max-height:min(384px,var(--radix-select-content-available-height))}.min-h-0{min-height:0px}.min-h-\\[6lh\\]{min-height:6lh}.min-h-full{min-height:100%}.min-h-min{min-height:-moz-min-content;min-height:min-content}.\\!w-8{width:32px!important}.w-20{width:80px}.w-4{width:16px}.w-48{width:192px}.w-5{width:20px}.w-6{width:24px}.w-64{width:256px}.w-7{width:28px}.w-8{width:32px}.w-9{width:36px}.w-full{width:100%}.w-screen{width:100vw}.\\!min-w-60{min-width:240px!important}.min-w-0{min-width:0px}.min-w-60{min-width:240px}.min-w-9{min-width:36px}.min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.min-w-max{min-width:-moz-max-content;min-width:max-content}.min-w-min{min-width:-moz-min-content;min-width:min-content}.max-w-64{max-width:256px}.max-w-\\[400px\\]{max-width:400px}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-bottom{transform-origin:bottom}.origin-bottom-left{transform-origin:bottom left}.origin-bottom-right{transform-origin:bottom right}.origin-top{transform-origin:top}.origin-top-left{transform-origin:top left}.origin-top-right{transform-origin:top right}.-translate-x-1\\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(calc(var(--el-overlay-padding)) * -1);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-1\\/2{--tw-translate-y: 50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\\[calc\\(var\\(--el-overlay-padding\\)\\)\\]{--tw-translate-y: calc(var(--el-overlay-padding));transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-full{--tw-translate-y: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-180{--tw-rotate: -180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-150{--tw-scale-x: 1.5;--tw-scale-y: 1.5;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-75{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-90{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\\[0\\.1667\\]{--tw-scale-x: .1667;--tw-scale-y: .1667;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.place-content-center{place-content:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.gap-1{gap:4px}.gap-2{gap:8px}.gap-2\\.5{gap:10px}.gap-3{gap:12px}.gap-8{gap:32px}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-all{word-break:break-all}.rounded-\\[calc\\(var\\(--el-button-radius\\)\\+4px\\)\\]{border-radius:calc(var(--el-button-radius) + 4px)}.rounded-bubble{border-radius:var(--el-bubble-radius)}.rounded-button{border-radius:var(--el-button-radius)}.rounded-compact-sheet{border-radius:var(--el-compact-sheet-radius)}.rounded-dropdown-sheet{border-radius:var(--el-dropdown-sheet-radius)}.rounded-full{border-radius:9999px}.rounded-input{border-radius:var(--el-input-radius)}.rounded-sheet{border-radius:var(--el-sheet-radius)}.border{border-width:1px}.border-accent{border-color:var(--el-accent)}.border-base{border-color:var(--el-base)}.border-base-border{border-color:var(--el-base-border)}.bg-accent{background-color:var(--el-accent)}.bg-base{background-color:var(--el-base)}.bg-base-active{background-color:var(--el-base-active)}.bg-base-border{background-color:var(--el-base-border)}.bg-base-hover{background-color:var(--el-base-hover)}.bg-cover{background-size:cover}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:4px}.p-1\\.5{padding:6px}.p-2{padding:8px}.p-3{padding:12px}.p-4{padding:16px}.px-1{padding-left:4px;padding-right:4px}.px-1\\.5{padding-left:6px;padding-right:6px}.px-2{padding-left:8px;padding-right:8px}.px-2\\.5{padding-left:10px;padding-right:10px}.px-3{padding-left:12px;padding-right:12px}.px-4{padding-left:16px;padding-right:16px}.px-8{padding-left:32px;padding-right:32px}.py-1\\.5{padding-top:6px;padding-bottom:6px}.py-2\\.5{padding-top:10px;padding-bottom:10px}.py-4{padding-top:16px;padding-bottom:16px}.py-\\[calc\\(theme\\(spacing\\.2\\)-1px\\)\\]{padding-top:7px;padding-bottom:7px}.pb-1{padding-bottom:4px}.pb-2{padding-bottom:8px}.pb-3{padding-bottom:12px}.pl-16{padding-left:64px}.pr-16{padding-right:64px}.pr-3{padding-right:12px}.pr-9{padding-right:36px}.pt-1{padding-top:4px}.pt-3{padding-top:12px}.pt-4{padding-top:16px}.text-center{text-align:center}.text-\\[10px\\]{font-size:10px}.text-lg{font-size:18px;line-height:26px}.text-md{font-size:16px;line-height:24px}.text-sm{font-size:14px;line-height:20px}.text-xl{font-size:20px;line-height:28px}.text-xs{font-size:12px;line-height:16px}.font-medium{font-weight:500}.text-accent-primary{color:var(--el-accent-primary)}.text-base-border{color:var(--el-base-border)}.text-base-error{color:var(--el-base-error)}.text-base-primary{color:var(--el-base-primary)}.text-base-subtle{color:var(--el-base-subtle)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-30{opacity:.3}.shadow-header{--tw-shadow: 0 0 1px 0 rgba(0, 0, 0, .4), 0 2px 2px 0 rgba(0, 0, 0, .04);--tw-shadow-colored: 0 0 1px 0 var(--tw-shadow-color), 0 2px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 2px 40px 1px rgba(0, 0, 0, .12);--tw-shadow-colored: 0 2px 40px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 2px 24px 1px rgba(0, 0, 0, .16);--tw-shadow-colored: 0 2px 24px 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[border-radius\\]{transition-property:border-radius;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[margin\\]{transition-property:margin;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[opacity\\,width\\,height\\,transform\\,flex-grow\\]{transition-property:opacity,width,height,transform,flex-grow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,left\\,top\\,opacity\\,scale\\]{transition-property:transform,left,top,opacity,scale;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[transform\\,opacity\\]{transition-property:transform,opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.overlay{position:absolute;inset:var(--el-overlay-padding);right:calc(var(--el-overlay-padding) + var(--removed-body-scroll-bar-size, 0px))}.focus-ring{--tw-ring-color: var(--el-accent);--tw-ring-offset-width: 2px;--tw-ring-offset-color: var(--el-base)}.focus-ring:focus-visible{outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.animate-text{background-image:linear-gradient(75deg,var(--el-base-primary),var(--el-base-subtle),var(--el-base-primary),var(--el-base-subtle));background-size:300% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:TextAnimation 2s linear infinite}@keyframes TextAnimation{0%{background-position:0 0}to{background-position:100% 0}}.\\!terms h6,.terms h6{font-size:12px;line-height:16px;font-weight:500;color:var(--el-base-primary)}.\\!terms h5,.terms h5{font-size:14px;line-height:20px;font-weight:500;color:var(--el-base-primary)}.\\!terms h4,.terms h4{font-size:16px;line-height:24px;font-weight:500;color:var(--el-base-primary)}.\\!terms h3,.terms h3{font-size:18px;line-height:26px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:20px;line-height:28px;font-weight:500;color:var(--el-base-primary)}.\\!terms h2,.terms h2{font-size:24px;line-height:30px;font-weight:500;color:var(--el-base-primary)}.\\[field-sizing\\:content\\]{field-sizing:content}.\\[line-height\\:var\\(--el-overlay-padding\\)\\]{line-height:var(--el-overlay-padding)}.\\[overflow-wrap\\:break-word\\]{overflow-wrap:break-word}.dev-host,:host{pointer-events:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1000;font-size:16px;line-height:24px;color:var(--el-base-primary);font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;scrollbar-color:#e5e7eb transparent}.placeholder\\:text-base-subtle::-moz-placeholder{color:var(--el-base-subtle)}.placeholder\\:text-base-subtle::placeholder{color:var(--el-base-subtle)}.hover\\:border-accent-hover:hover{border-color:var(--el-accent-hover)}.hover\\:border-base-hover:hover{border-color:var(--el-base-hover)}.hover\\:bg-accent-hover:hover{background-color:var(--el-accent-hover)}.hover\\:bg-base-hover:hover{background-color:var(--el-base-hover)}.hover\\:opacity-50:hover{opacity:.5}.focus-visible\\:underline-offset-2:focus-visible{text-underline-offset:2px}.focus-visible\\:opacity-100:focus-visible{opacity:1}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.active\\:border-accent-active:active{border-color:var(--el-accent-active)}.active\\:border-base-active:active{border-color:var(--el-base-active)}.active\\:bg-accent-active:active{background-color:var(--el-accent-active)}.active\\:bg-base-active:active{background-color:var(--el-base-active)}.data-hidden\\:-translate-y-4[data-shown=false]{--tw-translate-y: -16px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:translate-x-full[data-shown=false]{--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:translate-y-2[data-shown=false]{--tw-translate-y: 8px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-100[data-shown=false]{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-75[data-shown=false]{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:scale-90[data-shown=false]{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-hidden\\:opacity-0[data-shown=false]{opacity:0}.data-\\[highlighted\\]\\:bg-base-active[data-highlighted]{background-color:var(--el-base-active)}',Ch=["tiny","compact","full"];function fb(t){return Ch.includes(t)?t:Ch[0]}const pb=["top-left","top","top-right","bottom-left","bottom","bottom-right"];function mb(t){return pb.includes(t)?t:"bottom-right"}const wh={main_label:"Need help?",start_call:"Start a call",start_chat:"Start a chat",send_message:"Send",new_call:"New call",end_call:"End",mute_microphone:"Mute microphone",change_language:"Change language",collapse:"Collapse",expand:"Expand",copied:"Copied!",accept_terms:"Accept",dismiss_terms:"Cancel",listening_status:"Listening",speaking_status:"Talk to interrupt",connecting_status:"Connecting",chatting_status:"Chatting with AI Agent",input_label:"Text message input",input_placeholder:"Send a message",input_placeholder_text_only:"Send a message",input_placeholder_new_conversation:"Start a new conversation",user_ended_conversation:"You ended the conversation",agent_ended_conversation:"The agent ended the conversation",conversation_id:"ID",error_occurred:"An error occurred",copy_id:"Copy ID",initiate_feedback:"How was this conversation?",request_follow_up_feedback:"Tell us more",thanks_for_feedback:"Thank you for your feedback!",thanks_for_feedback_details:"Your feedback helps us improve our service and better support you in the future.",follow_up_feedback_placeholder:"Tell us more about your experience...",submit:"Submit",go_back:"Go back"},gb=Object.keys(wh),_h={base:"#ffffff",base_hover:"#f9fafb",base_active:"#f3f4f6",base_border:"#e5e7eb",base_subtle:"#6b7280",base_primary:"#000000",base_error:"#ef4444",accent:"#000000",accent_hover:"#1f2937",accent_active:"#374151",accent_border:"#4b5563",accent_subtle:"#6b7280",accent_primary:"#ffffff",overlay_padding:32,button_radius:18,input_radius:10,bubble_radius:15,sheet_radius:"calc(var(--el-button-radius) + 6px)",compact_sheet_radius:"calc(var(--el-button-radius) + 12px)",dropdown_sheet_radius:"calc(var(--el-input-radius) + 6px)"},vb=Object.keys(_h);function bb(t="us"){switch(t){case"eu-residency":case"in-residency":case"us":case"global":return t;default:return console.warn(`[ConversationalAI] Invalid server-location: ${t}. Defaulting to "us"`),"us"}}function et(t){const e=sn(t);if(e==null)throw new Error(`${t.displayName} cannot be used outside of provider`);return e}const Sh=Re(null);function yb({value:t,children:e}){const n=oe(()=>Object.fromEntries(da.map(i=>[i,Je(t[i])])),[]);return da.forEach(i=>{n[i].value=t[i]}),m(Sh.Provider,{value:n,children:e})}function kb(){return et(Sh)}function ie(t){return kb()[t]}const Th=Re(null);function Cb({children:t}){const e=ie("server-location"),n=oe(()=>{const i=Ye(()=>bb(e.value)),r={us:"https://api.us.elevenlabs.io","eu-residency":"https://api.eu.residency.elevenlabs.io","in-residency":"https://api.in.residency.elevenlabs.io",global:"https://api.elevenlabs.io"},s={us:"wss://api.us.elevenlabs.io","eu-residency":"wss://api.eu.residency.elevenlabs.io","in-residency":"wss://api.in.residency.elevenlabs.io",global:"wss://api.elevenlabs.io"};return{location:i,serverUrl:Ye(()=>r[i.value]),webSocketUrl:Ye(()=>s[i.value])}},[]);return m(Th.Provider,{value:n,children:t})}function ua(){return et(Th)}const ji={en:{name:"English",flagCode:"us",languageCode:"en"},zh:{name:"中文",flagCode:"cn",languageCode:"zh"},es:{name:"Español",flagCode:"es",languageCode:"es"},hi:{name:"हिन्दी",flagCode:"in",languageCode:"hi"},pt:{name:"Português (Portugal)",flagCode:"pt",languageCode:"pt"},"pt-br":{name:"Português (Brasil)",flagCode:"br",languageCode:"pt-br"},fr:{name:"Français",flagCode:"fr",languageCode:"fr"},de:{name:"Deutsch",flagCode:"de",languageCode:"de"},ja:{name:"日本語",flagCode:"jp",languageCode:"ja"},ar:{name:"العربية",flagCode:"ae",languageCode:"ar"},ru:{name:"Русский",flagCode:"ru",languageCode:"ru"},ko:{name:"한국어",flagCode:"kr",languageCode:"ko"},id:{name:"Bahasa Indonesia",flagCode:"id",languageCode:"id"},it:{name:"Italiano",flagCode:"it",languageCode:"it"},nl:{name:"Nederlands",flagCode:"nl",languageCode:"nl"},tr:{name:"Türkçe",flagCode:"tr",languageCode:"tr"},pl:{name:"Polski",flagCode:"pl",languageCode:"pl"},sv:{name:"Svenska",flagCode:"se",languageCode:"sv"},ms:{name:"Bahasa Melayu",flagCode:"my",languageCode:"ms"},ro:{name:"Română",flagCode:"ro",languageCode:"ro"},uk:{name:"Українська",flagCode:"ua",languageCode:"uk"},el:{name:"Ελληνικά",flagCode:"gr",languageCode:"el"},cs:{name:"Čeština",flagCode:"cz",languageCode:"cs"},da:{name:"Dansk",flagCode:"dk",languageCode:"da"},fi:{name:"Suomi",flagCode:"fi",languageCode:"fi"},bg:{name:"Български",flagCode:"bg",languageCode:"bg"},hr:{name:"Hrvatski",flagCode:"hr",languageCode:"hr"},sk:{name:"Slovenčina",flagCode:"sk",languageCode:"sk"},ta:{name:"தமிழ்",flagCode:"in",languageCode:"ta"},hu:{name:"Magyar",flagCode:"hu",languageCode:"hu"},no:{name:"Norsk",flagCode:"no",languageCode:"no"},vi:{name:"Tiếng Việt",flagCode:"vn",languageCode:"vi"},tl:{name:"Filipino",flagCode:"ph",languageCode:"tl"}};function ha(t){return Object.keys(ji).includes(t??"")}const xh=Re(null);function wb({children:t}){const e=Ae(),n=ie("language"),i=ie("override-language"),r=Ie(n.peek()??e.peek().language),s=ue(()=>(e.value.supported_language_overrides??[]).filter(ha)),o=ue(()=>s.value.map(c=>ji[c]).sort((c,l)=>c.name.localeCompare(l.name))),a=oe(()=>({language:Ye(()=>ha(i.value)?ji[i.value]:ha(r.value)&&s.value.includes(r.value)?ji[r.value]:ji[e.value.language]),setLanguage:c=>{r.value=c},options:o,showPicker:Ye(()=>o.value.length>0)}),[]);return m(xh.Provider,{value:a,children:t})}function ri(){return et(xh)}const _b="0.5.0",Ph=Re(null);function Sb({children:t}){const e=Ae(),n=ue(()=>e.value.mic_muting_enabled??!1),i=Ie(!1),r=oe(()=>({isMuted:Ye(()=>n.value?i.value:!1),setIsMuted:s=>{i.value=s},isMutingEnabled:n}),[]);return m(Ph.Provider,{value:r,children:t})}function Eh(){return et(Ph)}const Rh=Re(null);function Tb({children:t}){const{language:e}=ri(),n=ie("override-prompt"),i=ie("override-first-message"),r=ie("override-voice-id"),s=ie("override-text-only"),o=ie("user-id"),a=ue(()=>({agent:{prompt:{prompt:n.value},firstMessage:i.value,language:e.value.languageCode},tts:{voiceId:r.value},conversation:{textOnly:Qt(s.value)??void 0}})),c=ie("dynamic-variables"),l=ue(()=>{if(c.value)try{return JSON.parse(c.value)}catch(g){console.error(`[ConversationalAI] Cannot parse dynamic-variables: ${g==null?void 0:g.message}`)}}),{webSocketUrl:d}=ua(),u=ie("agent-id"),h=ie("signed-url"),f=fa(),v=Ab(),p=ue(()=>{const g=v.value,b={dynamicVariables:l.value,overrides:a.value,connectionDelay:{default:300},textOnly:f.value,userId:o.value||void 0};return u.value?g?{agentId:u.value,origin:d.value,connectionType:"webrtc",...b}:{agentId:u.value,origin:d.value,connectionType:"websocket",...b}:h.value?{signedUrl:h.value,connectionType:"websocket",...b}:(console.error("[ConversationalAI] Either agent-id or signed-url is required"),null)});return p.value?m(Rh.Provider,{value:p,children:t}):null}function xb(){return et(Rh)}const Ih=Re(null);function Pb({children:t}){const e=Ae(),n=oe(()=>{const i=e.peek().terms_key,r=i?!!localStorage.getItem(i):!1,s=Je(!1),o=Je(r),a=Ye(()=>!e.value.terms_html||o.value);let c=[];return{termsShown:s,termsAccepted:a,dismissTerms:()=>{s.value=!1,c.forEach(l=>l.reject()),c=[]},acceptTerms:()=>{o.value=!0,s.value=!1;const l=e.peek().terms_key;l&&localStorage.setItem(l,"true"),c.forEach(d=>d.resolve()),c=[]},requestTerms:async()=>{a.peek()||(s.value=!0,await new Promise((l,d)=>{c.push({resolve:l,reject:d})}))}}},[]);return m(Ih.Provider,{value:n,children:t})}function zr(){return et(Ih)}const Oh=Re(null);function Eb({children:t}){const e=Rb();return Ct(()=>{if(e.conversationTextOnly.value===!0){e.transcript.value;const n=setTimeout(()=>{e.endSession()},600*1e3);return()=>{clearTimeout(n)}}}),m(Oh.Provider,{value:e,children:t})}function Be(){return et(Oh)}function Rb(){const t=B(null),e=B(null),n=B(!1),i=B(null),r=B(!1),s=Ae();Dh();const o=zr(),a=xb(),{isMuted:c}=Eh();return Ct(()=>{var l;const d=c.value;(l=t==null?void 0:t.current)==null||l.setMicMuted(d)}),G(()=>()=>{var l;(l=t.current)==null||l.endSession()},[]),oe(()=>{const l=Je("disconnected"),d=Ye(()=>l.value==="disconnected"),u=Je("listening"),h=Ye(()=>u.value==="speaking"),f=Je(null),v=Je(null),p=Je(!1),g=Je([]),b=Je(0),k=Je(null);return{status:l,isSpeaking:h,mode:u,isDisconnected:d,lastId:v,error:f,canSendFeedback:p,conversationIndex:b,conversationTextOnly:k,transcript:g,startSession:async(w,y)=>{var _,S,x,I,R,A,M;if(await o.requestTerms(),(_=t.current)!=null&&_.isOpen())return t.current.getId();if(e.current)return(await e.current).getId();let N=structuredClone(a.peek());y&&s.value.supports_text_only&&(N.textOnly=!0,s.value.text_only||(N.overrides??(N.overrides={}),(S=N.overrides).conversation??(S.conversation={}),N.overrides.conversation.textOnly=!0));try{N=Ib(w,N)}catch(q){console.error("[ConversationalAI] Error triggering call event:",q)}k.value=N.textOnly??!1,g.value=y?[{type:"message",role:"user",message:y,isText:!0,conversationIndex:b.peek()}]:[];try{if(e.current=lb.startSession({...N,overrides:{...N.overrides,client:{...(x=N.overrides)==null?void 0:x.client,source:((R=(I=N.overrides)==null?void 0:I.client)==null?void 0:R.source)||"widget",version:((M=(A=N.overrides)==null?void 0:A.client)==null?void 0:M.version)||_b}},onModeChange:F=>{u.value=F.mode},onStatusChange:F=>{l.value=F.status},onCanSendFeedbackChange:F=>{p.value=F.canSendFeedback},onMessage:({source:F,message:te})=>{if(k.peek()===!0&&F==="ai"&&!n.current){n.current=!0;return}else F==="ai"&&(n.current=!0);if(F==="ai"&&r.current){r.current=!1;return}g.value=[...g.value,{type:"message",role:F,message:te,isText:!1,conversationIndex:b.peek()}]},onAgentChatResponsePart:({text:F,type:te})=>{const H=g.peek();if(te==="start")r.current=!0,i.current=H.length,g.value=[...H,{type:"message",role:"ai",message:"",isText:!0,conversationIndex:b.peek()}];else if(te==="delta"){const J=i.current;if(J!==null&&H[J]){const W=[...H],Z=W[J];Z.type==="message"&&(W[J]={...Z,message:Z.message+F},g.value=W)}}else te==="stop"&&(i.current=null)},onDisconnect:F=>{n.current=!1,k.value=null,i.current=null,r.current=!1,g.value=[...g.value,F.reason==="error"?{type:"error",message:F.message,conversationIndex:b.peek()}:{type:"disconnection",role:F.reason==="user"?"user":"ai",conversationIndex:b.peek()}],b.value++,F.reason==="error"&&(f.value=F.message,console.error("[ConversationalAI] Disconnected due to an error:",F.message))}}),t.current=await e.current,t.current.setMicMuted(c.peek()),y){const F=t.current;setTimeout(()=>F.sendUserMessage(y),100)}const q=t.current.getId();return v.value=q,f.value=null,q}catch(q){let F="Could not start a conversation.";q instanceof CloseEvent?F=q.reason||F:q instanceof Error&&(F=q.message||F),f.value=F,g.value=[...g.value,{type:"error",message:F,conversationIndex:b.peek()}]}finally{e.current=null}},endSession:async()=>{const w=t.current;t.current=null,await(w==null?void 0:w.endSession())},getInputVolume:()=>{var w;return((w=t.current)==null?void 0:w.getInputVolume())??0},getOutputVolume:()=>{var w;return((w=t.current)==null?void 0:w.getOutputVolume())??0},sendFeedback:w=>{var y;(y=t.current)==null||y.sendFeedback(w)},sendUserMessage:w=>{var y;(y=t.current)==null||y.sendUserMessage(w),g.value=[...g.value,{type:"message",role:"user",message:w,isText:!0,conversationIndex:b.peek()}]},sendUserActivity:()=>{var w;(w=t.current)==null||w.sendUserActivity()}}},[a,c])}function Ib(t,e){try{const n=new CustomEvent("elevenlabs-convai:call",{bubbles:!0,composed:!0,detail:{config:e}});return t.dispatchEvent(n),n.detail.config}catch(n){return console.error("[ConversationalAI] Could not trigger call event:",n),e}}const Ah=Re(null);function Ob({children:t}){const{serverUrl:e}=ua(),n=ie("agent-id"),i=ie("override-config"),r=ie("signed-url"),s=Ie(null);Ct(()=>{if(i.value)try{const y=JSON.parse(i.value);if(y){s.value=y;return}}catch(y){console.error(`[ConversationalAI] Cannot parse override-config: ${y==null?void 0:y.message}`)}let b=n.value,k;if(r.value){const y=new URL(r.value).searchParams;b=y.get("agent_id")??n.value,k=y.get("conversation_signature")??void 0}if(!b){s.value=null;return}const w=new AbortController;return Mb(b,e.value,w.signal,k).then(y=>{w.signal.aborted||(s.value=y)}).catch(y=>{console.error(`[ConversationalAI] Cannot fetch config for agent ${n.value}: ${y==null?void 0:y.message}`),w.signal.aborted||(s.value=null)}),()=>{w.abort()}});const o=ie("variant"),a=ie("placement"),c=ie("terms-key"),l=ie("mic-muting"),d=ie("transcript"),u=ie("text-input"),h=ie("default-expanded"),f=ie("always-expanded"),v=ie("override-text-only"),p=ie("use-rtc"),g=ue(()=>{if(!s.value)return null;const b=o.value??s.value.variant,k=a.value??s.value.placement,w=c.value??s.value.terms_key,y=Qt(v.value)??s.value.text_only??!1,_=Qt(l.value)??s.value.mic_muting_enabled,S=Qt(d.value)??s.value.transcript_enabled,x=Qt(u.value)??s.value.text_input_enabled,I=Qt(f.value)??s.value.always_expanded??!1,R=Qt(h.value)??s.value.default_expanded??!1,A=Qt(p.value)??s.value.use_rtc??!1;return{...s.value,variant:fb(b),placement:mb(k),terms_key:w,mic_muting_enabled:!y&&_,transcript_enabled:y||S,text_input_enabled:y||x,always_expanded:I,default_expanded:R,use_rtc:A}});return g.value?m(Ah.Provider,{value:g,children:t}):null}function Ae(){return et(Ah)}function fa(){const t=ie("override-text-only"),e=Ae();return ue(()=>Qt(t.value)??e.value.text_only??!1)}function Wr(){const t=fa(),{conversationTextOnly:e}=Be();return ue(()=>e.value??t.value)}function Dh(){const t=ie("override-first-message"),e=Ae(),{language:n}=ri();return ue(()=>{var i,r;return t.value??((r=(i=e.value.language_presets)==null?void 0:i[n.value.languageCode])==null?void 0:r.first_message)??e.value.first_message??null})}function Ab(){const t=Ae();return ue(()=>t.value.use_rtc??!1)}function Db(){const t=Ae();return ue(()=>t.value.end_feedback!==void 0)}async function Mb(t,e,n,i){const r=await(await fetch(`${e}/v1/convai/agents/${t}/widget${i?`?conversation_signature=${encodeURIComponent(i)}`:""}`,{signal:n})).json();if(!r.widget_config)throw new Error("Response does not contain widget_config");return r.widget_config}const Nb=tr(function(){const t=Ae(),e=ue(()=>{const n=t.value.styles;return`:host, :root {
255
+ ${vb.map(i=>`${Lb(i)}: ${Ub((n==null?void 0:n[i])??_h[i])};`).join(`
246
256
  `)}
247
- }`});return b("style",{children:[e,tb]})});function Sb(t){return`--el-${t.replace(/_/g,"-")}`}function Tb(t){return typeof t=="number"?`${t}px`:t}const Ph=Ae(null);function xb({children:t}){const e=Oe(),{language:n}=ri(),i=re("text-contents"),r=de(()=>{try{if(i.value){const o=JSON.parse(i.value);if(typeof o=="object")return o}}catch(o){console.error("[ConversationalAI] Cannot parse text-contents:",o)}return{}}),s=ce(()=>Object.fromEntries(sb.map(o=>[o,Ke(()=>{var a,c,l,d;return r.value[o]??((l=(c=(a=e.value.language_presets)==null?void 0:a[n.value.languageCode])==null?void 0:c.text_contents)==null?void 0:l[o])??((d=e.value.text_contents)==null?void 0:d[o])??mh[o]})])),[]);return b(Ph.Provider,{value:s,children:t})}function We(){return ft(Ph)}const Rh=Ae(null);function Eb({children:t}){const e=Oe(),n=re("avatar-image-url"),i=re("avatar-orb-color-1"),r=re("avatar-orb-color-2"),s=Je(""),o=de(()=>n.value?{type:"image",url:n.value}:i.value&&r.value?{type:"orb",color_1:i.value,color_2:r.value}:e.value.avatar),a=de(()=>{switch(o.value.type){case"url":return o.value.custom_url;case"orb":return s.value;case"image":return o.value.url}}),c=ce(()=>({config:o,previewUrl:a,canvasUrl:s}),[]);return b(Rh.Provider,{value:c,children:t})}function fa(){return ft(Rh)}const Ih=Ae(null);function Wr({children:t,...e}){const[n,i]=F(null);return b("div",{ref:i,...e,children:n&&b(Ih.Provider,{value:n,children:t})})}function Pb(){return ft(Ih)}function pa(t){return t&&typeof t=="object"&&"peek"in t}function Rb(t){const e=pa(t),n=Je(e?t.peek():t);return e?t:(n.value=t,n)}function Oh(t){return pa(t)?t.value:t}function Ib(t){return pa(t)?t.peek():t}function Dh(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Ah(...t){return e=>{let n=!1;const i=t.map(r=>{const s=Dh(r,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let r=0;r<i.length;r++){const s=i[r];typeof s=="function"?s():Dh(t[r],null)}}}}function Le(...t){return z(Ah(...t),t)}function Vi(t){const e=Ob(t),n=Y((i,r)=>{const{children:s,...o}=i,a=nn.toArray(s),c=a.find(Ab);if(c){const l=c.props.children,d=a.map(u=>u===c?nn.count(l)>1?nn.only(null):Ut(l)?l.props.children:null:u);return b(e,{...o,ref:r,children:Ut(l)?_i(l,void 0,d):null})}return b(e,{...o,ref:r,children:s})});return n.displayName=`${t}.Slot`,n}var Mh=Vi("Slot");function Ob(t){const e=Y((n,i)=>{const{children:r,...s}=n;if(Ut(r)){const o=Nb(r),a=Mb(s,r.props);return r.type!==ge&&(a.ref=i?Ah(i,o):o),_i(r,a)}return nn.count(r)>1?nn.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Db=Symbol("radix.slottable");function Ab(t){return Ut(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Db}function Mb(t,e){const n={...e};for(const i in e){const r=t[i],s=e[i];/^on[A-Z]/.test(i)?r&&s?n[i]=(...o)=>{const a=s(...o);return r(...o),a}:r&&(n[i]=r):i==="style"?n[i]={...r,...s}:i==="className"&&(n[i]=[r,s].filter(Boolean).join(" "))}return{...t,...n}}function Nb(t){var e,n;let i=(e=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:e.get,r=i&&"isReactWarning"in i&&i.isReactWarning;return r?t.ref:(i=(n=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:n.get,r=i&&"isReactWarning"in i&&i.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}const ma=window.matchMedia("(prefers-reduced-motion: reduce)");function Nh(){const t=Je(ma.matches);return H(()=>{const e=n=>{t.value=n.matches};return ma.addEventListener("change",e),()=>ma.removeEventListener("change",e)},[]),t}function Lh({onStart:t,onEnd:e}){const n=B();n.current??(n.current=new Set);const i=B(t);i.current=t;const r=B(e);r.current=e;const s=Je(!1),o=z(c=>{var l,d;c.target===c.currentTarget&&((l=n.current)==null||l.add(c.propertyName),s.peek()||(s.value=!0,(d=i.current)==null||d.call(i)))},[]),a=z(c=>{var l,d,u;c.target===c.currentTarget&&((l=n.current)==null||l.delete(c.propertyName),(d=n.current)!=null&&d.size||(s.value=!1,(u=r.current)==null||u.call(r)))},[]);return{transitioning:s,handlers:{onTransitionStart:o,onTransitionEnd:a}}}function it(t){const e=Nh().value?Lb:Ub;return b(e,{...t})}function Lb({active:t,...e}){return Oh(t)?b(Mh,{"data-shown":!0,...e}):null}function Ub({active:t,initial:e=t,...n}){const i=Rb(t),r=Je(Ib(e));Bt(()=>{i.value&&(r.value=i.value)});const{handlers:s}=Lh({onEnd:()=>{r.value=i.value}});return!i.value&&!r.value?null:b(Mh,{"data-shown":i.value&&r.value,...s,...n})}const Fb=`#version 300 es
257
+ }`});return m("style",{children:[e,hb]})});function Lb(t){return`--el-${t.replace(/_/g,"-")}`}function Ub(t){return typeof t=="number"?`${t}px`:t}const Mh=Re(null);function Fb({children:t}){const e=Ae(),{language:n}=ri(),i=ie("text-contents"),r=ue(()=>{try{if(i.value){const o=JSON.parse(i.value);if(typeof o=="object")return o}}catch(o){console.error("[ConversationalAI] Cannot parse text-contents:",o)}return{}}),s=oe(()=>Object.fromEntries(gb.map(o=>[o,Ye(()=>{var a,c,l,d;return r.value[o]??((l=(c=(a=e.value.language_presets)==null?void 0:a[n.value.languageCode])==null?void 0:c.text_contents)==null?void 0:l[o])??((d=e.value.text_contents)==null?void 0:d[o])??wh[o]})])),[]);return m(Mh.Provider,{value:s,children:t})}function xe(){return et(Mh)}const Nh=Re(null);function Bb({children:t}){const e=Ae(),n=ie("avatar-image-url"),i=ie("avatar-orb-color-1"),r=ie("avatar-orb-color-2"),s=Ie(""),o=ue(()=>n.value?{type:"image",url:n.value}:i.value&&r.value?{type:"orb",color_1:i.value,color_2:r.value}:e.value.avatar),a=ue(()=>{switch(o.value.type){case"url":return o.value.custom_url;case"orb":return s.value;case"image":return o.value.url}}),c=oe(()=>({config:o,previewUrl:a,canvasUrl:s}),[]);return m(Nh.Provider,{value:c,children:t})}function pa(){return et(Nh)}const Lh=Re(null);function Hr({children:t,...e}){const[n,i]=V(null);return m("div",{ref:i,...e,children:n&&m(Lh.Provider,{value:n,children:t})})}function jb(){return et(Lh)}function ma(t){return t&&typeof t=="object"&&"peek"in t}function Vb(t){const e=ma(t),n=Ie(e?t.peek():t);return e?t:(n.value=t,n)}function Uh(t){return ma(t)?t.value:t}function qb(t){return ma(t)?t.peek():t}function Fh(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Bh(...t){return e=>{let n=!1;const i=t.map(r=>{const s=Fh(r,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let r=0;r<i.length;r++){const s=i[r];typeof s=="function"?s():Fh(t[r],null)}}}}function Fe(...t){return j(Bh(...t),t)}function Vi(t){const e=$b(t),n=X((i,r)=>{const{children:s,...o}=i,a=on.toArray(s),c=a.find(Wb);if(c){const l=c.props.children,d=a.map(u=>u===c?on.count(l)>1?on.only(null):jt(l)?l.props.children:null:u);return m(e,{...o,ref:r,children:jt(l)?wi(l,void 0,d):null})}return m(e,{...o,ref:r,children:s})});return n.displayName=`${t}.Slot`,n}var jh=Vi("Slot");function $b(t){const e=X((n,i)=>{const{children:r,...s}=n;if(jt(r)){const o=Gb(r),a=Hb(s,r.props);return r.type!==ge&&(a.ref=i?Bh(i,o):o),wi(r,a)}return on.count(r)>1?on.only(null):null});return e.displayName=`${t}.SlotClone`,e}var zb=Symbol("radix.slottable");function Wb(t){return jt(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===zb}function Hb(t,e){const n={...e};for(const i in e){const r=t[i],s=e[i];/^on[A-Z]/.test(i)?r&&s?n[i]=(...o)=>{const a=s(...o);return r(...o),a}:r&&(n[i]=r):i==="style"?n[i]={...r,...s}:i==="className"&&(n[i]=[r,s].filter(Boolean).join(" "))}return{...t,...n}}function Gb(t){var e,n;let i=(e=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:e.get,r=i&&"isReactWarning"in i&&i.isReactWarning;return r?t.ref:(i=(n=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:n.get,r=i&&"isReactWarning"in i&&i.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}const ga=window.matchMedia("(prefers-reduced-motion: reduce)");function Vh(){const t=Ie(ga.matches);return G(()=>{const e=n=>{t.value=n.matches};return ga.addEventListener("change",e),()=>ga.removeEventListener("change",e)},[]),t}function qh({onStart:t,onEnd:e}){const n=B();n.current??(n.current=new Set);const i=B(t);i.current=t;const r=B(e);r.current=e;const s=Ie(!1),o=j(c=>{var l,d;c.target===c.currentTarget&&((l=n.current)==null||l.add(c.propertyName),s.peek()||(s.value=!0,(d=i.current)==null||d.call(i)))},[]),a=j(c=>{var l,d,u;c.target===c.currentTarget&&((l=n.current)==null||l.delete(c.propertyName),(d=n.current)!=null&&d.size||(s.value=!1,(u=r.current)==null||u.call(r)))},[]);return{transitioning:s,handlers:{onTransitionStart:o,onTransitionEnd:a}}}function je(t){const e=Vh().value?Kb:Jb;return m(e,{...t})}function Kb({active:t,...e}){return Uh(t)?m(jh,{"data-shown":!0,...e}):null}function Jb({active:t,initial:e=t,...n}){const i=Vb(t),r=Ie(qb(e));Ct(()=>{i.value&&(r.value=i.value)});const{handlers:s}=qh({onEnd:()=>{r.value=i.value}});return!i.value&&!r.value?null:m(jh,{"data-shown":i.value&&r.value,...s,...n})}const Yb=`#version 300 es
248
258
  precision highp float;
249
259
 
250
260
  uniform float uTime;
@@ -408,7 +418,7 @@ void main() {
408
418
 
409
419
  outColor = color;
410
420
  }
411
- `,Bb=`#version 300 es
421
+ `,Xb=`#version 300 es
412
422
  precision highp float;
413
423
 
414
424
  in vec2 position;
@@ -419,8 +429,8 @@ void main() {
419
429
  vUv = position * 0.5 + 0.5;
420
430
  gl_Position = vec4(position, 0, 1);
421
431
  }
422
- `,Uh=0,jb=new Float32Array([-1,1,-1,-1,1,1,1,-1]),Vb="https://storage.googleapis.com/eleven-public-cdn/images/perlin-noise.png",Fh=class _n{constructor(e){$e(this,"gl"),$e(this,"program"),$e(this,"startTime"),$e(this,"targetSpeed",0),$e(this,"speed",.5),$e(this,"rafId",null),$e(this,"resizeObserver"),$e(this,"colorA",[0,0,0]),$e(this,"colorB",[0,0,0]),$e(this,"offsets",new Float32Array(7).map(()=>Math.random()*Math.PI*2)),$e(this,"copyNoiseImage",()=>{this.gl&&(this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,_n.noiseImage),this.gl.generateMipmap(this.gl.TEXTURE_2D))}),$e(this,"toDataURL",()=>this.gl.canvas.toDataURL("image/png")),$e(this,"render",()=>{if(!this.gl){this.rafId=null;return}const o=(performance.now()-this.startTime)/1e3;this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uTime"),o),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.rafId=requestAnimationFrame(this.render)});const n=e.getContext("webgl2",{depth:!1,stencil:!1});this.gl=n,this.program=this.setupProgram(Fb,Bb);const i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([128,128,128,255])),_n.noiseImage||(_n.noiseImage=new Image,_n.noiseImage.crossOrigin="anonymous",_n.noiseImage.src=Vb),_n.noiseImage.complete?this.copyNoiseImage():_n.noiseImage.addEventListener("load",this.copyNoiseImage);const r=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,r),n.bufferData(n.ARRAY_BUFFER,jb,n.STATIC_DRAW),n.vertexAttribPointer(Uh,2,n.FLOAT,!1,0,0),n.enableVertexAttribArray(Uh),this.updateColors("#2792DC","#9CE6E6"),this.resizeObserver=new ResizeObserver(o=>{const a=o[0],c=a.devicePixelContentBoxSize?a.devicePixelContentBoxSize[0]:a.contentBoxSize[0];e.width=Math.min(512,c.inlineSize),e.height=Math.min(512,c.blockSize),this.updateViewport()});const s=e.parentElement;if(s)try{this.resizeObserver.observe(s,{box:"device-pixel-content-box"})}catch{this.resizeObserver.observe(s)}this.startTime=performance.now(),this.rafId=requestAnimationFrame(this.render)}dispose(){var e;this.rafId!==null&&cancelAnimationFrame(this.rafId),(e=this.resizeObserver)==null||e.disconnect(),this.gl=null,this.program=null}updateViewport(){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}updateColors(e,n){this.gl&&(this.colorA=this.updateColor("uColor1",e)??this.colorA,this.colorB=this.updateColor("uColor2",n)??this.colorB)}updateVolume(e,n){this.targetSpeed=.2+(1-Math.pow(n-1,2))*1.8,this.targetSpeed>this.speed&&(this.speed=this.targetSpeed),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uInputVolume"),e),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uOutputVolume"),n)}updateColor(e,n){try{const i=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,o=[Math.pow(i,2.2),Math.pow(r,2.2),Math.pow(s,2.2)];return this.gl.uniform3fv(this.gl.getUniformLocation(this.program,e),o),o}catch(i){console.error(`[ConversationalAI] Failed to parse ${n} as color:`,i)}}setupProgram(e,n){const i=this.getShader(this.gl.FRAGMENT_SHADER,e),r=this.getShader(this.gl.VERTEX_SHADER,n);if(!i||!r)throw new Error("Failed to compile shaders");if(this.program=this.gl.createProgram(),this.gl.attachShader(this.program,i),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),!this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS))throw new Error("Failed to link program");return this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"uPerlinTexture"),0),this.gl.uniform1fv(this.gl.getUniformLocation(this.program,"uOffsets"),this.offsets),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor1"),this.colorA),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor2"),this.colorB),this.program}getShader(e,n){const i=this.gl.createShader(e);return this.gl.shaderSource(i,n),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)?i:(this.gl.deleteShader(i),null)}};$e(Fh,"noiseImage");let qb=Fh;const $b={sm:"w-9 h-9",lg:"w-48 h-48"};function si({size:t="sm",className:e}){const{getInputVolume:n,getOutputVolume:i,isSpeaking:r,isDisconnected:s}=ze(),{config:o}=fa(),a=B(null),c=B(null);Bt(()=>{if(s.value){a.current.style.transform="",c.current.style.transform="";return}let d;function u(){const h=n(),p=i(),g=r.peek()?1:1-h*.4,f=r.peek()?1+p*.4:1;a.current.style.transform=`scale(${f})`,c.current.style.transform=`scale(${g})`,d=requestAnimationFrame(u)}return u(),()=>{cancelAnimationFrame(d)}});const l=de(()=>({backgroundImage:o.value.type==="image"?`url(${o.value.url})`:o.value.type==="url"?`url(${o.value.custom_url})`:void 0}));return b("div",{className:he("relative shrink-0",$b[t],e),children:[b("div",{ref:a,className:"absolute inset-0 rounded-full bg-base-border"}),b("div",{ref:c,style:l,className:"absolute inset-0 rounded-full overflow-hidden bg-base bg-cover",children:o.value.type==="orb"&&b(zb,{color1:o.value.color_1,color2:o.value.color_2})})]})}function zb({color1:t,color2:e}){const{canvasUrl:n}=fa(),[i,r]=F(null);H(()=>{i&&(i.updateColors(t,e),i.render(),n.value=i.toDataURL())},[i,t,e]);const s=z(o=>{if(o){const a=new qb(o);return r(a),()=>a.dispose()}else r(null)},[r]);return b("canvas",{className:"w-full h-full",ref:s})}const Wb={phone:Gb,"phone-off":Kb,chat:Jb,mic:Yb,"mic-off":Xb,check:ey,"chevron-down":Qb,"chevron-up":Zb,send:ty},Hb={sm:"text-xs",md:"text-lg"};function An({name:t,size:e="md",className:n}){const i=Wb[t];return b("slot",{name:`icon-${t}`,className:he("flex",Hb[e],n),"aria-hidden":!0,children:b(i,{})})}function Gb(t){return b("svg",{height:"1em",width:"1em",viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:b("path",{d:"M3.7489 2.25C2.93286 2.25 2.21942 2.92142 2.27338 3.7963C2.6686 10.2041 7.79483 15.3303 14.2026 15.7255C15.0775 15.7795 15.7489 15.066 15.7489 14.25V11.958C15.7489 11.2956 15.3144 10.7116 14.6799 10.5213L12.6435 9.91035C12.1149 9.75179 11.542 9.89623 11.1518 10.2864L10.5901 10.8482C9.15291 10.0389 7.95998 8.84599 7.15074 7.40881L7.71246 6.84709C8.10266 6.45689 8.24711 5.88396 8.08854 5.35541L7.47761 3.31898C7.28727 2.6845 6.70329 2.25 6.04087 2.25H3.7489Z"})})}function Kb(t){return b("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[b("path",{d:"M16.0303 3.53033C16.3232 3.23744 16.3232 2.76256 16.0303 2.46967C15.7374 2.17678 15.2626 2.17678 14.9697 2.46967L8.6271 8.81224C8.25925 8.3778 7.93185 7.90804 7.65074 7.40881L8.21246 6.84709C8.60266 6.45689 8.74711 5.88396 8.58854 5.35541L7.97761 3.31898C7.78727 2.6845 7.20329 2.25 6.54087 2.25H4.2489C3.43286 2.25 2.71942 2.92142 2.77338 3.7963C2.95462 6.73468 4.13069 9.40357 5.96899 11.4703L2.96967 14.4697C2.67678 14.7626 2.67678 15.2374 2.96967 15.5303C3.26256 15.8232 3.73744 15.8232 4.03033 15.5303L16.0303 3.53033Z"}),b("path",{d:"M14.7026 15.7255C12.2994 15.5773 10.0765 14.7636 8.21584 13.4665L10.9278 10.7545C10.9815 10.7863 11.0356 10.8175 11.0901 10.8482L11.6518 10.2864C12.042 9.89623 12.6149 9.75179 13.1435 9.91035L15.1799 10.5213C15.8144 10.7116 16.2489 11.2956 16.2489 11.958V14.25C16.2489 15.066 15.5775 15.7795 14.7026 15.7255Z"})]})}function Jb(t){return b("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:b("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M1.5 6.75C1.5 4.26472 3.51472 2.25 6 2.25H12C14.4853 2.25 16.5 4.26472 16.5 6.75V11.25C16.5 13.7353 14.4853 15.75 12 15.75H2.25C1.83579 15.75 1.5 15.4142 1.5 15V6.75ZM6 9.9375C5.48223 9.9375 5.0625 9.51777 5.0625 9C5.0625 8.48223 5.48223 8.0625 6 8.0625C6.51777 8.0625 6.9375 8.48223 6.9375 9C6.9375 9.51777 6.51777 9.9375 6 9.9375ZM9 9.9375C8.48223 9.9375 8.0625 9.51777 8.0625 9C8.0625 8.48223 8.48223 8.0625 9 8.0625C9.51777 8.0625 9.9375 8.48223 9.9375 9C9.9375 9.51777 9.51777 9.9375 9 9.9375ZM11.0625 9C11.0625 9.51777 11.4822 9.9375 12 9.9375C12.5178 9.9375 12.9375 9.51777 12.9375 9C12.9375 8.48223 12.5178 8.0625 12 8.0625C11.4822 8.0625 11.0625 8.48223 11.0625 9Z"})})}function Yb(t){return b("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[b("path",{d:"M9.50008 1.5C7.42901 1.5 5.75008 3.17893 5.75008 5.25V8.25C5.75008 10.3211 7.42901 12 9.50008 12C11.5712 12 13.2501 10.3211 13.2501 8.25V5.25C13.2501 3.17893 11.5712 1.5 9.50008 1.5Z"}),b("path",{d:"M4.88997 10.8417C4.66448 10.4943 4.20002 10.3954 3.85256 10.6209C3.50509 10.8463 3.40621 11.3108 3.63169 11.6583C4.47442 12.9569 6.08493 14.6838 8.75008 14.9616V15.75C8.75008 16.1642 9.08587 16.5 9.50008 16.5C9.9143 16.5 10.2501 16.1642 10.2501 15.75V14.9616C12.9152 14.6838 14.5257 12.9569 15.3685 11.6583C15.594 11.3108 15.4951 10.8463 15.1476 10.6209C14.8001 10.3954 14.3357 10.4943 14.1102 10.8417C13.3305 12.0432 11.9002 13.5 9.50008 13.5C7.1 13.5 5.66968 12.0432 4.88997 10.8417Z"})]})}function Xb(t){return b("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[b("path",{d:"M13.25 8.25C13.25 8.64791 13.188 9.03135 13.0732 9.39119L6.57947 2.8975C7.26687 2.04521 8.31974 1.5 9.49995 1.5C11.571 1.5 13.25 3.17893 13.25 5.25V8.25Z"}),b("path",{d:"M2.21967 1.71967C2.51256 1.42678 2.98744 1.42678 3.28033 1.71967L16.7803 15.2197C17.0732 15.5126 17.0732 15.9874 16.7803 16.2803C16.4874 16.5732 16.0126 16.5732 15.7197 16.2803L13.2828 13.8435C12.4719 14.4022 11.4678 14.8338 10.25 14.9614V15.75C10.25 16.1642 9.91422 16.5 9.50001 16.5C9.08579 16.5 8.75001 16.1642 8.75001 15.75V14.9616C6.08485 14.6838 4.47434 12.9569 3.63162 11.6583C3.40614 11.3108 3.50502 10.8463 3.85248 10.6209C4.19995 10.3954 4.66441 10.4943 4.88989 10.8417C5.6696 12.0432 7.09993 13.5 9.50001 13.5C10.5978 13.5 11.4845 13.1981 12.1992 12.7598L11.0875 11.6482C10.605 11.8739 10.0667 12 9.50001 12C7.42894 12 5.75001 10.3211 5.75001 8.25V6.31067L2.21967 2.78033C1.92678 2.48744 1.92678 2.01256 2.21967 1.71967Z"})]})}function Qb(t){return b("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:b("path",{d:"m6 9 6 6 6-6"})})}function Zb(t){return b("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:b("path",{d:"m18 15-6-6-6 6"})})}function ey(t){return b("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:b("path",{d:"M20 6 9 17l-5-5"})})}function ty(t){return b("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 20 20",fill:"currentColor",...t,children:b("path",{d:"M2.59413 5.1485C2.04 3.39377 3.86657 1.83482 5.51245 2.65776L16.47 8.13653C18.0055 8.90429 18.0055 11.0955 16.47 11.8633L5.51245 17.3421C3.86656 18.165 2.04 16.6061 2.59413 14.8513L3.86297 10.8333H7.50006C7.9603 10.8333 8.33339 10.4602 8.33339 10C8.33339 9.53976 7.9603 9.16667 7.50006 9.16667H3.86302L2.59413 5.1485Z",fill:"black"})})}function Yt(t){const e=Nh().value?ny:iy;return b(e,{...t})}function ny({visible:t,className:e,grow:n,dep:i,...r}){return t?b("div",{className:he(n&&"grow",e),...r}):null}function iy({visible:t,children:e,className:n,grow:i,dep:r,...s}){const[o,a]=F(t),[c,l]=F(null),[d,u]=F(null),h=B(e);t&&(h.current=e);const p=z(m=>{l(m),m&&!t&&(m.style.width="0px",m.style.height="0px")},[]);H(()=>{d&&(d.style.transition="none",d.style.opacity="0",d.offsetWidth,d.style.transition="",d.style.opacity="")},[r]),ce(()=>{c&&(c.style.width=`${c.offsetWidth}px`,c.style.height=`${c.offsetHeight}px`)},[c,t,r]),H(()=>{if(!c||!d)return;t&&a(!0);const m=t?d.offsetWidth:0,v=t?d.offsetHeight:0;c.style.width=!t||c.offsetWidth!==m?`${m}px`:"",c.style.height=!t||c.offsetHeight!==v?`${v}px`:""},[c,d,t,r]);const{transitioning:g,handlers:f}=Lh({onEnd:()=>{t?(c.style.width="",c.style.height=""):a(!1)}});return b("div",{ref:p,className:he("relative inline-flex shrink-0 justify-center items-center transition-[opacity,width,height,transform,flex-grow] duration-200 min-w-0",!t&&"opacity-0 scale-75",t&&i&&"grow",t&&o&&!g.value&&"z-1"),...f,children:b("div",{ref:u,className:he("shrink-0 min-h-min min-w-min transition-opacity duration-200",i&&"grow",n),...s,children:(t||o)&&h.current})})}const ry={primary:"text-accent-primary border border-accent bg-accent hover:border-accent-hover hover:bg-accent-hover active:border-accent-active active:bg-accent-active",secondary:"text-base-primary border border-base-border bg-base hover:bg-base-hover active:bg-base-active"},gn=Y(function({variant:t="secondary",children:e,icon:n,className:i,iconClassName:r,truncate:s=!0,...o},a){const c=!!n&&!e;return b("button",{ref:a,className:he("h-9 flex px-2.5 text-sm items-center transition-colors justify-center rounded-button duration-200 focus-ring overflow-hidden select-none",ry[t],c&&"min-w-9",i),type:"button",...o,children:[n&&b(An,{className:he("transition-[margin] duration-200",c&&"-mx-0.5",r),name:n}),b(Yt,{visible:!!e,dep:e,children:b("span",{className:"block whitespace-nowrap max-w-64 truncate px-1.5",children:e})})]})});function ga({className:t,...e}){const{status:n,isSpeaking:i}=ze(),r=zr(),s=We(),o=de(()=>n.value!=="connected"?s.connecting_status.value:r.value?s.chatting_status.value:i.value?s.speaking_status.value:s.listening_status.value),[a,c]=F(o.peek());return Bt(()=>{const l=o.value;if(n.value==="connected"&&i.value)c(l);else{const d=setTimeout(()=>{c(l)},500);return()=>clearTimeout(d)}}),b("div",{className:he("py-1.5 px-3 bg-base-active overflow-hidden rounded-bubble text-sm",t),...e,children:b(it,{initial:!1,active:!0,children:b("div",{className:"animate-text whitespace-nowrap transition-[opacity,transform] ease-out duration-200 data-hidden:opacity-0 transform data-hidden:translate-y-2",children:a})},a)})}function Bh(t,[e,n]){return Math.min(n,Math.max(e,t))}function xe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(i){if(t==null||t(i),n===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function va(t,e=[]){let n=[];function i(s,o){const a=Ae(o),c=n.length;n=[...n,o];const l=u=>{var h;const{scope:p,children:g,...f}=u,m=((h=p==null?void 0:p[t])==null?void 0:h[c])||a,v=ce(()=>f,Object.values(f));return b(m.Provider,{value:v,children:g})};l.displayName=s+"Provider";function d(u,h){var p;const g=((p=h==null?void 0:h[t])==null?void 0:p[c])||a,f=tn(g);if(f)return f;if(o!==void 0)return o;throw new Error(`\`${u}\` must be used within \`${s}\``)}return[l,d]}const r=()=>{const s=n.map(o=>Ae(o));return function(o){const a=(o==null?void 0:o[t])||s;return ce(()=>({[`__scope${t}`]:{...o,[t]:a}}),[o,a])}};return r.scopeName=t,[i,sy(r,...e)]}function sy(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const i=t.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(r){const s=i.reduce((o,{useScope:a,scopeName:c})=>{const l=a(r)[`__scope${c}`];return{...o,...l}},{});return ce(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}function oy(t){const e=t+"CollectionProvider",[n,i]=va(e),[r,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),o=f=>{const{scope:m,children:v}=f,y=Ft.useRef(null),_=Ft.useRef(new Map).current;return b(r,{scope:m,itemMap:_,collectionRef:y,children:v})};o.displayName=e;const a=t+"CollectionSlot",c=Vi(a),l=Ft.forwardRef((f,m)=>{const{scope:v,children:y}=f,_=s(a,v),k=Le(m,_.collectionRef);return b(c,{ref:k,children:y})});l.displayName=a;const d=t+"CollectionItemSlot",u="data-radix-collection-item",h=Vi(d),p=Ft.forwardRef((f,m)=>{const{scope:v,children:y,..._}=f,k=Ft.useRef(null),w=Le(m,k),S=s(d,v);return Ft.useEffect(()=>(S.itemMap.set(k,{ref:k,..._}),()=>void S.itemMap.delete(k))),b(h,{[u]:"",ref:w,children:y})});p.displayName=d;function g(f){const m=s(t+"CollectionConsumer",f);return Ft.useCallback(()=>{const v=m.collectionRef.current;if(!v)return[];const y=Array.from(v.querySelectorAll(`[${u}]`));return Array.from(m.itemMap.values()).sort((_,k)=>y.indexOf(_.ref.current)-y.indexOf(k.ref.current))},[m.collectionRef,m.itemMap])}return[{Provider:o,Slot:l,ItemSlot:p},g,i]}var ay=Ae(void 0);function cy(t){const e=tn(ay);return t||e||"ltr"}var ly=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],we=ly.reduce((t,e)=>{const n=Vi(`Primitive.${e}`),i=Y((r,s)=>{const{asChild:o,...a}=r,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),b(c,{...a,ref:s})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{});function dy(t,e){t&&ir(()=>t.dispatchEvent(e))}function Mn(t){const e=B(t);return H(()=>{e.current=t}),ce(()=>(...n)=>{var i;return(i=e.current)==null?void 0:i.call(e,...n)},[])}function uy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t);H(()=>{const i=r=>{r.key==="Escape"&&n(r)};return e.addEventListener("keydown",i,{capture:!0}),()=>e.removeEventListener("keydown",i,{capture:!0})},[n,e])}var hy="DismissableLayer",ba="dismissableLayer.update",fy="dismissableLayer.pointerDownOutside",py="dismissableLayer.focusOutside",jh,Vh=Ae({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),qh=Y((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:i,onPointerDownOutside:r,onFocusOutside:s,onInteractOutside:o,onDismiss:a,...c}=t,l=tn(Vh),[d,u]=F(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=F({}),g=Le(e,x=>u(x)),f=Array.from(l.layers),[m]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),v=f.indexOf(m),y=d?f.indexOf(d):-1,_=l.layersWithOutsidePointerEventsDisabled.size>0,k=y>=v,w=vy(x=>{const I=x.target,O=[...l.branches].some(R=>R.contains(I));!k||O||(r==null||r(x),o==null||o(x),x.defaultPrevented||a==null||a())},h),S=by(x=>{const I=x.target;[...l.branches].some(O=>O.contains(I))||(s==null||s(x),o==null||o(x),x.defaultPrevented||a==null||a())},h);return uy(x=>{y===l.layers.size-1&&(i==null||i(x),!x.defaultPrevented&&a&&(x.preventDefault(),a()))},h),H(()=>{if(d)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(jh=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(d)),l.layers.add(d),$h(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=jh)}},[d,h,n,l]),H(()=>()=>{d&&(l.layers.delete(d),l.layersWithOutsidePointerEventsDisabled.delete(d),$h())},[d,l]),H(()=>{const x=()=>p({});return document.addEventListener(ba,x),()=>document.removeEventListener(ba,x)},[]),b(we.div,{...c,ref:g,style:{pointerEvents:_?k?"auto":"none":void 0,...t.style},onFocusCapture:xe(t.onFocusCapture,S.onFocusCapture),onBlurCapture:xe(t.onBlurCapture,S.onBlurCapture),onPointerDownCapture:xe(t.onPointerDownCapture,w.onPointerDownCapture)})});qh.displayName=hy;var my="DismissableLayerBranch",gy=Y((t,e)=>{const n=tn(Vh),i=B(null),r=Le(e,i);return H(()=>{const s=i.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),b(we.div,{...t,ref:r})});gy.displayName=my;function vy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1),r=B(()=>{});return H(()=>{const s=a=>{if(a.target&&!i.current){let c=function(){zh(fy,n,l,{discrete:!0})};const l={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",r.current),r.current=c,e.addEventListener("click",r.current,{once:!0})):c()}else e.removeEventListener("click",r.current);i.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",s),e.removeEventListener("click",r.current)}},[e,n]),{onPointerDownCapture:()=>i.current=!0}}function by(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1);return H(()=>{const r=s=>{s.target&&!i.current&&zh(py,n,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function $h(){const t=new CustomEvent(ba);document.dispatchEvent(t)}function zh(t,e,n,{discrete:i}){const r=n.originalEvent.target,s=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&r.addEventListener(t,e,{once:!0}),i?dy(r,s):r.dispatchEvent(s)}var ya=0;function yy(){H(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??Wh()),document.body.insertAdjacentElement("beforeend",t[1]??Wh()),ya++,()=>{ya===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),ya--}},[])}function Wh(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var ka="focusScope.autoFocusOnMount",Ca="focusScope.autoFocusOnUnmount",Hh={bubbles:!1,cancelable:!0},ky="FocusScope",Gh=Y((t,e)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:r,onUnmountAutoFocus:s,...o}=t,[a,c]=F(null),l=Mn(r),d=Mn(s),u=B(null),h=Le(e,f=>c(f)),p=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;H(()=>{if(i){let f=function(_){if(p.paused||!a)return;const k=_.target;a.contains(k)?u.current=k:vn(u.current,{select:!0})},m=function(_){if(p.paused||!a)return;const k=_.relatedTarget;k!==null&&(a.contains(k)||vn(u.current,{select:!0}))},v=function(_){if(document.activeElement===document.body)for(const k of _)k.removedNodes.length>0&&vn(a)};document.addEventListener("focusin",f),document.addEventListener("focusout",m);const y=new MutationObserver(v);return a&&y.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",f),document.removeEventListener("focusout",m),y.disconnect()}}},[i,a,p.paused]),H(()=>{if(a){Yh.add(p);const f=document.activeElement;if(!a.contains(f)){const m=new CustomEvent(ka,Hh);a.addEventListener(ka,l),a.dispatchEvent(m),m.defaultPrevented||(Cy(xy(Kh(a)),{select:!0}),document.activeElement===f&&vn(a))}return()=>{a.removeEventListener(ka,l),setTimeout(()=>{const m=new CustomEvent(Ca,Hh);a.addEventListener(Ca,d),a.dispatchEvent(m),m.defaultPrevented||vn(f??document.body,{select:!0}),a.removeEventListener(Ca,d),Yh.remove(p)},0)}}},[a,l,d,p]);const g=z(f=>{if(!n&&!i||p.paused)return;const m=f.key==="Tab"&&!f.altKey&&!f.ctrlKey&&!f.metaKey,v=document.activeElement;if(m&&v){const y=f.currentTarget,[_,k]=_y(y);_&&k?!f.shiftKey&&v===k?(f.preventDefault(),n&&vn(_,{select:!0})):f.shiftKey&&v===_&&(f.preventDefault(),n&&vn(k,{select:!0})):v===y&&f.preventDefault()}},[n,i,p.paused]);return b(we.div,{tabIndex:-1,...o,ref:h,onKeyDown:g})});Gh.displayName=ky;function Cy(t,{select:e=!1}={}){const n=document.activeElement;for(const i of t)if(vn(i,{select:e}),document.activeElement!==n)return}function _y(t){const e=Kh(t),n=Jh(e,t),i=Jh(e.reverse(),t);return[n,i]}function Kh(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const r=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||r?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function Jh(t,e){for(const n of t)if(!wy(n,{upTo:e}))return n}function wy(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function Sy(t){return t instanceof HTMLInputElement&&"select"in t}function vn(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&Sy(t)&&e&&t.select()}}var Yh=Ty();function Ty(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=Xh(t,e),t.unshift(e)},remove(e){var n;t=Xh(t,e),(n=t[0])==null||n.resume()}}}function Xh(t,e){const n=[...t],i=n.indexOf(e);return i!==-1&&n.splice(i,1),n}function xy(t){return t.filter(e=>e.tagName!=="A")}var He=globalThis!=null&&globalThis.document?Lt:()=>{},Ey=Qc[" useId ".trim().toString()]||(()=>{}),Py=0;function _a(t){const[e,n]=F(Ey());return He(()=>{n(i=>i??String(Py++))},[t]),e?`radix-${e}`:""}const Ry=["top","right","bottom","left"],bn=Math.min,Ze=Math.max,Hr=Math.round,Gr=Math.floor,Pt=t=>({x:t,y:t}),Iy={left:"right",right:"left",bottom:"top",top:"bottom"},Oy={start:"end",end:"start"};function wa(t,e,n){return Ze(t,bn(e,n))}function Xt(t,e){return typeof t=="function"?t(e):t}function Qt(t){return t.split("-")[0]}function oi(t){return t.split("-")[1]}function Sa(t){return t==="x"?"y":"x"}function Ta(t){return t==="y"?"height":"width"}const Dy=new Set(["top","bottom"]);function Rt(t){return Dy.has(Qt(t))?"y":"x"}function xa(t){return Sa(Rt(t))}function Ay(t,e,n){n===void 0&&(n=!1);const i=oi(t),r=xa(t),s=Ta(r);let o=r==="x"?i===(n?"end":"start")?"right":"left":i==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=Kr(o)),[o,Kr(o)]}function My(t){const e=Kr(t);return[Ea(t),e,Ea(e)]}function Ea(t){return t.replace(/start|end/g,e=>Oy[e])}const Qh=["left","right"],Zh=["right","left"],Ny=["top","bottom"],Ly=["bottom","top"];function Uy(t,e,n){switch(t){case"top":case"bottom":return n?e?Zh:Qh:e?Qh:Zh;case"left":case"right":return e?Ny:Ly;default:return[]}}function Fy(t,e,n,i){const r=oi(t);let s=Uy(Qt(t),n==="start",i);return r&&(s=s.map(o=>o+"-"+r),e&&(s=s.concat(s.map(Ea)))),s}function Kr(t){return t.replace(/left|right|bottom|top/g,e=>Iy[e])}function By(t){return{top:0,right:0,bottom:0,left:0,...t}}function ef(t){return typeof t!="number"?By(t):{top:t,right:t,bottom:t,left:t}}function Jr(t){const{x:e,y:n,width:i,height:r}=t;return{width:i,height:r,top:n,left:e,right:e+i,bottom:n+r,x:e,y:n}}function tf(t,e,n){let{reference:i,floating:r}=t;const s=Rt(e),o=xa(e),a=Ta(o),c=Qt(e),l=s==="y",d=i.x+i.width/2-r.width/2,u=i.y+i.height/2-r.height/2,h=i[a]/2-r[a]/2;let p;switch(c){case"top":p={x:d,y:i.y-r.height};break;case"bottom":p={x:d,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:u};break;case"left":p={x:i.x-r.width,y:u};break;default:p={x:i.x,y:i.y}}switch(oi(e)){case"start":p[o]-=h*(n&&l?-1:1);break;case"end":p[o]+=h*(n&&l?-1:1);break}return p}const jy=async(t,e,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:s=[],platform:o}=n,a=s.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(e));let l=await o.getElementRects({reference:t,floating:e,strategy:r}),{x:d,y:u}=tf(l,i,c),h=i,p={},g=0;for(let f=0;f<a.length;f++){const{name:m,fn:v}=a[f],{x:y,y:_,data:k,reset:w}=await v({x:d,y:u,initialPlacement:i,placement:h,strategy:r,middlewareData:p,rects:l,platform:o,elements:{reference:t,floating:e}});d=y??d,u=_??u,p={...p,[m]:{...p[m],...k}},w&&g<=50&&(g++,typeof w=="object"&&(w.placement&&(h=w.placement),w.rects&&(l=w.rects===!0?await o.getElementRects({reference:t,floating:e,strategy:r}):w.rects),{x:d,y:u}=tf(l,h,c)),f=-1)}return{x:d,y:u,placement:h,strategy:r,middlewareData:p}};async function qi(t,e){var n;e===void 0&&(e={});const{x:i,y:r,platform:s,rects:o,elements:a,strategy:c}=t,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:p=0}=Xt(e,t),g=ef(p),f=a[h?u==="floating"?"reference":"floating":u],m=Jr(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(f)))==null||n?f:f.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),v=u==="floating"?{x:i,y:r,width:o.floating.width,height:o.floating.height}:o.reference,y=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),_=await(s.isElement==null?void 0:s.isElement(y))?await(s.getScale==null?void 0:s.getScale(y))||{x:1,y:1}:{x:1,y:1},k=Jr(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:y,strategy:c}):v);return{top:(m.top-k.top+g.top)/_.y,bottom:(k.bottom-m.bottom+g.bottom)/_.y,left:(m.left-k.left+g.left)/_.x,right:(k.right-m.right+g.right)/_.x}}const Vy=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:i,placement:r,rects:s,platform:o,elements:a,middlewareData:c}=e,{element:l,padding:d=0}=Xt(t,e)||{};if(l==null)return{};const u=ef(d),h={x:n,y:i},p=xa(r),g=Ta(p),f=await o.getDimensions(l),m=p==="y",v=m?"top":"left",y=m?"bottom":"right",_=m?"clientHeight":"clientWidth",k=s.reference[g]+s.reference[p]-h[p]-s.floating[g],w=h[p]-s.reference[p],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l));let x=S?S[_]:0;(!x||!await(o.isElement==null?void 0:o.isElement(S)))&&(x=a.floating[_]||s.floating[g]);const I=k/2-w/2,O=x/2-f[g]/2-1,R=bn(u[v],O),A=bn(u[y],O),M=R,q=x-f[g]-A,$=x/2-f[g]/2+I,oe=wa(M,$,q),J=!c.arrow&&oi(r)!=null&&$!==oe&&s.reference[g]/2-($<M?R:A)-f[g]/2<0,Z=J?$<M?$-M:$-q:0;return{[p]:h[p]+Z,data:{[p]:oe,centerOffset:$-oe-Z,...J&&{alignmentOffset:Z}},reset:J}}}),qy=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,i;const{placement:r,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:l}=e,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...m}=Xt(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const v=Qt(r),y=Rt(a),_=Qt(a)===a,k=await(c.isRTL==null?void 0:c.isRTL(l.floating)),w=h||(_||!f?[Kr(a)]:My(a)),S=g!=="none";!h&&S&&w.push(...Fy(a,f,g,k));const x=[a,...w],I=await qi(e,m),O=[];let R=((i=s.flip)==null?void 0:i.overflows)||[];if(d&&O.push(I[v]),u){const $=Ay(r,o,k);O.push(I[$[0]],I[$[1]])}if(R=[...R,{placement:r,overflows:O}],!O.every($=>$<=0)){var A,M;const $=(((A=s.flip)==null?void 0:A.index)||0)+1,oe=x[$];if(oe&&(!(u==="alignment"&&y!==Rt(oe))||R.every(Z=>Rt(Z.placement)===y?Z.overflows[0]>0:!0)))return{data:{index:$,overflows:R},reset:{placement:oe}};let J=(M=R.filter(Z=>Z.overflows[0]<=0).sort((Z,W)=>Z.overflows[1]-W.overflows[1])[0])==null?void 0:M.placement;if(!J)switch(p){case"bestFit":{var q;const Z=(q=R.filter(W=>{if(S){const te=Rt(W.placement);return te===y||te==="y"}return!0}).map(W=>[W.placement,W.overflows.filter(te=>te>0).reduce((te,De)=>te+De,0)]).sort((W,te)=>W[1]-te[1])[0])==null?void 0:q[0];Z&&(J=Z);break}case"initialPlacement":J=a;break}if(r!==J)return{reset:{placement:J}}}return{}}}};function nf(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function rf(t){return Ry.some(e=>t[e]>=0)}const $y=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:i="referenceHidden",...r}=Xt(t,e);switch(i){case"referenceHidden":{const s=await qi(e,{...r,elementContext:"reference"}),o=nf(s,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:rf(o)}}}case"escaped":{const s=await qi(e,{...r,altBoundary:!0}),o=nf(s,n.floating);return{data:{escapedOffsets:o,escaped:rf(o)}}}default:return{}}}}},sf=new Set(["left","top"]);async function zy(t,e){const{placement:n,platform:i,elements:r}=t,s=await(i.isRTL==null?void 0:i.isRTL(r.floating)),o=Qt(n),a=oi(n),c=Rt(n)==="y",l=sf.has(o)?-1:1,d=s&&c?-1:1,u=Xt(e,t);let{mainAxis:h,crossAxis:p,alignmentAxis:g}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&typeof g=="number"&&(p=a==="end"?g*-1:g),c?{x:p*d,y:h*l}:{x:h*l,y:p*d}}const Wy=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,i;const{x:r,y:s,placement:o,middlewareData:a}=e,c=await zy(e,t);return o===((n=a.offset)==null?void 0:n.placement)&&(i=a.arrow)!=null&&i.alignmentOffset?{}:{x:r+c.x,y:s+c.y,data:{...c,placement:o}}}}},Hy=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:r}=e,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:m=>{let{x:v,y}=m;return{x:v,y}}},...c}=Xt(t,e),l={x:n,y:i},d=await qi(e,c),u=Rt(Qt(r)),h=Sa(u);let p=l[h],g=l[u];if(s){const m=h==="y"?"top":"left",v=h==="y"?"bottom":"right",y=p+d[m],_=p-d[v];p=wa(y,p,_)}if(o){const m=u==="y"?"top":"left",v=u==="y"?"bottom":"right",y=g+d[m],_=g-d[v];g=wa(y,g,_)}const f=a.fn({...e,[h]:p,[u]:g});return{...f,data:{x:f.x-n,y:f.y-i,enabled:{[h]:s,[u]:o}}}}}},Gy=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:i,placement:r,rects:s,middlewareData:o}=e,{offset:a=0,mainAxis:c=!0,crossAxis:l=!0}=Xt(t,e),d={x:n,y:i},u=Rt(r),h=Sa(u);let p=d[h],g=d[u];const f=Xt(a,e),m=typeof f=="number"?{mainAxis:f,crossAxis:0}:{mainAxis:0,crossAxis:0,...f};if(c){const _=h==="y"?"height":"width",k=s.reference[h]-s.floating[_]+m.mainAxis,w=s.reference[h]+s.reference[_]-m.mainAxis;p<k?p=k:p>w&&(p=w)}if(l){var v,y;const _=h==="y"?"width":"height",k=sf.has(Qt(r)),w=s.reference[u]-s.floating[_]+(k&&((v=o.offset)==null?void 0:v[u])||0)+(k?0:m.crossAxis),S=s.reference[u]+s.reference[_]+(k?0:((y=o.offset)==null?void 0:y[u])||0)-(k?m.crossAxis:0);g<w?g=w:g>S&&(g=S)}return{[h]:p,[u]:g}}}},Ky=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,i;const{placement:r,rects:s,platform:o,elements:a}=e,{apply:c=()=>{},...l}=Xt(t,e),d=await qi(e,l),u=Qt(r),h=oi(r),p=Rt(r)==="y",{width:g,height:f}=s.floating;let m,v;u==="top"||u==="bottom"?(m=u,v=h===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(v=u,m=h==="end"?"top":"bottom");const y=f-d.top-d.bottom,_=g-d.left-d.right,k=bn(f-d[m],y),w=bn(g-d[v],_),S=!e.middlewareData.shift;let x=k,I=w;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(I=_),(i=e.middlewareData.shift)!=null&&i.enabled.y&&(x=y),S&&!h){const R=Ze(d.left,0),A=Ze(d.right,0),M=Ze(d.top,0),q=Ze(d.bottom,0);p?I=g-2*(R!==0||A!==0?R+A:Ze(d.left,d.right)):x=f-2*(M!==0||q!==0?M+q:Ze(d.top,d.bottom))}await c({...e,availableWidth:I,availableHeight:x});const O=await o.getDimensions(a.floating);return g!==O.width||f!==O.height?{reset:{rects:!0}}:{}}}};function Yr(){return typeof window<"u"}function ai(t){return of(t)?(t.nodeName||"").toLowerCase():"#document"}function et(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function It(t){var e;return(e=(of(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function of(t){return Yr()?t instanceof Node||t instanceof et(t).Node:!1}function pt(t){return Yr()?t instanceof Element||t instanceof et(t).Element:!1}function Ot(t){return Yr()?t instanceof HTMLElement||t instanceof et(t).HTMLElement:!1}function af(t){return!Yr()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof et(t).ShadowRoot}const Jy=new Set(["inline","contents"]);function $i(t){const{overflow:e,overflowX:n,overflowY:i,display:r}=mt(t);return/auto|scroll|overlay|hidden|clip/.test(e+i+n)&&!Jy.has(r)}const Yy=new Set(["table","td","th"]);function Xy(t){return Yy.has(ai(t))}const Qy=[":popover-open",":modal"];function Xr(t){return Qy.some(e=>{try{return t.matches(e)}catch{return!1}})}const Zy=["transform","translate","scale","rotate","perspective"],ek=["transform","translate","scale","rotate","perspective","filter"],tk=["paint","layout","strict","content"];function Pa(t){const e=Ra(),n=pt(t)?mt(t):t;return Zy.some(i=>n[i]?n[i]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||ek.some(i=>(n.willChange||"").includes(i))||tk.some(i=>(n.contain||"").includes(i))}function nk(t){let e=yn(t);for(;Ot(e)&&!ci(e);){if(Pa(e))return e;if(Xr(e))return null;e=yn(e)}return null}function Ra(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const ik=new Set(["html","body","#document"]);function ci(t){return ik.has(ai(t))}function mt(t){return et(t).getComputedStyle(t)}function Qr(t){return pt(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function yn(t){if(ai(t)==="html")return t;const e=t.assignedSlot||t.parentNode||af(t)&&t.host||It(t);return af(e)?e.host:e}function cf(t){const e=yn(t);return ci(e)?t.ownerDocument?t.ownerDocument.body:t.body:Ot(e)&&$i(e)?e:cf(e)}function zi(t,e,n){var i;e===void 0&&(e=[]),n===void 0&&(n=!0);const r=cf(t),s=r===((i=t.ownerDocument)==null?void 0:i.body),o=et(r);if(s){const a=Ia(o);return e.concat(o,o.visualViewport||[],$i(r)?r:[],a&&n?zi(a):[])}return e.concat(r,zi(r,[],n))}function Ia(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function lf(t){const e=mt(t);let n=parseFloat(e.width)||0,i=parseFloat(e.height)||0;const r=Ot(t),s=r?t.offsetWidth:n,o=r?t.offsetHeight:i,a=Hr(n)!==s||Hr(i)!==o;return a&&(n=s,i=o),{width:n,height:i,$:a}}function Oa(t){return pt(t)?t:t.contextElement}function li(t){const e=Oa(t);if(!Ot(e))return Pt(1);const n=e.getBoundingClientRect(),{width:i,height:r,$:s}=lf(e);let o=(s?Hr(n.width):n.width)/i,a=(s?Hr(n.height):n.height)/r;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const rk=Pt(0);function df(t){const e=et(t);return!Ra()||!e.visualViewport?rk:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function sk(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==et(t)?!1:e}function Nn(t,e,n,i){e===void 0&&(e=!1),n===void 0&&(n=!1);const r=t.getBoundingClientRect(),s=Oa(t);let o=Pt(1);e&&(i?pt(i)&&(o=li(i)):o=li(t));const a=sk(s,n,i)?df(s):Pt(0);let c=(r.left+a.x)/o.x,l=(r.top+a.y)/o.y,d=r.width/o.x,u=r.height/o.y;if(s){const h=et(s),p=i&&pt(i)?et(i):i;let g=h,f=Ia(g);for(;f&&i&&p!==g;){const m=li(f),v=f.getBoundingClientRect(),y=mt(f),_=v.left+(f.clientLeft+parseFloat(y.paddingLeft))*m.x,k=v.top+(f.clientTop+parseFloat(y.paddingTop))*m.y;c*=m.x,l*=m.y,d*=m.x,u*=m.y,c+=_,l+=k,g=et(f),f=Ia(g)}}return Jr({width:d,height:u,x:c,y:l})}function Da(t,e){const n=Qr(t).scrollLeft;return e?e.left+n:Nn(It(t)).left+n}function uf(t,e,n){n===void 0&&(n=!1);const i=t.getBoundingClientRect(),r=i.left+e.scrollLeft-(n?0:Da(t,i)),s=i.top+e.scrollTop;return{x:r,y:s}}function ok(t){let{elements:e,rect:n,offsetParent:i,strategy:r}=t;const s=r==="fixed",o=It(i),a=e?Xr(e.floating):!1;if(i===o||a&&s)return n;let c={scrollLeft:0,scrollTop:0},l=Pt(1);const d=Pt(0),u=Ot(i);if((u||!u&&!s)&&((ai(i)!=="body"||$i(o))&&(c=Qr(i)),Ot(i))){const p=Nn(i);l=li(i),d.x=p.x+i.clientLeft,d.y=p.y+i.clientTop}const h=o&&!u&&!s?uf(o,c,!0):Pt(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+h.x,y:n.y*l.y-c.scrollTop*l.y+d.y+h.y}}function ak(t){return Array.from(t.getClientRects())}function ck(t){const e=It(t),n=Qr(t),i=t.ownerDocument.body,r=Ze(e.scrollWidth,e.clientWidth,i.scrollWidth,i.clientWidth),s=Ze(e.scrollHeight,e.clientHeight,i.scrollHeight,i.clientHeight);let o=-n.scrollLeft+Da(t);const a=-n.scrollTop;return mt(i).direction==="rtl"&&(o+=Ze(e.clientWidth,i.clientWidth)-r),{width:r,height:s,x:o,y:a}}function lk(t,e){const n=et(t),i=It(t),r=n.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(r){s=r.width,o=r.height;const l=Ra();(!l||l&&e==="fixed")&&(a=r.offsetLeft,c=r.offsetTop)}return{width:s,height:o,x:a,y:c}}const dk=new Set(["absolute","fixed"]);function uk(t,e){const n=Nn(t,!0,e==="fixed"),i=n.top+t.clientTop,r=n.left+t.clientLeft,s=Ot(t)?li(t):Pt(1),o=t.clientWidth*s.x,a=t.clientHeight*s.y,c=r*s.x,l=i*s.y;return{width:o,height:a,x:c,y:l}}function hf(t,e,n){let i;if(e==="viewport")i=lk(t,n);else if(e==="document")i=ck(It(t));else if(pt(e))i=uk(e,n);else{const r=df(t);i={x:e.x-r.x,y:e.y-r.y,width:e.width,height:e.height}}return Jr(i)}function ff(t,e){const n=yn(t);return n===e||!pt(n)||ci(n)?!1:mt(n).position==="fixed"||ff(n,e)}function hk(t,e){const n=e.get(t);if(n)return n;let i=zi(t,[],!1).filter(a=>pt(a)&&ai(a)!=="body"),r=null;const s=mt(t).position==="fixed";let o=s?yn(t):t;for(;pt(o)&&!ci(o);){const a=mt(o),c=Pa(o);!c&&a.position==="fixed"&&(r=null),(s?!c&&!r:!c&&a.position==="static"&&r&&dk.has(r.position)||$i(o)&&!c&&ff(t,o))?i=i.filter(l=>l!==o):r=a,o=yn(o)}return e.set(t,i),i}function fk(t){let{element:e,boundary:n,rootBoundary:i,strategy:r}=t;const s=[...n==="clippingAncestors"?Xr(e)?[]:hk(e,this._c):[].concat(n),i],o=s[0],a=s.reduce((c,l)=>{const d=hf(e,l,r);return c.top=Ze(d.top,c.top),c.right=bn(d.right,c.right),c.bottom=bn(d.bottom,c.bottom),c.left=Ze(d.left,c.left),c},hf(e,o,r));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}}function pk(t){const{width:e,height:n}=lf(t);return{width:e,height:n}}function mk(t,e,n){const i=Ot(e),r=It(e),s=n==="fixed",o=Nn(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const c=Pt(0);function l(){c.x=Da(r)}if(i||!i&&!s)if((ai(e)!=="body"||$i(r))&&(a=Qr(e)),i){const p=Nn(e,!0,s,e);c.x=p.x+e.clientLeft,c.y=p.y+e.clientTop}else r&&l();s&&!i&&r&&l();const d=r&&!i&&!s?uf(r,a):Pt(0),u=o.left+a.scrollLeft-c.x-d.x,h=o.top+a.scrollTop-c.y-d.y;return{x:u,y:h,width:o.width,height:o.height}}function Aa(t){return mt(t).position==="static"}function pf(t,e){if(!Ot(t)||mt(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return It(t)===n&&(n=n.ownerDocument.body),n}function mf(t,e){const n=et(t);if(Xr(t))return n;if(!Ot(t)){let r=yn(t);for(;r&&!ci(r);){if(pt(r)&&!Aa(r))return r;r=yn(r)}return n}let i=pf(t,e);for(;i&&Xy(i)&&Aa(i);)i=pf(i,e);return i&&ci(i)&&Aa(i)&&!Pa(i)?n:i||nk(t)||n}const gk=async function(t){const e=this.getOffsetParent||mf,n=this.getDimensions,i=await n(t.floating);return{reference:mk(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}};function vk(t){return mt(t).direction==="rtl"}const bk={convertOffsetParentRelativeRectToViewportRelativeRect:ok,getDocumentElement:It,getClippingRect:fk,getOffsetParent:mf,getElementRects:gk,getClientRects:ak,getDimensions:pk,getScale:li,isElement:pt,isRTL:vk};function gf(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function yk(t,e){let n=null,i;const r=It(t);function s(){var a;clearTimeout(i),(a=n)==null||a.disconnect(),n=null}function o(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),s();const l=t.getBoundingClientRect(),{left:d,top:u,width:h,height:p}=l;if(a||e(),!h||!p)return;const g=Gr(u),f=Gr(r.clientWidth-(d+h)),m=Gr(r.clientHeight-(u+p)),v=Gr(d),y={rootMargin:-g+"px "+-f+"px "+-m+"px "+-v+"px",threshold:Ze(0,bn(1,c))||1};let _=!0;function k(w){const S=w[0].intersectionRatio;if(S!==c){if(!_)return o();S?o(!1,S):i=setTimeout(()=>{o(!1,1e-7)},1e3)}S===1&&!gf(l,t.getBoundingClientRect())&&o(),_=!1}try{n=new IntersectionObserver(k,{...y,root:r.ownerDocument})}catch{n=new IntersectionObserver(k,y)}n.observe(t)}return o(!0),s}function kk(t,e,n,i){i===void 0&&(i={});const{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=i,l=Oa(t),d=r||s?[...l?zi(l):[],...zi(e)]:[];d.forEach(v=>{r&&v.addEventListener("scroll",n,{passive:!0}),s&&v.addEventListener("resize",n)});const u=l&&a?yk(l,n):null;let h=-1,p=null;o&&(p=new ResizeObserver(v=>{let[y]=v;y&&y.target===l&&p&&(p.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var _;(_=p)==null||_.observe(e)})),n()}),l&&!c&&p.observe(l),p.observe(e));let g,f=c?Nn(t):null;c&&m();function m(){const v=Nn(t);f&&!gf(f,v)&&n(),f=v,g=requestAnimationFrame(m)}return n(),()=>{var v;d.forEach(y=>{r&&y.removeEventListener("scroll",n),s&&y.removeEventListener("resize",n)}),u==null||u(),(v=p)==null||v.disconnect(),p=null,c&&cancelAnimationFrame(g)}}const Ck=Wy,_k=Hy,wk=qy,Sk=Ky,Tk=$y,vf=Vy,xk=Gy,Ek=(t,e,n)=>{const i=new Map,r={platform:bk,...n},s={...r.platform,_c:i};return jy(t,e,{...r,platform:s})};var Pk=typeof document<"u",Rk=function(){},Zr=Pk?Lt:Rk;function es(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,i,r;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(i=n;i--!==0;)if(!es(t[i],e[i]))return!1;return!0}if(r=Object.keys(t),n=r.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!{}.hasOwnProperty.call(e,r[i]))return!1;for(i=n;i--!==0;){const s=r[i];if(!(s==="_owner"&&t.$$typeof)&&!es(t[s],e[s]))return!1}return!0}return t!==t&&e!==e}function bf(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function yf(t,e){const n=bf(t);return Math.round(e*n)/n}function Ma(t){const e=B(t);return Zr(()=>{e.current=t}),e}function Ik(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:i=[],platform:r,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:c,open:l}=t,[d,u]=F({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[h,p]=F(i);es(h,i)||p(i);const[g,f]=F(null),[m,v]=F(null),y=z(W=>{W!==S.current&&(S.current=W,f(W))},[]),_=z(W=>{W!==x.current&&(x.current=W,v(W))},[]),k=s||g,w=o||m,S=B(null),x=B(null),I=B(d),O=c!=null,R=Ma(c),A=Ma(r),M=Ma(l),q=z(()=>{if(!S.current||!x.current)return;const W={placement:e,strategy:n,middleware:h};A.current&&(W.platform=A.current),Ek(S.current,x.current,W).then(te=>{const De={...te,isPositioned:M.current!==!1};$.current&&!es(I.current,De)&&(I.current=De,ir(()=>{u(De)}))})},[h,e,n,A,M]);Zr(()=>{l===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,u(W=>({...W,isPositioned:!1})))},[l]);const $=B(!1);Zr(()=>($.current=!0,()=>{$.current=!1}),[]),Zr(()=>{if(k&&(S.current=k),w&&(x.current=w),k&&w){if(R.current)return R.current(k,w,q);q()}},[k,w,q,R,O]);const oe=ce(()=>({reference:S,floating:x,setReference:y,setFloating:_}),[y,_]),J=ce(()=>({reference:k,floating:w}),[k,w]),Z=ce(()=>{const W={position:n,left:0,top:0};if(!J.floating)return W;const te=yf(J.floating,d.x),De=yf(J.floating,d.y);return a?{...W,transform:"translate("+te+"px, "+De+"px)",...bf(J.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:te,top:De}},[n,a,J.floating,d.x,d.y]);return ce(()=>({...d,update:q,refs:oe,elements:J,floatingStyles:Z}),[d,q,oe,J,Z])}const Ok=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:i,padding:r}=typeof t=="function"?t(n):t;return i&&e(i)?i.current!=null?vf({element:i.current,padding:r}).fn(n):{}:i?vf({element:i,padding:r}).fn(n):{}}}},Dk=(t,e)=>({...Ck(t),options:[t,e]}),Ak=(t,e)=>({..._k(t),options:[t,e]}),Mk=(t,e)=>({...xk(t),options:[t,e]}),Nk=(t,e)=>({...wk(t),options:[t,e]}),Lk=(t,e)=>({...Sk(t),options:[t,e]}),Uk=(t,e)=>({...Tk(t),options:[t,e]}),Fk=(t,e)=>({...Ok(t),options:[t,e]});var Bk="Arrow",kf=Y((t,e)=>{const{children:n,width:i=10,height:r=5,...s}=t;return b(we.svg,{...s,ref:e,width:i,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:b("polygon",{points:"0,0 30,0 15,10"})})});kf.displayName=Bk;var jk=kf;function Vk(t){const[e,n]=F(void 0);return He(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const i=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const s=r[0];let o,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;o=l.inlineSize,a=l.blockSize}else o=t.offsetWidth,a=t.offsetHeight;n({width:o,height:a})});return i.observe(t,{box:"border-box"}),()=>i.unobserve(t)}else n(void 0)},[t]),e}var Na="Popper",[Cf,_f]=va(Na),[qk,wf]=Cf(Na),Sf=t=>{const{__scopePopper:e,children:n}=t,[i,r]=F(null);return b(qk,{scope:e,anchor:i,onAnchorChange:r,children:n})};Sf.displayName=Na;var Tf="PopperAnchor",xf=Y((t,e)=>{const{__scopePopper:n,virtualRef:i,...r}=t,s=wf(Tf,n),o=B(null),a=Le(e,o),c=B(null);return H(()=>{const l=c.current;c.current=(i==null?void 0:i.current)||o.current,l!==c.current&&s.onAnchorChange(c.current)}),i?null:b(we.div,{...r,ref:a})});xf.displayName=Tf;var La="PopperContent",[$k,zk]=Cf(La),Ef=Y((t,e)=>{var n,i,r,s,o,a;const{__scopePopper:c,side:l="bottom",sideOffset:d=0,align:u="center",alignOffset:h=0,arrowPadding:p=0,avoidCollisions:g=!0,collisionBoundary:f=[],collisionPadding:m=0,sticky:v="partial",hideWhenDetached:y=!1,updatePositionStrategy:_="optimized",onPlaced:k,...w}=t,S=wf(La,c),[x,I]=F(null),O=Le(e,tt=>I(tt)),[R,A]=F(null),M=Vk(R),q=(M==null?void 0:M.width)??0,$=(M==null?void 0:M.height)??0,oe=l+(u!=="center"?"-"+u:""),J=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},Z=Array.isArray(f)?f:[f],W=Z.length>0,te={padding:J,boundary:Z.filter(Hk),altBoundary:W},{refs:De,floatingStyles:vt,placement:Zt,isPositioned:rt,middlewareData:Ue}=Ik({strategy:"fixed",placement:oe,whileElementsMounted:(...tt)=>kk(...tt,{animationFrame:_==="always"}),elements:{reference:S.anchor},middleware:[Dk({mainAxis:d+$,alignmentAxis:h}),g&&Ak({mainAxis:!0,crossAxis:!1,limiter:v==="partial"?Mk():void 0,...te}),g&&Nk({...te}),Lk({...te,apply:({elements:tt,rects:Hi,availableWidth:Gi,availableHeight:Ki})=>{const{width:H_,height:G_}=Hi.reference,fs=tt.floating.style;fs.setProperty("--radix-popper-available-width",`${Gi}px`),fs.setProperty("--radix-popper-available-height",`${Ki}px`),fs.setProperty("--radix-popper-anchor-width",`${H_}px`),fs.setProperty("--radix-popper-anchor-height",`${G_}px`)}}),R&&Fk({element:R,padding:p}),Gk({arrowWidth:q,arrowHeight:$}),y&&Uk({strategy:"referenceHidden",...te})]}),[At,bt]=If(Zt),V=Mn(k);He(()=>{rt&&(V==null||V())},[rt,V]);const me=(n=Ue.arrow)==null?void 0:n.x,Se=(i=Ue.arrow)==null?void 0:i.y,ne=((r=Ue.arrow)==null?void 0:r.centerOffset)!==0,[be,Ee]=F();return He(()=>{x&&Ee(window.getComputedStyle(x).zIndex)},[x]),b("div",{ref:De.setFloating,"data-radix-popper-content-wrapper":"",style:{...vt,transform:rt?vt.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:be,"--radix-popper-transform-origin":[(s=Ue.transformOrigin)==null?void 0:s.x,(o=Ue.transformOrigin)==null?void 0:o.y].join(" "),...((a=Ue.hide)==null?void 0:a.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:b($k,{scope:c,placedSide:At,onArrowChange:A,arrowX:me,arrowY:Se,shouldHideArrow:ne,children:b(we.div,{"data-side":At,"data-align":bt,...w,ref:O,style:{...w.style,animation:rt?void 0:"none"}})})})});Ef.displayName=La;var Pf="PopperArrow",Wk={top:"bottom",right:"left",bottom:"top",left:"right"},Rf=Y(function(t,e){const{__scopePopper:n,...i}=t,r=zk(Pf,n),s=Wk[r.placedSide];return b("span",{ref:r.onArrowChange,style:{position:"absolute",left:r.arrowX,top:r.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[r.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[r.placedSide],visibility:r.shouldHideArrow?"hidden":void 0},children:b(jk,{...i,ref:e,style:{...i.style,display:"block"}})})});Rf.displayName=Pf;function Hk(t){return t!==null}var Gk=t=>({name:"transformOrigin",options:t,fn(e){var n,i,r;const{placement:s,rects:o,middlewareData:a}=e,c=((n=a.arrow)==null?void 0:n.centerOffset)!==0,l=c?0:t.arrowWidth,d=c?0:t.arrowHeight,[u,h]=If(s),p={start:"0%",center:"50%",end:"100%"}[h],g=(((i=a.arrow)==null?void 0:i.x)??0)+l/2,f=(((r=a.arrow)==null?void 0:r.y)??0)+d/2;let m="",v="";return u==="bottom"?(m=c?p:`${g}px`,v=`${-d}px`):u==="top"?(m=c?p:`${g}px`,v=`${o.floating.height+d}px`):u==="right"?(m=`${-d}px`,v=c?p:`${f}px`):u==="left"&&(m=`${o.floating.width+d}px`,v=c?p:`${f}px`),{data:{x:m,y:v}}}});function If(t){const[e,n="center"]=t.split("-");return[e,n]}var Kk=Sf,Jk=xf,Yk=Ef,Xk=Rf,Qk="Portal",Of=Y((t,e)=>{var n;const{container:i,...r}=t,[s,o]=F(!1);He(()=>o(!0),[]);const a=i||s&&((n=globalThis==null?void 0:globalThis.document)==null?void 0:n.body);return a?Ft.createPortal(b(we.div,{...r,ref:e}),a):null});Of.displayName=Qk;var Zk=Qc[" useInsertionEffect ".trim().toString()]||He;function Df({prop:t,defaultProp:e,onChange:n=()=>{},caller:i}){const[r,s,o]=eC({defaultProp:e,onChange:n}),a=t!==void 0,c=a?t:r;{const d=B(t!==void 0);H(()=>{const u=d.current;u!==a&&console.warn(`${i} is changing from ${u?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,i])}const l=z(d=>{var u;if(a){const h=tC(d)?d(t):d;h!==t&&((u=o.current)==null||u.call(o,h))}else s(d)},[a,t,s,o]);return[c,l]}function eC({defaultProp:t,onChange:e}){const[n,i]=F(t),r=B(n),s=B(e);return Zk(()=>{s.current=e},[e]),H(()=>{var o;r.current!==n&&((o=s.current)==null||o.call(s,n),r.current=n)},[n,r]),[n,i,s]}function tC(t){return typeof t=="function"}function nC(t){const e=B({value:t,previous:t});return ce(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var Af=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),iC="VisuallyHidden",rC=Y((t,e)=>b(we.span,{...t,ref:e,style:{...Af,...t.style}}));rC.displayName=iC;var sC=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},di=new WeakMap,ts=new WeakMap,ns={},Ua=0,Mf=function(t){return t&&(t.host||Mf(t.parentNode))},oC=function(t,e){return e.map(function(n){if(t.contains(n))return n;var i=Mf(n);return i&&t.contains(i)?i:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},aC=function(t,e,n,i){var r=oC(e,Array.isArray(t)?t:[t]);ns[n]||(ns[n]=new WeakMap);var s=ns[n],o=[],a=new Set,c=new Set(r),l=function(u){!u||a.has(u)||(a.add(u),l(u.parentNode))};r.forEach(l);var d=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(i),g=p!==null&&p!=="false",f=(di.get(h)||0)+1,m=(s.get(h)||0)+1;di.set(h,f),s.set(h,m),o.push(h),f===1&&g&&ts.set(h,!0),m===1&&h.setAttribute(n,"true"),g||h.setAttribute(i,"true")}catch(v){console.error("aria-hidden: cannot operate on ",h,v)}})};return d(e),a.clear(),Ua++,function(){o.forEach(function(u){var h=di.get(u)-1,p=s.get(u)-1;di.set(u,h),s.set(u,p),h||(ts.has(u)||u.removeAttribute(i),ts.delete(u)),p||u.removeAttribute(n)}),Ua--,Ua||(di=new WeakMap,di=new WeakMap,ts=new WeakMap,ns={})}},cC=function(t,e,n){n===void 0&&(n="data-aria-hidden");var i=Array.from(Array.isArray(t)?t:[t]),r=sC(t);return r?(i.push.apply(i,Array.from(r.querySelectorAll("[aria-live], script"))),aC(i,r,n,"aria-hidden")):function(){return null}},Dt=function(){return Dt=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},Dt.apply(this,arguments)};function Nf(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function lC(t,e,n){for(var i=0,r=e.length,s;i<r;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))}var is="right-scroll-bar-position",rs="width-before-scroll-bar",dC="with-scroll-bars-hidden",uC="--removed-body-scroll-bar-size";function Fa(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function hC(t,e){var n=F(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(i){var r=n.value;r!==i&&(n.value=i,n.callback(i,r))}}}})[0];return n.callback=e,n.facade}var fC=typeof window<"u"?Lt:H,Lf=new WeakMap;function pC(t,e){var n=hC(null,function(i){return t.forEach(function(r){return Fa(r,i)})});return fC(function(){var i=Lf.get(n);if(i){var r=new Set(i),s=new Set(t),o=n.current;r.forEach(function(a){s.has(a)||Fa(a,null)}),s.forEach(function(a){r.has(a)||Fa(a,o)})}Lf.set(n,t)},[t]),n}function mC(t){return t}function gC(t,e){e===void 0&&(e=mC);var n=[],i=!1,r={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(s){var o=e(s,i);return n.push(o),function(){n=n.filter(function(a){return a!==o})}},assignSyncMedium:function(s){for(i=!0;n.length;){var o=n;n=[],o.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){i=!0;var o=[];if(n.length){var a=n;n=[],a.forEach(s),o=n}var c=function(){var d=o;o=[],d.forEach(s)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){o.push(d),l()},filter:function(d){return o=o.filter(d),n}}}};return r}function vC(t){t===void 0&&(t={});var e=gC(null);return e.options=Dt({async:!0,ssr:!1},t),e}var Uf=function(t){var e=t.sideCar,n=Nf(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=e.read();if(!i)throw new Error("Sidecar medium not found");return fe(i,Dt({},n))};Uf.isSideCarExport=!0;function bC(t,e){return t.useMedium(e),Uf}var Ff=vC(),Ba=function(){},ss=Y(function(t,e){var n=B(null),i=F({onScrollCapture:Ba,onWheelCapture:Ba,onTouchMoveCapture:Ba}),r=i[0],s=i[1],o=t.forwardProps,a=t.children,c=t.className,l=t.removeScrollBar,d=t.enabled,u=t.shards,h=t.sideCar,p=t.noRelative,g=t.noIsolation,f=t.inert,m=t.allowPinchZoom,v=t.as,y=v===void 0?"div":v,_=t.gapMode,k=Nf(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),w=h,S=pC([n,e]),x=Dt(Dt({},k),r);return fe(ge,null,d&&fe(w,{sideCar:Ff,removeScrollBar:l,shards:u,noRelative:p,noIsolation:g,inert:f,setCallbacks:s,allowPinchZoom:!!m,lockRef:n,gapMode:_}),o?_i(nn.only(a),Dt(Dt({},x),{ref:S})):fe(y,Dt({},x,{className:c,ref:S}),a))});ss.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ss.classNames={fullWidth:rs,zeroRight:is};var yC=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function kC(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=yC();return e&&t.setAttribute("nonce",e),t}function CC(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function _C(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var wC=function(){var t=0,e=null;return{add:function(n){t==0&&(e=kC())&&(CC(e,n),_C(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},SC=function(){var t=wC();return function(e,n){H(function(){return t.add(e),function(){t.remove()}},[e&&n])}},Bf=function(){var t=SC(),e=function(n){var i=n.styles,r=n.dynamic;return t(i,r),null};return e},TC={left:0,top:0,right:0,gap:0},ja=function(t){return parseInt(t||"",10)||0},xC=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],i=e[t==="padding"?"paddingTop":"marginTop"],r=e[t==="padding"?"paddingRight":"marginRight"];return[ja(n),ja(i),ja(r)]},EC=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return TC;var e=xC(t),n=document.documentElement.clientWidth,i=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,i-n+e[2]-e[0])}},PC=Bf(),ui="data-scroll-locked",RC=function(t,e,n,i){var r=t.left,s=t.top,o=t.right,a=t.gap;return n===void 0&&(n="margin"),`
423
- .`.concat(dC,` {
432
+ `,$h=0,Qb=new Float32Array([-1,1,-1,-1,1,1,1,-1]),Zb="https://storage.googleapis.com/eleven-public-cdn/images/perlin-noise.png",zh=class _n{constructor(e){Ge(this,"gl"),Ge(this,"program"),Ge(this,"startTime"),Ge(this,"targetSpeed",0),Ge(this,"speed",.5),Ge(this,"rafId",null),Ge(this,"resizeObserver"),Ge(this,"colorA",[0,0,0]),Ge(this,"colorB",[0,0,0]),Ge(this,"offsets",new Float32Array(7).map(()=>Math.random()*Math.PI*2)),Ge(this,"copyNoiseImage",()=>{this.gl&&(this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,_n.noiseImage),this.gl.generateMipmap(this.gl.TEXTURE_2D))}),Ge(this,"toDataURL",()=>this.gl.canvas.toDataURL("image/png")),Ge(this,"render",()=>{if(!this.gl){this.rafId=null;return}const o=(performance.now()-this.startTime)/1e3;this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uTime"),o),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.rafId=requestAnimationFrame(this.render)});const n=e.getContext("webgl2",{depth:!1,stencil:!1});this.gl=n,this.program=this.setupProgram(Yb,Xb);const i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([128,128,128,255])),_n.noiseImage||(_n.noiseImage=new Image,_n.noiseImage.crossOrigin="anonymous",_n.noiseImage.src=Zb),_n.noiseImage.complete?this.copyNoiseImage():_n.noiseImage.addEventListener("load",this.copyNoiseImage);const r=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,r),n.bufferData(n.ARRAY_BUFFER,Qb,n.STATIC_DRAW),n.vertexAttribPointer($h,2,n.FLOAT,!1,0,0),n.enableVertexAttribArray($h),this.updateColors("#2792DC","#9CE6E6"),this.resizeObserver=new ResizeObserver(o=>{const a=o[0],c=a.devicePixelContentBoxSize?a.devicePixelContentBoxSize[0]:a.contentBoxSize[0];e.width=Math.min(512,c.inlineSize),e.height=Math.min(512,c.blockSize),this.updateViewport()});const s=e.parentElement;if(s)try{this.resizeObserver.observe(s,{box:"device-pixel-content-box"})}catch{this.resizeObserver.observe(s)}this.startTime=performance.now(),this.rafId=requestAnimationFrame(this.render)}dispose(){var e;this.rafId!==null&&cancelAnimationFrame(this.rafId),(e=this.resizeObserver)==null||e.disconnect(),this.gl=null,this.program=null}updateViewport(){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}updateColors(e,n){this.gl&&(this.colorA=this.updateColor("uColor1",e)??this.colorA,this.colorB=this.updateColor("uColor2",n)??this.colorB)}updateVolume(e,n){this.targetSpeed=.2+(1-Math.pow(n-1,2))*1.8,this.targetSpeed>this.speed&&(this.speed=this.targetSpeed),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uInputVolume"),e),this.gl.uniform1f(this.gl.getUniformLocation(this.program,"uOutputVolume"),n)}updateColor(e,n){try{const i=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,o=[Math.pow(i,2.2),Math.pow(r,2.2),Math.pow(s,2.2)];return this.gl.uniform3fv(this.gl.getUniformLocation(this.program,e),o),o}catch(i){console.error(`[ConversationalAI] Failed to parse ${n} as color:`,i)}}setupProgram(e,n){const i=this.getShader(this.gl.FRAGMENT_SHADER,e),r=this.getShader(this.gl.VERTEX_SHADER,n);if(!i||!r)throw new Error("Failed to compile shaders");if(this.program=this.gl.createProgram(),this.gl.attachShader(this.program,i),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),!this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS))throw new Error("Failed to link program");return this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"uPerlinTexture"),0),this.gl.uniform1fv(this.gl.getUniformLocation(this.program,"uOffsets"),this.offsets),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor1"),this.colorA),this.gl.uniform3fv(this.gl.getUniformLocation(this.program,"uColor2"),this.colorB),this.program}getShader(e,n){const i=this.gl.createShader(e);return this.gl.shaderSource(i,n),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)?i:(this.gl.deleteShader(i),null)}};Ge(zh,"noiseImage");let ey=zh;const ty={sm:"w-9 h-9",lg:"w-48 h-48"};function si({size:t="sm",className:e}){const{getInputVolume:n,getOutputVolume:i,isSpeaking:r,isDisconnected:s}=Be(),{config:o}=pa(),a=B(null),c=B(null);Ct(()=>{if(s.value){a.current.style.transform="",c.current.style.transform="";return}let d;function u(){const h=n(),f=i(),v=r.peek()?1:1-h*.4,p=r.peek()?1+f*.4:1;a.current.style.transform=`scale(${p})`,c.current.style.transform=`scale(${v})`,d=requestAnimationFrame(u)}return u(),()=>{cancelAnimationFrame(d)}});const l=ue(()=>({backgroundImage:o.value.type==="image"?`url(${o.value.url})`:o.value.type==="url"?`url(${o.value.custom_url})`:void 0}));return m("div",{className:ae("relative shrink-0",ty[t],e),children:[m("div",{ref:a,className:"absolute inset-0 rounded-full bg-base-border"}),m("div",{ref:c,style:l,className:"absolute inset-0 rounded-full overflow-hidden bg-base bg-cover",children:o.value.type==="orb"&&m(ny,{color1:o.value.color_1,color2:o.value.color_2})})]})}function ny({color1:t,color2:e}){const{canvasUrl:n}=pa(),[i,r]=V(null);G(()=>{i&&(i.updateColors(t,e),i.render(),n.value=i.toDataURL())},[i,t,e]);const s=j(o=>{if(o){const a=new ey(o);return r(a),()=>a.dispose()}else r(null)},[r]);return m("canvas",{className:"w-full h-full",ref:s})}const iy={phone:sy,"phone-off":oy,chat:ay,mic:cy,"mic-off":ly,check:hy,"chevron-down":dy,"chevron-up":uy,send:fy,star:py},ry={sm:"text-xs",md:"text-lg",lg:"text-xl"};function It({name:t,size:e="md",className:n}){const i=iy[t];return m("slot",{name:`icon-${t}`,className:ae("flex",ry[e],n),"aria-hidden":!0,children:m(i,{})})}function sy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{d:"M3.7489 2.25C2.93286 2.25 2.21942 2.92142 2.27338 3.7963C2.6686 10.2041 7.79483 15.3303 14.2026 15.7255C15.0775 15.7795 15.7489 15.066 15.7489 14.25V11.958C15.7489 11.2956 15.3144 10.7116 14.6799 10.5213L12.6435 9.91035C12.1149 9.75179 11.542 9.89623 11.1518 10.2864L10.5901 10.8482C9.15291 10.0389 7.95998 8.84599 7.15074 7.40881L7.71246 6.84709C8.10266 6.45689 8.24711 5.88396 8.08854 5.35541L7.47761 3.31898C7.28727 2.6845 6.70329 2.25 6.04087 2.25H3.7489Z"})})}function oy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M16.0303 3.53033C16.3232 3.23744 16.3232 2.76256 16.0303 2.46967C15.7374 2.17678 15.2626 2.17678 14.9697 2.46967L8.6271 8.81224C8.25925 8.3778 7.93185 7.90804 7.65074 7.40881L8.21246 6.84709C8.60266 6.45689 8.74711 5.88396 8.58854 5.35541L7.97761 3.31898C7.78727 2.6845 7.20329 2.25 6.54087 2.25H4.2489C3.43286 2.25 2.71942 2.92142 2.77338 3.7963C2.95462 6.73468 4.13069 9.40357 5.96899 11.4703L2.96967 14.4697C2.67678 14.7626 2.67678 15.2374 2.96967 15.5303C3.26256 15.8232 3.73744 15.8232 4.03033 15.5303L16.0303 3.53033Z"}),m("path",{d:"M14.7026 15.7255C12.2994 15.5773 10.0765 14.7636 8.21584 13.4665L10.9278 10.7545C10.9815 10.7863 11.0356 10.8175 11.0901 10.8482L11.6518 10.2864C12.042 9.89623 12.6149 9.75179 13.1435 9.91035L15.1799 10.5213C15.8144 10.7116 16.2489 11.2956 16.2489 11.958V14.25C16.2489 15.066 15.5775 15.7795 14.7026 15.7255Z"})]})}function ay(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M1.5 6.75C1.5 4.26472 3.51472 2.25 6 2.25H12C14.4853 2.25 16.5 4.26472 16.5 6.75V11.25C16.5 13.7353 14.4853 15.75 12 15.75H2.25C1.83579 15.75 1.5 15.4142 1.5 15V6.75ZM6 9.9375C5.48223 9.9375 5.0625 9.51777 5.0625 9C5.0625 8.48223 5.48223 8.0625 6 8.0625C6.51777 8.0625 6.9375 8.48223 6.9375 9C6.9375 9.51777 6.51777 9.9375 6 9.9375ZM9 9.9375C8.48223 9.9375 8.0625 9.51777 8.0625 9C8.0625 8.48223 8.48223 8.0625 9 8.0625C9.51777 8.0625 9.9375 8.48223 9.9375 9C9.9375 9.51777 9.51777 9.9375 9 9.9375ZM11.0625 9C11.0625 9.51777 11.4822 9.9375 12 9.9375C12.5178 9.9375 12.9375 9.51777 12.9375 9C12.9375 8.48223 12.5178 8.0625 12 8.0625C11.4822 8.0625 11.0625 8.48223 11.0625 9Z"})})}function cy(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M9.50008 1.5C7.42901 1.5 5.75008 3.17893 5.75008 5.25V8.25C5.75008 10.3211 7.42901 12 9.50008 12C11.5712 12 13.2501 10.3211 13.2501 8.25V5.25C13.2501 3.17893 11.5712 1.5 9.50008 1.5Z"}),m("path",{d:"M4.88997 10.8417C4.66448 10.4943 4.20002 10.3954 3.85256 10.6209C3.50509 10.8463 3.40621 11.3108 3.63169 11.6583C4.47442 12.9569 6.08493 14.6838 8.75008 14.9616V15.75C8.75008 16.1642 9.08587 16.5 9.50008 16.5C9.9143 16.5 10.2501 16.1642 10.2501 15.75V14.9616C12.9152 14.6838 14.5257 12.9569 15.3685 11.6583C15.594 11.3108 15.4951 10.8463 15.1476 10.6209C14.8001 10.3954 14.3357 10.4943 14.1102 10.8417C13.3305 12.0432 11.9002 13.5 9.50008 13.5C7.1 13.5 5.66968 12.0432 4.88997 10.8417Z"})]})}function ly(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 19 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:[m("path",{d:"M13.25 8.25C13.25 8.64791 13.188 9.03135 13.0732 9.39119L6.57947 2.8975C7.26687 2.04521 8.31974 1.5 9.49995 1.5C11.571 1.5 13.25 3.17893 13.25 5.25V8.25Z"}),m("path",{d:"M2.21967 1.71967C2.51256 1.42678 2.98744 1.42678 3.28033 1.71967L16.7803 15.2197C17.0732 15.5126 17.0732 15.9874 16.7803 16.2803C16.4874 16.5732 16.0126 16.5732 15.7197 16.2803L13.2828 13.8435C12.4719 14.4022 11.4678 14.8338 10.25 14.9614V15.75C10.25 16.1642 9.91422 16.5 9.50001 16.5C9.08579 16.5 8.75001 16.1642 8.75001 15.75V14.9616C6.08485 14.6838 4.47434 12.9569 3.63162 11.6583C3.40614 11.3108 3.50502 10.8463 3.85248 10.6209C4.19995 10.3954 4.66441 10.4943 4.88989 10.8417C5.6696 12.0432 7.09993 13.5 9.50001 13.5C10.5978 13.5 11.4845 13.1981 12.1992 12.7598L11.0875 11.6482C10.605 11.8739 10.0667 12 9.50001 12C7.42894 12 5.75001 10.3211 5.75001 8.25V6.31067L2.21967 2.78033C1.92678 2.48744 1.92678 2.01256 2.21967 1.71967Z"})]})}function dy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"m6 9 6 6 6-6"})})}function uy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"m18 15-6-6-6 6"})})}function hy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...t,children:m("path",{d:"M20 6 9 17l-5-5"})})}function fy(t){return m("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",width:"1em",viewBox:"0 0 20 20",fill:"currentColor",...t,children:m("path",{d:"M2.59413 5.1485C2.04 3.39377 3.86657 1.83482 5.51245 2.65776L16.47 8.13653C18.0055 8.90429 18.0055 11.0955 16.47 11.8633L5.51245 17.3421C3.86656 18.165 2.04 16.6061 2.59413 14.8513L3.86297 10.8333H7.50006C7.9603 10.8333 8.33339 10.4602 8.33339 10C8.33339 9.53976 7.9603 9.16667 7.50006 9.16667H3.86302L2.59413 5.1485Z",fill:"black"})})}function py(t){return m("svg",{height:"1em",width:"1em",viewBox:"0 0 21 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t,children:m("path",{d:"M11.8621 0.854898C11.3145 -0.284967 9.68804 -0.284965 9.1404 0.854899L6.77181 5.78487C6.77181 5.78487 6.76902 5.78867 6.7646 5.78925L1.31499 6.50272C0.0591912 6.66713 -0.452868 8.21568 0.474832 9.09033L4.45896 12.8466C4.46075 12.8483 4.46059 12.8502 4.46059 12.8502L3.46003 18.2169C3.22657 19.4691 4.55184 20.4152 5.66108 19.8172L10.4957 17.2111C10.4991 17.2093 10.5035 17.2093 10.5068 17.2111L15.3415 19.8172C16.4507 20.4152 17.776 19.4691 17.5425 18.2169L16.542 12.8502C16.542 12.8502 16.5418 12.8483 16.5436 12.8466L20.5277 9.09033C21.4554 8.21568 20.9434 6.66713 19.6876 6.50272L14.2379 5.78925C14.2335 5.78867 14.2307 5.78487 14.2307 5.78487L11.8621 0.854898Z"})})}function my({orbColor:t,circleBackgroundColor:e,starColor:n,className:i}){return m("slot",{name:"icon-feedback",className:ae("flex",i),"aria-hidden":!0,children:m("svg",{width:"100%",height:"100%",viewBox:"0 0 82 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[m("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M9 42C9 59.6731 23.3269 74 41 74C58.6731 74 73 59.6731 73 42C73 24.3269 58.6731 10 41 10C23.3269 10 9 24.3269 9 42ZM29.4529 18.5973C31.1347 18.0574 32.8641 17.5023 34.9844 16.6005C42.2533 13.5091 48.3526 11.9217 51.7782 14.094C53.5063 15.1899 54.4051 16.7749 55.6117 18.9024C56.7969 20.9922 58.279 23.6057 61.1358 26.7937C62.2737 28.0636 63.3886 29.2195 64.4371 30.3064C68.7007 34.7263 71.8645 38.0061 70.9949 43.1697C70.2965 47.316 67.9794 49.4559 65.6038 51.65C63.4317 53.656 61.2107 55.7073 60.1332 59.3786C57.8774 67.0653 53.5327 71.9113 48.3526 72.7468C43.1725 73.5823 36.6555 75.1698 29.8043 70.1567C26.1949 67.5157 25.229 64.3182 24.1947 60.894C23.2657 57.8184 22.2814 54.56 19.2768 51.3577C14.1619 45.9062 10.2533 29.6345 19.2768 23.0339C23.736 20.4327 26.5223 19.5382 29.4529 18.5973Z",fill:t,"fill-opacity":"0.15",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M43.5 73.4212C40.4387 73.4212 35.0039 71.1025 37.556 56.4696C40.143 41.6365 42.6582 40.577 44.6991 25.744C46.3318 13.8775 41.1635 8.87964 33 10.9988",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M43.5 73.4212C40.4387 73.4212 35.0039 71.1025 37.556 56.4696C40.143 41.6365 42.6582 40.577 44.6991 25.744C46.3318 13.8775 41.1635 8.87964 33 10.9988",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M21.9366 68.1987C21.3549 66.5119 21.0386 60.9231 28.1376 53.3448C37.0114 43.8719 40.5 43.9579 51.4911 31.7482C59.5691 22.7747 59.1723 17.0524 58.0993 15.4626",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M9.26819 42.161C10.4003 43.5337 15.6951 46.3853 25.7661 44.3926C38.3548 41.9018 52.434 40.307 57.694 41.0287C70.352 42.7655 71.4138 51.3035 71.4138 51.3035",stroke:t,"stroke-opacity":"0.35"}),m("path",{d:"M22 16.4916C18.815 21.85 19.6451 26.0591 27.9943 32.0828C38.4307 39.6124 50.2985 48.8304 53.5024 53.1027C58.6684 59.9914 59.5 67.928 59.5 67.928",stroke:t,"stroke-opacity":"0.35"}),m("rect",{x:"9.26099",y:"10",width:"63.7129",height:"63.7129",rx:"31.8565",stroke:t,"stroke-opacity":"0.43","stroke-width":"1.5"}),m("g",{"clip-path":"url(#clip0_7006_42127)",children:[m("circle",{cx:"62.4996",cy:"18.2032",r:"15.0195",transform:"rotate(6.27205 62.4996 18.2032)",fill:e}),m("path",{d:"M60.7142 12.1753C62.057 10.0714 65.2294 10.4202 66.0833 12.7654L66.6158 14.2308L68.1251 14.6217C70.5415 15.2484 71.1908 18.3742 69.2237 19.911L67.9944 20.8704L68.0896 22.4262C68.2403 24.9178 65.4681 26.5011 63.3987 25.1056L62.1065 24.2326L60.6555 24.8041C58.3322 25.7172 55.9702 23.5694 56.6585 21.1698L57.0884 19.6717L56.0977 18.4684C54.5112 16.541 55.8231 13.6307 58.318 13.5438L59.8751 13.4899L60.7142 12.1753Z",fill:n,stroke:e,"stroke-width":"3.27381"}),m("path",{d:"M63.925 5.23719C71.0867 6.02431 76.2545 12.4676 75.4676 19.6293C74.6805 26.7911 68.2364 31.959 61.0746 31.1718C53.9129 30.3845 48.7459 23.9406 49.533 16.7789C50.3203 9.61739 56.7634 4.45029 63.925 5.23719ZM63.6957 7.32326C57.6866 6.66302 52.2797 10.9991 51.6191 17.0082C50.9586 23.0174 55.2946 28.4251 61.3038 29.0858C67.3132 29.7462 72.7211 25.4094 73.3816 19.4C74.0418 13.3908 69.705 7.98372 63.6957 7.32326Z",fill:n,stroke:e,"stroke-width":"0.3","stroke-linecap":"round","stroke-linejoin":"round"})]}),m("ellipse",{cx:"41",cy:"85",rx:"15",ry:"3",fill:t,"fill-opacity":"0.35"}),m("defs",{children:m("clipPath",{id:"clip0_7006_42127",children:m("rect",{width:"33",height:"33",fill:"white",transform:"translate(47.9012) rotate(6.27205)"})})})]})})}function Zt(t){const e=Vh().value?gy:vy;return m(e,{...t})}function gy({visible:t,className:e,grow:n,dep:i,...r}){return t?m("div",{className:ae(n&&"grow",e),...r}):null}function vy({visible:t,children:e,className:n,grow:i,dep:r,...s}){const[o,a]=V(t),[c,l]=V(null),[d,u]=V(null),h=B(e);t&&(h.current=e);const f=j(g=>{l(g),g&&!t&&(g.style.width="0px",g.style.height="0px")},[]);G(()=>{d&&(d.style.transition="none",d.style.opacity="0",d.offsetWidth,d.style.transition="",d.style.opacity="")},[r]),oe(()=>{c&&(c.style.width=`${c.offsetWidth}px`,c.style.height=`${c.offsetHeight}px`)},[c,t,r]),G(()=>{if(!c||!d)return;t&&a(!0);const g=t?d.offsetWidth:0,b=t?d.offsetHeight:0;c.style.width=!t||c.offsetWidth!==g?`${g}px`:"",c.style.height=!t||c.offsetHeight!==b?`${b}px`:""},[c,d,t,r]);const{transitioning:v,handlers:p}=qh({onEnd:()=>{t?(c.style.width="",c.style.height=""):a(!1)}});return m("div",{ref:f,className:ae("relative inline-flex shrink-0 justify-center items-center transition-[opacity,width,height,transform,flex-grow] duration-200 min-w-0",!t&&"opacity-0 scale-75",t&&i&&"grow",t&&o&&!v.value&&"z-1"),...p,children:m("div",{ref:u,className:ae("shrink-0 min-h-min min-w-min transition-opacity duration-200",i&&"grow",n),...s,children:(t||o)&&h.current})})}const by={primary:"text-accent-primary border border-accent bg-accent hover:border-accent-hover hover:bg-accent-hover active:border-accent-active active:bg-accent-active",secondary:"text-base-primary border border-base-border bg-base hover:bg-base-hover active:bg-base-active",ghost:"text-base-primary border border-base bg-base hover:bg-base-hover hover:border-base-hover active:bg-base-active active:border-base-active"},pt=X(function({variant:t="secondary",children:e,icon:n,className:i,iconClassName:r,truncate:s=!0,...o},a){const c=!!n&&!e;return m("button",{ref:a,className:ae("h-9 flex px-2.5 text-sm items-center transition-colors justify-center rounded-button duration-200 focus-ring overflow-hidden select-none",by[t],c&&"min-w-9",i),type:"button",...o,children:[n&&m(It,{className:ae("transition-[margin] duration-200",c&&"-mx-0.5",r),name:n}),m(Zt,{visible:!!e,dep:e,children:m("span",{className:"block whitespace-nowrap max-w-64 truncate px-1.5",children:e})})]})});function va({className:t,...e}){const{status:n,isSpeaking:i}=Be(),r=Wr(),s=xe(),o=ue(()=>n.value!=="connected"?s.connecting_status.value:r.value?s.chatting_status.value:i.value?s.speaking_status.value:s.listening_status.value),[a,c]=V(o.peek());return Ct(()=>{const l=o.value;if(n.value==="connected"&&i.value)c(l);else{const d=setTimeout(()=>{c(l)},500);return()=>clearTimeout(d)}}),m("div",{className:ae("py-1.5 px-3 bg-base-active overflow-hidden rounded-bubble text-sm",t),...e,children:m(je,{initial:!1,active:!0,children:m("div",{className:"animate-text whitespace-nowrap transition-[opacity,transform] ease-out duration-200 data-hidden:opacity-0 transform data-hidden:translate-y-2",children:a})},a)})}const Wh=Re(null);function yy({children:t}){const e=Ie(null),n=Ie(""),i=Ie("initial"),{lastId:r}=Be(),s=ie("agent-id"),{serverUrl:o}=ua(),a=j(async u=>{const h=r.value,f=s.value;if(!h||!f){console.warn("[ConversationalAI] Cannot submit rating: missing agent_id or conversation_id");return}try{e.value=u,i.value="submitted-rating",await gh(h,{rating:u},o.value)}catch(v){console.error("[ConversationalAI] Failed to submit rating:",v)}},[]),c=j(async()=>{const u=r.value,h=s.value;if(!u||!h){console.warn("[ConversationalAI] Cannot submit feedback: missing agent_id or conversation_id");return}if(e.value===null){console.warn("[ConversationalAI] Cannot submit feedback: rating not set");return}if(n.value)try{i.value="submitted-follow-up",await gh(u,{rating:e.value,comment:n.value||void 0},o.value)}catch(f){console.error("[ConversationalAI] Failed to submit feedback:",f)}},[]),l=j(()=>{e.value=null,n.value="",i.value="initial"},[]);Ct(()=>{r.value!==null&&l()});const d=oe(()=>({rating:e,feedbackText:n,feedbackProgress:i,submitRating:a,submitFeedback:c,reset:l}),[a,c,l]);return m(Wh.Provider,{value:d,children:t})}function ba(){return et(Wh)}const Hh=Re(null);function ky({defaultContent:t="transcript",children:e}){const n=Ie(t),i=oe(()=>{const r=n.value==="feedback"?{showHeaderBack:!0,onHeaderBack:()=>{n.value="transcript"}}:{showHeaderBack:!1};return{currentContent:n,currentConfig:r}},[n.value]);return m(Hh.Provider,{value:i,children:e})}function ya(){return et(Hh)}const Gh=(t,e)=>Array.from({length:e-t+1},(n,i)=>i+t),Cy=({isFilled:t,iconName:e})=>m("span",{className:ae("w-8 h-8 grid place-content-center",t?"text-base-primary":"text-base-border"),children:m(It,{name:e,size:"lg"})}),wy=({value:t,rating:e,hoverRating:n,onClick:i,onHover:r,onKeyDown:s,iconName:o})=>{const a=e.value!==null&&t<=e.value,c=n.value!==null&&t<=n.value,l=j(u=>{u.stopPropagation(),i(t)},[i,t]),d=j(u=>{s(u,t)},[s,t]);return m("button",{type:"button",role:"radio","aria-checked":a,"aria-label":t.toString(),onMouseEnter:()=>r(t),onClick:l,onKeyDown:d,className:ae("w-8 h-8 grid place-content-center rounded-full focus-ring transition-colors cursor-pointer",a||c?"text-base-primary":"text-base-border"),children:m(It,{name:o,size:"lg"})})},_y=({onRate:t,min:e=1,max:n=5,ariaLabel:i,icon:r="star"})=>{const s=Ie(null),o=Ie(null),a=Gh(e,n),c=j(h=>{o.value=h},[o]),l=j(()=>{o.value=null},[o]),d=j(h=>{s.value=h,t(h)},[s,t]),u=j((h,f)=>{if(h.key==="Enter"||h.key===" ")h.preventDefault(),s.value=f,t(f);else if(h.key==="ArrowLeft"||h.key==="ArrowDown"){if(h.preventDefault(),f-1>=e){const v=h.currentTarget,p=v==null?void 0:v.previousElementSibling;p==null||p.focus()}}else if((h.key==="ArrowRight"||h.key==="ArrowUp")&&(h.preventDefault(),f+1<=n)){const v=h.currentTarget,p=v==null?void 0:v.nextElementSibling;p==null||p.focus()}},[s,t,e,n]);return m("div",{role:"radiogroup","aria-label":i,className:"flex no-wrap cursor-pointer",onMouseLeave:l,children:a.map(h=>m(wy,{value:h,rating:s,hoverRating:o,onClick:d,onHover:c,onKeyDown:u,iconName:r},h))})};function Kh({rating:t,min:e=1,max:n=5,icon:i="star"}){const r=Gh(e,n);return m("div",{className:"flex no-wrap",role:"img","aria-label":`Rating: ${t} out of ${n}`,children:r.map(s=>m(Cy,{isFilled:t>=s,iconName:i},s))})}function Sy({icon:t,onRate:e}){const n=xe();return m("div",{className:"flex flex-col items-center",children:[m("div",{className:"text-sm text-base-primary font-medium",children:n.initiate_feedback}),m("div",{className:"py-4",children:m(_y,{onRate:e,ariaLabel:n.initiate_feedback,icon:t})})]})}function Ty({icon:t,rating:e,showFollowUpButton:n,onFollowUpClick:i}){const r=xe();return m("div",{className:"flex flex-col items-center gap-3 mb-4",children:[m("div",{className:"text-sm text-base-primary font-medium",children:r.thanks_for_feedback}),m(Kh,{rating:e,min:1,max:5,icon:t}),n&&m(pt,{variant:"secondary",onClick:i,children:r.request_follow_up_feedback})]})}function xy({icon:t="star"}){const{currentContent:e}=ya(),{rating:n,feedbackProgress:i,submitRating:r}=ba(),s=i.value!=="initial"&&n.value!==null,o=j(c=>{r(c),e.value="feedback"},[r]),a=j(()=>{e.value="feedback"},[]);return s?m(Ty,{icon:t,rating:n.value??0,showFollowUpButton:i.value!=="submitted-follow-up",onFollowUpClick:a}):m(Sy,{icon:t,onRate:o})}function Py({entry:t}){const{previewUrl:e}=pa();return m("div",{className:ae("flex gap-2.5 transition-[opacity,transform] duration-200 data-hidden:opacity-0 data-hidden:scale-75",t.role==="user"?"justify-end pl-16 origin-top-right":"pr-16 origin-top-left"),children:[t.role==="ai"&&m("img",{src:e,alt:"AI agent avatar",className:"bg-base-border shrink-0 w-5 h-5 rounded-full"}),m("div",{dir:"auto",className:ae("px-3 py-2.5 rounded-bubble text-sm min-w-0 [overflow-wrap:break-word]",t.role==="user"?"bg-accent text-accent-primary":"bg-base-active text-base-primary"),children:t.message})]})}function Ey({entry:t}){const e=xe(),{lastId:n}=Be(),i=Db();return m("div",{className:"mt-3 px-8 flex flex-col",children:[i&&m(xy,{}),m("div",{className:"text-xs text-base-subtle text-center transition-opacity duration-200 data-hidden:opacity-0",children:[t.role==="user"?e.user_ended_conversation:e.agent_ended_conversation,m("br",{}),n.value&&m("span",{className:"break-all",children:[e.conversation_id,": ",n.value]})]})]})}function Ry({entry:t}){const e=xe(),{lastId:n}=Be();return m("div",{className:"mt-2 px-8 text-xs text-base-error text-center transition-opacity duration-200 data-hidden:opacity-0",children:[e.error_occurred,m("br",{}),t.message,n.value&&m(ge,{children:[m("br",{}),m("span",{className:"text-base-subtle break-all",children:[e.conversation_id,": ",n.value]})]})]})}function Iy({entry:t,animateIn:e}){return m(je,{initial:!e,active:!0,children:t.type==="message"?m(Py,{entry:t}):t.type==="disconnection"?m(Ey,{entry:t}):m(Ry,{entry:t})})}const Oy=16;function Ay({scrollPinned:t,transcript:e}){const n=B(null),i=B(0),r=B(null),s=B(!1),o=B(!1),a=u=>{var h;(h=n.current)==null||h.scrollTo({top:n.current.scrollHeight,behavior:u?"smooth":"instant"})},c=()=>{const u=n.current;if(!u||!s.current||o.current)return;const h=u.scrollTop,f=u.scrollHeight-u.clientHeight,v=f-h;if(Math.abs(v)<1){u.scrollTop=f,r.current=requestAnimationFrame(c);return}const p=v*.2,g=2;u.scrollTop=h+Math.max(p,g),r.current=requestAnimationFrame(c)},l=()=>{!n.current||o.current||s.current||(s.current=!0,r.current=requestAnimationFrame(c))},d=B(!0);return G(()=>(d.current=!1,a(!1),()=>{r.current&&cancelAnimationFrame(r.current)}),[]),Ct(()=>{var u;const h=e.value;if(!t.peek())return;const f=h[h.length-1];if((f==null?void 0:f.type)==="message"&&(f==null?void 0:f.role)==="ai"&&(f==null?void 0:f.isText)===!0){const v=((u=f.message)==null?void 0:u.length)||0;i.current===0&&v>0?(i.current=v,o.current=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{!o.current&&t.peek()&&(a(!1),l())})})):v>i.current&&(i.current=v,l())}else i.current=0,s.current=!1,o.current=!1,r.current&&(cancelAnimationFrame(r.current),r.current=null),a(!0)}),m("div",{ref:n,onScroll:u=>{const h=u.currentTarget.scrollTop>=u.currentTarget.scrollHeight-u.currentTarget.clientHeight-Oy;t.value=h,!h&&s.current&&(o.current=!0,s.current=!1,r.current&&(cancelAnimationFrame(r.current),r.current=null))},className:"px-4 pt-3 pb-3 grow flex flex-col gap-3 overflow-x-hidden overflow-y-auto",children:e.value.map((u,h)=>m(Iy,{entry:u,animateIn:!d.current},`${h}-${u.conversationIndex}`))})}function Jh({className:t,...e}){return m("textarea",{className:ae("px-3 py-[calc(theme(spacing.2)-1px)] border text-sm text-base-primary bg-base border-base-border rounded-input focus-ring resize-none [field-sizing:content] placeholder:text-base-subtle",t),...e})}function ka({visible:t,...e}){const n=xe(),{isMuted:i,isMutingEnabled:r,setIsMuted:s}=Eh(),o=j(()=>{s(!i.peek())},[s]);return r.value?m(Zt,{visible:t,className:"p-1",children:m(pt,{"aria-label":n.mute_microphone,"aria-pressed":i,icon:i.value?"mic-off":"mic",onClick:o,...e})}):null}function Ca({iconOnly:t,isDisconnected:e,children:n,...i}){const{endSession:r,startSession:s}=Be(),o=xe();return m(pt,{variant:e?"primary":"secondary",icon:e?"phone":"phone-off",onClick:e?a=>s(a.currentTarget):r,"aria-label":e?o.start_call:o.end_call,...i,children:t?void 0:n??(e?o.start_call:o.end_call)})}function Dy({showTranscript:t,scrollPinned:e}){const n=Ie(""),i=Wr(),{text_input_enabled:r}=Ae().value,s=xe(),{isDisconnected:o,status:a,startSession:c,sendUserMessage:l,sendUserActivity:d,conversationIndex:u}=Be(),h=j(async g=>{g.preventDefault();const b=n.value.trim();b&&(e.value=!0,n.value="",o.value?await c(g.currentTarget,b):l(b))},[n,e,o,c,l]),f=j(async g=>{g.key==="Enter"&&!g.shiftKey&&await h(g)},[h]),v=j(g=>{n.value=g.currentTarget.value},[n]),p=ue(()=>!!n.value.trim());return m("div",{className:"shrink-0 overflow-hidden flex p-3 items-end justify-end",children:[r&&m("div",{className:"relative grow min-w-0 flex z-1 m-1",children:[m(Jh,{rows:1,"aria-label":s.input_label,value:n,onInput:d,onChange:v,onKeyDown:f,className:"min-w-0 w-full max-h-[8lh] pr-9",placeholder:i.value?o.value&&u.value>0?s.input_placeholder_new_conversation:s.input_placeholder_text_only:s.input_placeholder}),m(je,{active:p,children:m("button",{"aria-label":s.send_message,className:"absolute right-1 bottom-1 w-7 h-7 flex items-center justify-center hover:bg-base-hover active:bg-base-active rounded-button focus-ring transition-[transform,opacity] duration-200 data-hidden:opacity-0 data-hidden:scale-90",onClick:h,children:m(It,{name:"send"})})})]}),m("div",{className:"flex h-11 items-center",children:[m(ka,{visible:!i.value&&!o.value}),m(Zt,{visible:!o.value||t,className:"p-1",children:m(Ca,{iconOnly:!o.value,isDisconnected:o.value,disabled:a.value==="disconnecting"||a.value==="connecting",children:s.new_call})})]})]})}function My(){const t=xe(),{rating:e,feedbackText:n}=ba(),i=j(r=>{n.value=r.currentTarget.value},[]);return m("div",{className:"grow flex flex-col overflow-y-auto overflow-x-hidden px-4",children:m("div",{className:"flex flex-col gap-8 min-h-full pt-4 pb-2",children:[m("div",{className:"flex flex-col items-center justify-center gap-3",children:[m(my,{orbColor:"var(--el-base-subtle)",circleBackgroundColor:"var(--el-base)",starColor:"var(--el-base-primary)",className:"w-20 h-22"}),e.value!==null&&m(Kh,{rating:e.value,min:1,max:5}),m("div",{className:"text-center",children:[m("p",{className:"text-sm text-base-primary font-medium",children:t.thanks_for_feedback}),m("p",{className:"text-sm text-base-subtle",children:t.thanks_for_feedback_details})]})]}),m(Jh,{className:"w-full min-h-[6lh]",placeholder:t.follow_up_feedback_placeholder,rows:6,value:n,onInput:i})]})})}function Ny(){const t=xe(),{currentContent:e}=ya(),{submitFeedback:n}=ba(),i=j(()=>{n(),e.value="transcript"},[n]);return m("div",{className:"shrink-0 overflow-hidden flex p-3 items-end justify-end",children:m(pt,{variant:"primary",onClick:i,children:t.submit})})}function Yh(t,[e,n]){return Math.min(n,Math.max(e,t))}function Pe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(i){if(t==null||t(i),n===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function wa(t,e=[]){let n=[];function i(s,o){const a=Re(o),c=n.length;n=[...n,o];const l=u=>{var h;const{scope:f,children:v,...p}=u,g=((h=f==null?void 0:f[t])==null?void 0:h[c])||a,b=oe(()=>p,Object.values(p));return m(g.Provider,{value:b,children:v})};l.displayName=s+"Provider";function d(u,h){var f;const v=((f=h==null?void 0:h[t])==null?void 0:f[c])||a,p=sn(v);if(p)return p;if(o!==void 0)return o;throw new Error(`\`${u}\` must be used within \`${s}\``)}return[l,d]}const r=()=>{const s=n.map(o=>Re(o));return function(o){const a=(o==null?void 0:o[t])||s;return oe(()=>({[`__scope${t}`]:{...o,[t]:a}}),[o,a])}};return r.scopeName=t,[i,Ly(r,...e)]}function Ly(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const i=t.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(r){const s=i.reduce((o,{useScope:a,scopeName:c})=>{const l=a(r)[`__scope${c}`];return{...o,...l}},{});return oe(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}function Uy(t){const e=t+"CollectionProvider",[n,i]=wa(e),[r,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),o=p=>{const{scope:g,children:b}=p,k=Vt.useRef(null),w=Vt.useRef(new Map).current;return m(r,{scope:g,itemMap:w,collectionRef:k,children:b})};o.displayName=e;const a=t+"CollectionSlot",c=Vi(a),l=Vt.forwardRef((p,g)=>{const{scope:b,children:k}=p,w=s(a,b),y=Fe(g,w.collectionRef);return m(c,{ref:y,children:k})});l.displayName=a;const d=t+"CollectionItemSlot",u="data-radix-collection-item",h=Vi(d),f=Vt.forwardRef((p,g)=>{const{scope:b,children:k,...w}=p,y=Vt.useRef(null),_=Fe(g,y),S=s(d,b);return Vt.useEffect(()=>(S.itemMap.set(y,{ref:y,...w}),()=>void S.itemMap.delete(y))),m(h,{[u]:"",ref:_,children:k})});f.displayName=d;function v(p){const g=s(t+"CollectionConsumer",p);return Vt.useCallback(()=>{const b=g.collectionRef.current;if(!b)return[];const k=Array.from(b.querySelectorAll(`[${u}]`));return Array.from(g.itemMap.values()).sort((w,y)=>k.indexOf(w.ref.current)-k.indexOf(y.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:o,Slot:l,ItemSlot:f},v,i]}var Fy=Re(void 0);function By(t){const e=sn(Fy);return t||e||"ltr"}var jy=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_e=jy.reduce((t,e)=>{const n=Vi(`Primitive.${e}`),i=X((r,s)=>{const{asChild:o,...a}=r,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),m(c,{...a,ref:s})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{});function Vy(t,e){t&&ir(()=>t.dispatchEvent(e))}function Mn(t){const e=B(t);return G(()=>{e.current=t}),oe(()=>(...n)=>{var i;return(i=e.current)==null?void 0:i.call(e,...n)},[])}function qy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t);G(()=>{const i=r=>{r.key==="Escape"&&n(r)};return e.addEventListener("keydown",i,{capture:!0}),()=>e.removeEventListener("keydown",i,{capture:!0})},[n,e])}var $y="DismissableLayer",_a="dismissableLayer.update",zy="dismissableLayer.pointerDownOutside",Wy="dismissableLayer.focusOutside",Xh,Qh=Re({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Zh=X((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:i,onPointerDownOutside:r,onFocusOutside:s,onInteractOutside:o,onDismiss:a,...c}=t,l=sn(Qh),[d,u]=V(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=V({}),v=Fe(e,x=>u(x)),p=Array.from(l.layers),[g]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=p.indexOf(g),k=d?p.indexOf(d):-1,w=l.layersWithOutsidePointerEventsDisabled.size>0,y=k>=b,_=Ky(x=>{const I=x.target,R=[...l.branches].some(A=>A.contains(I));!y||R||(r==null||r(x),o==null||o(x),x.defaultPrevented||a==null||a())},h),S=Jy(x=>{const I=x.target;[...l.branches].some(R=>R.contains(I))||(s==null||s(x),o==null||o(x),x.defaultPrevented||a==null||a())},h);return qy(x=>{k===l.layers.size-1&&(i==null||i(x),!x.defaultPrevented&&a&&(x.preventDefault(),a()))},h),G(()=>{if(d)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(Xh=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(d)),l.layers.add(d),ef(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=Xh)}},[d,h,n,l]),G(()=>()=>{d&&(l.layers.delete(d),l.layersWithOutsidePointerEventsDisabled.delete(d),ef())},[d,l]),G(()=>{const x=()=>f({});return document.addEventListener(_a,x),()=>document.removeEventListener(_a,x)},[]),m(_e.div,{...c,ref:v,style:{pointerEvents:w?y?"auto":"none":void 0,...t.style},onFocusCapture:Pe(t.onFocusCapture,S.onFocusCapture),onBlurCapture:Pe(t.onBlurCapture,S.onBlurCapture),onPointerDownCapture:Pe(t.onPointerDownCapture,_.onPointerDownCapture)})});Zh.displayName=$y;var Hy="DismissableLayerBranch",Gy=X((t,e)=>{const n=sn(Qh),i=B(null),r=Fe(e,i);return G(()=>{const s=i.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),m(_e.div,{...t,ref:r})});Gy.displayName=Hy;function Ky(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1),r=B(()=>{});return G(()=>{const s=a=>{if(a.target&&!i.current){let c=function(){tf(zy,n,l,{discrete:!0})};const l={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",r.current),r.current=c,e.addEventListener("click",r.current,{once:!0})):c()}else e.removeEventListener("click",r.current);i.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",s),e.removeEventListener("click",r.current)}},[e,n]),{onPointerDownCapture:()=>i.current=!0}}function Jy(t,e=globalThis==null?void 0:globalThis.document){const n=Mn(t),i=B(!1);return G(()=>{const r=s=>{s.target&&!i.current&&tf(Wy,n,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function ef(){const t=new CustomEvent(_a);document.dispatchEvent(t)}function tf(t,e,n,{discrete:i}){const r=n.originalEvent.target,s=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&r.addEventListener(t,e,{once:!0}),i?Vy(r,s):r.dispatchEvent(s)}var Sa=0;function Yy(){G(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??nf()),document.body.insertAdjacentElement("beforeend",t[1]??nf()),Sa++,()=>{Sa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Sa--}},[])}function nf(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Ta="focusScope.autoFocusOnMount",xa="focusScope.autoFocusOnUnmount",rf={bubbles:!1,cancelable:!0},Xy="FocusScope",sf=X((t,e)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:r,onUnmountAutoFocus:s,...o}=t,[a,c]=V(null),l=Mn(r),d=Mn(s),u=B(null),h=Fe(e,p=>c(p)),f=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;G(()=>{if(i){let p=function(w){if(f.paused||!a)return;const y=w.target;a.contains(y)?u.current=y:bn(u.current,{select:!0})},g=function(w){if(f.paused||!a)return;const y=w.relatedTarget;y!==null&&(a.contains(y)||bn(u.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const y of w)y.removedNodes.length>0&&bn(a)};document.addEventListener("focusin",p),document.addEventListener("focusout",g);const k=new MutationObserver(b);return a&&k.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",g),k.disconnect()}}},[i,a,f.paused]),G(()=>{if(a){cf.add(f);const p=document.activeElement;if(!a.contains(p)){const g=new CustomEvent(Ta,rf);a.addEventListener(Ta,l),a.dispatchEvent(g),g.defaultPrevented||(Qy(ik(of(a)),{select:!0}),document.activeElement===p&&bn(a))}return()=>{a.removeEventListener(Ta,l),setTimeout(()=>{const g=new CustomEvent(xa,rf);a.addEventListener(xa,d),a.dispatchEvent(g),g.defaultPrevented||bn(p??document.body,{select:!0}),a.removeEventListener(xa,d),cf.remove(f)},0)}}},[a,l,d,f]);const v=j(p=>{if(!n&&!i||f.paused)return;const g=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,b=document.activeElement;if(g&&b){const k=p.currentTarget,[w,y]=Zy(k);w&&y?!p.shiftKey&&b===y?(p.preventDefault(),n&&bn(w,{select:!0})):p.shiftKey&&b===w&&(p.preventDefault(),n&&bn(y,{select:!0})):b===k&&p.preventDefault()}},[n,i,f.paused]);return m(_e.div,{tabIndex:-1,...o,ref:h,onKeyDown:v})});sf.displayName=Xy;function Qy(t,{select:e=!1}={}){const n=document.activeElement;for(const i of t)if(bn(i,{select:e}),document.activeElement!==n)return}function Zy(t){const e=of(t),n=af(e,t),i=af(e.reverse(),t);return[n,i]}function of(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const r=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||r?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function af(t,e){for(const n of t)if(!ek(n,{upTo:e}))return n}function ek(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function tk(t){return t instanceof HTMLInputElement&&"select"in t}function bn(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&tk(t)&&e&&t.select()}}var cf=nk();function nk(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=lf(t,e),t.unshift(e)},remove(e){var n;t=lf(t,e),(n=t[0])==null||n.resume()}}}function lf(t,e){const n=[...t],i=n.indexOf(e);return i!==-1&&n.splice(i,1),n}function ik(t){return t.filter(e=>e.tagName!=="A")}var Ke=globalThis!=null&&globalThis.document?Bt:()=>{},rk=tl[" useId ".trim().toString()]||(()=>{}),sk=0;function Pa(t){const[e,n]=V(rk());return Ke(()=>{n(i=>i??String(sk++))},[t]),e?`radix-${e}`:""}const ok=["top","right","bottom","left"],yn=Math.min,tt=Math.max,Gr=Math.round,Kr=Math.floor,Ot=t=>({x:t,y:t}),ak={left:"right",right:"left",bottom:"top",top:"bottom"},ck={start:"end",end:"start"};function Ea(t,e,n){return tt(t,yn(e,n))}function en(t,e){return typeof t=="function"?t(e):t}function tn(t){return t.split("-")[0]}function oi(t){return t.split("-")[1]}function Ra(t){return t==="x"?"y":"x"}function Ia(t){return t==="y"?"height":"width"}const lk=new Set(["top","bottom"]);function At(t){return lk.has(tn(t))?"y":"x"}function Oa(t){return Ra(At(t))}function dk(t,e,n){n===void 0&&(n=!1);const i=oi(t),r=Oa(t),s=Ia(r);let o=r==="x"?i===(n?"end":"start")?"right":"left":i==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=Jr(o)),[o,Jr(o)]}function uk(t){const e=Jr(t);return[Aa(t),e,Aa(e)]}function Aa(t){return t.replace(/start|end/g,e=>ck[e])}const df=["left","right"],uf=["right","left"],hk=["top","bottom"],fk=["bottom","top"];function pk(t,e,n){switch(t){case"top":case"bottom":return n?e?uf:df:e?df:uf;case"left":case"right":return e?hk:fk;default:return[]}}function mk(t,e,n,i){const r=oi(t);let s=pk(tn(t),n==="start",i);return r&&(s=s.map(o=>o+"-"+r),e&&(s=s.concat(s.map(Aa)))),s}function Jr(t){return t.replace(/left|right|bottom|top/g,e=>ak[e])}function gk(t){return{top:0,right:0,bottom:0,left:0,...t}}function hf(t){return typeof t!="number"?gk(t):{top:t,right:t,bottom:t,left:t}}function Yr(t){const{x:e,y:n,width:i,height:r}=t;return{width:i,height:r,top:n,left:e,right:e+i,bottom:n+r,x:e,y:n}}function ff(t,e,n){let{reference:i,floating:r}=t;const s=At(e),o=Oa(e),a=Ia(o),c=tn(e),l=s==="y",d=i.x+i.width/2-r.width/2,u=i.y+i.height/2-r.height/2,h=i[a]/2-r[a]/2;let f;switch(c){case"top":f={x:d,y:i.y-r.height};break;case"bottom":f={x:d,y:i.y+i.height};break;case"right":f={x:i.x+i.width,y:u};break;case"left":f={x:i.x-r.width,y:u};break;default:f={x:i.x,y:i.y}}switch(oi(e)){case"start":f[o]-=h*(n&&l?-1:1);break;case"end":f[o]+=h*(n&&l?-1:1);break}return f}const vk=async(t,e,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:s=[],platform:o}=n,a=s.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(e));let l=await o.getElementRects({reference:t,floating:e,strategy:r}),{x:d,y:u}=ff(l,i,c),h=i,f={},v=0;for(let p=0;p<a.length;p++){const{name:g,fn:b}=a[p],{x:k,y:w,data:y,reset:_}=await b({x:d,y:u,initialPlacement:i,placement:h,strategy:r,middlewareData:f,rects:l,platform:o,elements:{reference:t,floating:e}});d=k??d,u=w??u,f={...f,[g]:{...f[g],...y}},_&&v<=50&&(v++,typeof _=="object"&&(_.placement&&(h=_.placement),_.rects&&(l=_.rects===!0?await o.getElementRects({reference:t,floating:e,strategy:r}):_.rects),{x:d,y:u}=ff(l,h,c)),p=-1)}return{x:d,y:u,placement:h,strategy:r,middlewareData:f}};async function qi(t,e){var n;e===void 0&&(e={});const{x:i,y:r,platform:s,rects:o,elements:a,strategy:c}=t,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:f=0}=en(e,t),v=hf(f),p=a[h?u==="floating"?"reference":"floating":u],g=Yr(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(p)))==null||n?p:p.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),b=u==="floating"?{x:i,y:r,width:o.floating.width,height:o.floating.height}:o.reference,k=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),w=await(s.isElement==null?void 0:s.isElement(k))?await(s.getScale==null?void 0:s.getScale(k))||{x:1,y:1}:{x:1,y:1},y=Yr(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:k,strategy:c}):b);return{top:(g.top-y.top+v.top)/w.y,bottom:(y.bottom-g.bottom+v.bottom)/w.y,left:(g.left-y.left+v.left)/w.x,right:(y.right-g.right+v.right)/w.x}}const bk=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:i,placement:r,rects:s,platform:o,elements:a,middlewareData:c}=e,{element:l,padding:d=0}=en(t,e)||{};if(l==null)return{};const u=hf(d),h={x:n,y:i},f=Oa(r),v=Ia(f),p=await o.getDimensions(l),g=f==="y",b=g?"top":"left",k=g?"bottom":"right",w=g?"clientHeight":"clientWidth",y=s.reference[v]+s.reference[f]-h[f]-s.floating[v],_=h[f]-s.reference[f],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l));let x=S?S[w]:0;(!x||!await(o.isElement==null?void 0:o.isElement(S)))&&(x=a.floating[w]||s.floating[v]);const I=y/2-_/2,R=x/2-p[v]/2-1,A=yn(u[b],R),M=yn(u[k],R),N=A,q=x-p[v]-M,F=x/2-p[v]/2+I,te=Ea(N,F,q),H=!c.arrow&&oi(r)!=null&&F!==te&&s.reference[v]/2-(F<N?A:M)-p[v]/2<0,J=H?F<N?F-N:F-q:0;return{[f]:h[f]+J,data:{[f]:te,centerOffset:F-te-J,...H&&{alignmentOffset:J}},reset:H}}}),yk=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,i;const{placement:r,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:l}=e,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:p=!0,...g}=en(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const b=tn(r),k=At(a),w=tn(a)===a,y=await(c.isRTL==null?void 0:c.isRTL(l.floating)),_=h||(w||!p?[Jr(a)]:uk(a)),S=v!=="none";!h&&S&&_.push(...mk(a,p,v,y));const x=[a,..._],I=await qi(e,g),R=[];let A=((i=s.flip)==null?void 0:i.overflows)||[];if(d&&R.push(I[b]),u){const F=dk(r,o,y);R.push(I[F[0]],I[F[1]])}if(A=[...A,{placement:r,overflows:R}],!R.every(F=>F<=0)){var M,N;const F=(((M=s.flip)==null?void 0:M.index)||0)+1,te=x[F];if(te&&(!(u==="alignment"&&k!==At(te))||A.every(J=>At(J.placement)===k?J.overflows[0]>0:!0)))return{data:{index:F,overflows:A},reset:{placement:te}};let H=(N=A.filter(J=>J.overflows[0]<=0).sort((J,W)=>J.overflows[1]-W.overflows[1])[0])==null?void 0:N.placement;if(!H)switch(f){case"bestFit":{var q;const J=(q=A.filter(W=>{if(S){const Z=At(W.placement);return Z===k||Z==="y"}return!0}).map(W=>[W.placement,W.overflows.filter(Z=>Z>0).reduce((Z,Ne)=>Z+Ne,0)]).sort((W,Z)=>W[1]-Z[1])[0])==null?void 0:q[0];J&&(H=J);break}case"initialPlacement":H=a;break}if(r!==H)return{reset:{placement:H}}}return{}}}};function pf(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function mf(t){return ok.some(e=>t[e]>=0)}const kk=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:i="referenceHidden",...r}=en(t,e);switch(i){case"referenceHidden":{const s=await qi(e,{...r,elementContext:"reference"}),o=pf(s,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:mf(o)}}}case"escaped":{const s=await qi(e,{...r,altBoundary:!0}),o=pf(s,n.floating);return{data:{escapedOffsets:o,escaped:mf(o)}}}default:return{}}}}},gf=new Set(["left","top"]);async function Ck(t,e){const{placement:n,platform:i,elements:r}=t,s=await(i.isRTL==null?void 0:i.isRTL(r.floating)),o=tn(n),a=oi(n),c=At(n)==="y",l=gf.has(o)?-1:1,d=s&&c?-1:1,u=en(e,t);let{mainAxis:h,crossAxis:f,alignmentAxis:v}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&typeof v=="number"&&(f=a==="end"?v*-1:v),c?{x:f*d,y:h*l}:{x:h*l,y:f*d}}const wk=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,i;const{x:r,y:s,placement:o,middlewareData:a}=e,c=await Ck(e,t);return o===((n=a.offset)==null?void 0:n.placement)&&(i=a.arrow)!=null&&i.alignmentOffset?{}:{x:r+c.x,y:s+c.y,data:{...c,placement:o}}}}},_k=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:r}=e,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:g=>{let{x:b,y:k}=g;return{x:b,y:k}}},...c}=en(t,e),l={x:n,y:i},d=await qi(e,c),u=At(tn(r)),h=Ra(u);let f=l[h],v=l[u];if(s){const g=h==="y"?"top":"left",b=h==="y"?"bottom":"right",k=f+d[g],w=f-d[b];f=Ea(k,f,w)}if(o){const g=u==="y"?"top":"left",b=u==="y"?"bottom":"right",k=v+d[g],w=v-d[b];v=Ea(k,v,w)}const p=a.fn({...e,[h]:f,[u]:v});return{...p,data:{x:p.x-n,y:p.y-i,enabled:{[h]:s,[u]:o}}}}}},Sk=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:i,placement:r,rects:s,middlewareData:o}=e,{offset:a=0,mainAxis:c=!0,crossAxis:l=!0}=en(t,e),d={x:n,y:i},u=At(r),h=Ra(u);let f=d[h],v=d[u];const p=en(a,e),g=typeof p=="number"?{mainAxis:p,crossAxis:0}:{mainAxis:0,crossAxis:0,...p};if(c){const w=h==="y"?"height":"width",y=s.reference[h]-s.floating[w]+g.mainAxis,_=s.reference[h]+s.reference[w]-g.mainAxis;f<y?f=y:f>_&&(f=_)}if(l){var b,k;const w=h==="y"?"width":"height",y=gf.has(tn(r)),_=s.reference[u]-s.floating[w]+(y&&((b=o.offset)==null?void 0:b[u])||0)+(y?0:g.crossAxis),S=s.reference[u]+s.reference[w]+(y?0:((k=o.offset)==null?void 0:k[u])||0)-(y?g.crossAxis:0);v<_?v=_:v>S&&(v=S)}return{[h]:f,[u]:v}}}},Tk=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,i;const{placement:r,rects:s,platform:o,elements:a}=e,{apply:c=()=>{},...l}=en(t,e),d=await qi(e,l),u=tn(r),h=oi(r),f=At(r)==="y",{width:v,height:p}=s.floating;let g,b;u==="top"||u==="bottom"?(g=u,b=h===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(b=u,g=h==="end"?"top":"bottom");const k=p-d.top-d.bottom,w=v-d.left-d.right,y=yn(p-d[g],k),_=yn(v-d[b],w),S=!e.middlewareData.shift;let x=y,I=_;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(I=w),(i=e.middlewareData.shift)!=null&&i.enabled.y&&(x=k),S&&!h){const A=tt(d.left,0),M=tt(d.right,0),N=tt(d.top,0),q=tt(d.bottom,0);f?I=v-2*(A!==0||M!==0?A+M:tt(d.left,d.right)):x=p-2*(N!==0||q!==0?N+q:tt(d.top,d.bottom))}await c({...e,availableWidth:I,availableHeight:x});const R=await o.getDimensions(a.floating);return v!==R.width||p!==R.height?{reset:{rects:!0}}:{}}}};function Xr(){return typeof window<"u"}function ai(t){return vf(t)?(t.nodeName||"").toLowerCase():"#document"}function nt(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Dt(t){var e;return(e=(vf(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function vf(t){return Xr()?t instanceof Node||t instanceof nt(t).Node:!1}function mt(t){return Xr()?t instanceof Element||t instanceof nt(t).Element:!1}function Mt(t){return Xr()?t instanceof HTMLElement||t instanceof nt(t).HTMLElement:!1}function bf(t){return!Xr()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof nt(t).ShadowRoot}const xk=new Set(["inline","contents"]);function $i(t){const{overflow:e,overflowX:n,overflowY:i,display:r}=gt(t);return/auto|scroll|overlay|hidden|clip/.test(e+i+n)&&!xk.has(r)}const Pk=new Set(["table","td","th"]);function Ek(t){return Pk.has(ai(t))}const Rk=[":popover-open",":modal"];function Qr(t){return Rk.some(e=>{try{return t.matches(e)}catch{return!1}})}const Ik=["transform","translate","scale","rotate","perspective"],Ok=["transform","translate","scale","rotate","perspective","filter"],Ak=["paint","layout","strict","content"];function Da(t){const e=Ma(),n=mt(t)?gt(t):t;return Ik.some(i=>n[i]?n[i]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||Ok.some(i=>(n.willChange||"").includes(i))||Ak.some(i=>(n.contain||"").includes(i))}function Dk(t){let e=kn(t);for(;Mt(e)&&!ci(e);){if(Da(e))return e;if(Qr(e))return null;e=kn(e)}return null}function Ma(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Mk=new Set(["html","body","#document"]);function ci(t){return Mk.has(ai(t))}function gt(t){return nt(t).getComputedStyle(t)}function Zr(t){return mt(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function kn(t){if(ai(t)==="html")return t;const e=t.assignedSlot||t.parentNode||bf(t)&&t.host||Dt(t);return bf(e)?e.host:e}function yf(t){const e=kn(t);return ci(e)?t.ownerDocument?t.ownerDocument.body:t.body:Mt(e)&&$i(e)?e:yf(e)}function zi(t,e,n){var i;e===void 0&&(e=[]),n===void 0&&(n=!0);const r=yf(t),s=r===((i=t.ownerDocument)==null?void 0:i.body),o=nt(r);if(s){const a=Na(o);return e.concat(o,o.visualViewport||[],$i(r)?r:[],a&&n?zi(a):[])}return e.concat(r,zi(r,[],n))}function Na(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function kf(t){const e=gt(t);let n=parseFloat(e.width)||0,i=parseFloat(e.height)||0;const r=Mt(t),s=r?t.offsetWidth:n,o=r?t.offsetHeight:i,a=Gr(n)!==s||Gr(i)!==o;return a&&(n=s,i=o),{width:n,height:i,$:a}}function La(t){return mt(t)?t:t.contextElement}function li(t){const e=La(t);if(!Mt(e))return Ot(1);const n=e.getBoundingClientRect(),{width:i,height:r,$:s}=kf(e);let o=(s?Gr(n.width):n.width)/i,a=(s?Gr(n.height):n.height)/r;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const Nk=Ot(0);function Cf(t){const e=nt(t);return!Ma()||!e.visualViewport?Nk:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function Lk(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==nt(t)?!1:e}function Nn(t,e,n,i){e===void 0&&(e=!1),n===void 0&&(n=!1);const r=t.getBoundingClientRect(),s=La(t);let o=Ot(1);e&&(i?mt(i)&&(o=li(i)):o=li(t));const a=Lk(s,n,i)?Cf(s):Ot(0);let c=(r.left+a.x)/o.x,l=(r.top+a.y)/o.y,d=r.width/o.x,u=r.height/o.y;if(s){const h=nt(s),f=i&&mt(i)?nt(i):i;let v=h,p=Na(v);for(;p&&i&&f!==v;){const g=li(p),b=p.getBoundingClientRect(),k=gt(p),w=b.left+(p.clientLeft+parseFloat(k.paddingLeft))*g.x,y=b.top+(p.clientTop+parseFloat(k.paddingTop))*g.y;c*=g.x,l*=g.y,d*=g.x,u*=g.y,c+=w,l+=y,v=nt(p),p=Na(v)}}return Yr({width:d,height:u,x:c,y:l})}function Ua(t,e){const n=Zr(t).scrollLeft;return e?e.left+n:Nn(Dt(t)).left+n}function wf(t,e,n){n===void 0&&(n=!1);const i=t.getBoundingClientRect(),r=i.left+e.scrollLeft-(n?0:Ua(t,i)),s=i.top+e.scrollTop;return{x:r,y:s}}function Uk(t){let{elements:e,rect:n,offsetParent:i,strategy:r}=t;const s=r==="fixed",o=Dt(i),a=e?Qr(e.floating):!1;if(i===o||a&&s)return n;let c={scrollLeft:0,scrollTop:0},l=Ot(1);const d=Ot(0),u=Mt(i);if((u||!u&&!s)&&((ai(i)!=="body"||$i(o))&&(c=Zr(i)),Mt(i))){const f=Nn(i);l=li(i),d.x=f.x+i.clientLeft,d.y=f.y+i.clientTop}const h=o&&!u&&!s?wf(o,c,!0):Ot(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+h.x,y:n.y*l.y-c.scrollTop*l.y+d.y+h.y}}function Fk(t){return Array.from(t.getClientRects())}function Bk(t){const e=Dt(t),n=Zr(t),i=t.ownerDocument.body,r=tt(e.scrollWidth,e.clientWidth,i.scrollWidth,i.clientWidth),s=tt(e.scrollHeight,e.clientHeight,i.scrollHeight,i.clientHeight);let o=-n.scrollLeft+Ua(t);const a=-n.scrollTop;return gt(i).direction==="rtl"&&(o+=tt(e.clientWidth,i.clientWidth)-r),{width:r,height:s,x:o,y:a}}function jk(t,e){const n=nt(t),i=Dt(t),r=n.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(r){s=r.width,o=r.height;const l=Ma();(!l||l&&e==="fixed")&&(a=r.offsetLeft,c=r.offsetTop)}return{width:s,height:o,x:a,y:c}}const Vk=new Set(["absolute","fixed"]);function qk(t,e){const n=Nn(t,!0,e==="fixed"),i=n.top+t.clientTop,r=n.left+t.clientLeft,s=Mt(t)?li(t):Ot(1),o=t.clientWidth*s.x,a=t.clientHeight*s.y,c=r*s.x,l=i*s.y;return{width:o,height:a,x:c,y:l}}function _f(t,e,n){let i;if(e==="viewport")i=jk(t,n);else if(e==="document")i=Bk(Dt(t));else if(mt(e))i=qk(e,n);else{const r=Cf(t);i={x:e.x-r.x,y:e.y-r.y,width:e.width,height:e.height}}return Yr(i)}function Sf(t,e){const n=kn(t);return n===e||!mt(n)||ci(n)?!1:gt(n).position==="fixed"||Sf(n,e)}function $k(t,e){const n=e.get(t);if(n)return n;let i=zi(t,[],!1).filter(a=>mt(a)&&ai(a)!=="body"),r=null;const s=gt(t).position==="fixed";let o=s?kn(t):t;for(;mt(o)&&!ci(o);){const a=gt(o),c=Da(o);!c&&a.position==="fixed"&&(r=null),(s?!c&&!r:!c&&a.position==="static"&&r&&Vk.has(r.position)||$i(o)&&!c&&Sf(t,o))?i=i.filter(l=>l!==o):r=a,o=kn(o)}return e.set(t,i),i}function zk(t){let{element:e,boundary:n,rootBoundary:i,strategy:r}=t;const s=[...n==="clippingAncestors"?Qr(e)?[]:$k(e,this._c):[].concat(n),i],o=s[0],a=s.reduce((c,l)=>{const d=_f(e,l,r);return c.top=tt(d.top,c.top),c.right=yn(d.right,c.right),c.bottom=yn(d.bottom,c.bottom),c.left=tt(d.left,c.left),c},_f(e,o,r));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}}function Wk(t){const{width:e,height:n}=kf(t);return{width:e,height:n}}function Hk(t,e,n){const i=Mt(e),r=Dt(e),s=n==="fixed",o=Nn(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const c=Ot(0);function l(){c.x=Ua(r)}if(i||!i&&!s)if((ai(e)!=="body"||$i(r))&&(a=Zr(e)),i){const f=Nn(e,!0,s,e);c.x=f.x+e.clientLeft,c.y=f.y+e.clientTop}else r&&l();s&&!i&&r&&l();const d=r&&!i&&!s?wf(r,a):Ot(0),u=o.left+a.scrollLeft-c.x-d.x,h=o.top+a.scrollTop-c.y-d.y;return{x:u,y:h,width:o.width,height:o.height}}function Fa(t){return gt(t).position==="static"}function Tf(t,e){if(!Mt(t)||gt(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Dt(t)===n&&(n=n.ownerDocument.body),n}function xf(t,e){const n=nt(t);if(Qr(t))return n;if(!Mt(t)){let r=kn(t);for(;r&&!ci(r);){if(mt(r)&&!Fa(r))return r;r=kn(r)}return n}let i=Tf(t,e);for(;i&&Ek(i)&&Fa(i);)i=Tf(i,e);return i&&ci(i)&&Fa(i)&&!Da(i)?n:i||Dk(t)||n}const Gk=async function(t){const e=this.getOffsetParent||xf,n=this.getDimensions,i=await n(t.floating);return{reference:Hk(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}};function Kk(t){return gt(t).direction==="rtl"}const Jk={convertOffsetParentRelativeRectToViewportRelativeRect:Uk,getDocumentElement:Dt,getClippingRect:zk,getOffsetParent:xf,getElementRects:Gk,getClientRects:Fk,getDimensions:Wk,getScale:li,isElement:mt,isRTL:Kk};function Pf(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function Yk(t,e){let n=null,i;const r=Dt(t);function s(){var a;clearTimeout(i),(a=n)==null||a.disconnect(),n=null}function o(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),s();const l=t.getBoundingClientRect(),{left:d,top:u,width:h,height:f}=l;if(a||e(),!h||!f)return;const v=Kr(u),p=Kr(r.clientWidth-(d+h)),g=Kr(r.clientHeight-(u+f)),b=Kr(d),k={rootMargin:-v+"px "+-p+"px "+-g+"px "+-b+"px",threshold:tt(0,yn(1,c))||1};let w=!0;function y(_){const S=_[0].intersectionRatio;if(S!==c){if(!w)return o();S?o(!1,S):i=setTimeout(()=>{o(!1,1e-7)},1e3)}S===1&&!Pf(l,t.getBoundingClientRect())&&o(),w=!1}try{n=new IntersectionObserver(y,{...k,root:r.ownerDocument})}catch{n=new IntersectionObserver(y,k)}n.observe(t)}return o(!0),s}function Xk(t,e,n,i){i===void 0&&(i={});const{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=i,l=La(t),d=r||s?[...l?zi(l):[],...zi(e)]:[];d.forEach(b=>{r&&b.addEventListener("scroll",n,{passive:!0}),s&&b.addEventListener("resize",n)});const u=l&&a?Yk(l,n):null;let h=-1,f=null;o&&(f=new ResizeObserver(b=>{let[k]=b;k&&k.target===l&&f&&(f.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(e)})),n()}),l&&!c&&f.observe(l),f.observe(e));let v,p=c?Nn(t):null;c&&g();function g(){const b=Nn(t);p&&!Pf(p,b)&&n(),p=b,v=requestAnimationFrame(g)}return n(),()=>{var b;d.forEach(k=>{r&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),u==null||u(),(b=f)==null||b.disconnect(),f=null,c&&cancelAnimationFrame(v)}}const Qk=wk,Zk=_k,eC=yk,tC=Tk,nC=kk,Ef=bk,iC=Sk,rC=(t,e,n)=>{const i=new Map,r={platform:Jk,...n},s={...r.platform,_c:i};return vk(t,e,{...r,platform:s})};var sC=typeof document<"u",oC=function(){},es=sC?Bt:oC;function ts(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,i,r;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(i=n;i--!==0;)if(!ts(t[i],e[i]))return!1;return!0}if(r=Object.keys(t),n=r.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!{}.hasOwnProperty.call(e,r[i]))return!1;for(i=n;i--!==0;){const s=r[i];if(!(s==="_owner"&&t.$$typeof)&&!ts(t[s],e[s]))return!1}return!0}return t!==t&&e!==e}function Rf(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function If(t,e){const n=Rf(t);return Math.round(e*n)/n}function Ba(t){const e=B(t);return es(()=>{e.current=t}),e}function aC(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:i=[],platform:r,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:c,open:l}=t,[d,u]=V({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[h,f]=V(i);ts(h,i)||f(i);const[v,p]=V(null),[g,b]=V(null),k=j(W=>{W!==S.current&&(S.current=W,p(W))},[]),w=j(W=>{W!==x.current&&(x.current=W,b(W))},[]),y=s||v,_=o||g,S=B(null),x=B(null),I=B(d),R=c!=null,A=Ba(c),M=Ba(r),N=Ba(l),q=j(()=>{if(!S.current||!x.current)return;const W={placement:e,strategy:n,middleware:h};M.current&&(W.platform=M.current),rC(S.current,x.current,W).then(Z=>{const Ne={...Z,isPositioned:N.current!==!1};F.current&&!ts(I.current,Ne)&&(I.current=Ne,ir(()=>{u(Ne)}))})},[h,e,n,M,N]);es(()=>{l===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,u(W=>({...W,isPositioned:!1})))},[l]);const F=B(!1);es(()=>(F.current=!0,()=>{F.current=!1}),[]),es(()=>{if(y&&(S.current=y),_&&(x.current=_),y&&_){if(A.current)return A.current(y,_,q);q()}},[y,_,q,A,R]);const te=oe(()=>({reference:S,floating:x,setReference:k,setFloating:w}),[k,w]),H=oe(()=>({reference:y,floating:_}),[y,_]),J=oe(()=>{const W={position:n,left:0,top:0};if(!H.floating)return W;const Z=If(H.floating,d.x),Ne=If(H.floating,d.y);return a?{...W,transform:"translate("+Z+"px, "+Ne+"px)",...Rf(H.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:Z,top:Ne}},[n,a,H.floating,d.x,d.y]);return oe(()=>({...d,update:q,refs:te,elements:H,floatingStyles:J}),[d,q,te,H,J])}const cC=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:i,padding:r}=typeof t=="function"?t(n):t;return i&&e(i)?i.current!=null?Ef({element:i.current,padding:r}).fn(n):{}:i?Ef({element:i,padding:r}).fn(n):{}}}},lC=(t,e)=>({...Qk(t),options:[t,e]}),dC=(t,e)=>({...Zk(t),options:[t,e]}),uC=(t,e)=>({...iC(t),options:[t,e]}),hC=(t,e)=>({...eC(t),options:[t,e]}),fC=(t,e)=>({...tC(t),options:[t,e]}),pC=(t,e)=>({...nC(t),options:[t,e]}),mC=(t,e)=>({...cC(t),options:[t,e]});var gC="Arrow",Of=X((t,e)=>{const{children:n,width:i=10,height:r=5,...s}=t;return m(_e.svg,{...s,ref:e,width:i,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:m("polygon",{points:"0,0 30,0 15,10"})})});Of.displayName=gC;var vC=Of;function bC(t){const[e,n]=V(void 0);return Ke(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const i=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const s=r[0];let o,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;o=l.inlineSize,a=l.blockSize}else o=t.offsetWidth,a=t.offsetHeight;n({width:o,height:a})});return i.observe(t,{box:"border-box"}),()=>i.unobserve(t)}else n(void 0)},[t]),e}var ja="Popper",[Af,Df]=wa(ja),[yC,Mf]=Af(ja),Nf=t=>{const{__scopePopper:e,children:n}=t,[i,r]=V(null);return m(yC,{scope:e,anchor:i,onAnchorChange:r,children:n})};Nf.displayName=ja;var Lf="PopperAnchor",Uf=X((t,e)=>{const{__scopePopper:n,virtualRef:i,...r}=t,s=Mf(Lf,n),o=B(null),a=Fe(e,o),c=B(null);return G(()=>{const l=c.current;c.current=(i==null?void 0:i.current)||o.current,l!==c.current&&s.onAnchorChange(c.current)}),i?null:m(_e.div,{...r,ref:a})});Uf.displayName=Lf;var Va="PopperContent",[kC,CC]=Af(Va),Ff=X((t,e)=>{var n,i,r,s,o,a;const{__scopePopper:c,side:l="bottom",sideOffset:d=0,align:u="center",alignOffset:h=0,arrowPadding:f=0,avoidCollisions:v=!0,collisionBoundary:p=[],collisionPadding:g=0,sticky:b="partial",hideWhenDetached:k=!1,updatePositionStrategy:w="optimized",onPlaced:y,..._}=t,S=Mf(Va,c),[x,I]=V(null),R=Fe(e,it=>I(it)),[A,M]=V(null),N=bC(A),q=(N==null?void 0:N.width)??0,F=(N==null?void 0:N.height)??0,te=l+(u!=="center"?"-"+u:""),H=typeof g=="number"?g:{top:0,right:0,bottom:0,left:0,...g},J=Array.isArray(p)?p:[p],W=J.length>0,Z={padding:H,boundary:J.filter(_C),altBoundary:W},{refs:Ne,floatingStyles:bt,placement:nn,isPositioned:st,middlewareData:Ve}=aC({strategy:"fixed",placement:te,whileElementsMounted:(...it)=>Xk(...it,{animationFrame:w==="always"}),elements:{reference:S.anchor},middleware:[lC({mainAxis:d+F,alignmentAxis:h}),v&&dC({mainAxis:!0,crossAxis:!1,limiter:b==="partial"?uC():void 0,...Z}),v&&hC({...Z}),fC({...Z,apply:({elements:it,rects:Hi,availableWidth:Gi,availableHeight:Ki})=>{const{width:y_,height:k_}=Hi.reference,ps=it.floating.style;ps.setProperty("--radix-popper-available-width",`${Gi}px`),ps.setProperty("--radix-popper-available-height",`${Ki}px`),ps.setProperty("--radix-popper-anchor-width",`${y_}px`),ps.setProperty("--radix-popper-anchor-height",`${k_}px`)}}),A&&mC({element:A,padding:f}),SC({arrowWidth:q,arrowHeight:F}),k&&pC({strategy:"referenceHidden",...Z})]}),[Lt,yt]=Vf(nn),z=Mn(y);Ke(()=>{st&&(z==null||z())},[st,z]);const me=(n=Ve.arrow)==null?void 0:n.x,Se=(i=Ve.arrow)==null?void 0:i.y,re=((r=Ve.arrow)==null?void 0:r.centerOffset)!==0,[be,Ee]=V();return Ke(()=>{x&&Ee(window.getComputedStyle(x).zIndex)},[x]),m("div",{ref:Ne.setFloating,"data-radix-popper-content-wrapper":"",style:{...bt,transform:st?bt.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:be,"--radix-popper-transform-origin":[(s=Ve.transformOrigin)==null?void 0:s.x,(o=Ve.transformOrigin)==null?void 0:o.y].join(" "),...((a=Ve.hide)==null?void 0:a.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:m(kC,{scope:c,placedSide:Lt,onArrowChange:M,arrowX:me,arrowY:Se,shouldHideArrow:re,children:m(_e.div,{"data-side":Lt,"data-align":yt,..._,ref:R,style:{..._.style,animation:st?void 0:"none"}})})})});Ff.displayName=Va;var Bf="PopperArrow",wC={top:"bottom",right:"left",bottom:"top",left:"right"},jf=X(function(t,e){const{__scopePopper:n,...i}=t,r=CC(Bf,n),s=wC[r.placedSide];return m("span",{ref:r.onArrowChange,style:{position:"absolute",left:r.arrowX,top:r.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[r.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[r.placedSide],visibility:r.shouldHideArrow?"hidden":void 0},children:m(vC,{...i,ref:e,style:{...i.style,display:"block"}})})});jf.displayName=Bf;function _C(t){return t!==null}var SC=t=>({name:"transformOrigin",options:t,fn(e){var n,i,r;const{placement:s,rects:o,middlewareData:a}=e,c=((n=a.arrow)==null?void 0:n.centerOffset)!==0,l=c?0:t.arrowWidth,d=c?0:t.arrowHeight,[u,h]=Vf(s),f={start:"0%",center:"50%",end:"100%"}[h],v=(((i=a.arrow)==null?void 0:i.x)??0)+l/2,p=(((r=a.arrow)==null?void 0:r.y)??0)+d/2;let g="",b="";return u==="bottom"?(g=c?f:`${v}px`,b=`${-d}px`):u==="top"?(g=c?f:`${v}px`,b=`${o.floating.height+d}px`):u==="right"?(g=`${-d}px`,b=c?f:`${p}px`):u==="left"&&(g=`${o.floating.width+d}px`,b=c?f:`${p}px`),{data:{x:g,y:b}}}});function Vf(t){const[e,n="center"]=t.split("-");return[e,n]}var TC=Nf,xC=Uf,PC=Ff,EC=jf,RC="Portal",qf=X((t,e)=>{var n;const{container:i,...r}=t,[s,o]=V(!1);Ke(()=>o(!0),[]);const a=i||s&&((n=globalThis==null?void 0:globalThis.document)==null?void 0:n.body);return a?Vt.createPortal(m(_e.div,{...r,ref:e}),a):null});qf.displayName=RC;var IC=tl[" useInsertionEffect ".trim().toString()]||Ke;function $f({prop:t,defaultProp:e,onChange:n=()=>{},caller:i}){const[r,s,o]=OC({defaultProp:e,onChange:n}),a=t!==void 0,c=a?t:r;{const d=B(t!==void 0);G(()=>{const u=d.current;u!==a&&console.warn(`${i} is changing from ${u?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,i])}const l=j(d=>{var u;if(a){const h=AC(d)?d(t):d;h!==t&&((u=o.current)==null||u.call(o,h))}else s(d)},[a,t,s,o]);return[c,l]}function OC({defaultProp:t,onChange:e}){const[n,i]=V(t),r=B(n),s=B(e);return IC(()=>{s.current=e},[e]),G(()=>{var o;r.current!==n&&((o=s.current)==null||o.call(s,n),r.current=n)},[n,r]),[n,i,s]}function AC(t){return typeof t=="function"}function DC(t){const e=B({value:t,previous:t});return oe(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var zf=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),MC="VisuallyHidden",NC=X((t,e)=>m(_e.span,{...t,ref:e,style:{...zf,...t.style}}));NC.displayName=MC;var LC=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},di=new WeakMap,ns=new WeakMap,is={},qa=0,Wf=function(t){return t&&(t.host||Wf(t.parentNode))},UC=function(t,e){return e.map(function(n){if(t.contains(n))return n;var i=Wf(n);return i&&t.contains(i)?i:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},FC=function(t,e,n,i){var r=UC(e,Array.isArray(t)?t:[t]);is[n]||(is[n]=new WeakMap);var s=is[n],o=[],a=new Set,c=new Set(r),l=function(u){!u||a.has(u)||(a.add(u),l(u.parentNode))};r.forEach(l);var d=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(h){if(a.has(h))d(h);else try{var f=h.getAttribute(i),v=f!==null&&f!=="false",p=(di.get(h)||0)+1,g=(s.get(h)||0)+1;di.set(h,p),s.set(h,g),o.push(h),p===1&&v&&ns.set(h,!0),g===1&&h.setAttribute(n,"true"),v||h.setAttribute(i,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return d(e),a.clear(),qa++,function(){o.forEach(function(u){var h=di.get(u)-1,f=s.get(u)-1;di.set(u,h),s.set(u,f),h||(ns.has(u)||u.removeAttribute(i),ns.delete(u)),f||u.removeAttribute(n)}),qa--,qa||(di=new WeakMap,di=new WeakMap,ns=new WeakMap,is={})}},BC=function(t,e,n){n===void 0&&(n="data-aria-hidden");var i=Array.from(Array.isArray(t)?t:[t]),r=LC(t);return r?(i.push.apply(i,Array.from(r.querySelectorAll("[aria-live], script"))),FC(i,r,n,"aria-hidden")):function(){return null}},Nt=function(){return Nt=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},Nt.apply(this,arguments)};function Hf(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function jC(t,e,n){for(var i=0,r=e.length,s;i<r;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))}var rs="right-scroll-bar-position",ss="width-before-scroll-bar",VC="with-scroll-bars-hidden",qC="--removed-body-scroll-bar-size";function $a(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function $C(t,e){var n=V(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(i){var r=n.value;r!==i&&(n.value=i,n.callback(i,r))}}}})[0];return n.callback=e,n.facade}var zC=typeof window<"u"?Bt:G,Gf=new WeakMap;function WC(t,e){var n=$C(null,function(i){return t.forEach(function(r){return $a(r,i)})});return zC(function(){var i=Gf.get(n);if(i){var r=new Set(i),s=new Set(t),o=n.current;r.forEach(function(a){s.has(a)||$a(a,null)}),s.forEach(function(a){r.has(a)||$a(a,o)})}Gf.set(n,t)},[t]),n}function HC(t){return t}function GC(t,e){e===void 0&&(e=HC);var n=[],i=!1,r={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(s){var o=e(s,i);return n.push(o),function(){n=n.filter(function(a){return a!==o})}},assignSyncMedium:function(s){for(i=!0;n.length;){var o=n;n=[],o.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){i=!0;var o=[];if(n.length){var a=n;n=[],a.forEach(s),o=n}var c=function(){var d=o;o=[],d.forEach(s)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){o.push(d),l()},filter:function(d){return o=o.filter(d),n}}}};return r}function KC(t){t===void 0&&(t={});var e=GC(null);return e.options=Nt({async:!0,ssr:!1},t),e}var Kf=function(t){var e=t.sideCar,n=Hf(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=e.read();if(!i)throw new Error("Sidecar medium not found");return fe(i,Nt({},n))};Kf.isSideCarExport=!0;function JC(t,e){return t.useMedium(e),Kf}var Jf=KC(),za=function(){},os=X(function(t,e){var n=B(null),i=V({onScrollCapture:za,onWheelCapture:za,onTouchMoveCapture:za}),r=i[0],s=i[1],o=t.forwardProps,a=t.children,c=t.className,l=t.removeScrollBar,d=t.enabled,u=t.shards,h=t.sideCar,f=t.noRelative,v=t.noIsolation,p=t.inert,g=t.allowPinchZoom,b=t.as,k=b===void 0?"div":b,w=t.gapMode,y=Hf(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),_=h,S=WC([n,e]),x=Nt(Nt({},y),r);return fe(ge,null,d&&fe(_,{sideCar:Jf,removeScrollBar:l,shards:u,noRelative:f,noIsolation:v,inert:p,setCallbacks:s,allowPinchZoom:!!g,lockRef:n,gapMode:w}),o?wi(on.only(a),Nt(Nt({},x),{ref:S})):fe(k,Nt({},x,{className:c,ref:S}),a))});os.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},os.classNames={fullWidth:ss,zeroRight:rs};var YC=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function XC(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=YC();return e&&t.setAttribute("nonce",e),t}function QC(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function ZC(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var ew=function(){var t=0,e=null;return{add:function(n){t==0&&(e=XC())&&(QC(e,n),ZC(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},tw=function(){var t=ew();return function(e,n){G(function(){return t.add(e),function(){t.remove()}},[e&&n])}},Yf=function(){var t=tw(),e=function(n){var i=n.styles,r=n.dynamic;return t(i,r),null};return e},nw={left:0,top:0,right:0,gap:0},Wa=function(t){return parseInt(t||"",10)||0},iw=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],i=e[t==="padding"?"paddingTop":"marginTop"],r=e[t==="padding"?"paddingRight":"marginRight"];return[Wa(n),Wa(i),Wa(r)]},rw=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return nw;var e=iw(t),n=document.documentElement.clientWidth,i=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,i-n+e[2]-e[0])}},sw=Yf(),ui="data-scroll-locked",ow=function(t,e,n,i){var r=t.left,s=t.top,o=t.right,a=t.gap;return n===void 0&&(n="margin"),`
433
+ .`.concat(VC,` {
424
434
  overflow: hidden `).concat(i,`;
425
435
  padding-right: `).concat(a,"px ").concat(i,`;
426
436
  }
@@ -437,26 +447,26 @@ void main() {
437
447
  `),n==="padding"&&"padding-right: ".concat(a,"px ").concat(i,";")].filter(Boolean).join(""),`
438
448
  }
439
449
 
440
- .`).concat(is,` {
450
+ .`).concat(rs,` {
441
451
  right: `).concat(a,"px ").concat(i,`;
442
452
  }
443
453
 
444
- .`).concat(rs,` {
454
+ .`).concat(ss,` {
445
455
  margin-right: `).concat(a,"px ").concat(i,`;
446
456
  }
447
457
 
448
- .`).concat(is," .").concat(is,` {
458
+ .`).concat(rs," .").concat(rs,` {
449
459
  right: 0 `).concat(i,`;
450
460
  }
451
461
 
452
- .`).concat(rs," .").concat(rs,` {
462
+ .`).concat(ss," .").concat(ss,` {
453
463
  margin-right: 0 `).concat(i,`;
454
464
  }
455
465
 
456
466
  body[`).concat(ui,`] {
457
- `).concat(uC,": ").concat(a,`px;
467
+ `).concat(qC,": ").concat(a,`px;
458
468
  }
459
- `)},jf=function(){var t=parseInt(document.body.getAttribute(ui)||"0",10);return isFinite(t)?t:0},IC=function(){H(function(){return document.body.setAttribute(ui,(jf()+1).toString()),function(){var t=jf()-1;t<=0?document.body.removeAttribute(ui):document.body.setAttribute(ui,t.toString())}},[])},OC=function(t){var e=t.noRelative,n=t.noImportant,i=t.gapMode,r=i===void 0?"margin":i;IC();var s=ce(function(){return EC(r)},[r]);return fe(PC,{styles:RC(s,!e,r,n?"":"!important")})},Va=!1;if(typeof window<"u")try{var os=Object.defineProperty({},"passive",{get:function(){return Va=!0,!0}});window.addEventListener("test",os,os),window.removeEventListener("test",os,os)}catch{Va=!1}var hi=Va?{passive:!1}:!1,DC=function(t){return t.tagName==="TEXTAREA"},Vf=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!DC(t)&&n[e]==="visible")},AC=function(t){return Vf(t,"overflowY")},MC=function(t){return Vf(t,"overflowX")},qf=function(t,e){var n=e.ownerDocument,i=e;do{typeof ShadowRoot<"u"&&i instanceof ShadowRoot&&(i=i.host);var r=$f(t,i);if(r){var s=zf(t,i),o=s[1],a=s[2];if(o>a)return!0}i=i.parentNode}while(i&&i!==n.body);return!1},NC=function(t){var e=t.scrollTop,n=t.scrollHeight,i=t.clientHeight;return[e,n,i]},LC=function(t){var e=t.scrollLeft,n=t.scrollWidth,i=t.clientWidth;return[e,n,i]},$f=function(t,e){return t==="v"?AC(e):MC(e)},zf=function(t,e){return t==="v"?NC(e):LC(e)},UC=function(t,e){return t==="h"&&e==="rtl"?-1:1},FC=function(t,e,n,i,r){var s=UC(t,window.getComputedStyle(e).direction),o=s*i,a=n.target,c=e.contains(a),l=!1,d=o>0,u=0,h=0;do{if(!a)break;var p=zf(t,a),g=p[0],f=p[1],m=p[2],v=f-m-s*g;(g||v)&&$f(t,a)&&(u+=v,h+=g);var y=a.parentNode;a=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y}while(!c&&a!==document.body||c&&(e.contains(a)||e===a));return(d&&Math.abs(u)<1||!d&&Math.abs(h)<1)&&(l=!0),l},as=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},Wf=function(t){return[t.deltaX,t.deltaY]},Hf=function(t){return t&&"current"in t?t.current:t},BC=function(t,e){return t[0]===e[0]&&t[1]===e[1]},jC=function(t){return`
469
+ `)},Xf=function(){var t=parseInt(document.body.getAttribute(ui)||"0",10);return isFinite(t)?t:0},aw=function(){G(function(){return document.body.setAttribute(ui,(Xf()+1).toString()),function(){var t=Xf()-1;t<=0?document.body.removeAttribute(ui):document.body.setAttribute(ui,t.toString())}},[])},cw=function(t){var e=t.noRelative,n=t.noImportant,i=t.gapMode,r=i===void 0?"margin":i;aw();var s=oe(function(){return rw(r)},[r]);return fe(sw,{styles:ow(s,!e,r,n?"":"!important")})},Ha=!1;if(typeof window<"u")try{var as=Object.defineProperty({},"passive",{get:function(){return Ha=!0,!0}});window.addEventListener("test",as,as),window.removeEventListener("test",as,as)}catch{Ha=!1}var hi=Ha?{passive:!1}:!1,lw=function(t){return t.tagName==="TEXTAREA"},Qf=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!lw(t)&&n[e]==="visible")},dw=function(t){return Qf(t,"overflowY")},uw=function(t){return Qf(t,"overflowX")},Zf=function(t,e){var n=e.ownerDocument,i=e;do{typeof ShadowRoot<"u"&&i instanceof ShadowRoot&&(i=i.host);var r=ep(t,i);if(r){var s=tp(t,i),o=s[1],a=s[2];if(o>a)return!0}i=i.parentNode}while(i&&i!==n.body);return!1},hw=function(t){var e=t.scrollTop,n=t.scrollHeight,i=t.clientHeight;return[e,n,i]},fw=function(t){var e=t.scrollLeft,n=t.scrollWidth,i=t.clientWidth;return[e,n,i]},ep=function(t,e){return t==="v"?dw(e):uw(e)},tp=function(t,e){return t==="v"?hw(e):fw(e)},pw=function(t,e){return t==="h"&&e==="rtl"?-1:1},mw=function(t,e,n,i,r){var s=pw(t,window.getComputedStyle(e).direction),o=s*i,a=n.target,c=e.contains(a),l=!1,d=o>0,u=0,h=0;do{if(!a)break;var f=tp(t,a),v=f[0],p=f[1],g=f[2],b=p-g-s*v;(v||b)&&ep(t,a)&&(u+=b,h+=v);var k=a.parentNode;a=k&&k.nodeType===Node.DOCUMENT_FRAGMENT_NODE?k.host:k}while(!c&&a!==document.body||c&&(e.contains(a)||e===a));return(d&&Math.abs(u)<1||!d&&Math.abs(h)<1)&&(l=!0),l},cs=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},np=function(t){return[t.deltaX,t.deltaY]},ip=function(t){return t&&"current"in t?t.current:t},gw=function(t,e){return t[0]===e[0]&&t[1]===e[1]},vw=function(t){return`
460
470
  .block-interactivity-`.concat(t,` {pointer-events: none;}
461
471
  .allow-interactivity-`).concat(t,` {pointer-events: all;}
462
- `)},VC=0,fi=[];function qC(t){var e=B([]),n=B([0,0]),i=B(),r=F(VC++)[0],s=F(Bf)[0],o=B(t);H(function(){o.current=t},[t]),H(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(r));var f=lC([t.lockRef.current],(t.shards||[]).map(Hf)).filter(Boolean);return f.forEach(function(m){return m.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),f.forEach(function(m){return m.classList.remove("allow-interactivity-".concat(r))})}}},[t.inert,t.lockRef.current,t.shards]);var a=z(function(f,m){if("touches"in f&&f.touches.length===2||f.type==="wheel"&&f.ctrlKey)return!o.current.allowPinchZoom;var v=as(f),y=n.current,_="deltaX"in f?f.deltaX:y[0]-v[0],k="deltaY"in f?f.deltaY:y[1]-v[1],w,S=f.target,x=Math.abs(_)>Math.abs(k)?"h":"v";if("touches"in f&&x==="h"&&S.type==="range")return!1;var I=qf(x,S);if(!I)return!0;if(I?w=x:(w=x==="v"?"h":"v",I=qf(x,S)),!I)return!1;if(!i.current&&"changedTouches"in f&&(_||k)&&(i.current=w),!w)return!0;var O=i.current||w;return FC(O,m,f,O==="h"?_:k)},[]),c=z(function(f){var m=f;if(!(!fi.length||fi[fi.length-1]!==s)){var v="deltaY"in m?Wf(m):as(m),y=e.current.filter(function(w){return w.name===m.type&&(w.target===m.target||m.target===w.shadowParent)&&BC(w.delta,v)})[0];if(y&&y.should){m.cancelable&&m.preventDefault();return}if(!y){var _=(o.current.shards||[]).map(Hf).filter(Boolean).filter(function(w){return w.contains(m.target)}),k=_.length>0?a(m,_[0]):!o.current.noIsolation;k&&m.cancelable&&m.preventDefault()}}},[]),l=z(function(f,m,v,y){var _={name:f,delta:m,target:v,should:y,shadowParent:$C(v)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(k){return k!==_})},1)},[]),d=z(function(f){n.current=as(f),i.current=void 0},[]),u=z(function(f){l(f.type,Wf(f),f.target,a(f,t.lockRef.current))},[]),h=z(function(f){l(f.type,as(f),f.target,a(f,t.lockRef.current))},[]);H(function(){return fi.push(s),t.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:h}),document.addEventListener("wheel",c,hi),document.addEventListener("touchmove",c,hi),document.addEventListener("touchstart",d,hi),function(){fi=fi.filter(function(f){return f!==s}),document.removeEventListener("wheel",c,hi),document.removeEventListener("touchmove",c,hi),document.removeEventListener("touchstart",d,hi)}},[]);var p=t.removeScrollBar,g=t.inert;return fe(ge,null,g?fe(s,{styles:jC(r)}):null,p?fe(OC,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function $C(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const zC=bC(Ff,qC);var Gf=Y(function(t,e){return fe(ss,Dt({},t,{ref:e,sideCar:zC}))});Gf.classNames=ss.classNames;var WC=[" ","Enter","ArrowUp","ArrowDown"],HC=[" ","Enter"],Ln="Select",[cs,ls,GC]=oy(Ln),[pi,X_]=va(Ln,[GC,_f]),ds=_f(),[KC,kn]=pi(Ln),[JC,YC]=pi(Ln),Kf=t=>{const{__scopeSelect:e,children:n,open:i,defaultOpen:r,onOpenChange:s,value:o,defaultValue:a,onValueChange:c,dir:l,name:d,autoComplete:u,disabled:h,required:p,form:g}=t,f=ds(e),[m,v]=F(null),[y,_]=F(null),[k,w]=F(!1),S=cy(l),[x,I]=Df({prop:i,defaultProp:r??!1,onChange:s,caller:Ln}),[O,R]=Df({prop:o,defaultProp:a,onChange:c,caller:Ln}),A=B(null),M=m?g||!!m.closest("form"):!0,[q,$]=F(new Set),oe=Array.from(q).map(J=>J.props.value).join(";");return b(Kk,{...f,children:b(KC,{required:p,scope:e,trigger:m,onTriggerChange:v,valueNode:y,onValueNodeChange:_,valueNodeHasChildren:k,onValueNodeHasChildrenChange:w,contentId:_a(),value:O,onValueChange:R,open:x,onOpenChange:I,dir:S,triggerPointerDownPosRef:A,disabled:h,children:[b(cs.Provider,{scope:e,children:b(JC,{scope:t.__scopeSelect,onNativeOptionAdd:z(J=>{$(Z=>new Set(Z).add(J))},[]),onNativeOptionRemove:z(J=>{$(Z=>{const W=new Set(Z);return W.delete(J),W})},[]),children:n})}),M?b(mp,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:u,value:O,onChange:J=>R(J.target.value),disabled:h,form:g,children:[O===void 0?b("option",{value:""}):null,Array.from(q)]},oe):null]})})};Kf.displayName=Ln;var Jf="SelectTrigger",Yf=Y((t,e)=>{const{__scopeSelect:n,disabled:i=!1,...r}=t,s=ds(n),o=kn(Jf,n),a=o.disabled||i,c=Le(e,o.onTriggerChange),l=ls(n),d=B("touch"),[u,h,p]=vp(f=>{const m=l().filter(_=>!_.disabled),v=m.find(_=>_.value===o.value),y=bp(m,f,v);y!==void 0&&o.onValueChange(y.value)}),g=f=>{a||(o.onOpenChange(!0),p()),f&&(o.triggerPointerDownPosRef.current={x:Math.round(f.pageX),y:Math.round(f.pageY)})};return b(Jk,{asChild:!0,...s,children:b(we.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":gp(o.value)?"":void 0,...r,ref:c,onClick:xe(r.onClick,f=>{f.currentTarget.focus(),d.current!=="mouse"&&g(f)}),onPointerDown:xe(r.onPointerDown,f=>{d.current=f.pointerType;const m=f.target;m.hasPointerCapture(f.pointerId)&&m.releasePointerCapture(f.pointerId),f.button===0&&f.ctrlKey===!1&&f.pointerType==="mouse"&&(g(f),f.preventDefault())}),onKeyDown:xe(r.onKeyDown,f=>{const m=u.current!=="";!(f.ctrlKey||f.altKey||f.metaKey)&&f.key.length===1&&h(f.key),!(m&&f.key===" ")&&WC.includes(f.key)&&(g(),f.preventDefault())})})})});Yf.displayName=Jf;var Xf="SelectValue",XC=Y((t,e)=>{const{__scopeSelect:n,className:i,style:r,children:s,placeholder:o="",...a}=t,c=kn(Xf,n),{onValueNodeHasChildrenChange:l}=c,d=s!==void 0,u=Le(e,c.onValueNodeChange);return He(()=>{l(d)},[l,d]),b(we.span,{...a,ref:u,style:{pointerEvents:"none"},children:gp(c.value)?b(ge,{children:o}):s})});XC.displayName=Xf;var QC="SelectIcon",Qf=Y((t,e)=>{const{__scopeSelect:n,children:i,...r}=t;return b(we.span,{"aria-hidden":!0,...r,ref:e,children:i||"▼"})});Qf.displayName=QC;var ZC="SelectPortal",Zf=t=>b(Of,{asChild:!0,...t});Zf.displayName=ZC;var Un="SelectContent",ep=Y((t,e)=>{const n=kn(Un,t.__scopeSelect),[i,r]=F();if(He(()=>{r(new DocumentFragment)},[]),!n.open){const s=i;return s?nr(b(tp,{scope:t.__scopeSelect,children:b(cs.Slot,{scope:t.__scopeSelect,children:b("div",{children:t.children})})}),s):null}return b(np,{...t,ref:e})});ep.displayName=Un;var gt=10,[tp,Cn]=pi(Un),e_="SelectContentImpl",t_=Vi("SelectContent.RemoveScroll"),np=Y((t,e)=>{const{__scopeSelect:n,position:i="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:s,onPointerDownOutside:o,side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:h,collisionPadding:p,sticky:g,hideWhenDetached:f,avoidCollisions:m,...v}=t,y=kn(Un,n),[_,k]=F(null),[w,S]=F(null),x=Le(e,V=>k(V)),[I,O]=F(null),[R,A]=F(null),M=ls(n),[q,$]=F(!1),oe=B(!1);H(()=>{if(_)return cC(_)},[_]),yy();const J=z(V=>{const[me,...Se]=M().map(Ee=>Ee.ref.current),[ne]=Se.slice(-1),be=document.activeElement;for(const Ee of V)if(Ee===be||(Ee==null||Ee.scrollIntoView({block:"nearest"}),Ee===me&&w&&(w.scrollTop=0),Ee===ne&&w&&(w.scrollTop=w.scrollHeight),Ee==null||Ee.focus(),document.activeElement!==be))return},[M,w]),Z=z(()=>J([I,_]),[J,I,_]);H(()=>{q&&Z()},[q,Z]);const{onOpenChange:W,triggerPointerDownPosRef:te}=y;H(()=>{if(_){let V={x:0,y:0};const me=ne=>{var be,Ee;V={x:Math.abs(Math.round(ne.pageX)-(((be=te.current)==null?void 0:be.x)??0)),y:Math.abs(Math.round(ne.pageY)-(((Ee=te.current)==null?void 0:Ee.y)??0))}},Se=ne=>{V.x<=10&&V.y<=10?ne.preventDefault():_.contains(ne.target)||W(!1),document.removeEventListener("pointermove",me),te.current=null};return te.current!==null&&(document.addEventListener("pointermove",me),document.addEventListener("pointerup",Se,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",me),document.removeEventListener("pointerup",Se,{capture:!0})}}},[_,W,te]),H(()=>{const V=()=>W(!1);return window.addEventListener("blur",V),window.addEventListener("resize",V),()=>{window.removeEventListener("blur",V),window.removeEventListener("resize",V)}},[W]);const[De,vt]=vp(V=>{const me=M().filter(be=>!be.disabled),Se=me.find(be=>be.ref.current===document.activeElement),ne=bp(me,V,Se);ne&&setTimeout(()=>ne.ref.current.focus())}),Zt=z((V,me,Se)=>{const ne=!oe.current&&!Se;(y.value!==void 0&&y.value===me||ne)&&(O(V),ne&&(oe.current=!0))},[y.value]),rt=z(()=>_==null?void 0:_.focus(),[_]),Ue=z((V,me,Se)=>{const ne=!oe.current&&!Se;(y.value!==void 0&&y.value===me||ne)&&A(V)},[y.value]),At=i==="popper"?qa:ip,bt=At===qa?{side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:h,collisionPadding:p,sticky:g,hideWhenDetached:f,avoidCollisions:m}:{};return b(tp,{scope:n,content:_,viewport:w,onViewportChange:S,itemRefCallback:Zt,selectedItem:I,onItemLeave:rt,itemTextRefCallback:Ue,focusSelectedItem:Z,selectedItemText:R,position:i,isPositioned:q,searchRef:De,children:b(Gf,{as:t_,allowPinchZoom:!0,children:b(Gh,{asChild:!0,trapped:y.open,onMountAutoFocus:V=>{V.preventDefault()},onUnmountAutoFocus:xe(r,V=>{var me;(me=y.trigger)==null||me.focus({preventScroll:!0}),V.preventDefault()}),children:b(qh,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:V=>V.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:b(At,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:V=>V.preventDefault(),...v,...bt,onPlaced:()=>$(!0),ref:x,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:xe(v.onKeyDown,V=>{const me=V.ctrlKey||V.altKey||V.metaKey;if(V.key==="Tab"&&V.preventDefault(),!me&&V.key.length===1&&vt(V.key),["ArrowUp","ArrowDown","Home","End"].includes(V.key)){let Se=M().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);if(["ArrowUp","End"].includes(V.key)&&(Se=Se.slice().reverse()),["ArrowUp","ArrowDown"].includes(V.key)){const ne=V.target,be=Se.indexOf(ne);Se=Se.slice(be+1)}setTimeout(()=>J(Se)),V.preventDefault()}})})})})})})});np.displayName=e_;var n_="SelectItemAlignedPosition",ip=Y((t,e)=>{const{__scopeSelect:n,onPlaced:i,...r}=t,s=kn(Un,n),o=Cn(Un,n),[a,c]=F(null),[l,d]=F(null),u=Le(e,x=>d(x)),h=ls(n),p=B(!1),g=B(!0),{viewport:f,selectedItem:m,selectedItemText:v,focusSelectedItem:y}=o,_=z(()=>{if(s.trigger&&s.valueNode&&a&&l&&f&&m&&v){const x=s.trigger.getBoundingClientRect(),I=l.getBoundingClientRect(),O=s.valueNode.getBoundingClientRect(),R=v.getBoundingClientRect();if(s.dir!=="rtl"){const ne=R.left-I.left,be=O.left-ne,Ee=x.left-be,tt=x.width+Ee,Hi=Math.max(tt,I.width),Gi=window.innerWidth-gt,Ki=Bh(be,[gt,Math.max(gt,Gi-Hi)]);a.style.minWidth=tt+"px",a.style.left=Ki+"px"}else{const ne=I.right-R.right,be=window.innerWidth-O.right-ne,Ee=window.innerWidth-x.right-be,tt=x.width+Ee,Hi=Math.max(tt,I.width),Gi=window.innerWidth-gt,Ki=Bh(be,[gt,Math.max(gt,Gi-Hi)]);a.style.minWidth=tt+"px",a.style.right=Ki+"px"}const A=h(),M=window.innerHeight-gt*2,q=f.scrollHeight,$=window.getComputedStyle(l),oe=parseInt($.borderTopWidth,10),J=parseInt($.paddingTop,10),Z=parseInt($.borderBottomWidth,10),W=parseInt($.paddingBottom,10),te=oe+J+q+W+Z,De=Math.min(m.offsetHeight*5,te),vt=window.getComputedStyle(f),Zt=parseInt(vt.paddingTop,10),rt=parseInt(vt.paddingBottom,10),Ue=x.top+x.height/2-gt,At=M-Ue,bt=m.offsetHeight/2,V=m.offsetTop+bt,me=oe+J+V,Se=te-me;if(me<=Ue){const ne=A.length>0&&m===A[A.length-1].ref.current;a.style.bottom="0px";const be=l.clientHeight-f.offsetTop-f.offsetHeight,Ee=Math.max(At,bt+(ne?rt:0)+be+Z),tt=me+Ee;a.style.height=tt+"px"}else{const ne=A.length>0&&m===A[0].ref.current;a.style.top="0px";const be=Math.max(Ue,oe+f.offsetTop+(ne?Zt:0)+bt)+Se;a.style.height=be+"px",f.scrollTop=me-Ue+f.offsetTop}a.style.margin=`${gt}px 0`,a.style.minHeight=De+"px",a.style.maxHeight=M+"px",i==null||i(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,l,f,m,v,s.dir,i]);He(()=>_(),[_]);const[k,w]=F();He(()=>{l&&w(window.getComputedStyle(l).zIndex)},[l]);const S=z(x=>{x&&g.current===!0&&(_(),y==null||y(),g.current=!1)},[_,y]);return b(r_,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:S,children:b("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:b(we.div,{...r,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});ip.displayName=n_;var i_="SelectPopperPosition",qa=Y((t,e)=>{const{__scopeSelect:n,align:i="start",collisionPadding:r=gt,...s}=t,o=ds(n);return b(Yk,{...o,...s,ref:e,align:i,collisionPadding:r,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});qa.displayName=i_;var[r_,$a]=pi(Un,{}),za="SelectViewport",rp=Y((t,e)=>{const{__scopeSelect:n,nonce:i,...r}=t,s=Cn(za,n),o=$a(za,n),a=Le(e,s.onViewportChange),c=B(0);return b(ge,{children:[b("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),b(cs.Slot,{scope:n,children:b(we.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:xe(r.onScroll,l=>{const d=l.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:h}=o;if(h!=null&&h.current&&u){const p=Math.abs(c.current-d.scrollTop);if(p>0){const g=window.innerHeight-gt*2,f=parseFloat(u.style.minHeight),m=parseFloat(u.style.height),v=Math.max(f,m);if(v<g){const y=v+p,_=Math.min(g,y),k=y-_;u.style.height=_+"px",u.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,u.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});rp.displayName=za;var sp="SelectGroup",[s_,o_]=pi(sp),a_=Y((t,e)=>{const{__scopeSelect:n,...i}=t,r=_a();return b(s_,{scope:n,id:r,children:b(we.div,{role:"group","aria-labelledby":r,...i,ref:e})})});a_.displayName=sp;var op="SelectLabel",c_=Y((t,e)=>{const{__scopeSelect:n,...i}=t,r=o_(op,n);return b(we.div,{id:r.id,...i,ref:e})});c_.displayName=op;var us="SelectItem",[l_,ap]=pi(us),cp=Y((t,e)=>{const{__scopeSelect:n,value:i,disabled:r=!1,textValue:s,...o}=t,a=kn(us,n),c=Cn(us,n),l=a.value===i,[d,u]=F(s??""),[h,p]=F(!1),g=Le(e,y=>{var _;return(_=c.itemRefCallback)==null?void 0:_.call(c,y,i,r)}),f=_a(),m=B("touch"),v=()=>{r||(a.onValueChange(i),a.onOpenChange(!1))};if(i==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return b(l_,{scope:n,value:i,disabled:r,textId:f,isSelected:l,onItemTextChange:z(y=>{u(_=>_||((y==null?void 0:y.textContent)??"").trim())},[]),children:b(cs.ItemSlot,{scope:n,value:i,disabled:r,textValue:d,children:b(we.div,{role:"option","aria-labelledby":f,"data-highlighted":h?"":void 0,"aria-selected":l&&h,"data-state":l?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...o,ref:g,onFocus:xe(o.onFocus,()=>p(!0)),onBlur:xe(o.onBlur,()=>p(!1)),onClick:xe(o.onClick,()=>{m.current!=="mouse"&&v()}),onPointerUp:xe(o.onPointerUp,()=>{m.current==="mouse"&&v()}),onPointerDown:xe(o.onPointerDown,y=>{m.current=y.pointerType}),onPointerMove:xe(o.onPointerMove,y=>{var _;m.current=y.pointerType,r?(_=c.onItemLeave)==null||_.call(c):m.current==="mouse"&&y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:xe(o.onPointerLeave,y=>{var _;y.currentTarget===document.activeElement&&((_=c.onItemLeave)==null||_.call(c))}),onKeyDown:xe(o.onKeyDown,y=>{var _;((_=c.searchRef)==null?void 0:_.current)!==""&&y.key===" "||(HC.includes(y.key)&&v(),y.key===" "&&y.preventDefault())})})})})});cp.displayName=us;var Wi="SelectItemText",lp=Y((t,e)=>{const{__scopeSelect:n,className:i,style:r,...s}=t,o=kn(Wi,n),a=Cn(Wi,n),c=ap(Wi,n),l=YC(Wi,n),[d,u]=F(null),h=Le(e,v=>u(v),c.onItemTextChange,v=>{var y;return(y=a.itemTextRefCallback)==null?void 0:y.call(a,v,c.value,c.disabled)}),p=d==null?void 0:d.textContent,g=ce(()=>b("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:f,onNativeOptionRemove:m}=l;return He(()=>(f(g),()=>m(g)),[f,m,g]),b(ge,{children:[b(we.span,{id:c.textId,...s,ref:h}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?nr(s.children,o.valueNode):null]})});lp.displayName=Wi;var dp="SelectItemIndicator",up=Y((t,e)=>{const{__scopeSelect:n,...i}=t;return ap(dp,n).isSelected?b(we.span,{"aria-hidden":!0,...i,ref:e}):null});up.displayName=dp;var Wa="SelectScrollUpButton",hp=Y((t,e)=>{const n=Cn(Wa,t.__scopeSelect),i=$a(Wa,t.__scopeSelect),[r,s]=F(!1),o=Le(e,i.onScrollButtonChange);return He(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollTop>0;s(l)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?b(pp,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop-c.offsetHeight)}}):null});hp.displayName=Wa;var Ha="SelectScrollDownButton",fp=Y((t,e)=>{const n=Cn(Ha,t.__scopeSelect),i=$a(Ha,t.__scopeSelect),[r,s]=F(!1),o=Le(e,i.onScrollButtonChange);return He(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)<l;s(d)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?b(pp,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop+c.offsetHeight)}}):null});fp.displayName=Ha;var pp=Y((t,e)=>{const{__scopeSelect:n,onAutoScroll:i,...r}=t,s=Cn("SelectScrollButton",n),o=B(null),a=ls(n),c=z(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return H(()=>()=>c(),[c]),He(()=>{var l;const d=a().find(u=>u.ref.current===document.activeElement);(l=d==null?void 0:d.ref.current)==null||l.scrollIntoView({block:"nearest"})},[a]),b(we.div,{"aria-hidden":!0,...r,ref:e,style:{flexShrink:0,...r.style},onPointerDown:xe(r.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(i,50))}),onPointerMove:xe(r.onPointerMove,()=>{var l;(l=s.onItemLeave)==null||l.call(s),o.current===null&&(o.current=window.setInterval(i,50))}),onPointerLeave:xe(r.onPointerLeave,()=>{c()})})}),d_="SelectSeparator",u_=Y((t,e)=>{const{__scopeSelect:n,...i}=t;return b(we.div,{"aria-hidden":!0,...i,ref:e})});u_.displayName=d_;var Ga="SelectArrow",h_=Y((t,e)=>{const{__scopeSelect:n,...i}=t,r=ds(n),s=kn(Ga,n),o=Cn(Ga,n);return s.open&&o.position==="popper"?b(Xk,{...r,...i,ref:e}):null});h_.displayName=Ga;var f_="SelectBubbleInput",mp=Y(({__scopeSelect:t,value:e,...n},i)=>{const r=B(null),s=Le(i,r),o=nC(e);return H(()=>{const a=r.current;if(!a)return;const c=window.HTMLSelectElement.prototype,l=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==e&&l){const d=new Event("change",{bubbles:!0});l.call(a,e),a.dispatchEvent(d)}},[o,e]),b(we.select,{...n,style:{...Af,...n.style},ref:s,defaultValue:e})});mp.displayName=f_;function gp(t){return t===""||t===void 0}function vp(t){const e=Mn(t),n=B(""),i=B(0),r=z(o=>{const a=n.current+o;e(a),(function c(l){n.current=l,window.clearTimeout(i.current),l!==""&&(i.current=window.setTimeout(()=>c(""),1e3))})(a)},[e]),s=z(()=>{n.current="",window.clearTimeout(i.current)},[]);return H(()=>()=>window.clearTimeout(i.current),[]),[n,r,s]}function bp(t,e,n){const i=e.length>1&&Array.from(e).every(a=>a===e[0])?e[0]:e,r=n?t.indexOf(n):-1;let s=p_(t,Math.max(r,0));i.length===1&&(s=s.filter(a=>a!==n));const o=s.find(a=>a.textValue.toLowerCase().startsWith(i.toLowerCase()));return o!==n?o:void 0}function p_(t,e){return t.map((n,i)=>t[(e+i)%t.length])}var m_=Kf,yp=Yf,kp=Qf,g_=Zf,v_=ep,b_=rp,y_=cp,k_=lp,C_=up,__=hp,w_=fp;const S_={sm:"w-4 h-4",md:"w-6 h-6"};function Ka({size:t="md",flagCode:e,className:n,...i}){return b("img",{className:he("rounded-full object-cover",S_[t],n),src:`https://storage.googleapis.com/eleven-public-cdn/images/flags/circle-flags/${e}.svg`,alt:`${e.toUpperCase()} flag`,...i})}function Cp({children:t,...e}){const[n,i]=F(!1),{language:r,setLanguage:s,options:o}=ri(),a=Pb();return b(m_,{open:n,value:r.value.languageCode,onValueChange:c=>{s(c),i(!1)},onOpenChange:c=>{c&&i(!0)},children:[t,b(g_,{container:a,children:b(v_,{className:"overflow-hidden bg-base border border-base-border rounded-dropdown-sheet max-h-[min(384px,var(--radix-select-content-available-height))] min-w-[var(--radix-select-trigger-width)] z-10",position:"popper",sideOffset:8,align:"end",side:"top",onPointerDownOutside:()=>i(!1),onCloseAutoFocus:()=>i(!1),onEscapeKeyDown:()=>i(!1),...e,children:[b(__,{className:"flex items-center justify-center h-6 bg-base text-base-subtle cursor-default",children:b(An,{size:"sm",name:"chevron-up"})}),b(b_,{className:"p-1.5",children:o.value.map(c=>b(y_,{value:c.languageCode,className:"flex select-none items-center p-1.5 pr-3 gap-2 cursor-pointer rounded-input relative focus-visible:outline-none data-[highlighted]:bg-base-active text-sm",children:[b(Ka,{flagCode:c.flagCode}),b(k_,{children:c.name}),b(C_,{className:"text-base-primary p-1.5 -mr-1.5 ml-auto",children:b(An,{size:"sm",name:"check"})})]},c.languageCode))}),b(w_,{className:"flex items-center justify-center h-6 bg-base text-base-subtle cursor-default",children:b(An,{size:"sm",name:"chevron-down"})})]})})]})}function T_({className:t,...e}){const n=We(),{language:i,showPicker:r}=ri();return r.value?b(Cp,{align:"center",children:b(yp,{className:he("h-9 min-w-max rounded-button focus-ring px-2 flex gap-2 items-center text-base-primary bg-base hover:bg-base-hover active:bg-base-active font-medium",t),"aria-label":n.change_language,...e,children:[b(Ka,{size:"sm",flagCode:i.value.flagCode}),i.value.name,b(kp,{className:"text-base-subtle",asChild:!0,children:b(An,{size:"sm",name:"chevron-down"})})]})}):null}function x_({className:t,...e}){return b("textarea",{className:he("px-3 py-[calc(theme(spacing.2)-1px)] border text-sm text-base-primary bg-base border-base-border rounded-input focus-ring resize-none [field-sizing:content] placeholder:text-base-subtle",t),...e})}function Ja({visible:t,...e}){const n=We(),{isMuted:i,isMutingEnabled:r,setIsMuted:s}=_h(),o=z(()=>{s(!i.peek())},[s]);return r.value?b(Yt,{visible:t,className:"p-1",children:b(gn,{"aria-label":n.mute_microphone,"aria-pressed":i,icon:i.value?"mic-off":"mic",onClick:o,...e})}):null}function Ya({iconOnly:t,isDisconnected:e,children:n,...i}){const{endSession:r,startSession:s}=ze(),o=We();return b(gn,{variant:e?"primary":"secondary",icon:e?"phone":"phone-off",onClick:e?a=>s(a.currentTarget):r,"aria-label":e?o.start_call:o.end_call,...i,children:t?void 0:n??(e?o.start_call:o.end_call)})}function E_({showTranscript:t,scrollPinned:e}){const n=Je(""),i=zr(),{text_input_enabled:r}=Oe().value,s=We(),{isDisconnected:o,status:a,startSession:c,sendUserMessage:l,sendUserActivity:d,conversationIndex:u}=ze(),h=z(async m=>{m.preventDefault();const v=n.value.trim();v&&(e.value=!0,n.value="",o.value?await c(m.currentTarget,v):l(v))},[n,e,o,c,l]),p=z(async m=>{m.key==="Enter"&&!m.shiftKey&&await h(m)},[h]),g=z(m=>{n.value=m.currentTarget.value},[n]),f=de(()=>!!n.value.trim());return b("div",{className:"shrink-0 overflow-hidden flex p-3 items-end justify-end",children:[r&&b("div",{className:"relative grow min-w-0 flex z-1 m-1",children:[b(x_,{rows:1,"aria-label":s.input_label,value:n,onInput:d,onChange:g,onKeyDown:p,className:"min-w-0 w-full max-h-[8lh] pr-9",placeholder:i.value?o.value&&u.value>0?s.input_placeholder_new_conversation:s.input_placeholder_text_only:s.input_placeholder}),b(it,{active:f,children:b("button",{"aria-label":s.send_message,className:"absolute right-1 bottom-1 w-7 h-7 flex items-center justify-center hover:bg-base-hover active:bg-base-active rounded-button focus-ring transition-[transform,opacity] duration-200 data-hidden:opacity-0 data-hidden:scale-90",onClick:h,children:b(An,{name:"send"})})})]}),b("div",{className:"flex h-11 items-center",children:[b(Ja,{visible:!i.value&&!o.value}),b(Yt,{visible:!i.value&&(!o.value||t),className:"p-1",children:b(Ya,{iconOnly:!o.value,isDisconnected:o.value,disabled:a.value==="disconnecting"||a.value==="connecting",children:s.new_call})})]})]})}function P_({entry:t,animateIn:e}){const n=We(),{previewUrl:i}=fa(),{lastId:r}=ze();return b(it,{initial:!e,active:!0,children:t.type==="message"?b("div",{className:he("flex gap-2.5 transition-[opacity,transform] duration-200 data-hidden:opacity-0 data-hidden:scale-75",t.role=="user"?"justify-end pl-16 origin-top-right":"pr-16 origin-top-left"),children:[t.role==="ai"&&b("img",{src:i,alt:"AI agent avatar",className:"bg-base-border shrink-0 w-5 h-5 rounded-full"}),b("div",{dir:"auto",className:he("px-3 py-2.5 rounded-bubble text-sm min-w-0 [overflow-wrap:break-word]",t.role==="user"?"bg-accent text-accent-primary":"bg-base-active text-base-primary"),children:t.message})]}):t.type==="disconnection"?b("div",{className:"mt-2 px-8 text-xs text-base-subtle text-center transition-opacity duration-200 data-hidden:opacity-0",children:[t.role==="user"?n.user_ended_conversation:n.agent_ended_conversation,b("br",{}),r.value&&b("span",{className:"break-all",children:[n.conversation_id,": ",r.value]})]}):b("div",{className:"mt-2 px-8 text-xs text-base-error text-center transition-opacity duration-200 data-hidden:opacity-0",children:[n.error_occurred,b("br",{}),t.message,r.value&&b(ge,{children:[b("br",{}),b("span",{className:"text-base-subtle break-all",children:[n.conversation_id,": ",r.value]})]})]})})}const R_=16;function I_({scrollPinned:t,transcript:e}){const n=B(null),i=s=>{var o;(o=n.current)==null||o.scrollTo({top:n.current.scrollHeight,behavior:s?"smooth":"instant"})},r=B(!0);return H(()=>{r.current=!1,i(!1)},[]),Bt(()=>{e.value,t.peek()&&i(!0)}),b("div",{ref:n,onScroll:s=>{t.value=s.currentTarget.scrollTop>=s.currentTarget.scrollHeight-s.currentTarget.clientHeight-R_},className:"px-4 pb-3 grow flex flex-col gap-3 overflow-x-hidden overflow-y-auto",children:e.value.map((s,o)=>b(P_,{entry:s,animateIn:!r.current},`${s.message}-${o}-${s.conversationIndex}`))})}const O_={"top-left":"origin-top-left",top:"origin-top","top-right":"origin-top-right","bottom-left":"origin-bottom-left","bottom-right":"origin-bottom-right",bottom:"origin-bottom"};function _p({open:t}){const e=We(),n=ha(),i=zr(),r=Oe(),s=r.value.placement,{isDisconnected:o,startSession:a,transcript:c,conversationIndex:l}=ze(),d=Eh(),u=de(()=>{var g;return n.value||i.value?!d.value||!n.value?c.value:[{type:"message",role:"ai",message:d.value,isText:!0,conversationIndex:((g=c.value[0])==null?void 0:g.conversationIndex)??l.peek()},...c.value]:r.value.transcript_enabled?c.value:c.value.filter(f=>f.type!=="message"||f.isText)}),h=u.value.length>0||!o.value&&r.value.transcript_enabled,p=Je(!0);return b(it,{initial:!1,active:t,children:b("div",{className:he("flex flex-col overflow-hidden absolute bg-base shadow-lg pointer-events-auto rounded-sheet w-full max-w-[400px] h-[calc(100%-80px)] max-h-[550px]","transition-[transform,opacity] duration-200 data-hidden:scale-90 data-hidden:opacity-0",O_[s],s.startsWith("top")?r.value.always_expanded?"top-0":"top-20":r.value.always_expanded?"bottom-0":"bottom-20"),children:[b("div",{className:"bg-base shrink-0 flex gap-2 p-4 items-start",children:[b("div",{className:"relative w-16 h-16"}),b(it,{active:h&&!o.value,children:b(ga,{className:"rounded-bl-[calc(var(--el-bubble-radius)/3)] transition-opacity data-hidden:opacity-0"})})]}),b(I_,{transcript:u,scrollPinned:p}),b(E_,{scrollPinned:p,showTranscript:h}),b(it,{active:!h||o.value,children:b("div",{className:"absolute top-0 left-0 right-0 p-4 flex justify-center transition-[opacity,transform] duration-200 data-hidden:opacity-0 data-hidden:-translate-y-4",children:b(T_,{})})}),b("div",{className:he("absolute origin-top-left transition-[transform,left,top] duration-200 z-1",h?"top-4 left-4 scale-[0.333]":"top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 scale-100"),children:[b(si,{size:"lg"}),b(it,{active:!h&&o.value&&!n.value,children:b("div",{className:"absolute bottom-0 p-1 rounded-[calc(var(--el-button-radius)+4px)] bg-base left-1/2 -translate-x-1/2 translate-y-1/2 transition-[opacity,transform] data-hidden:opacity-0 data-hidden:scale-100 scale-150",children:b(gn,{"aria-label":e.start_call,variant:"primary",icon:"phone",onClick:g=>a(g.currentTarget)})})}),b(it,{active:!h&&!o.value,children:b("div",{className:"absolute -bottom-3 left-1/2 -translate-x-1/2 translate-y-full transition-[opacity,transform] data-hidden:opacity-0 data-hidden:scale-75",children:b(ga,{})})})]})]})})}function wp({expanded:t}){const e=zr(),n=Oe().value.variant,{isDisconnected:i}=ze(),r=We(),s=z(()=>{t.value=!t.value},[t]);return b(ge,{children:[n==="full"&&b(Yt,{visible:!t.value&&!i.value,className:"p-1",children:b(si,{})}),b(Yt,{grow:n!=="tiny",visible:!e.value&&!t.value&&!i.value,className:"p-1",children:b(Ya,{iconOnly:!0,isDisconnected:!1})}),b(Ja,{visible:!e.value&&!t.value&&!i.value}),b(Yt,{grow:i.value,visible:!0,className:"p-1",children:b(gn,{className:"w-full",variant:"primary",iconClassName:he((t.value||!i.value)&&"transition-transform duration-200",t.value&&"-rotate-180"),icon:t.value?"chevron-up":i.value?e.value?"chat":"phone":"chevron-up","aria-label":t.value?r.collapse:i.value?e.value?r.start_chat:r.start_call:r.expand,onClick:!t.value&&!i.value?s:void 0,children:!t.value&&i.value&&n!=="tiny"?e.value?r.start_chat:r.start_call:void 0})})]})}function D_({expanded:t,className:e,...n}){const{isDisconnected:i}=ze(),r=We();return b("div",{className:he("transition-[border-radius] flex flex-col p-2",!t.value&&i.value?"rounded-sheet":"rounded-compact-sheet",e),...n,children:[b(Yt,{visible:!t.value&&i.value,className:"p-1 !min-w-60",children:b("div",{className:"flex items-center gap-2",children:[b(si,{}),b("div",{className:"text-sm max-w-64",children:r.main_label})]})}),b("div",{className:"flex items-center",children:b(wp,{expanded:t})})]})}function A_({expanded:t,className:e,...n}){return b("div",{className:he("rounded-compact-sheet flex items-center p-2",e),...n,children:[b(Yt,{visible:!t.value,className:"p-1",children:b(si,{})}),b(wp,{expanded:t})]})}function M_({visible:t,className:e,...n}){const i=We(),{language:r,showPicker:s}=ri();return s.value?b(Yt,{visible:t,className:"p-1",children:b(Cp,{children:b(yp,{className:he("h-9 min-w-max border border-base-border rounded-button focus-ring px-1.5 flex gap-1 items-center transition-colors duration-200 hover:bg-base-hover active:bg-base-active",e),"aria-label":i.change_language,...n,children:[b(Ka,{flagCode:r.value.flagCode}),b(kp,{className:"px-1 text-base-subtle",asChild:!0,children:b(An,{size:"sm",name:"chevron-down"})})]})})}):null}function Sp(){const t=Oe().value.variant,{isDisconnected:e,status:n}=ze();return b(ge,{children:[b(Ya,{isDisconnected:e.value,iconOnly:t==="tiny",className:"w-full m-1 z-1",disabled:n.value==="disconnecting"||n.value==="connecting"}),b(M_,{visible:e.value}),b(Ja,{visible:!e.value})]})}function N_({className:t,...e}){const{isDisconnected:n}=ze(),i=We();return b("div",{className:he("flex flex-col p-2 rounded-sheet",t),...e,children:[b("div",{className:"flex items-center p-1 gap-2 min-w-60",children:[b(si,{}),b("div",{className:"relative text-sm max-w-64",children:[b("span",{className:he("block transition-[transform,opacity] duration-200",!n.value&&"opacity-0 scale-90"),children:i.main_label}),b(it,{active:!n.value,children:b(ga,{className:"absolute top-1/2 -translate-y-1/2 transition-[transform,opacity] duration-200 data-hidden:opacity-0 data-hidden:scale-90"})})]})]}),b("div",{className:"flex items-center",children:b(Sp,{})})]})}function L_({className:t,...e}){return b("div",{className:he("rounded-compact-sheet flex items-center p-2",t),...e,children:[b(si,{className:"mx-1"}),b(Sp,{})]})}function U_({expandable:t,expanded:e}){const n=Oe().value.variant,i=$r(),{isDisconnected:r}=ze(),s=z(async()=>{await i.requestTerms(),e.value=!e.peek()},[e]),o=n==="full";return t?b(o?D_:A_,{expanded:e,className:he("bg-base shadow-md pointer-events-auto overflow-hidden",(r.value||e.value)&&"cursor-pointer"),onClick:r.value||e.value?s:void 0}):b(o?N_:L_,{className:"bg-base shadow-md pointer-events-auto overflow-hidden"})}function F_(){const t=We(),e=Oe(),{dismissTerms:n,acceptTerms:i}=$r();return b("div",{className:"max-w-[400px] flex flex-col gap-2 bg-base shadow-md pointer-events-auto rounded-sheet p-3 text-sm",children:[b("div",{className:"flex flex-col gap-1 terms p-2 pt-1",dangerouslySetInnerHTML:{__html:e.value.terms_html??""}}),b("div",{className:"flex justify-end gap-2",children:[b(gn,{onClick:n,children:t.dismiss_terms}),b(gn,{onClick:i,variant:"primary",children:t.accept_terms})]})]})}function B_({copyText:t,children:e}){const n=We(),[i,r]=F(!1);H(()=>{if(i){const o=setTimeout(()=>{r(!1)},2e3);return()=>{clearTimeout(o)}}},[i]);const s=z(()=>{const o=Oh(t);o&&(navigator.clipboard.writeText(o),r(!0))},[]);return b(gn,{onClick:s,children:i?n.copied:e})}function j_({sawError:t}){const e=We(),{error:n,lastId:i}=ze(),r=z(()=>{t.value=!0},[]);return b("div",{className:"max-w-[400px] flex flex-col gap-2 bg-base shadow-md pointer-events-auto rounded-sheet p-3 text-sm",children:[b("div",{className:"p-2 pt-1",children:[b("h1",{className:"text-md font-medium pb-1",children:e.error_occurred}),n.value,i.value&&b(ge,{children:[b("br",{}),b("span",{className:"text-base-subtle",children:[e.conversation_id,": ",i.value]})]})]}),b("div",{className:"flex justify-end gap-2",children:[b(B_,{copyText:i,children:e.copy_id}),b(gn,{variant:"primary",onClick:r,children:"Close"})]})]})}function V_(){const t=Oe();return t.value.disable_banner?null:b("p",{className:he("whitespace-nowrap [line-height:var(--el-overlay-padding)] text-[10px] px-3",t.value.placement.startsWith("top")?"-translate-y-[calc(var(--el-overlay-padding))]":"translate-y-[calc(var(--el-overlay-padding))]"),children:[b("span",{className:"opacity-30",children:"Powered by ElevenLabs"})," ",b("a",{href:t.value.override_link||"https://elevenlabs.io/conversational-ai",className:"underline cursor-pointer pointer-events-auto focus-visible:outline-none opacity-30 hover:opacity-50 focus-visible:opacity-100 focus-visible:underline-offset-2",target:"_blank",children:"Agents"})]})}const mi={left:"items-start",center:"items-center",right:"items-end"},gi={top:"flex-col-reverse justify-end",bottom:"flex-col justify-end"},q_={"top-left":`${gi.top} ${mi.left}`,top:`${gi.top} ${mi.center}`,"top-right":`${gi.top} ${mi.right}`,"bottom-left":`${gi.bottom} ${mi.left}`,bottom:`${gi.bottom} ${mi.center}`,"bottom-right":`${gi.bottom} ${mi.right}`},hs={display:"none"},$_=tr(function(){const t=Oe(),e=Je(t.peek().default_expanded),n=Je(!1),{error:i}=ze(),r=$r(),s=de(()=>t.value.transcript_enabled||t.value.text_input_enabled),o=de(()=>he("overlay !flex transition-opacity duration-200 data-hidden:opacity-0",q_[t.value.placement]));Bt(()=>{i.value&&(s.value?(n.value=!0,e.value=!0):n.value=!1)}),Bt(()=>{const u=h=>{var p,g,f;((p=h.detail)==null?void 0:p.action)==="expand"?e.value=!0:((g=h.detail)==null?void 0:g.action)==="collapse"?e.value=!1:((f=h.detail)==null?void 0:f.action)==="toggle"&&(e.value=!e.value)};return document.addEventListener("elevenlabs-agent:expand",u),()=>{document.removeEventListener("elevenlabs-agent:expand",u)}});const a=de(()=>!s.value&&i.value&&!n.value?"error":!r.termsAccepted.value&&r.termsShown.value?"terms":"conversation"),c=de(()=>a.value==="error"),l=de(()=>a.value==="terms"),d=de(()=>a.value==="conversation");return b(ge,{children:[b(it,{initial:!1,active:d,children:b(Wr,{className:o,style:hs,children:t.value.always_expanded?b(_p,{open:!0}):b(ge,{children:[s.value&&b(_p,{open:e}),b(U_,{expandable:s.value,expanded:e})]})})}),b(it,{initial:!1,active:l,children:b(Wr,{className:o,style:hs,children:b(F_,{})})}),b(it,{initial:!1,active:c,children:b(Wr,{className:o,style:hs,children:b(j_,{sawError:n})})}),b(Wr,{className:o,style:hs,children:b(V_,{})})]})});function z_(t){return b(cb,{value:t,children:b(db,{children:b(kb,{children:b(gb,{children:b(ub,{children:b(fb,{children:b(pb,{children:b(vb,{children:b(xb,{children:b(Eb,{children:[b(wb,{}),b($_,{})]})})})})})})})})})})}function W_(t="elevenlabs-convai"){Op(z_,t,[...da],{shadow:!0,mode:"open"})}W_()})();
472
+ `)},bw=0,fi=[];function yw(t){var e=B([]),n=B([0,0]),i=B(),r=V(bw++)[0],s=V(Yf)[0],o=B(t);G(function(){o.current=t},[t]),G(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(r));var p=jC([t.lockRef.current],(t.shards||[]).map(ip)).filter(Boolean);return p.forEach(function(g){return g.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),p.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(r))})}}},[t.inert,t.lockRef.current,t.shards]);var a=j(function(p,g){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!o.current.allowPinchZoom;var b=cs(p),k=n.current,w="deltaX"in p?p.deltaX:k[0]-b[0],y="deltaY"in p?p.deltaY:k[1]-b[1],_,S=p.target,x=Math.abs(w)>Math.abs(y)?"h":"v";if("touches"in p&&x==="h"&&S.type==="range")return!1;var I=Zf(x,S);if(!I)return!0;if(I?_=x:(_=x==="v"?"h":"v",I=Zf(x,S)),!I)return!1;if(!i.current&&"changedTouches"in p&&(w||y)&&(i.current=_),!_)return!0;var R=i.current||_;return mw(R,g,p,R==="h"?w:y)},[]),c=j(function(p){var g=p;if(!(!fi.length||fi[fi.length-1]!==s)){var b="deltaY"in g?np(g):cs(g),k=e.current.filter(function(_){return _.name===g.type&&(_.target===g.target||g.target===_.shadowParent)&&gw(_.delta,b)})[0];if(k&&k.should){g.cancelable&&g.preventDefault();return}if(!k){var w=(o.current.shards||[]).map(ip).filter(Boolean).filter(function(_){return _.contains(g.target)}),y=w.length>0?a(g,w[0]):!o.current.noIsolation;y&&g.cancelable&&g.preventDefault()}}},[]),l=j(function(p,g,b,k){var w={name:p,delta:g,target:b,should:k,shadowParent:kw(b)};e.current.push(w),setTimeout(function(){e.current=e.current.filter(function(y){return y!==w})},1)},[]),d=j(function(p){n.current=cs(p),i.current=void 0},[]),u=j(function(p){l(p.type,np(p),p.target,a(p,t.lockRef.current))},[]),h=j(function(p){l(p.type,cs(p),p.target,a(p,t.lockRef.current))},[]);G(function(){return fi.push(s),t.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:h}),document.addEventListener("wheel",c,hi),document.addEventListener("touchmove",c,hi),document.addEventListener("touchstart",d,hi),function(){fi=fi.filter(function(p){return p!==s}),document.removeEventListener("wheel",c,hi),document.removeEventListener("touchmove",c,hi),document.removeEventListener("touchstart",d,hi)}},[]);var f=t.removeScrollBar,v=t.inert;return fe(ge,null,v?fe(s,{styles:vw(r)}):null,f?fe(cw,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function kw(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const Cw=JC(Jf,yw);var rp=X(function(t,e){return fe(os,Nt({},t,{ref:e,sideCar:Cw}))});rp.classNames=os.classNames;var ww=[" ","Enter","ArrowUp","ArrowDown"],_w=[" ","Enter"],Ln="Select",[ls,ds,Sw]=Uy(Ln),[pi,S_]=wa(Ln,[Sw,Df]),us=Df(),[Tw,Cn]=pi(Ln),[xw,Pw]=pi(Ln),sp=t=>{const{__scopeSelect:e,children:n,open:i,defaultOpen:r,onOpenChange:s,value:o,defaultValue:a,onValueChange:c,dir:l,name:d,autoComplete:u,disabled:h,required:f,form:v}=t,p=us(e),[g,b]=V(null),[k,w]=V(null),[y,_]=V(!1),S=By(l),[x,I]=$f({prop:i,defaultProp:r??!1,onChange:s,caller:Ln}),[R,A]=$f({prop:o,defaultProp:a,onChange:c,caller:Ln}),M=B(null),N=g?v||!!g.closest("form"):!0,[q,F]=V(new Set),te=Array.from(q).map(H=>H.props.value).join(";");return m(TC,{...p,children:m(Tw,{required:f,scope:e,trigger:g,onTriggerChange:b,valueNode:k,onValueNodeChange:w,valueNodeHasChildren:y,onValueNodeHasChildrenChange:_,contentId:Pa(),value:R,onValueChange:A,open:x,onOpenChange:I,dir:S,triggerPointerDownPosRef:M,disabled:h,children:[m(ls.Provider,{scope:e,children:m(xw,{scope:t.__scopeSelect,onNativeOptionAdd:j(H=>{F(J=>new Set(J).add(H))},[]),onNativeOptionRemove:j(H=>{F(J=>{const W=new Set(J);return W.delete(H),W})},[]),children:n})}),N?m(xp,{"aria-hidden":!0,required:f,tabIndex:-1,name:d,autoComplete:u,value:R,onChange:H=>A(H.target.value),disabled:h,form:v,children:[R===void 0?m("option",{value:""}):null,Array.from(q)]},te):null]})})};sp.displayName=Ln;var op="SelectTrigger",ap=X((t,e)=>{const{__scopeSelect:n,disabled:i=!1,...r}=t,s=us(n),o=Cn(op,n),a=o.disabled||i,c=Fe(e,o.onTriggerChange),l=ds(n),d=B("touch"),[u,h,f]=Ep(p=>{const g=l().filter(w=>!w.disabled),b=g.find(w=>w.value===o.value),k=Rp(g,p,b);k!==void 0&&o.onValueChange(k.value)}),v=p=>{a||(o.onOpenChange(!0),f()),p&&(o.triggerPointerDownPosRef.current={x:Math.round(p.pageX),y:Math.round(p.pageY)})};return m(xC,{asChild:!0,...s,children:m(_e.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":Pp(o.value)?"":void 0,...r,ref:c,onClick:Pe(r.onClick,p=>{p.currentTarget.focus(),d.current!=="mouse"&&v(p)}),onPointerDown:Pe(r.onPointerDown,p=>{d.current=p.pointerType;const g=p.target;g.hasPointerCapture(p.pointerId)&&g.releasePointerCapture(p.pointerId),p.button===0&&p.ctrlKey===!1&&p.pointerType==="mouse"&&(v(p),p.preventDefault())}),onKeyDown:Pe(r.onKeyDown,p=>{const g=u.current!=="";!(p.ctrlKey||p.altKey||p.metaKey)&&p.key.length===1&&h(p.key),!(g&&p.key===" ")&&ww.includes(p.key)&&(v(),p.preventDefault())})})})});ap.displayName=op;var cp="SelectValue",Ew=X((t,e)=>{const{__scopeSelect:n,className:i,style:r,children:s,placeholder:o="",...a}=t,c=Cn(cp,n),{onValueNodeHasChildrenChange:l}=c,d=s!==void 0,u=Fe(e,c.onValueNodeChange);return Ke(()=>{l(d)},[l,d]),m(_e.span,{...a,ref:u,style:{pointerEvents:"none"},children:Pp(c.value)?m(ge,{children:o}):s})});Ew.displayName=cp;var Rw="SelectIcon",lp=X((t,e)=>{const{__scopeSelect:n,children:i,...r}=t;return m(_e.span,{"aria-hidden":!0,...r,ref:e,children:i||"▼"})});lp.displayName=Rw;var Iw="SelectPortal",dp=t=>m(qf,{asChild:!0,...t});dp.displayName=Iw;var Un="SelectContent",up=X((t,e)=>{const n=Cn(Un,t.__scopeSelect),[i,r]=V();if(Ke(()=>{r(new DocumentFragment)},[]),!n.open){const s=i;return s?nr(m(hp,{scope:t.__scopeSelect,children:m(ls.Slot,{scope:t.__scopeSelect,children:m("div",{children:t.children})})}),s):null}return m(fp,{...t,ref:e})});up.displayName=Un;var vt=10,[hp,wn]=pi(Un),Ow="SelectContentImpl",Aw=Vi("SelectContent.RemoveScroll"),fp=X((t,e)=>{const{__scopeSelect:n,position:i="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:s,onPointerDownOutside:o,side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:h,collisionPadding:f,sticky:v,hideWhenDetached:p,avoidCollisions:g,...b}=t,k=Cn(Un,n),[w,y]=V(null),[_,S]=V(null),x=Fe(e,z=>y(z)),[I,R]=V(null),[A,M]=V(null),N=ds(n),[q,F]=V(!1),te=B(!1);G(()=>{if(w)return BC(w)},[w]),Yy();const H=j(z=>{const[me,...Se]=N().map(Ee=>Ee.ref.current),[re]=Se.slice(-1),be=document.activeElement;for(const Ee of z)if(Ee===be||(Ee==null||Ee.scrollIntoView({block:"nearest"}),Ee===me&&_&&(_.scrollTop=0),Ee===re&&_&&(_.scrollTop=_.scrollHeight),Ee==null||Ee.focus(),document.activeElement!==be))return},[N,_]),J=j(()=>H([I,w]),[H,I,w]);G(()=>{q&&J()},[q,J]);const{onOpenChange:W,triggerPointerDownPosRef:Z}=k;G(()=>{if(w){let z={x:0,y:0};const me=re=>{var be,Ee;z={x:Math.abs(Math.round(re.pageX)-(((be=Z.current)==null?void 0:be.x)??0)),y:Math.abs(Math.round(re.pageY)-(((Ee=Z.current)==null?void 0:Ee.y)??0))}},Se=re=>{z.x<=10&&z.y<=10?re.preventDefault():w.contains(re.target)||W(!1),document.removeEventListener("pointermove",me),Z.current=null};return Z.current!==null&&(document.addEventListener("pointermove",me),document.addEventListener("pointerup",Se,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",me),document.removeEventListener("pointerup",Se,{capture:!0})}}},[w,W,Z]),G(()=>{const z=()=>W(!1);return window.addEventListener("blur",z),window.addEventListener("resize",z),()=>{window.removeEventListener("blur",z),window.removeEventListener("resize",z)}},[W]);const[Ne,bt]=Ep(z=>{const me=N().filter(be=>!be.disabled),Se=me.find(be=>be.ref.current===document.activeElement),re=Rp(me,z,Se);re&&setTimeout(()=>re.ref.current.focus())}),nn=j((z,me,Se)=>{const re=!te.current&&!Se;(k.value!==void 0&&k.value===me||re)&&(R(z),re&&(te.current=!0))},[k.value]),st=j(()=>w==null?void 0:w.focus(),[w]),Ve=j((z,me,Se)=>{const re=!te.current&&!Se;(k.value!==void 0&&k.value===me||re)&&M(z)},[k.value]),Lt=i==="popper"?Ga:pp,yt=Lt===Ga?{side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:h,collisionPadding:f,sticky:v,hideWhenDetached:p,avoidCollisions:g}:{};return m(hp,{scope:n,content:w,viewport:_,onViewportChange:S,itemRefCallback:nn,selectedItem:I,onItemLeave:st,itemTextRefCallback:Ve,focusSelectedItem:J,selectedItemText:A,position:i,isPositioned:q,searchRef:Ne,children:m(rp,{as:Aw,allowPinchZoom:!0,children:m(sf,{asChild:!0,trapped:k.open,onMountAutoFocus:z=>{z.preventDefault()},onUnmountAutoFocus:Pe(r,z=>{var me;(me=k.trigger)==null||me.focus({preventScroll:!0}),z.preventDefault()}),children:m(Zh,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:z=>z.preventDefault(),onDismiss:()=>k.onOpenChange(!1),children:m(Lt,{role:"listbox",id:k.contentId,"data-state":k.open?"open":"closed",dir:k.dir,onContextMenu:z=>z.preventDefault(),...b,...yt,onPlaced:()=>F(!0),ref:x,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Pe(b.onKeyDown,z=>{const me=z.ctrlKey||z.altKey||z.metaKey;if(z.key==="Tab"&&z.preventDefault(),!me&&z.key.length===1&&bt(z.key),["ArrowUp","ArrowDown","Home","End"].includes(z.key)){let Se=N().filter(re=>!re.disabled).map(re=>re.ref.current);if(["ArrowUp","End"].includes(z.key)&&(Se=Se.slice().reverse()),["ArrowUp","ArrowDown"].includes(z.key)){const re=z.target,be=Se.indexOf(re);Se=Se.slice(be+1)}setTimeout(()=>H(Se)),z.preventDefault()}})})})})})})});fp.displayName=Ow;var Dw="SelectItemAlignedPosition",pp=X((t,e)=>{const{__scopeSelect:n,onPlaced:i,...r}=t,s=Cn(Un,n),o=wn(Un,n),[a,c]=V(null),[l,d]=V(null),u=Fe(e,x=>d(x)),h=ds(n),f=B(!1),v=B(!0),{viewport:p,selectedItem:g,selectedItemText:b,focusSelectedItem:k}=o,w=j(()=>{if(s.trigger&&s.valueNode&&a&&l&&p&&g&&b){const x=s.trigger.getBoundingClientRect(),I=l.getBoundingClientRect(),R=s.valueNode.getBoundingClientRect(),A=b.getBoundingClientRect();if(s.dir!=="rtl"){const re=A.left-I.left,be=R.left-re,Ee=x.left-be,it=x.width+Ee,Hi=Math.max(it,I.width),Gi=window.innerWidth-vt,Ki=Yh(be,[vt,Math.max(vt,Gi-Hi)]);a.style.minWidth=it+"px",a.style.left=Ki+"px"}else{const re=I.right-A.right,be=window.innerWidth-R.right-re,Ee=window.innerWidth-x.right-be,it=x.width+Ee,Hi=Math.max(it,I.width),Gi=window.innerWidth-vt,Ki=Yh(be,[vt,Math.max(vt,Gi-Hi)]);a.style.minWidth=it+"px",a.style.right=Ki+"px"}const M=h(),N=window.innerHeight-vt*2,q=p.scrollHeight,F=window.getComputedStyle(l),te=parseInt(F.borderTopWidth,10),H=parseInt(F.paddingTop,10),J=parseInt(F.borderBottomWidth,10),W=parseInt(F.paddingBottom,10),Z=te+H+q+W+J,Ne=Math.min(g.offsetHeight*5,Z),bt=window.getComputedStyle(p),nn=parseInt(bt.paddingTop,10),st=parseInt(bt.paddingBottom,10),Ve=x.top+x.height/2-vt,Lt=N-Ve,yt=g.offsetHeight/2,z=g.offsetTop+yt,me=te+H+z,Se=Z-me;if(me<=Ve){const re=M.length>0&&g===M[M.length-1].ref.current;a.style.bottom="0px";const be=l.clientHeight-p.offsetTop-p.offsetHeight,Ee=Math.max(Lt,yt+(re?st:0)+be+J),it=me+Ee;a.style.height=it+"px"}else{const re=M.length>0&&g===M[0].ref.current;a.style.top="0px";const be=Math.max(Ve,te+p.offsetTop+(re?nn:0)+yt)+Se;a.style.height=be+"px",p.scrollTop=me-Ve+p.offsetTop}a.style.margin=`${vt}px 0`,a.style.minHeight=Ne+"px",a.style.maxHeight=N+"px",i==null||i(),requestAnimationFrame(()=>f.current=!0)}},[h,s.trigger,s.valueNode,a,l,p,g,b,s.dir,i]);Ke(()=>w(),[w]);const[y,_]=V();Ke(()=>{l&&_(window.getComputedStyle(l).zIndex)},[l]);const S=j(x=>{x&&v.current===!0&&(w(),k==null||k(),v.current=!1)},[w,k]);return m(Nw,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:f,onScrollButtonChange:S,children:m("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:y},children:m(_e.div,{...r,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});pp.displayName=Dw;var Mw="SelectPopperPosition",Ga=X((t,e)=>{const{__scopeSelect:n,align:i="start",collisionPadding:r=vt,...s}=t,o=us(n);return m(PC,{...o,...s,ref:e,align:i,collisionPadding:r,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Ga.displayName=Mw;var[Nw,Ka]=pi(Un,{}),Ja="SelectViewport",mp=X((t,e)=>{const{__scopeSelect:n,nonce:i,...r}=t,s=wn(Ja,n),o=Ka(Ja,n),a=Fe(e,s.onViewportChange),c=B(0);return m(ge,{children:[m("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),m(ls.Slot,{scope:n,children:m(_e.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:Pe(r.onScroll,l=>{const d=l.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:h}=o;if(h!=null&&h.current&&u){const f=Math.abs(c.current-d.scrollTop);if(f>0){const v=window.innerHeight-vt*2,p=parseFloat(u.style.minHeight),g=parseFloat(u.style.height),b=Math.max(p,g);if(b<v){const k=b+f,w=Math.min(v,k),y=k-w;u.style.height=w+"px",u.style.bottom==="0px"&&(d.scrollTop=y>0?y:0,u.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});mp.displayName=Ja;var gp="SelectGroup",[Lw,Uw]=pi(gp),Fw=X((t,e)=>{const{__scopeSelect:n,...i}=t,r=Pa();return m(Lw,{scope:n,id:r,children:m(_e.div,{role:"group","aria-labelledby":r,...i,ref:e})})});Fw.displayName=gp;var vp="SelectLabel",Bw=X((t,e)=>{const{__scopeSelect:n,...i}=t,r=Uw(vp,n);return m(_e.div,{id:r.id,...i,ref:e})});Bw.displayName=vp;var hs="SelectItem",[jw,bp]=pi(hs),yp=X((t,e)=>{const{__scopeSelect:n,value:i,disabled:r=!1,textValue:s,...o}=t,a=Cn(hs,n),c=wn(hs,n),l=a.value===i,[d,u]=V(s??""),[h,f]=V(!1),v=Fe(e,k=>{var w;return(w=c.itemRefCallback)==null?void 0:w.call(c,k,i,r)}),p=Pa(),g=B("touch"),b=()=>{r||(a.onValueChange(i),a.onOpenChange(!1))};if(i==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return m(jw,{scope:n,value:i,disabled:r,textId:p,isSelected:l,onItemTextChange:j(k=>{u(w=>w||((k==null?void 0:k.textContent)??"").trim())},[]),children:m(ls.ItemSlot,{scope:n,value:i,disabled:r,textValue:d,children:m(_e.div,{role:"option","aria-labelledby":p,"data-highlighted":h?"":void 0,"aria-selected":l&&h,"data-state":l?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...o,ref:v,onFocus:Pe(o.onFocus,()=>f(!0)),onBlur:Pe(o.onBlur,()=>f(!1)),onClick:Pe(o.onClick,()=>{g.current!=="mouse"&&b()}),onPointerUp:Pe(o.onPointerUp,()=>{g.current==="mouse"&&b()}),onPointerDown:Pe(o.onPointerDown,k=>{g.current=k.pointerType}),onPointerMove:Pe(o.onPointerMove,k=>{var w;g.current=k.pointerType,r?(w=c.onItemLeave)==null||w.call(c):g.current==="mouse"&&k.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Pe(o.onPointerLeave,k=>{var w;k.currentTarget===document.activeElement&&((w=c.onItemLeave)==null||w.call(c))}),onKeyDown:Pe(o.onKeyDown,k=>{var w;((w=c.searchRef)==null?void 0:w.current)!==""&&k.key===" "||(_w.includes(k.key)&&b(),k.key===" "&&k.preventDefault())})})})})});yp.displayName=hs;var Wi="SelectItemText",kp=X((t,e)=>{const{__scopeSelect:n,className:i,style:r,...s}=t,o=Cn(Wi,n),a=wn(Wi,n),c=bp(Wi,n),l=Pw(Wi,n),[d,u]=V(null),h=Fe(e,b=>u(b),c.onItemTextChange,b=>{var k;return(k=a.itemTextRefCallback)==null?void 0:k.call(a,b,c.value,c.disabled)}),f=d==null?void 0:d.textContent,v=oe(()=>m("option",{value:c.value,disabled:c.disabled,children:f},c.value),[c.disabled,c.value,f]),{onNativeOptionAdd:p,onNativeOptionRemove:g}=l;return Ke(()=>(p(v),()=>g(v)),[p,g,v]),m(ge,{children:[m(_e.span,{id:c.textId,...s,ref:h}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?nr(s.children,o.valueNode):null]})});kp.displayName=Wi;var Cp="SelectItemIndicator",wp=X((t,e)=>{const{__scopeSelect:n,...i}=t;return bp(Cp,n).isSelected?m(_e.span,{"aria-hidden":!0,...i,ref:e}):null});wp.displayName=Cp;var Ya="SelectScrollUpButton",_p=X((t,e)=>{const n=wn(Ya,t.__scopeSelect),i=Ka(Ya,t.__scopeSelect),[r,s]=V(!1),o=Fe(e,i.onScrollButtonChange);return Ke(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollTop>0;s(l)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?m(Tp,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop-c.offsetHeight)}}):null});_p.displayName=Ya;var Xa="SelectScrollDownButton",Sp=X((t,e)=>{const n=wn(Xa,t.__scopeSelect),i=Ka(Xa,t.__scopeSelect),[r,s]=V(!1),o=Fe(e,i.onScrollButtonChange);return Ke(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)<l;s(d)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?m(Tp,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop+c.offsetHeight)}}):null});Sp.displayName=Xa;var Tp=X((t,e)=>{const{__scopeSelect:n,onAutoScroll:i,...r}=t,s=wn("SelectScrollButton",n),o=B(null),a=ds(n),c=j(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return G(()=>()=>c(),[c]),Ke(()=>{var l;const d=a().find(u=>u.ref.current===document.activeElement);(l=d==null?void 0:d.ref.current)==null||l.scrollIntoView({block:"nearest"})},[a]),m(_e.div,{"aria-hidden":!0,...r,ref:e,style:{flexShrink:0,...r.style},onPointerDown:Pe(r.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(i,50))}),onPointerMove:Pe(r.onPointerMove,()=>{var l;(l=s.onItemLeave)==null||l.call(s),o.current===null&&(o.current=window.setInterval(i,50))}),onPointerLeave:Pe(r.onPointerLeave,()=>{c()})})}),Vw="SelectSeparator",qw=X((t,e)=>{const{__scopeSelect:n,...i}=t;return m(_e.div,{"aria-hidden":!0,...i,ref:e})});qw.displayName=Vw;var Qa="SelectArrow",$w=X((t,e)=>{const{__scopeSelect:n,...i}=t,r=us(n),s=Cn(Qa,n),o=wn(Qa,n);return s.open&&o.position==="popper"?m(EC,{...r,...i,ref:e}):null});$w.displayName=Qa;var zw="SelectBubbleInput",xp=X(({__scopeSelect:t,value:e,...n},i)=>{const r=B(null),s=Fe(i,r),o=DC(e);return G(()=>{const a=r.current;if(!a)return;const c=window.HTMLSelectElement.prototype,l=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==e&&l){const d=new Event("change",{bubbles:!0});l.call(a,e),a.dispatchEvent(d)}},[o,e]),m(_e.select,{...n,style:{...zf,...n.style},ref:s,defaultValue:e})});xp.displayName=zw;function Pp(t){return t===""||t===void 0}function Ep(t){const e=Mn(t),n=B(""),i=B(0),r=j(o=>{const a=n.current+o;e(a),(function c(l){n.current=l,window.clearTimeout(i.current),l!==""&&(i.current=window.setTimeout(()=>c(""),1e3))})(a)},[e]),s=j(()=>{n.current="",window.clearTimeout(i.current)},[]);return G(()=>()=>window.clearTimeout(i.current),[]),[n,r,s]}function Rp(t,e,n){const i=e.length>1&&Array.from(e).every(a=>a===e[0])?e[0]:e,r=n?t.indexOf(n):-1;let s=Ww(t,Math.max(r,0));i.length===1&&(s=s.filter(a=>a!==n));const o=s.find(a=>a.textValue.toLowerCase().startsWith(i.toLowerCase()));return o!==n?o:void 0}function Ww(t,e){return t.map((n,i)=>t[(e+i)%t.length])}var Hw=sp,Ip=ap,Op=lp,Gw=dp,Kw=up,Jw=mp,Yw=yp,Xw=kp,Qw=wp,Zw=_p,e_=Sp;const t_={sm:"w-4 h-4",md:"w-6 h-6"};function Za({size:t="md",flagCode:e,className:n,...i}){return m("img",{className:ae("rounded-full object-cover",t_[t],n),src:`https://storage.googleapis.com/eleven-public-cdn/images/flags/circle-flags/${e}.svg`,alt:`${e.toUpperCase()} flag`,...i})}function Ap({children:t,...e}){const[n,i]=V(!1),{language:r,setLanguage:s,options:o}=ri(),a=jb();return m(Hw,{open:n,value:r.value.languageCode,onValueChange:c=>{s(c),i(!1)},onOpenChange:c=>{c&&i(!0)},children:[t,m(Gw,{container:a,children:m(Kw,{className:"overflow-hidden bg-base border border-base-border rounded-dropdown-sheet max-h-[min(384px,var(--radix-select-content-available-height))] min-w-[var(--radix-select-trigger-width)] z-10",position:"popper",sideOffset:8,align:"end",side:"top",onPointerDownOutside:()=>i(!1),onCloseAutoFocus:()=>i(!1),onEscapeKeyDown:()=>i(!1),...e,children:[m(Zw,{className:"flex items-center justify-center h-6 bg-base text-base-subtle cursor-default",children:m(It,{size:"sm",name:"chevron-up"})}),m(Jw,{className:"p-1.5",children:o.value.map(c=>m(Yw,{value:c.languageCode,className:"flex select-none items-center p-1.5 pr-3 gap-2 cursor-pointer rounded-input relative focus-visible:outline-none data-[highlighted]:bg-base-active text-sm",children:[m(Za,{flagCode:c.flagCode}),m(Xw,{children:c.name}),m(Qw,{className:"text-base-primary p-1.5 -mr-1.5 ml-auto",children:m(It,{size:"sm",name:"check"})})]},c.languageCode))}),m(e_,{className:"flex items-center justify-center h-6 bg-base text-base-subtle cursor-default",children:m(It,{size:"sm",name:"chevron-down"})})]})})]})}function n_({className:t,...e}){const n=xe(),{language:i,showPicker:r}=ri();return r.value?m(Ap,{align:"center",children:m(Ip,{className:ae("h-9 min-w-max rounded-button focus-ring px-2 flex gap-2 items-center text-base-primary bg-base hover:bg-base-hover active:bg-base-active font-medium",t),"aria-label":n.change_language,...e,children:[m(Za,{size:"sm",flagCode:i.value.flagCode}),i.value.name,m(Op,{className:"text-base-subtle",asChild:!0,children:m(It,{size:"sm",name:"chevron-down"})})]})}):null}function i_({showBackButton:t,onBackClick:e,showStatusLabel:n,showShadow:i,showLanguageSelector:r}){const s=xe();return m("div",{className:ae("bg-base shrink-0 relative",i&&"shadow-header"),children:[m("div",{className:"flex gap-2 p-4 items-start",children:[t?m(pt,{variant:"ghost",onClick:e,"aria-label":s.go_back,className:"!h-8 !w-8",children:m(It,{name:"chevron-up",className:"-rotate-90",size:"sm"})}):m("div",{className:"relative w-8 h-8"}),m(je,{active:n,children:m(va,{className:"transition-opacity data-hidden:opacity-0"})})]}),m(je,{active:r,children:m("div",{className:"absolute top-0 left-0 right-0 p-4 flex justify-center transition-[opacity,transform] duration-200 data-hidden:opacity-0 data-hidden:-translate-y-4",children:m(n_,{})})})]})}const r_={"top-left":"origin-top-left",top:"origin-top","top-right":"origin-top-right","bottom-left":"origin-bottom-left","bottom-right":"origin-bottom-right",bottom:"origin-bottom"};function Dp({open:t}){const e=xe(),n=fa(),i=Wr(),r=Ae(),s=r.value.placement,{isDisconnected:o,startSession:a,transcript:c,conversationIndex:l}=Be(),d=Dh(),{currentContent:u,currentConfig:h}=ya(),f=ue(()=>{var b;return n.value||i.value?!d.value||!n.value?c.value:[{type:"message",role:"ai",message:d.value,isText:!0,conversationIndex:((b=c.value[0])==null?void 0:b.conversationIndex)??l.peek()},...c.value]:r.value.transcript_enabled?c.value:c.value.filter(k=>k.type!=="message"||k.isText)}),v=f.value.length>0||!o.value&&r.value.transcript_enabled,p=Ie(!0),g=u.value!=="feedback";return m(je,{initial:!1,active:t,children:m("div",{className:ae("flex flex-col overflow-hidden absolute bg-base shadow-lg pointer-events-auto rounded-sheet w-full max-w-[400px] h-[calc(100%-80px)] max-h-[550px]","transition-[transform,opacity] duration-200 data-hidden:scale-90 data-hidden:opacity-0",r_[s],s.startsWith("top")?r.value.always_expanded?"top-0":"top-20":r.value.always_expanded?"bottom-0":"bottom-20"),children:[m(i_,{showBackButton:h.showHeaderBack,onBackClick:h.onHeaderBack,showStatusLabel:v&&!o.value,showShadow:v,showLanguageSelector:u.value!=="feedback"&&(!v||o.value)}),m(je,{active:u.value==="transcript",children:m("div",{className:"grow flex flex-col min-h-0 transition-opacity duration-300 ease-out data-hidden:opacity-0",children:[m(Ay,{transcript:f,scrollPinned:p}),m(Dy,{scrollPinned:p,showTranscript:v})]})}),m(je,{active:u.value==="feedback",children:m("div",{className:"absolute inset-0 top-[88px] flex flex-col bg-base transition-transform duration-300 ease-out data-hidden:translate-x-full",children:[m(My,{}),m(Ny,{})]})}),m(je,{active:g,children:m("div",{className:ae("absolute origin-top-left transition-[transform,left,top,opacity,scale] duration-200 z-1","data-hidden:opacity-0",v?"top-4 left-4 scale-[0.1667]":"top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 scale-100"),children:[m(si,{size:"lg"}),m(je,{active:!v&&o.value&&!n.value,children:m("div",{className:"absolute bottom-0 p-1 rounded-[calc(var(--el-button-radius)+4px)] bg-base left-1/2 -translate-x-1/2 translate-y-1/2 transition-[opacity,transform] data-hidden:opacity-0 data-hidden:scale-100 scale-150",children:m(pt,{"aria-label":e.start_call,variant:"primary",icon:"phone",onClick:b=>a(b.currentTarget)})})}),m(je,{active:!v&&!o.value,children:m("div",{className:"absolute -bottom-3 left-1/2 -translate-x-1/2 translate-y-full transition-[opacity,transform] data-hidden:opacity-0 data-hidden:scale-75",children:m(va,{})})})]})})]})})}function Mp({expanded:t}){const e=Wr(),n=Ae().value.variant,{isDisconnected:i}=Be(),r=xe(),s=j(()=>{t.value=!t.value},[t]);return m(ge,{children:[n==="full"&&m(Zt,{visible:!t.value&&!i.value,className:"p-1",children:m(si,{})}),m(Zt,{grow:n!=="tiny",visible:!e.value&&!t.value&&!i.value,className:"p-1",children:m(Ca,{iconOnly:!0,isDisconnected:!1})}),m(ka,{visible:!e.value&&!t.value&&!i.value}),m(Zt,{grow:i.value,visible:!0,className:"p-1",children:m(pt,{className:"w-full",variant:"primary",iconClassName:ae((t.value||!i.value)&&"transition-transform duration-200",t.value&&"-rotate-180"),icon:t.value?"chevron-up":i.value?e.value?"chat":"phone":"chevron-up","aria-label":t.value?r.collapse:i.value?e.value?r.start_chat:r.start_call:r.expand,onClick:!t.value&&!i.value?s:void 0,children:!t.value&&i.value&&n!=="tiny"?e.value?r.start_chat:r.start_call:void 0})})]})}function s_({expanded:t,className:e,...n}){const{isDisconnected:i}=Be(),r=xe();return m("div",{className:ae("transition-[border-radius] flex flex-col p-2",!t.value&&i.value?"rounded-sheet":"rounded-compact-sheet",e),...n,children:[m(Zt,{visible:!t.value&&i.value,className:"p-1 !min-w-60",children:m("div",{className:"flex items-center gap-2",children:[m(si,{}),m("div",{className:"text-sm max-w-64",children:r.main_label})]})}),m("div",{className:"flex items-center",children:m(Mp,{expanded:t})})]})}function o_({expanded:t,className:e,...n}){return m("div",{className:ae("rounded-compact-sheet flex items-center p-2",e),...n,children:[m(Zt,{visible:!t.value,className:"p-1",children:m(si,{})}),m(Mp,{expanded:t})]})}function a_({visible:t,className:e,...n}){const i=xe(),{language:r,showPicker:s}=ri();return s.value?m(Zt,{visible:t,className:"p-1",children:m(Ap,{children:m(Ip,{className:ae("h-9 min-w-max border border-base-border rounded-button focus-ring px-1.5 flex gap-1 items-center transition-colors duration-200 hover:bg-base-hover active:bg-base-active",e),"aria-label":i.change_language,...n,children:[m(Za,{flagCode:r.value.flagCode}),m(Op,{className:"px-1 text-base-subtle",asChild:!0,children:m(It,{size:"sm",name:"chevron-down"})})]})})}):null}function Np(){const t=Ae().value.variant,{isDisconnected:e,status:n}=Be();return m(ge,{children:[m(Ca,{isDisconnected:e.value,iconOnly:t==="tiny",className:"w-full m-1 z-1",disabled:n.value==="disconnecting"||n.value==="connecting"}),m(a_,{visible:e.value}),m(ka,{visible:!e.value})]})}function c_({className:t,...e}){const{isDisconnected:n}=Be(),i=xe();return m("div",{className:ae("flex flex-col p-2 rounded-sheet",t),...e,children:[m("div",{className:"flex items-center p-1 gap-2 min-w-60",children:[m(si,{}),m("div",{className:"relative text-sm max-w-64",children:[m("span",{className:ae("block transition-[transform,opacity] duration-200",!n.value&&"opacity-0 scale-90"),children:i.main_label}),m(je,{active:!n.value,children:m(va,{className:"absolute top-1/2 -translate-y-1/2 transition-[transform,opacity] duration-200 data-hidden:opacity-0 data-hidden:scale-90"})})]})]}),m("div",{className:"flex items-center",children:m(Np,{})})]})}function l_({className:t,...e}){return m("div",{className:ae("rounded-compact-sheet flex items-center p-2",t),...e,children:[m(si,{className:"mx-1"}),m(Np,{})]})}function d_({expandable:t,expanded:e}){const n=Ae().value.variant,i=zr(),{isDisconnected:r}=Be(),s=j(async()=>{await i.requestTerms(),e.value=!e.peek()},[e]),o=n==="full";return t?m(o?s_:o_,{expanded:e,className:ae("bg-base shadow-md pointer-events-auto overflow-hidden",(r.value||e.value)&&"cursor-pointer"),onClick:r.value||e.value?s:void 0}):m(o?c_:l_,{className:"bg-base shadow-md pointer-events-auto overflow-hidden"})}function u_(){const t=xe(),e=Ae(),{dismissTerms:n,acceptTerms:i}=zr();return m("div",{className:"max-w-[400px] flex flex-col gap-2 bg-base shadow-md pointer-events-auto rounded-sheet p-3 text-sm",children:[m("div",{className:"flex flex-col gap-1 terms p-2 pt-1",dangerouslySetInnerHTML:{__html:e.value.terms_html??""}}),m("div",{className:"flex justify-end gap-2",children:[m(pt,{onClick:n,children:t.dismiss_terms}),m(pt,{onClick:i,variant:"primary",children:t.accept_terms})]})]})}function h_({copyText:t,children:e}){const n=xe(),[i,r]=V(!1);G(()=>{if(i){const o=setTimeout(()=>{r(!1)},2e3);return()=>{clearTimeout(o)}}},[i]);const s=j(()=>{const o=Uh(t);o&&(navigator.clipboard.writeText(o),r(!0))},[]);return m(pt,{onClick:s,children:i?n.copied:e})}function f_({sawError:t}){const e=xe(),{error:n,lastId:i}=Be(),r=j(()=>{t.value=!0},[]);return m("div",{className:"max-w-[400px] flex flex-col gap-2 bg-base shadow-md pointer-events-auto rounded-sheet p-3 text-sm",children:[m("div",{className:"p-2 pt-1",children:[m("h1",{className:"text-md font-medium pb-1",children:e.error_occurred}),n.value,i.value&&m(ge,{children:[m("br",{}),m("span",{className:"text-base-subtle",children:[e.conversation_id,": ",i.value]})]})]}),m("div",{className:"flex justify-end gap-2",children:[m(h_,{copyText:i,children:e.copy_id}),m(pt,{variant:"primary",onClick:r,children:"Close"})]})]})}function p_(){const t=Ae();return t.value.disable_banner?null:m("p",{className:ae("whitespace-nowrap [line-height:var(--el-overlay-padding)] text-[10px] px-3",t.value.placement.startsWith("top")?"-translate-y-[calc(var(--el-overlay-padding))]":"translate-y-[calc(var(--el-overlay-padding))]"),children:[m("span",{className:"opacity-30",children:"Powered by ElevenLabs"})," ",m("a",{href:t.value.override_link||"https://elevenlabs.io/conversational-ai",className:"underline cursor-pointer pointer-events-auto focus-visible:outline-none opacity-30 hover:opacity-50 focus-visible:opacity-100 focus-visible:underline-offset-2",target:"_blank",children:"Agents"})]})}const mi={left:"items-start",center:"items-center",right:"items-end"},gi={top:"flex-col-reverse justify-end",bottom:"flex-col justify-end"},m_={"top-left":`${gi.top} ${mi.left}`,top:`${gi.top} ${mi.center}`,"top-right":`${gi.top} ${mi.right}`,"bottom-left":`${gi.bottom} ${mi.left}`,bottom:`${gi.bottom} ${mi.center}`,"bottom-right":`${gi.bottom} ${mi.right}`},fs={display:"none"},g_=tr(function(){const t=Ae(),e=Ie(t.peek().default_expanded),n=Ie(!1),{error:i}=Be(),r=zr(),s=ue(()=>t.value.transcript_enabled||t.value.text_input_enabled),o=ue(()=>ae("overlay !flex transition-opacity duration-200 data-hidden:opacity-0",m_[t.value.placement]));Ct(()=>{i.value&&(s.value?(n.value=!0,e.value=!0):n.value=!1)}),Ct(()=>{const u=h=>{var f,v,p;((f=h.detail)==null?void 0:f.action)==="expand"?e.value=!0:((v=h.detail)==null?void 0:v.action)==="collapse"?e.value=!1:((p=h.detail)==null?void 0:p.action)==="toggle"&&(e.value=!e.value)};return document.addEventListener("elevenlabs-agent:expand",u),()=>{document.removeEventListener("elevenlabs-agent:expand",u)}});const a=ue(()=>!s.value&&i.value&&!n.value?"error":!r.termsAccepted.value&&r.termsShown.value?"terms":"conversation"),c=ue(()=>a.value==="error"),l=ue(()=>a.value==="terms"),d=ue(()=>a.value==="conversation");return m(ge,{children:[m(je,{initial:!1,active:d,children:m(Hr,{className:o,style:fs,children:t.value.always_expanded?m(Dp,{open:!0}):m(ge,{children:[s.value&&m(Dp,{open:e}),m(d_,{expandable:s.value,expanded:e})]})})}),m(je,{initial:!1,active:l,children:m(Hr,{className:o,style:fs,children:m(u_,{})})}),m(je,{initial:!1,active:c,children:m(Hr,{className:o,style:fs,children:m(f_,{sawError:n})})}),m(Hr,{className:o,style:fs,children:m(p_,{})})]})});function v_(t){return m(yb,{value:t,children:m(Cb,{children:m(Ob,{children:m(Pb,{children:m(wb,{children:m(Sb,{children:m(Tb,{children:m(Eb,{children:m(Fb,{children:m(Bb,{children:m(ky,{children:m(yy,{children:[m(Nb,{}),m(g_,{})]})})})})})})})})})})})})}function b_(t="elevenlabs-convai"){qp(v_,t,[...da],{shadow:!0,mode:"open"})}b_()})();