hanc-webrtc-widgets 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,34 +1,34 @@
1
- (function(L,Qe){typeof exports=="object"&&typeof module<"u"?Qe(exports):typeof define=="function"&&define.amd?define(["exports"],Qe):(L=typeof globalThis<"u"?globalThis:L||self,Qe(L.HancWebrtcWidgets={}))})(this,(function(L){"use strict";/**
1
+ (function(N,Ze){typeof exports=="object"&&typeof module<"u"?Ze(exports):typeof define=="function"&&define.amd?define(["exports"],Ze):(N=typeof globalThis<"u"?globalThis:N||self,Ze(N.HancWebrtcWidgets={}))})(this,(function(N){"use strict";/**
2
2
  * @license
3
3
  * Copyright 2019 Google LLC
4
4
  * SPDX-License-Identifier: BSD-3-Clause
5
- */var cc;const Qe=globalThis,hn=Qe.ShadowRoot&&(Qe.ShadyCSS===void 0||Qe.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,pn=Symbol(),Bs=new WeakMap;let js=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==pn)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(hn&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=Bs.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Bs.set(t,e))}return e}toString(){return this.cssText}};const hc=n=>new js(typeof n=="string"?n:n+"",void 0,pn),fn=(n,...e)=>{const t=n.length===1?n[0]:e.reduce((i,s,r)=>i+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+n[r+1],n[0]);return new js(t,n,pn)},pc=(n,e)=>{if(hn)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),s=Qe.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=t.cssText,n.appendChild(i)}},qs=hn?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return hc(t)})(n):n;/**
5
+ */var hc;const Ze=globalThis,fn=Ze.ShadowRoot&&(Ze.ShadyCSS===void 0||Ze.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,mn=Symbol(),Vs=new WeakMap;let $s=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==mn)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(fn&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=Vs.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Vs.set(t,e))}return e}toString(){return this.cssText}};const gc=n=>new $s(typeof n=="string"?n:n+"",void 0,mn),gn=(n,...e)=>{const t=n.length===1?n[0]:e.reduce((i,s,r)=>i+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+n[r+1],n[0]);return new $s(t,n,mn)},vc=(n,e)=>{if(fn)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),s=Ze.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=t.cssText,n.appendChild(i)}},Ws=fn?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return gc(t)})(n):n;/**
6
6
  * @license
7
7
  * Copyright 2017 Google LLC
8
8
  * SPDX-License-Identifier: BSD-3-Clause
9
- */const{is:fc,defineProperty:mc,getOwnPropertyDescriptor:gc,getOwnPropertyNames:vc,getOwnPropertySymbols:bc,getPrototypeOf:yc}=Object,Ze=globalThis,Vs=Ze.trustedTypes,Sc=Vs?Vs.emptyScript:"",mn=Ze.reactiveElementPolyfillSupport,Yt=(n,e)=>n,Ci={toAttribute(n,e){switch(e){case Boolean:n=n?Sc:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},gn=(n,e)=>!fc(n,e),$s={attribute:!0,type:String,converter:Ci,reflect:!1,useDefault:!1,hasChanged:gn};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ze.litPropertyMetadata??(Ze.litPropertyMetadata=new WeakMap);let Et=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=$s){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(e,i,t);s!==void 0&&mc(this.prototype,e,s)}}static getPropertyDescriptor(e,t,i){const{get:s,set:r}=gc(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o}};return{get:s,set(o){const a=s==null?void 0:s.call(this);r==null||r.call(this,o),this.requestUpdate(e,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??$s}static _$Ei(){if(this.hasOwnProperty(Yt("elementProperties")))return;const e=yc(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Yt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Yt("properties"))){const t=this.properties,i=[...vc(t),...bc(t)];for(const s of i)this.createProperty(s,t[s])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[i,s]of t)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const s=this._$Eu(t,i);s!==void 0&&this._$Eh.set(s,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const s of i)t.unshift(qs(s))}else e!==void 0&&t.push(qs(e));return t}static _$Eu(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return pc(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostConnected)==null?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostDisconnected)==null?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){var r;const i=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,i);if(s!==void 0&&i.reflect===!0){const o=(((r=i.converter)==null?void 0:r.toAttribute)!==void 0?i.converter:Ci).toAttribute(t,i.type);this._$Em=e,o==null?this.removeAttribute(s):this.setAttribute(s,o),this._$Em=null}}_$AK(e,t){var r,o;const i=this.constructor,s=i._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((r=a.converter)==null?void 0:r.fromAttribute)!==void 0?a.converter:Ci;this._$Em=s;const d=c.fromAttribute(t,a.type);this[s]=d??((o=this._$Ej)==null?void 0:o.get(s))??d,this._$Em=null}}requestUpdate(e,t,i,s=!1,r){var o;if(e!==void 0){const a=this.constructor;if(s===!1&&(r=this[e]),i??(i=a.getPropertyOptions(e)),!((i.hasChanged??gn)(r,t)||i.useDefault&&i.reflect&&r===((o=this._$Ej)==null?void 0:o.get(e))&&!this.hasAttribute(a._$Eu(e,i))))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:s,wrapped:r},o){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??t??this[e]),r!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),s===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:a}=o,c=this[r];a!==!0||this._$AL.has(r)||c===void 0||this.C(r,void 0,o,c)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(i=this._$EO)==null||i.forEach(s=>{var r;return(r=s.hostUpdate)==null?void 0:r.call(s)}),this.update(t)):this._$EM()}catch(s){throw e=!1,this._$EM(),s}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};Et.elementStyles=[],Et.shadowRootOptions={mode:"open"},Et[Yt("elementProperties")]=new Map,Et[Yt("finalized")]=new Map,mn==null||mn({ReactiveElement:Et}),(Ze.reactiveElementVersions??(Ze.reactiveElementVersions=[])).push("2.1.2");/**
9
+ */const{is:bc,defineProperty:yc,getOwnPropertyDescriptor:Sc,getOwnPropertyNames:kc,getOwnPropertySymbols:Cc,getPrototypeOf:Tc}=Object,et=globalThis,Gs=et.trustedTypes,Ec=Gs?Gs.emptyScript:"",vn=et.reactiveElementPolyfillSupport,Xt=(n,e)=>n,Ti={toAttribute(n,e){switch(e){case Boolean:n=n?Ec:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},bn=(n,e)=>!bc(n,e),Hs={attribute:!0,type:String,converter:Ti,reflect:!1,useDefault:!1,hasChanged:bn};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),et.litPropertyMetadata??(et.litPropertyMetadata=new WeakMap);let wt=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Hs){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(e,i,t);s!==void 0&&yc(this.prototype,e,s)}}static getPropertyDescriptor(e,t,i){const{get:s,set:r}=Sc(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o}};return{get:s,set(o){const a=s==null?void 0:s.call(this);r==null||r.call(this,o),this.requestUpdate(e,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Hs}static _$Ei(){if(this.hasOwnProperty(Xt("elementProperties")))return;const e=Tc(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Xt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Xt("properties"))){const t=this.properties,i=[...kc(t),...Cc(t)];for(const s of i)this.createProperty(s,t[s])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[i,s]of t)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const s=this._$Eu(t,i);s!==void 0&&this._$Eh.set(s,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const s of i)t.unshift(Ws(s))}else e!==void 0&&t.push(Ws(e));return t}static _$Eu(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return vc(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostConnected)==null?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostDisconnected)==null?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){var r;const i=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,i);if(s!==void 0&&i.reflect===!0){const o=(((r=i.converter)==null?void 0:r.toAttribute)!==void 0?i.converter:Ti).toAttribute(t,i.type);this._$Em=e,o==null?this.removeAttribute(s):this.setAttribute(s,o),this._$Em=null}}_$AK(e,t){var r,o;const i=this.constructor,s=i._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((r=a.converter)==null?void 0:r.fromAttribute)!==void 0?a.converter:Ti;this._$Em=s;const d=c.fromAttribute(t,a.type);this[s]=d??((o=this._$Ej)==null?void 0:o.get(s))??d,this._$Em=null}}requestUpdate(e,t,i,s=!1,r){var o;if(e!==void 0){const a=this.constructor;if(s===!1&&(r=this[e]),i??(i=a.getPropertyOptions(e)),!((i.hasChanged??bn)(r,t)||i.useDefault&&i.reflect&&r===((o=this._$Ej)==null?void 0:o.get(e))&&!this.hasAttribute(a._$Eu(e,i))))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:s,wrapped:r},o){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??t??this[e]),r!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),s===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:a}=o,c=this[r];a!==!0||this._$AL.has(r)||c===void 0||this.C(r,void 0,o,c)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(i=this._$EO)==null||i.forEach(s=>{var r;return(r=s.hostUpdate)==null?void 0:r.call(s)}),this.update(t)):this._$EM()}catch(s){throw e=!1,this._$EM(),s}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};wt.elementStyles=[],wt.shadowRootOptions={mode:"open"},wt[Xt("elementProperties")]=new Map,wt[Xt("finalized")]=new Map,vn==null||vn({ReactiveElement:wt}),(et.reactiveElementVersions??(et.reactiveElementVersions=[])).push("2.1.2");/**
10
10
  * @license
11
11
  * Copyright 2017 Google LLC
12
12
  * SPDX-License-Identifier: BSD-3-Clause
13
- */const Xt=globalThis,Ws=n=>n,Ei=Xt.trustedTypes,Gs=Ei?Ei.createPolicy("lit-html",{createHTML:n=>n}):void 0,Hs="$lit$",et=`lit$${Math.random().toFixed(9).slice(2)}$`,zs="?"+et,kc=`<${zs}>`,pt=document,Qt=()=>pt.createComment(""),Zt=n=>n===null||typeof n!="object"&&typeof n!="function",vn=Array.isArray,Tc=n=>vn(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",bn=`[
14
- \f\r]`,ei=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ks=/-->/g,Js=/>/g,ft=RegExp(`>|${bn}(?:([^\\s"'>=/]+)(${bn}*=${bn}*(?:[^
15
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Ys=/'/g,Xs=/"/g,Qs=/^(?:script|style|textarea|title)$/i,Cc=n=>(e,...t)=>({_$litType$:n,strings:e,values:t}),Pt=Cc(1),Rt=Symbol.for("lit-noChange"),oe=Symbol.for("lit-nothing"),Zs=new WeakMap,mt=pt.createTreeWalker(pt,129);function er(n,e){if(!vn(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return Gs!==void 0?Gs.createHTML(e):e}const Ec=(n,e)=>{const t=n.length-1,i=[];let s,r=e===2?"<svg>":e===3?"<math>":"",o=ei;for(let a=0;a<t;a++){const c=n[a];let d,l,u=-1,h=0;for(;h<c.length&&(o.lastIndex=h,l=o.exec(c),l!==null);)h=o.lastIndex,o===ei?l[1]==="!--"?o=Ks:l[1]!==void 0?o=Js:l[2]!==void 0?(Qs.test(l[2])&&(s=RegExp("</"+l[2],"g")),o=ft):l[3]!==void 0&&(o=ft):o===ft?l[0]===">"?(o=s??ei,u=-1):l[1]===void 0?u=-2:(u=o.lastIndex-l[2].length,d=l[1],o=l[3]===void 0?ft:l[3]==='"'?Xs:Ys):o===Xs||o===Ys?o=ft:o===Ks||o===Js?o=ei:(o=ft,s=void 0);const f=o===ft&&n[a+1].startsWith("/>")?" ":"";r+=o===ei?c+kc:u>=0?(i.push(d),c.slice(0,u)+Hs+c.slice(u)+et+f):c+et+(u===-2?a:f)}return[er(n,r+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class ti{constructor({strings:e,_$litType$:t},i){let s;this.parts=[];let r=0,o=0;const a=e.length-1,c=this.parts,[d,l]=Ec(e,t);if(this.el=ti.createElement(d,i),mt.currentNode=this.el.content,t===2||t===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=mt.nextNode())!==null&&c.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Hs)){const h=l[o++],f=s.getAttribute(u).split(et),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:f,ctor:g[1]==="."?Rc:g[1]==="?"?wc:g[1]==="@"?_c:Pi}),s.removeAttribute(u)}else u.startsWith(et)&&(c.push({type:6,index:r}),s.removeAttribute(u));if(Qs.test(s.tagName)){const u=s.textContent.split(et),h=u.length-1;if(h>0){s.textContent=Ei?Ei.emptyScript:"";for(let f=0;f<h;f++)s.append(u[f],Qt()),mt.nextNode(),c.push({type:2,index:++r});s.append(u[h],Qt())}}}else if(s.nodeType===8)if(s.data===zs)c.push({type:2,index:r});else{let u=-1;for(;(u=s.data.indexOf(et,u+1))!==-1;)c.push({type:7,index:r}),u+=et.length-1}r++}}static createElement(e,t){const i=pt.createElement("template");return i.innerHTML=e,i}}function wt(n,e,t=n,i){var o,a;if(e===Rt)return e;let s=i!==void 0?(o=t._$Co)==null?void 0:o[i]:t._$Cl;const r=Zt(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==r&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),r===void 0?s=void 0:(s=new r(n),s._$AT(n,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=s:t._$Cl=s),s!==void 0&&(e=wt(n,s._$AS(n,e.values),s,i)),e}class Pc{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,s=((e==null?void 0:e.creationScope)??pt).importNode(t,!0);mt.currentNode=s;let r=mt.nextNode(),o=0,a=0,c=i[0];for(;c!==void 0;){if(o===c.index){let d;c.type===2?d=new ii(r,r.nextSibling,this,e):c.type===1?d=new c.ctor(r,c.name,c.strings,this,e):c.type===6&&(d=new xc(r,this,e)),this._$AV.push(d),c=i[++a]}o!==(c==null?void 0:c.index)&&(r=mt.nextNode(),o++)}return mt.currentNode=pt,s}p(e){let t=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class ii{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,i,s){this.type=2,this._$AH=oe,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=wt(this,e,t),Zt(e)?e===oe||e==null||e===""?(this._$AH!==oe&&this._$AR(),this._$AH=oe):e!==this._$AH&&e!==Rt&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Tc(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==oe&&Zt(this._$AH)?this._$AA.nextSibling.data=e:this.T(pt.createTextNode(e)),this._$AH=e}$(e){var r;const{values:t,_$litType$:i}=e,s=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=ti.createElement(er(i.h,i.h[0]),this.options)),i);if(((r=this._$AH)==null?void 0:r._$AD)===s)this._$AH.p(t);else{const o=new Pc(s,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=Zs.get(e.strings);return t===void 0&&Zs.set(e.strings,t=new ti(e)),t}k(e){vn(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,s=0;for(const r of e)s===t.length?t.push(i=new ii(this.O(Qt()),this.O(Qt()),this,this.options)):i=t[s],i._$AI(r),s++;s<t.length&&(this._$AR(i&&i._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,t);e!==this._$AB;){const s=Ws(e).nextSibling;Ws(e).remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class Pi{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,s,r){this.type=1,this._$AH=oe,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=r,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=oe}_$AI(e,t=this,i,s){const r=this.strings;let o=!1;if(r===void 0)e=wt(this,e,t,0),o=!Zt(e)||e!==this._$AH&&e!==Rt,o&&(this._$AH=e);else{const a=e;let c,d;for(e=r[0],c=0;c<r.length-1;c++)d=wt(this,a[i+c],t,c),d===Rt&&(d=this._$AH[c]),o||(o=!Zt(d)||d!==this._$AH[c]),d===oe?e=oe:e!==oe&&(e+=(d??"")+r[c+1]),this._$AH[c]=d}o&&!s&&this.j(e)}j(e){e===oe?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Rc extends Pi{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===oe?void 0:e}}class wc extends Pi{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==oe)}}class _c extends Pi{constructor(e,t,i,s,r){super(e,t,i,s,r),this.type=5}_$AI(e,t=this){if((e=wt(this,e,t,0)??oe)===Rt)return;const i=this._$AH,s=e===oe&&i!==oe||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,r=e!==oe&&(i===oe||s);s&&this.element.removeEventListener(this.name,this,i),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class xc{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){wt(this,e)}}const yn=Xt.litHtmlPolyfillSupport;yn==null||yn(ti,ii),(Xt.litHtmlVersions??(Xt.litHtmlVersions=[])).push("3.3.2");const Ic=(n,e,t)=>{const i=(t==null?void 0:t.renderBefore)??e;let s=i._$litPart$;if(s===void 0){const r=(t==null?void 0:t.renderBefore)??null;i._$litPart$=s=new ii(e.insertBefore(Qt(),r),r,void 0,t??{})}return s._$AI(n),s};/**
13
+ */const Qt=globalThis,zs=n=>n,Ei=Qt.trustedTypes,Ks=Ei?Ei.createPolicy("lit-html",{createHTML:n=>n}):void 0,Js="$lit$",tt=`lit$${Math.random().toFixed(9).slice(2)}$`,Ys="?"+tt,wc=`<${Ys}>`,ft=document,Zt=()=>ft.createComment(""),ei=n=>n===null||typeof n!="object"&&typeof n!="function",yn=Array.isArray,Pc=n=>yn(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",Sn=`[
14
+ \f\r]`,ti=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Xs=/-->/g,Qs=/>/g,mt=RegExp(`>|${Sn}(?:([^\\s"'>=/]+)(${Sn}*=${Sn}*(?:[^
15
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Zs=/'/g,er=/"/g,tr=/^(?:script|style|textarea|title)$/i,Rc=n=>(e,...t)=>({_$litType$:n,strings:e,values:t}),Pt=Rc(1),Rt=Symbol.for("lit-noChange"),ce=Symbol.for("lit-nothing"),ir=new WeakMap,gt=ft.createTreeWalker(ft,129);function nr(n,e){if(!yn(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ks!==void 0?Ks.createHTML(e):e}const _c=(n,e)=>{const t=n.length-1,i=[];let s,r=e===2?"<svg>":e===3?"<math>":"",o=ti;for(let a=0;a<t;a++){const c=n[a];let d,l,u=-1,h=0;for(;h<c.length&&(o.lastIndex=h,l=o.exec(c),l!==null);)h=o.lastIndex,o===ti?l[1]==="!--"?o=Xs:l[1]!==void 0?o=Qs:l[2]!==void 0?(tr.test(l[2])&&(s=RegExp("</"+l[2],"g")),o=mt):l[3]!==void 0&&(o=mt):o===mt?l[0]===">"?(o=s??ti,u=-1):l[1]===void 0?u=-2:(u=o.lastIndex-l[2].length,d=l[1],o=l[3]===void 0?mt:l[3]==='"'?er:Zs):o===er||o===Zs?o=mt:o===Xs||o===Qs?o=ti:(o=mt,s=void 0);const f=o===mt&&n[a+1].startsWith("/>")?" ":"";r+=o===ti?c+wc:u>=0?(i.push(d),c.slice(0,u)+Js+c.slice(u)+tt+f):c+tt+(u===-2?a:f)}return[nr(n,r+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class ii{constructor({strings:e,_$litType$:t},i){let s;this.parts=[];let r=0,o=0;const a=e.length-1,c=this.parts,[d,l]=_c(e,t);if(this.el=ii.createElement(d,i),gt.currentNode=this.el.content,t===2||t===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=gt.nextNode())!==null&&c.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Js)){const h=l[o++],f=s.getAttribute(u).split(tt),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:f,ctor:g[1]==="."?Ic:g[1]==="?"?Ac:g[1]==="@"?Mc:wi}),s.removeAttribute(u)}else u.startsWith(tt)&&(c.push({type:6,index:r}),s.removeAttribute(u));if(tr.test(s.tagName)){const u=s.textContent.split(tt),h=u.length-1;if(h>0){s.textContent=Ei?Ei.emptyScript:"";for(let f=0;f<h;f++)s.append(u[f],Zt()),gt.nextNode(),c.push({type:2,index:++r});s.append(u[h],Zt())}}}else if(s.nodeType===8)if(s.data===Ys)c.push({type:2,index:r});else{let u=-1;for(;(u=s.data.indexOf(tt,u+1))!==-1;)c.push({type:7,index:r}),u+=tt.length-1}r++}}static createElement(e,t){const i=ft.createElement("template");return i.innerHTML=e,i}}function _t(n,e,t=n,i){var o,a;if(e===Rt)return e;let s=i!==void 0?(o=t._$Co)==null?void 0:o[i]:t._$Cl;const r=ei(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==r&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),r===void 0?s=void 0:(s=new r(n),s._$AT(n,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=s:t._$Cl=s),s!==void 0&&(e=_t(n,s._$AS(n,e.values),s,i)),e}class xc{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,s=((e==null?void 0:e.creationScope)??ft).importNode(t,!0);gt.currentNode=s;let r=gt.nextNode(),o=0,a=0,c=i[0];for(;c!==void 0;){if(o===c.index){let d;c.type===2?d=new ni(r,r.nextSibling,this,e):c.type===1?d=new c.ctor(r,c.name,c.strings,this,e):c.type===6&&(d=new Oc(r,this,e)),this._$AV.push(d),c=i[++a]}o!==(c==null?void 0:c.index)&&(r=gt.nextNode(),o++)}return gt.currentNode=ft,s}p(e){let t=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class ni{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,i,s){this.type=2,this._$AH=ce,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=_t(this,e,t),ei(e)?e===ce||e==null||e===""?(this._$AH!==ce&&this._$AR(),this._$AH=ce):e!==this._$AH&&e!==Rt&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Pc(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==ce&&ei(this._$AH)?this._$AA.nextSibling.data=e:this.T(ft.createTextNode(e)),this._$AH=e}$(e){var r;const{values:t,_$litType$:i}=e,s=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=ii.createElement(nr(i.h,i.h[0]),this.options)),i);if(((r=this._$AH)==null?void 0:r._$AD)===s)this._$AH.p(t);else{const o=new xc(s,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=ir.get(e.strings);return t===void 0&&ir.set(e.strings,t=new ii(e)),t}k(e){yn(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,s=0;for(const r of e)s===t.length?t.push(i=new ni(this.O(Zt()),this.O(Zt()),this,this.options)):i=t[s],i._$AI(r),s++;s<t.length&&(this._$AR(i&&i._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,t);e!==this._$AB;){const s=zs(e).nextSibling;zs(e).remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class wi{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,s,r){this.type=1,this._$AH=ce,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=r,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=ce}_$AI(e,t=this,i,s){const r=this.strings;let o=!1;if(r===void 0)e=_t(this,e,t,0),o=!ei(e)||e!==this._$AH&&e!==Rt,o&&(this._$AH=e);else{const a=e;let c,d;for(e=r[0],c=0;c<r.length-1;c++)d=_t(this,a[i+c],t,c),d===Rt&&(d=this._$AH[c]),o||(o=!ei(d)||d!==this._$AH[c]),d===ce?e=ce:e!==ce&&(e+=(d??"")+r[c+1]),this._$AH[c]=d}o&&!s&&this.j(e)}j(e){e===ce?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Ic extends wi{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===ce?void 0:e}}class Ac extends wi{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==ce)}}class Mc extends wi{constructor(e,t,i,s,r){super(e,t,i,s,r),this.type=5}_$AI(e,t=this){if((e=_t(this,e,t,0)??ce)===Rt)return;const i=this._$AH,s=e===ce&&i!==ce||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,r=e!==ce&&(i===ce||s);s&&this.element.removeEventListener(this.name,this,i),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class Oc{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){_t(this,e)}}const kn=Qt.litHtmlPolyfillSupport;kn==null||kn(ii,ni),(Qt.litHtmlVersions??(Qt.litHtmlVersions=[])).push("3.3.2");const Dc=(n,e,t)=>{const i=(t==null?void 0:t.renderBefore)??e;let s=i._$litPart$;if(s===void 0){const r=(t==null?void 0:t.renderBefore)??null;i._$litPart$=s=new ni(e.insertBefore(Zt(),r),r,void 0,t??{})}return s._$AI(n),s};/**
16
16
  * @license
17
17
  * Copyright 2017 Google LLC
18
18
  * SPDX-License-Identifier: BSD-3-Clause
19
- */const gt=globalThis;class _t extends Et{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t;const e=super.createRenderRoot();return(t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Ic(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return Rt}}_t._$litElement$=!0,_t.finalized=!0,(cc=gt.litElementHydrateSupport)==null||cc.call(gt,{LitElement:_t});const Sn=gt.litElementPolyfillSupport;Sn==null||Sn({LitElement:_t}),(gt.litElementVersions??(gt.litElementVersions=[])).push("4.2.2");/**
19
+ */const vt=globalThis;class xt extends wt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t;const e=super.createRenderRoot();return(t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Dc(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return Rt}}xt._$litElement$=!0,xt.finalized=!0,(hc=vt.litElementHydrateSupport)==null||hc.call(vt,{LitElement:xt});const Cn=vt.litElementPolyfillSupport;Cn==null||Cn({LitElement:xt}),(vt.litElementVersions??(vt.litElementVersions=[])).push("4.2.2");/**
20
20
  * @license
21
21
  * Copyright 2017 Google LLC
22
22
  * SPDX-License-Identifier: BSD-3-Clause
23
- */const tr=n=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(n,e)}):customElements.define(n,e)};/**
23
+ */const sr=n=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(n,e)}):customElements.define(n,e)};/**
24
24
  * @license
25
25
  * Copyright 2017 Google LLC
26
26
  * SPDX-License-Identifier: BSD-3-Clause
27
- */const Ac={attribute:!0,type:String,converter:Ci,reflect:!1,hasChanged:gn},Mc=(n=Ac,e,t)=>{const{kind:i,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),i==="setter"&&((n=Object.create(n)).wrapped=!0),r.set(t.name,n),i==="accessor"){const{name:o}=t;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,n,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,n,a),a}}}if(i==="setter"){const{name:o}=t;return function(a){const c=this[o];e.call(this,a),this.requestUpdate(o,c,n,!0,a)}}throw Error("Unsupported decorator location: "+i)};function j(n){return(e,t)=>typeof t=="object"?Mc(n,e,t):((i,s,r)=>{const o=s.hasOwnProperty(r);return s.constructor.createProperty(r,i),o?Object.getOwnPropertyDescriptor(s,r):void 0})(n,e,t)}/**
27
+ */const Lc={attribute:!0,type:String,converter:Ti,reflect:!1,hasChanged:bn},Nc=(n=Lc,e,t)=>{const{kind:i,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),i==="setter"&&((n=Object.create(n)).wrapped=!0),r.set(t.name,n),i==="accessor"){const{name:o}=t;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,n,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,n,a),a}}}if(i==="setter"){const{name:o}=t;return function(a){const c=this[o];e.call(this,a),this.requestUpdate(o,c,n,!0,a)}}throw Error("Unsupported decorator location: "+i)};function F(n){return(e,t)=>typeof t=="object"?Nc(n,e,t):((i,s,r)=>{const o=s.hasOwnProperty(r);return s.constructor.createProperty(r,i),o?Object.getOwnPropertyDescriptor(s,r):void 0})(n,e,t)}/**
28
28
  * @license
29
29
  * Copyright 2017 Google LLC
30
30
  * SPDX-License-Identifier: BSD-3-Clause
31
- */function ir(n){return j({...n,state:!0,attribute:!1})}const Oc=fn`
31
+ */function Pi(n){return F({...n,state:!0,attribute:!1})}const Uc=gn`
32
32
  :host {
33
33
  display: block;
34
34
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
@@ -38,21 +38,20 @@
38
38
  position: relative;
39
39
  padding: var(--hanc-padding, 24px);
40
40
  border-radius: var(--hanc-radius, 28px);
41
- backdrop-filter: blur(40px);
42
41
  display: flex;
43
42
  flex-direction: column;
44
43
  align-items: center;
45
44
  gap: 20px;
46
- width: var(--hanc-width, 500px);
47
- // box-shadow:
48
- // 0 25px 50px rgba(0, 0, 0, 0.3),
49
- // inset 0 1px 0 rgba(255, 255, 255, 0.1);
45
+ max-width: var(--hanc-width, 500px);
50
46
  }
51
47
 
48
+ .widget[data-state='connecting'] {
49
+ cursor: not-allowed;
50
+ }
52
51
  .orb-container {
53
52
  position: relative;
54
- width: var(--hanc-orb-size, 180px);
55
- height: var(--hanc-orb-size, 180px);
53
+ max-width: var(--hanc-orb-size, 180px);
54
+ max-height: var(--hanc-orb-size, 180px);
56
55
  cursor: pointer;
57
56
  transition: filter 0.45s ease;
58
57
  will-change: transform, filter;
@@ -68,6 +67,12 @@
68
67
  animation: orb-twist-active 10s ease-in-out infinite;
69
68
  }
70
69
 
70
+ .orb-container[data-state='connecting'] {
71
+ pointer-events: none;
72
+ opacity: 0.75;
73
+ filter: saturate(0.7) brightness(0.9);
74
+ }
75
+
71
76
  .orb-container[data-active='true'] {
72
77
  filter:
73
78
  drop-shadow(0 0 16px var(--hanc-orb-active-glow, rgba(139, 92, 246, 0.35)))
@@ -186,7 +191,7 @@
186
191
  animation: none;
187
192
  }
188
193
  }
189
- `,nr=fn`
194
+ `,rr=gn`
190
195
  * {
191
196
  box-sizing: border-box;
192
197
  margin: 0;
@@ -199,8 +204,8 @@
199
204
  font-size: inherit;
200
205
  font-weight: inherit;
201
206
  }
202
- `;function Dc(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Nc=Object.defineProperty,Lc=(n,e,t)=>e in n?Nc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,sr=(n,e,t)=>Lc(n,typeof e!="symbol"?e+"":e,t);class fe{constructor(){sr(this,"_locking"),sr(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function Q(n,e){if(!n)throw new Error(e)}const Uc=34028234663852886e22,Fc=-34028234663852886e22,Bc=4294967295,jc=2147483647,qc=-2147483648;function Ri(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>jc||n<qc)throw new Error("invalid int 32: "+n)}function kn(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Bc||n<0)throw new Error("invalid uint 32: "+n)}function rr(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Uc||n<Fc))throw new Error("invalid float 32: "+n)}const ar=Symbol("@bufbuild/protobuf/enum-type");function Vc(n){const e=n[ar];return Q(e,"missing enum type on enum object"),e}function or(n,e,t,i){n[ar]=cr(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function cr(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=dr(o);r.push(a),i[o.name]=a,s[o.no]=a}return{typeName:n,values:r,findName(o){return i[o]},findNumber(o){return s[o]}}}function $c(n,e,t){const i={};for(const s of e){const r=dr(s);i[r.localName]=r.no,i[r.no]=r.localName}return or(i,n,e),i}function dr(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Tn{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Wc(n,e,t,i){var s;const r=(s=i==null?void 0:i.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new Tn),Object.assign(o,{runtime:n,typeName:e,fields:n.util.newFieldList(t),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 n.util.equals(o,a,c)}}),o}function Gc(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Cn(n,e,t){for(let r=0;r<28;r=r+7){const o=n>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const i=n>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const wi=4294967296;function lr(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(o,a){const c=Number(n.slice(o,a));s*=t,i=i*t+c,i>=wi&&(s=s+(i/wi|0),i=i%wi)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?hr(i,s):En(i,s)}function Hc(n,e){let t=En(n,e);const i=t.hi&2147483648;i&&(t=hr(t.lo,t.hi));const s=ur(t.lo,t.hi);return i?"-"+s:s}function ur(n,e){if({lo:n,hi:e}=zc(n,e),e<=2097151)return String(wi*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,o=i+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+pr(o)+pr(r)}function zc(n,e){return{lo:n>>>0,hi:e>>>0}}function En(n,e){return{lo:n|0,hi:e|0}}function hr(n,e){return e=~e,n?n=~n+1:e+=1,En(n,e)}const pr=n=>{const e=String(n);return"0000000".slice(e.length)+e};function fr(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function Kc(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Jc(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>r||d<s)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>a||d<o)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=s=>Q(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>Q(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),lr(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),lr(s)},dec(s,r){return Hc(s,r)},uDec(s,r){return ur(s,r)}}}const Y=Jc();var k;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(k||(k={}));var tt;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(tt||(tt={}));function it(n,e,t){if(e===t)return!0;if(n==k.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==t}return!1}function xt(n,e){switch(n){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==0?Y.zero:"0";case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function mr(n,e){switch(n){case k.BOOL:return e===!1;case k.STRING:return e==="";case k.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var te;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(te||(te={}));class Yc{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 s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(kn(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ri(e),fr(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 t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){rr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){kn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ri(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ri(e),e=(e<<1^e>>31)>>>0,fr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=Y.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=Y.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=Y.enc(e);return Cn(t.lo,t.hi,this.buf),this}sint64(e){let t=Y.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return Cn(s,r,this.buf),this}uint64(e){let t=Y.uEnc(e);return Cn(t.lo,t.hi,this.buf),this}}class Xc{constructor(e,t){this.varint64=Gc,this.uint32=Kc,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case te.Varint:for(;this.buf[this.pos++]&128;);break;case te.Bit64:this.pos+=4;case te.Bit32:this.pos+=4;break;case te.LengthDelimited:let s=this.uint32();this.pos+=s;break;case te.StartGroup:for(;;){const[r,o]=this.tag();if(o===te.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}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 Y.dec(...this.varint64())}uint64(){return Y.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,Y.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Y.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Y.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(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Qc(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function gr(n){const e=n.field.localName,t=Object.create(null);return t[e]=Zc(n),[t,()=>t[e]]}function Zc(n){const e=n.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 xt(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function ed(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Ve="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),_i=[];for(let n=0;n<Ve.length;n++)_i[Ve[n].charCodeAt(0)]=n;_i[45]=Ve.indexOf("+"),_i[95]=Ve.indexOf("/");const vr={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,o=0;for(let a=0;a<n.length;a++){if(r=_i[n.charCodeAt(a)],r===void 0)switch(n[a]){case"=":s=0;case`
203
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[i++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[i++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[i++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=Ve[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=Ve[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=Ve[s|i>>6],e+=Ve[i&63],t=0;break}return t&&(e+=Ve[s],e+="=",t==1&&(e+="=")),e}};function td(n,e,t){yr(e,n);const i=e.runtime.bin.makeReadOptions(t),s=ed(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,o]=gr(e);for(const a of s)e.runtime.bin.readField(r,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function id(n,e,t,i){yr(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(br(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const o=r.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,t,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function br(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function yr(n,e){Q(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Sr(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!mr(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function kr(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?xt(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function $e(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(Tn.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Tr(n,e){return $e(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;const Cr={ignoreUnknownFields:!1},Er={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function nd(n){return n?Object.assign(Object.assign({},Cr),n):Cr}function sd(n){return n?Object.assign(Object.assign({},Er),n):Er}const xi=Symbol(),Ii=Symbol();function rd(){return{makeReadOptions:nd,makeWriteOptions:sd,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(Ne(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=n.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const d=s.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(o,'"'));s.set(c.oneof,o)}Pr(i,a,c,t,n)}else{let d=!1;if(r!=null&&r.findExtension&&o.startsWith("[")&&o.endsWith("]")){const l=r.findExtension(o.substring(1,o.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=gr(l);Pr(u,a,l.field,t,l),id(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!Sr(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!od(s))continue}const o=s.oneof?n[s.oneof.localName].value:n[s.localName],a=Rr(s,o,e);a!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(n)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&br(n,a)){const c=td(n,a,e),d=Rr(a.field,c,e);d!==void 0&&(i[a.field.jsonName]=d)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return i},readScalar(n,e,t){return ni(n,e,t??tt.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||mr(n,e)))return Ai(n,e)},debug:Ne}}function Ne(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function Pr(n,e,t,i,s){let r=t.localName;if(t.repeated){if(Q(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ne(e)));const o=n[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ne(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,i));break;case"enum":const c=Pn(t.T,a,i.ignoreUnknownFields,!0);c!==Ii&&o.push(c);break;case"scalar":try{o.push(ni(t.T,a,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ne(a));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ne(e)));const o=n[r];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=ad(t.K,a)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ne(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":o[d]=t.V.T.fromJson(c,i);break;case"enum":const l=Pn(t.V.T,c,i.ignoreUnknownFields,!0);l!==Ii&&(o[d]=l);break;case"scalar":try{o[d]=ni(t.V.T,c,tt.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ne(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=n[r];$e(a)?a.fromJson(e,i):(n[r]=a=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Pn(t.T,e,i.ignoreUnknownFields,!1);switch(c){case xi:kr(t,n);break;case Ii:break;default:n[r]=c;break}break;case"scalar":try{const d=ni(t.T,e,t.L,!1);switch(d){case xi:kr(t,n);break;default:n[r]=d;break}}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ne(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function ad(n,e){if(n===k.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return ni(n,e,tt.BIGINT,!0).toString()}function ni(n,e,t,i){if(e===null)return i?xt(n,t):xi;switch(n){case k.DOUBLE:case k.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 s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return n==k.FLOAT&&rr(s),s;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return n==k.UINT32||n==k.FIXED32?kn(r):Ri(r),r;case k.INT64:case k.SFIXED64:case k.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=Y.parse(e);return t?o.toString():o;case k.FIXED64:case k.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=Y.uParse(e);return t?a.toString():a;case k.BOOL:if(typeof e!="boolean")break;return e;case k.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case k.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return vr.dec(e)}throw new Error}function Pn(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:xi;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s!==void 0)return s.no;if(t)return Ii;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Ne(e)))}function od(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function Rr(n,e,t){if(n.kind=="map"){Q(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[o,a]of s)i[o.toString()]=Ai(n.V.T,a);break;case"message":for(const[o,a]of s)i[o.toString()]=a.toJson(t);break;case"enum":const r=n.V.T;for(const[o,a]of s)i[o.toString()]=Rn(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){Q(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(Ai(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(Rn(n.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)i.push(e[s].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return Ai(n.T,e);case"enum":return Rn(n.T,e,t.enumAsInteger);case"message":return Tr(n.T,e).toJson(t)}}function Rn(n,e,t){var i;if(Q(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=n.findNumber(e);return(i=s==null?void 0:s.name)!==null&&i!==void 0?i:e}function Ai(n,e){switch(n){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return Q(typeof e=="number"),e;case k.FLOAT:case k.DOUBLE:return Q(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case k.STRING:return Q(typeof e=="string"),e;case k.BOOL:return Q(typeof e=="boolean"),e;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return Q(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case k.BYTES:return Q(e instanceof Uint8Array),vr.enc(e)}}const It=Symbol("@bufbuild/protobuf/unknown-fields"),wr={readUnknownFields:!0,readerFactory:n=>new Xc(n)},_r={writeUnknownFields:!0,writerFactory:()=>new Yc};function cd(n){return n?Object.assign(Object.assign({},wr),n):wr}function dd(n){return n?Object.assign(Object.assign({},_r),n):_r}function ld(){return{makeReadOptions:cd,makeWriteOptions:dd,listUnknownFields(n){var e;return(e=n[It])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[It]},writeUnknownFields(n,e){const i=n[It];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[It])||(s[It]=[]),s[It].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),o=s?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(s===!0&&c==te.EndGroup));){const d=r.fields.find(a);if(!d){const l=e.skip(c,a);i.readUnknownFields&&this.onUnknownField(n,a,c,l);continue}xr(n,e,d,c,i)}if(s&&(c!=te.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:xr,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!Sr(s,n)){if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?n[s.oneof.localName].value:n[s.localName];Ir(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&Ir(n,e,t,i)}}}function xr(n,e,t,i,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=o&&delete n.value,n.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?k.INT32:t.T;let c=Oi;if(t.kind=="scalar"&&t.L>0&&(c=hd),r){let h=n[o];if(i==te.LengthDelimited&&a!=k.STRING&&a!=k.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,a))}else h.push(c(e,a))}else n[o]=c(e,a);break;case"message":const d=t.T;r?n[o].push(Mi(e,new d,s,t)):$e(n[o])?Mi(e,n[o],s,t):(n[o]=Mi(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[o]=d.fieldWrapper.unwrapField(n[o])));break;case"map":let[l,u]=ud(t,e,s);n[o][l]=u;break}}function Mi(n,e,t,i){const s=e.getType().runtime.bin,r=i==null?void 0:i.delimited;return s.readMessage(e,n,r?i.no:n.uint32(),t,r),e}function ud(n,e,t){const i=e.uint32(),s=e.pos+i;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=Oi(e,n.K);break;case 2:switch(n.V.kind){case"scalar":o=Oi(e,n.V.T);break;case"enum":o=e.int32();break;case"message":o=Mi(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=xt(n.K,tt.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(n.V.kind){case"scalar":o=xt(n.V.T,tt.BIGINT);break;case"enum":o=n.V.T.values[0].no;break;case"message":o=new n.V.T;break}return[r,o]}function hd(n,e){const t=Oi(n,e);return typeof t=="bigint"?t.toString():t}function Oi(n,e){switch(e){case k.STRING:return n.string();case k.BOOL:return n.bool();case k.DOUBLE:return n.double();case k.FLOAT:return n.float();case k.INT32:return n.int32();case k.INT64:return n.int64();case k.UINT64:return n.uint64();case k.FIXED64:return n.fixed64();case k.BYTES:return n.bytes();case k.FIXED32:return n.fixed32();case k.SFIXED32:return n.sfixed32();case k.SFIXED64:return n.sfixed64();case k.SINT64:return n.sint64();case k.UINT32:return n.uint32();case k.SINT32:return n.sint32()}}function Ir(n,e,t,i){Q(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?k.INT32:n.T;if(s)if(Q(Array.isArray(e)),n.packed)fd(t,r,n.no,e);else for(const o of e)si(t,r,n.no,o);else si(t,r,n.no,e);break;case"message":if(s){Q(Array.isArray(e));for(const o of e)Ar(t,i,n,o)}else Ar(t,i,n,e);break;case"map":Q(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))pd(t,i,n,o,a);break}}function pd(n,e,t,i,s){n.tag(t.no,te.LengthDelimited),n.fork();let r=i;switch(t.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:r=Number.parseInt(i);break;case k.BOOL:Q(i=="true"||i=="false"),r=i=="true";break}switch(si(n,t.K,1,r),t.V.kind){case"scalar":si(n,t.V.T,2,s);break;case"enum":si(n,k.INT32,2,s);break;case"message":Q(s!==void 0),n.tag(2,te.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function Ar(n,e,t,i){const s=Tr(t.T,i);t.delimited?n.tag(t.no,te.StartGroup).raw(s.toBinary(e)).tag(t.no,te.EndGroup):n.tag(t.no,te.LengthDelimited).bytes(s.toBinary(e))}function si(n,e,t,i){Q(i!==void 0);let[s,r]=Mr(e);n.tag(t,s)[r](i)}function fd(n,e,t,i){if(!i.length)return;n.tag(t,te.LengthDelimited).fork();let[,s]=Mr(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function Mr(n){let e=te.Varint;switch(n){case k.BYTES:case k.STRING:e=te.LengthDelimited;break;case k.DOUBLE:case k.FIXED64:case k.SFIXED64:e=te.Bit64;break;case k.FIXED32:case k.SFIXED32:case k.FLOAT:e=te.Bit32;break}const t=k[n].toLowerCase();return[e,t]}function md(){return{setEnumType:or,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const s=i.localName,r=e,o=n;if(o[s]!=null)switch(i.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=i.findField(a);let d=o[s].value;c&&c.kind=="message"&&!$e(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===k.BYTES&&(d=ri(d)),r[s]={case:a,value:d};break;case"scalar":case"enum":let l=o[s];i.T===k.BYTES&&(l=i.repeated?l.map(ri):ri(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===k.BYTES)for(const[f,g]of Object.entries(o[s]))r[s][f]=ri(g);else Object.assign(r[s],o[s]);break;case"message":const h=i.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=i.T;if(i.repeated)r[s]=o[s].map(h=>$e(h,u)?h:new u(h));else{const h=o[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=ri(h):r[s]=h:r[s]=$e(h,u)?h:new u(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((o,a)=>i.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>it(i.T,o,r[a]));case"enum":return s.every((o,a)=>it(k.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=s,a=r;return i.T.fieldWrapper&&(o!==void 0&&!$e(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!$e(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return it(k.INT32,s,r);case"scalar":return it(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=i.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return it(k.INT32,s.value,r.value);case"scalar":return it(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const d=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const l=i.V.T;return d.every(h=>l.equals(s[h],r[h]));case"enum":return d.every(h=>it(k.INT32,s[h],r[h]));case"scalar":const u=i.V.T;return d.every(h=>it(u,s[h],r[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const r=n[s.localName];let o;if(s.repeated)o=r.map(Di);else if(s.kind=="map"){o=i[s.localName];for(const[a,c]of Object.entries(r))o[a]=Di(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Di(r.value)}:{case:void 0}:o=Di(r);i[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function Di(n){if(n===void 0)return n;if($e(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function ri(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function gd(n,e,t){return{syntax:n,json:rd(),bin:ld(),util:Object.assign(Object.assign({},md()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return Wc(this,i,s,r)},makeEnum:$c,makeEnumType:cr,getEnumType:Vc,makeExtension(i,s,r){return Qc(this,i,s,r)}}}class vd{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}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,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Or(n,e){const t=Dr(n);return e?t:Cd(Td(t))}function bd(n){return Or(n,!1)}const yd=Dr;function Dr(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const Sd=new Set(["constructor","toString","toJSON","valueOf"]),kd=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Nr=n=>"".concat(n,"$"),Td=n=>kd.has(n)?Nr(n):n,Cd=n=>Sd.has(n)?Nr(n):n;class Ed{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=bd(e)}addField(e){Q(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 t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function Pd(n,e){var t,i,s,r,o,a;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=Or(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:yd(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(s=l.L)!==null&&s!==void 0?s:tt.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(o=l.req)!==null&&o!==void 0?o:!1,u.opt=(a=l.opt)!==null&&a!==void 0?a:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=k.BYTES&&l.T!=k.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new Ed(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const v=gd("proto3",n=>new vd(n,e=>Pd(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=xt(e.T,e.L);break}}});class ye extends Tn{constructor(e){super(),this.seconds=Y.zero,this.nanos=0,v.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(v.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 s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>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=Y.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>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 s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ye.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ye({seconds:Y.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ye().fromBinary(e,t)}static fromJson(e,t){return new ye().fromJson(e,t)}static fromJsonString(e,t){return new ye().fromJsonString(e,t)}static equals(e,t){return v.util.equals(ye,e,t)}}ye.runtime=v,ye.typeName="google.protobuf.Timestamp",ye.fields=v.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Rd=v.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ye},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:wd,repeated:!0},{no:5,name:"events",kind:"message",T:xd,repeated:!0}]),wd=v.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:_d,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),_d=v.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ye},{no:3,name:"value",kind:"scalar",T:2}]),xd=v.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:ye},{no:7,name:"normalized_end_timestamp",kind:"message",T:ye,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Lr=v.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),we=v.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),se=v.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"}]),wn=v.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ai=v.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),oi=v.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),_e=v.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"}]),vt=v.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"}]),Id=v.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ce=v.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"}]),Ni=v.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:Li,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:Yr}]),Li=v.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Ad=v.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:v.getEnumType(se),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}]),bt=v.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:v.getEnumType(At)},{no:4,name:"tracks",kind:"message",T:Mt,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:Ad},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:v.getEnumType(ci)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:v.getEnumType(_e)},{no:18,name:"kind_details",kind:"enum",T:v.getEnumType(Md),repeated:!0}]),At=v.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ci=v.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),Md=v.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ae=v.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Od=v.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:nt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Ur)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Mt=v.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:v.getEnumType(we)},{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:v.getEnumType(se)},{no:10,name:"layers",kind:"message",T:nt,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:Od,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:v.getEnumType(ae)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Yr},{no:19,name:"audio_features",kind:"enum",T:v.getEnumType(ce),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(Lr)}]),nt=v.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(wn)},{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}]),Ur=v.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),me=v.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:v.getEnumType(q)},{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:_n,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Dd,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:qr,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Nd,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Rd,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Ui,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:xn,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:In,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:An,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Fi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Bi,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:ji,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Fr,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),q=v.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Fr=v.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:v.getEnumType(ae)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),Br=v.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:_n,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Ui,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:xn,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:In,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:An,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Fi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Bi,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:ji,oneof:"value"}]),Dd=v.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:jr,repeated:!0}]),jr=v.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}]),_n=v.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}]),qr=v.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Nd=v.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:Ld,repeated:!0}]),Ld=v.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}]),Ui=v.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}]),xn=v.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}]),In=v.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),An=v.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:Vr,oneof:"value"}]),Vr=v.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}]),$r=v.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Wr=v.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:v.getEnumType(Gr)},{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}]),Gr=v.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Hr=v.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:v.getEnumType(zr)},{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}]),zr=v.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"}]),Kr=v.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Jr},{no:2,name:"screen",kind:"message",T:Jr},{no:3,name:"resume_connection",kind:"enum",T:v.getEnumType(oi)},{no:4,name:"disabled_codecs",kind:"message",T:Ud},{no:5,name:"force_relay",kind:"enum",T:v.getEnumType(oi)}]),Jr=v.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:v.getEnumType(oi)}]),Ud=v.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Li,repeated:!0},{no:2,name:"publish",kind:"message",T:Li,repeated:!0}]),Yr=v.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Mn=v.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Xr=v.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:v.getEnumType(Mn)},{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"}),Qr=v.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Fi=v.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:v.getEnumType(ae)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Xr,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Qr,oneof:"content_header"}],{localName:"DataStream_Header"}),Bi=v.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"}),ji=v.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"}),Fd=v.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),xe=v.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),On=v.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Bd=v.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),jd=v.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:st,oneof:"message"},{no:2,name:"answer",kind:"message",T:st,oneof:"message"},{no:3,name:"trickle",kind:"message",T:qi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:di,oneof:"message"},{no:5,name:"mute",kind:"message",T:Vi,oneof:"message"},{no:6,name:"subscription",kind:"message",T:$i,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ea,oneof:"message"},{no:8,name:"leave",kind:"message",T:Wi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ia,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ra,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Bn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Le,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Un,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:ca,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Ln,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ta,oneof:"message"}]),Zr=v.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:qd,oneof:"message"},{no:2,name:"answer",kind:"message",T:st,oneof:"message"},{no:3,name:"offer",kind:"message",T:st,oneof:"message"},{no:4,name:"trickle",kind:"message",T:qi,oneof:"message"},{no:5,name:"update",kind:"message",T:Wd,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Nn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Wi,oneof:"message"},{no:9,name:"mute",kind:"message",T:Vi,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Gd,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Hd,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Kd,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Yd,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Qd,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:el,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:$d,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Vd,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:il,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:rl,oneof:"message"},{no:22,name:"request_response",kind:"message",T:al,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:ol,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:tl,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:ul,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Zd,oneof:"message"}]),Dn=v.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:nt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Ur)}]),di=v.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:v.getEnumType(we)},{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:v.getEnumType(se)},{no:9,name:"layers",kind:"message",T:nt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Dn,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:v.getEnumType(ae)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(Lr)},{no:17,name:"audio_features",kind:"enum",T:v.getEnumType(ce),repeated:!0}]),qi=v.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:v.getEnumType(xe)},{no:3,name:"final",kind:"scalar",T:8}]),Vi=v.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),qd=v.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Ni},{no:2,name:"participant",kind:"message",T:bt},{no:3,name:"other_participants",kind:"message",T:bt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:na,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:Kr},{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:Wr},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Li,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Vd=v.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:na,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Kr},{no:3,name:"server_info",kind:"message",T:Wr},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Nn=v.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Mt}]),$d=v.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),st=v.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},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),Wd=v.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:bt,repeated:!0}]),$i=v.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:$r,repeated:!0}]),ea=v.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:v.getEnumType(wn)},{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}]),Ln=v.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:v.getEnumType(ce),repeated:!0}]),ta=v.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}]),Wi=v.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:v.getEnumType(_e)},{no:3,name:"action",kind:"enum",T:v.getEnumType(Ot)},{no:4,name:"regions",kind:"message",T:nl}]),Ot=v.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ia=v.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:nt,repeated:!0}]),Un=v.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}]),na=v.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}]),Gd=v.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:jr,repeated:!0}]),Hd=v.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Ni}]),zd=v.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:v.getEnumType(ai)},{no:3,name:"score",kind:"scalar",T:2}]),Kd=v.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:zd,repeated:!0}]),Jd=v.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:v.getEnumType(On)}]),Yd=v.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Jd,repeated:!0}]),Fn=v.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(wn)},{no:2,name:"enabled",kind:"scalar",T:8}]),Xd=v.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Fn,repeated:!0}]),Qd=v.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Fn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Xd,repeated:!0}]),Zd=v.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Fd,repeated:!0}]),sa=v.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}]),ra=v.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:sa,repeated:!0}]),el=v.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}]),tl=v.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Ni},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:bt},{no:4,name:"other_participants",kind:"message",T:bt,repeated:!0}]),Bn=v.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:st},{no:2,name:"subscription",kind:"message",T:$i},{no:3,name:"publish_tracks",kind:"message",T:Nn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:oa,repeated:!0},{no:5,name:"offer",kind:"message",T:st},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:aa,repeated:!0}]),aa=v.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),oa=v.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:v.getEnumType(xe)}]),Le=v.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:v.getEnumType(Bd),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"}]),ca=v.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),il=v.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),nl=v.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:sl,repeated:!0}]),sl=v.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}]),rl=v.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:v.getEnumType(Id)}]),al=v.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:v.getEnumType(jn)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:qi,oneof:"request"},{no:5,name:"add_track",kind:"message",T:di,oneof:"request"},{no:6,name:"mute",kind:"message",T:Vi,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Un,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Ln,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:ta,oneof:"request"}]),jn=v.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),ol=v.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),da=v.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),cl=v.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Hr},{no:2,name:"connection_settings",kind:"message",T:da},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:di,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:st},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:v.getEnumType(vt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Bn}]),dl=v.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:v.getEnumType(ll)},{no:2,name:"join_request",kind:"scalar",T:12}]),ll=v.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),ul=v.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function hl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Gi={exports:{}},pl=Gi.exports,la;function fl(){return la||(la=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(pl,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(m,E){var S=m[E];if(typeof S.bind=="function")return S.bind(m);try{return Function.prototype.bind.call(S,m)}catch{return function(){return Function.prototype.apply.apply(S,[m,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 d(m){return m==="debug"&&(m="log"),typeof console===t?!1:m==="trace"&&i?c:console[m]!==void 0?a(console,m):console.log!==void 0?a(console,"log"):e}function l(){for(var m=this.getLevel(),E=0;E<s.length;E++){var S=s[E];this[S]=E<m?e:this.methodFactory(S,m,this.name)}if(this.log=this.debug,typeof console===t&&m<this.levels.SILENT)return"No console available for logging"}function u(m){return function(){typeof console!==t&&(l.call(this),this[m].apply(this,arguments))}}function h(m,E,S){return d(m)||u.apply(this,arguments)}function f(m,E){var S=this,w,I,b,y="loglevel";typeof m=="string"?y+=":"+m:typeof m=="symbol"&&(y=void 0);function C(N){var F=(s[N]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=F;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+F+";"}catch{}}}function A(){var N;if(!(typeof window===t||!y)){try{N=window.localStorage[y]}catch{}if(typeof N===t)try{var F=window.document.cookie,G=encodeURIComponent(y),ne=F.indexOf(G+"=");ne!==-1&&(N=/^([^;]+)/.exec(F.slice(ne+G.length+1))[1])}catch{}return S.levels[N]===void 0&&(N=void 0),N}}function D(){if(!(typeof window===t||!y)){try{window.localStorage.removeItem(y)}catch{}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function M(N){var F=N;if(typeof F=="string"&&S.levels[F.toUpperCase()]!==void 0&&(F=S.levels[F.toUpperCase()]),typeof F=="number"&&F>=0&&F<=S.levels.SILENT)return F;throw new TypeError("log.setLevel() called with invalid level: "+N)}S.name=m,S.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},S.methodFactory=E||h,S.getLevel=function(){return b??I??w},S.setLevel=function(N,F){return b=M(N),F!==!1&&C(b),l.call(S)},S.setDefaultLevel=function(N){I=M(N),A()||S.setLevel(N,!1)},S.resetLevel=function(){b=null,D(),l.call(S)},S.enableAll=function(N){S.setLevel(S.levels.TRACE,N)},S.disableAll=function(N){S.setLevel(S.levels.SILENT,N)},S.rebuild=function(){if(o!==S&&(w=M(o.getLevel())),l.call(S),o===S)for(var N in r)r[N].rebuild()},w=M(o?o.getLevel():"WARN");var O=A();O!=null&&(b=M(O)),l.call(S)}o=new f,o.getLogger=function(E){if(typeof E!="symbol"&&typeof E!="string"||E==="")throw new TypeError("You must supply a name when creating a logger.");var S=r[E];return S||(S=r[E]=new f(E,o.methodFactory)),S};var g=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return r},o.default=o,o})})(Gi)),Gi.exports}var Hi=fl(),qn;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(qn||(qn={}));var Ie;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Ie||(Ie={}));let B=Hi.getLogger("livekit");Object.values(Ie).map(n=>Hi.getLogger(n)),B.setDefaultLevel(qn.info);function We(n){const e=Hi.getLogger(n);return e.setDefaultLevel(B.getLevel()),e}const ml=Hi.getLogger("lk-e2ee"),li=7e3,gl=[0,300,4*300,9*300,16*300,li,li,li,li,li];class vl{constructor(e){this._retryDelays=e!==void 0?[...e]:gl}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function bl(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t}function p(n,e,t,i){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(l){try{d(i.next(l))}catch(u){o(u)}}function c(l){try{d(i.throw(l))}catch(u){o(u)}}function d(l){l.done?r(l.value):s(l.value).then(a,c)}d((i=i.apply(n,e||[])).next())})}function ua(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ge(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof ua=="function"?ua(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(o){return new Promise(function(a,c){o=n[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(d){r({value:d,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var zi={exports:{}},ha;function yl(){if(ha)return zi.exports;ha=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(y,C,A){return Function.prototype.apply.call(y,C,A)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:t=function(y){return Object.getOwnPropertyNames(y)};function i(b){console&&console.warn&&console.warn(b)}var s=Number.isNaN||function(y){return y!==y};function r(){r.init.call(this)}zi.exports=r,zi.exports.once=S,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(b){if(typeof b!="number"||b<0||s(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");o=b}}),r.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},r.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function c(b){return b._maxListeners===void 0?r.defaultMaxListeners:b._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(y){for(var C=[],A=1;A<arguments.length;A++)C.push(arguments[A]);var D=y==="error",M=this._events;if(M!==void 0)D=D&&M.error===void 0;else if(!D)return!1;if(D){var O;if(C.length>0&&(O=C[0]),O instanceof Error)throw O;var N=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw N.context=O,N}var F=M[y];if(F===void 0)return!1;if(typeof F=="function")e(F,this,C);else for(var G=F.length,ne=g(F,G),A=0;A<G;++A)e(ne[A],this,C);return!0};function d(b,y,C,A){var D,M,O;if(a(C),M=b._events,M===void 0?(M=b._events=Object.create(null),b._eventsCount=0):(M.newListener!==void 0&&(b.emit("newListener",y,C.listener?C.listener:C),M=b._events),O=M[y]),O===void 0)O=M[y]=C,++b._eventsCount;else if(typeof O=="function"?O=M[y]=A?[C,O]:[O,C]:A?O.unshift(C):O.push(C),D=c(b),D>0&&O.length>D&&!O.warned){O.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=b,N.type=y,N.count=O.length,i(N)}return b}r.prototype.addListener=function(y,C){return d(this,y,C,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(y,C){return d(this,y,C,!0)};function l(){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(b,y,C){var A={fired:!1,wrapFn:void 0,target:b,type:y,listener:C},D=l.bind(A);return D.listener=C,A.wrapFn=D,D}r.prototype.once=function(y,C){return a(C),this.on(y,u(this,y,C)),this},r.prototype.prependOnceListener=function(y,C){return a(C),this.prependListener(y,u(this,y,C)),this},r.prototype.removeListener=function(y,C){var A,D,M,O,N;if(a(C),D=this._events,D===void 0)return this;if(A=D[y],A===void 0)return this;if(A===C||A.listener===C)--this._eventsCount===0?this._events=Object.create(null):(delete D[y],D.removeListener&&this.emit("removeListener",y,A.listener||C));else if(typeof A!="function"){for(M=-1,O=A.length-1;O>=0;O--)if(A[O]===C||A[O].listener===C){N=A[O].listener,M=O;break}if(M<0)return this;M===0?A.shift():m(A,M),A.length===1&&(D[y]=A[0]),D.removeListener!==void 0&&this.emit("removeListener",y,N||C)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(y){var C,A,D;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[y]),this;if(arguments.length===0){var M=Object.keys(A),O;for(D=0;D<M.length;++D)O=M[D],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(C=A[y],typeof C=="function")this.removeListener(y,C);else if(C!==void 0)for(D=C.length-1;D>=0;D--)this.removeListener(y,C[D]);return this};function h(b,y,C){var A=b._events;if(A===void 0)return[];var D=A[y];return D===void 0?[]:typeof D=="function"?C?[D.listener||D]:[D]:C?E(D):g(D,D.length)}r.prototype.listeners=function(y){return h(this,y,!0)},r.prototype.rawListeners=function(y){return h(this,y,!1)},r.listenerCount=function(b,y){return typeof b.listenerCount=="function"?b.listenerCount(y):f.call(b,y)},r.prototype.listenerCount=f;function f(b){var y=this._events;if(y!==void 0){var C=y[b];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(b,y){for(var C=new Array(y),A=0;A<y;++A)C[A]=b[A];return C}function m(b,y){for(;y+1<b.length;y++)b[y]=b[y+1];b.pop()}function E(b){for(var y=new Array(b.length),C=0;C<y.length;++C)y[C]=b[C].listener||b[C];return y}function S(b,y){return new Promise(function(C,A){function D(O){b.removeListener(y,M),A(O)}function M(){typeof b.removeListener=="function"&&b.removeListener("error",D),C([].slice.call(arguments))}I(b,y,M,{once:!0}),y!=="error"&&w(b,D,{once:!0})})}function w(b,y,C){typeof b.on=="function"&&I(b,"error",y,C)}function I(b,y,C,A){if(typeof b.on=="function")A.once?b.once(y,C):b.on(y,C);else if(typeof b.addEventListener=="function")b.addEventListener(y,function D(M){A.once&&b.removeEventListener(y,D),C(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return zi.exports}var Ue=yl();let pa=!0,fa=!0;function ui(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function yt(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.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,r.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 Sl(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(pa=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function kl(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(fa=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function ma(){if(typeof window=="object"){if(pa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Vn(n,e){fa&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Tl(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(ui(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(ui(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(ui(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=ui(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function ga(n){return Object.prototype.toString.call(n)==="[object Object]"}function va(n){return ga(n)?Object.keys(n).reduce(function(e,t){const i=ga(n[t]),s=i?va(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function $n(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?$n(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{$n(n,n.get(s),t)})}))}function ba(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{n.forEach(a=>{a.type===i&&a.trackId===o.id&&$n(n,a,s)})}),s}const ya=ma;function Sa(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof a[d]=="object"?a[d]:{ideal:a[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};a=JSON.parse(JSON.stringify(a)),d(a.audio,"autoGainControl","googAutoGainControl"),d(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let d=a.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete a.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(m=>g.label.toLowerCase().includes(m)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=d.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=i(a.video),ya("chrome: "+JSON.stringify(a)),c(a)})}a.video=i(a.video)}return ya("chrome: "+JSON.stringify(a)),c(a)},r=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,d){s(a,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>a(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function ka(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Ta(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else yt(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ca(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,c){let d=s.apply(this,arguments);return d||(d=e(this,a),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.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 Ea(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>ba(o,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),yt(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>ba(r,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===i&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===i&&(r?o=!0:r=a),a.track===i)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Pa(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.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 t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>a.indexOf(d)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.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]}),s.apply(this,arguments)}}function Ra(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Pa(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,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(m=>m===l))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(m=>m.track===l))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(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const m=new n.MediaStream([l]);this._streams[u.id]=m,this._reverseStreams[m.id]=u,this.addStream(m)}return this.getSenders().find(m=>m.track===l)};function r(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],g=d._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function o(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],g=d._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[g=>{const m=r(this,g);h[0].apply(null,[m])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):l.apply(this,arguments).then(g=>r(this,g))}};n.RTCPeerConnection.prototype[d]=u[d]});const a=n.RTCPeerConnection.prototype.setLocalDescription;n.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(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:r(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._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(m=>l.track===m)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Wn(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function wa(n,e){yt(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var _a=Object.freeze({__proto__:null,fixNegotiationNeeded:wa,shimAddTrackRemoveTrack:Ra,shimAddTrackRemoveTrackWithNative:Pa,shimGetSendersWithDtmf:Ca,shimGetUserMedia:Sa,shimMediaStream:ka,shimOnTrack:Ta,shimPeerConnection:Wn,shimSenderReceiverGetStats:Ea});function xa(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){Vn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(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)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function Cl(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function Ia(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gn(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=n.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(o,a)}}function Aa(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ma(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),yt(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Oa(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){Vn("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Da(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function Na(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&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 r=e.apply(this,arguments);if(s){const{sender:o}=r,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 r})}function La(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Ua(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.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 Fa(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.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 Ba=Object.freeze({__proto__:null,shimAddTransceiver:Na,shimCreateAnswer:Fa,shimCreateOffer:Ua,shimGetDisplayMedia:Cl,shimGetParameters:La,shimGetUserMedia:xa,shimOnTrack:Ia,shimPeerConnection:Gn,shimRTCDataChannel:Da,shimReceiverGetStats:Ma,shimRemoveStream:Oa,shimSenderGetStats:Aa});function ja(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function qa(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,i.dispatchEvent(o)})}),e.apply(i,arguments)}}}function Va(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let a=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,d,l){const u=o.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=a}function $a(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(Wa(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}).bind(e))}function Wa(n){return n&&n.video!==void 0?Object.assign({},n,{video:va(n.video)}):n}function Ga(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(Vn("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(i.iceServers[o])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Ha(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function za(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!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.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!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.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ka(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Ja=Object.freeze({__proto__:null,shimAudioContext:Ka,shimCallbacksAPI:Va,shimConstraints:Wa,shimCreateOfferLegacy:za,shimGetUserMedia:$a,shimLocalStreamsAPI:ja,shimRTCIceServerUrls:Ga,shimRemoteStreamsAPI:qa,shimTrackEventTransceiver:Ha}),Hn={exports:{}},Ya;function El(){return Ya||(Ya=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
207
+ `;function Fc(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Bc=Object.defineProperty,jc=(n,e,t)=>e in n?Bc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ar=(n,e,t)=>jc(n,typeof e!="symbol"?e+"":e,t);class fe{constructor(){ar(this,"_locking"),ar(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function Z(n,e){if(!n)throw new Error(e)}const qc=34028234663852886e22,Vc=-34028234663852886e22,$c=4294967295,Wc=2147483647,Gc=-2147483648;function Ri(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>Wc||n<Gc)throw new Error("invalid int 32: "+n)}function Tn(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>$c||n<0)throw new Error("invalid uint 32: "+n)}function or(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>qc||n<Vc))throw new Error("invalid float 32: "+n)}const cr=Symbol("@bufbuild/protobuf/enum-type");function Hc(n){const e=n[cr];return Z(e,"missing enum type on enum object"),e}function dr(n,e,t,i){n[cr]=lr(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function lr(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=ur(o);r.push(a),i[o.name]=a,s[o.no]=a}return{typeName:n,values:r,findName(o){return i[o]},findNumber(o){return s[o]}}}function zc(n,e,t){const i={};for(const s of e){const r=ur(s);i[r.localName]=r.no,i[r.no]=r.localName}return dr(i,n,e),i}function ur(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class En{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Kc(n,e,t,i){var s;const r=(s=i==null?void 0:i.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new En),Object.assign(o,{runtime:n,typeName:e,fields:n.util.newFieldList(t),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 n.util.equals(o,a,c)}}),o}function Jc(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function wn(n,e,t){for(let r=0;r<28;r=r+7){const o=n>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const i=n>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const _i=4294967296;function hr(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(o,a){const c=Number(n.slice(o,a));s*=t,i=i*t+c,i>=_i&&(s=s+(i/_i|0),i=i%_i)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?fr(i,s):Pn(i,s)}function Yc(n,e){let t=Pn(n,e);const i=t.hi&2147483648;i&&(t=fr(t.lo,t.hi));const s=pr(t.lo,t.hi);return i?"-"+s:s}function pr(n,e){if({lo:n,hi:e}=Xc(n,e),e<=2097151)return String(_i*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,o=i+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+mr(o)+mr(r)}function Xc(n,e){return{lo:n>>>0,hi:e>>>0}}function Pn(n,e){return{lo:n|0,hi:e|0}}function fr(n,e){return e=~e,n?n=~n+1:e+=1,Pn(n,e)}const mr=n=>{const e=String(n);return"0000000".slice(e.length)+e};function gr(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function Qc(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Zc(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>r||d<s)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>a||d<o)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=s=>Z(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>Z(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),hr(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),hr(s)},dec(s,r){return Yc(s,r)},uDec(s,r){return pr(s,r)}}}const X=Zc();var C;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(C||(C={}));var it;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(it||(it={}));function nt(n,e,t){if(e===t)return!0;if(n==C.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return e==t}return!1}function It(n,e){switch(n){case C.BOOL:return!1;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return e==0?X.zero:"0";case C.DOUBLE:case C.FLOAT:return 0;case C.BYTES:return new Uint8Array(0);case C.STRING:return"";default:return 0}}function vr(n,e){switch(n){case C.BOOL:return e===!1;case C.STRING:return e==="";case C.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ie;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ie||(ie={}));class ed{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 s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Tn(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ri(e),gr(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 t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){or(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Tn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ri(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ri(e),e=(e<<1^e>>31)>>>0,gr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=X.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=X.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=X.enc(e);return wn(t.lo,t.hi,this.buf),this}sint64(e){let t=X.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return wn(s,r,this.buf),this}uint64(e){let t=X.uEnc(e);return wn(t.lo,t.hi,this.buf),this}}class td{constructor(e,t){this.varint64=Jc,this.uint32=Qc,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ie.Varint:for(;this.buf[this.pos++]&128;);break;case ie.Bit64:this.pos+=4;case ie.Bit32:this.pos+=4;break;case ie.LengthDelimited:let s=this.uint32();this.pos+=s;break;case ie.StartGroup:for(;;){const[r,o]=this.tag();if(o===ie.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}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 X.dec(...this.varint64())}uint64(){return X.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,X.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return X.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return X.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(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function id(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function br(n){const e=n.field.localName,t=Object.create(null);return t[e]=nd(n),[t,()=>t[e]]}function nd(n){const e=n.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 It(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function sd(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Ve="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),xi=[];for(let n=0;n<Ve.length;n++)xi[Ve[n].charCodeAt(0)]=n;xi[45]=Ve.indexOf("+"),xi[95]=Ve.indexOf("/");const yr={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,o=0;for(let a=0;a<n.length;a++){if(r=xi[n.charCodeAt(a)],r===void 0)switch(n[a]){case"=":s=0;case`
208
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[i++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[i++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[i++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=Ve[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=Ve[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=Ve[s|i>>6],e+=Ve[i&63],t=0;break}return t&&(e+=Ve[s],e+="=",t==1&&(e+="=")),e}};function rd(n,e,t){kr(e,n);const i=e.runtime.bin.makeReadOptions(t),s=sd(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,o]=br(e);for(const a of s)e.runtime.bin.readField(r,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function ad(n,e,t,i){kr(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(Sr(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const o=r.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,t,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function Sr(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function kr(n,e){Z(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Cr(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!vr(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Tr(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?It(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function $e(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(En.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Er(n,e){return $e(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}C.DOUBLE,C.FLOAT,C.INT64,C.UINT64,C.INT32,C.UINT32,C.BOOL,C.STRING,C.BYTES;const wr={ignoreUnknownFields:!1},Pr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function od(n){return n?Object.assign(Object.assign({},wr),n):wr}function cd(n){return n?Object.assign(Object.assign({},Pr),n):Pr}const Ii=Symbol(),Ai=Symbol();function dd(){return{makeReadOptions:od,makeWriteOptions:cd,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(Le(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=n.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const d=s.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(o,'"'));s.set(c.oneof,o)}Rr(i,a,c,t,n)}else{let d=!1;if(r!=null&&r.findExtension&&o.startsWith("[")&&o.endsWith("]")){const l=r.findExtension(o.substring(1,o.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=br(l);Rr(u,a,l.field,t,l),ad(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!Cr(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!ud(s))continue}const o=s.oneof?n[s.oneof.localName].value:n[s.localName],a=_r(s,o,e);a!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(n)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&Sr(n,a)){const c=rd(n,a,e),d=_r(a.field,c,e);d!==void 0&&(i[a.field.jsonName]=d)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return i},readScalar(n,e,t){return si(n,e,t??it.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||vr(n,e)))return Mi(n,e)},debug:Le}}function Le(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function Rr(n,e,t,i,s){let r=t.localName;if(t.repeated){if(Z(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Le(e)));const o=n[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Le(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,i));break;case"enum":const c=Rn(t.T,a,i.ignoreUnknownFields,!0);c!==Ai&&o.push(c);break;case"scalar":try{o.push(si(t.T,a,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Le(a));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Le(e)));const o=n[r];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=ld(t.K,a)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Le(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":o[d]=t.V.T.fromJson(c,i);break;case"enum":const l=Rn(t.V.T,c,i.ignoreUnknownFields,!0);l!==Ai&&(o[d]=l);break;case"scalar":try{o[d]=si(t.V.T,c,it.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Le(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=n[r];$e(a)?a.fromJson(e,i):(n[r]=a=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Rn(t.T,e,i.ignoreUnknownFields,!1);switch(c){case Ii:Tr(t,n);break;case Ai:break;default:n[r]=c;break}break;case"scalar":try{const d=si(t.T,e,t.L,!1);switch(d){case Ii:Tr(t,n);break;default:n[r]=d;break}}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Le(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function ld(n,e){if(n===C.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return si(n,e,it.BIGINT,!0).toString()}function si(n,e,t,i){if(e===null)return i?It(n,t):Ii;switch(n){case C.DOUBLE:case C.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 s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return n==C.FLOAT&&or(s),s;case C.INT32:case C.FIXED32:case C.SFIXED32:case C.SINT32:case C.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return n==C.UINT32||n==C.FIXED32?Tn(r):Ri(r),r;case C.INT64:case C.SFIXED64:case C.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=X.parse(e);return t?o.toString():o;case C.FIXED64:case C.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=X.uParse(e);return t?a.toString():a;case C.BOOL:if(typeof e!="boolean")break;return e;case C.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case C.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return yr.dec(e)}throw new Error}function Rn(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Ii;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s!==void 0)return s.no;if(t)return Ai;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Le(e)))}function ud(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function _r(n,e,t){if(n.kind=="map"){Z(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[o,a]of s)i[o.toString()]=Mi(n.V.T,a);break;case"message":for(const[o,a]of s)i[o.toString()]=a.toJson(t);break;case"enum":const r=n.V.T;for(const[o,a]of s)i[o.toString()]=_n(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){Z(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(Mi(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(_n(n.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)i.push(e[s].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return Mi(n.T,e);case"enum":return _n(n.T,e,t.enumAsInteger);case"message":return Er(n.T,e).toJson(t)}}function _n(n,e,t){var i;if(Z(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=n.findNumber(e);return(i=s==null?void 0:s.name)!==null&&i!==void 0?i:e}function Mi(n,e){switch(n){case C.INT32:case C.SFIXED32:case C.SINT32:case C.FIXED32:case C.UINT32:return Z(typeof e=="number"),e;case C.FLOAT:case C.DOUBLE:return Z(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case C.STRING:return Z(typeof e=="string"),e;case C.BOOL:return Z(typeof e=="boolean"),e;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return Z(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case C.BYTES:return Z(e instanceof Uint8Array),yr.enc(e)}}const At=Symbol("@bufbuild/protobuf/unknown-fields"),xr={readUnknownFields:!0,readerFactory:n=>new td(n)},Ir={writeUnknownFields:!0,writerFactory:()=>new ed};function hd(n){return n?Object.assign(Object.assign({},xr),n):xr}function pd(n){return n?Object.assign(Object.assign({},Ir),n):Ir}function fd(){return{makeReadOptions:hd,makeWriteOptions:pd,listUnknownFields(n){var e;return(e=n[At])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[At]},writeUnknownFields(n,e){const i=n[At];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[At])||(s[At]=[]),s[At].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),o=s?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(s===!0&&c==ie.EndGroup));){const d=r.fields.find(a);if(!d){const l=e.skip(c,a);i.readUnknownFields&&this.onUnknownField(n,a,c,l);continue}Ar(n,e,d,c,i)}if(s&&(c!=ie.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:Ar,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!Cr(s,n)){if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?n[s.oneof.localName].value:n[s.localName];Mr(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&Mr(n,e,t,i)}}}function Ar(n,e,t,i,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=o&&delete n.value,n.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?C.INT32:t.T;let c=Di;if(t.kind=="scalar"&&t.L>0&&(c=gd),r){let h=n[o];if(i==ie.LengthDelimited&&a!=C.STRING&&a!=C.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,a))}else h.push(c(e,a))}else n[o]=c(e,a);break;case"message":const d=t.T;r?n[o].push(Oi(e,new d,s,t)):$e(n[o])?Oi(e,n[o],s,t):(n[o]=Oi(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[o]=d.fieldWrapper.unwrapField(n[o])));break;case"map":let[l,u]=md(t,e,s);n[o][l]=u;break}}function Oi(n,e,t,i){const s=e.getType().runtime.bin,r=i==null?void 0:i.delimited;return s.readMessage(e,n,r?i.no:n.uint32(),t,r),e}function md(n,e,t){const i=e.uint32(),s=e.pos+i;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=Di(e,n.K);break;case 2:switch(n.V.kind){case"scalar":o=Di(e,n.V.T);break;case"enum":o=e.int32();break;case"message":o=Oi(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=It(n.K,it.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(n.V.kind){case"scalar":o=It(n.V.T,it.BIGINT);break;case"enum":o=n.V.T.values[0].no;break;case"message":o=new n.V.T;break}return[r,o]}function gd(n,e){const t=Di(n,e);return typeof t=="bigint"?t.toString():t}function Di(n,e){switch(e){case C.STRING:return n.string();case C.BOOL:return n.bool();case C.DOUBLE:return n.double();case C.FLOAT:return n.float();case C.INT32:return n.int32();case C.INT64:return n.int64();case C.UINT64:return n.uint64();case C.FIXED64:return n.fixed64();case C.BYTES:return n.bytes();case C.FIXED32:return n.fixed32();case C.SFIXED32:return n.sfixed32();case C.SFIXED64:return n.sfixed64();case C.SINT64:return n.sint64();case C.UINT32:return n.uint32();case C.SINT32:return n.sint32()}}function Mr(n,e,t,i){Z(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?C.INT32:n.T;if(s)if(Z(Array.isArray(e)),n.packed)bd(t,r,n.no,e);else for(const o of e)ri(t,r,n.no,o);else ri(t,r,n.no,e);break;case"message":if(s){Z(Array.isArray(e));for(const o of e)Or(t,i,n,o)}else Or(t,i,n,e);break;case"map":Z(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))vd(t,i,n,o,a);break}}function vd(n,e,t,i,s){n.tag(t.no,ie.LengthDelimited),n.fork();let r=i;switch(t.K){case C.INT32:case C.FIXED32:case C.UINT32:case C.SFIXED32:case C.SINT32:r=Number.parseInt(i);break;case C.BOOL:Z(i=="true"||i=="false"),r=i=="true";break}switch(ri(n,t.K,1,r),t.V.kind){case"scalar":ri(n,t.V.T,2,s);break;case"enum":ri(n,C.INT32,2,s);break;case"message":Z(s!==void 0),n.tag(2,ie.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function Or(n,e,t,i){const s=Er(t.T,i);t.delimited?n.tag(t.no,ie.StartGroup).raw(s.toBinary(e)).tag(t.no,ie.EndGroup):n.tag(t.no,ie.LengthDelimited).bytes(s.toBinary(e))}function ri(n,e,t,i){Z(i!==void 0);let[s,r]=Dr(e);n.tag(t,s)[r](i)}function bd(n,e,t,i){if(!i.length)return;n.tag(t,ie.LengthDelimited).fork();let[,s]=Dr(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function Dr(n){let e=ie.Varint;switch(n){case C.BYTES:case C.STRING:e=ie.LengthDelimited;break;case C.DOUBLE:case C.FIXED64:case C.SFIXED64:e=ie.Bit64;break;case C.FIXED32:case C.SFIXED32:case C.FLOAT:e=ie.Bit32;break}const t=C[n].toLowerCase();return[e,t]}function yd(){return{setEnumType:dr,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const s=i.localName,r=e,o=n;if(o[s]!=null)switch(i.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=i.findField(a);let d=o[s].value;c&&c.kind=="message"&&!$e(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===C.BYTES&&(d=ai(d)),r[s]={case:a,value:d};break;case"scalar":case"enum":let l=o[s];i.T===C.BYTES&&(l=i.repeated?l.map(ai):ai(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===C.BYTES)for(const[f,g]of Object.entries(o[s]))r[s][f]=ai(g);else Object.assign(r[s],o[s]);break;case"message":const h=i.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=i.T;if(i.repeated)r[s]=o[s].map(h=>$e(h,u)?h:new u(h));else{const h=o[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=ai(h):r[s]=h:r[s]=$e(h,u)?h:new u(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((o,a)=>i.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>nt(i.T,o,r[a]));case"enum":return s.every((o,a)=>nt(C.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=s,a=r;return i.T.fieldWrapper&&(o!==void 0&&!$e(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!$e(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return nt(C.INT32,s,r);case"scalar":return nt(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=i.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return nt(C.INT32,s.value,r.value);case"scalar":return nt(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const d=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const l=i.V.T;return d.every(h=>l.equals(s[h],r[h]));case"enum":return d.every(h=>nt(C.INT32,s[h],r[h]));case"scalar":const u=i.V.T;return d.every(h=>nt(u,s[h],r[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const r=n[s.localName];let o;if(s.repeated)o=r.map(Li);else if(s.kind=="map"){o=i[s.localName];for(const[a,c]of Object.entries(r))o[a]=Li(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Li(r.value)}:{case:void 0}:o=Li(r);i[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function Li(n){if(n===void 0)return n;if($e(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function ai(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Sd(n,e,t){return{syntax:n,json:dd(),bin:fd(),util:Object.assign(Object.assign({},yd()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return Kc(this,i,s,r)},makeEnum:zc,makeEnumType:lr,getEnumType:Hc,makeExtension(i,s,r){return id(this,i,s,r)}}}class kd{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}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,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Lr(n,e){const t=Nr(n);return e?t:Rd(Pd(t))}function Cd(n){return Lr(n,!1)}const Td=Nr;function Nr(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const Ed=new Set(["constructor","toString","toJSON","valueOf"]),wd=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ur=n=>"".concat(n,"$"),Pd=n=>wd.has(n)?Ur(n):n,Rd=n=>Ed.has(n)?Ur(n):n;class _d{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=Cd(e)}addField(e){Z(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 t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function xd(n,e){var t,i,s,r,o,a;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=Lr(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Td(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(s=l.L)!==null&&s!==void 0?s:it.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(o=l.req)!==null&&o!==void 0?o:!1,u.opt=(a=l.opt)!==null&&a!==void 0?a:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=C.BYTES&&l.T!=C.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new _d(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const v=Sd("proto3",n=>new kd(n,e=>xd(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=It(e.T,e.L);break}}});class ye extends En{constructor(e){super(),this.seconds=X.zero,this.nanos=0,v.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(v.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 s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>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=X.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>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 s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ye.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ye({seconds:X.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ye().fromBinary(e,t)}static fromJson(e,t){return new ye().fromJson(e,t)}static fromJsonString(e,t){return new ye().fromJsonString(e,t)}static equals(e,t){return v.util.equals(ye,e,t)}}ye.runtime=v,ye.typeName="google.protobuf.Timestamp",ye.fields=v.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Id=v.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ye},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ad,repeated:!0},{no:5,name:"events",kind:"message",T:Od,repeated:!0}]),Ad=v.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:Md,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Md=v.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ye},{no:3,name:"value",kind:"scalar",T:2}]),Od=v.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:ye},{no:7,name:"normalized_end_timestamp",kind:"message",T:ye,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Fr=v.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Re=v.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),re=v.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"}]),xn=v.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),oi=v.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ci=v.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),_e=v.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"}]),bt=v.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"}]),Dd=v.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),de=v.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"}]),Ni=v.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:Ui,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:Qr}]),Ui=v.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Ld=v.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:v.getEnumType(re),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}]),yt=v.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:v.getEnumType(Mt)},{no:4,name:"tracks",kind:"message",T:Ot,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:Ld},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:v.getEnumType(di)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:v.getEnumType(_e)},{no:18,name:"kind_details",kind:"enum",T:v.getEnumType(Nd),repeated:!0}]),Mt=v.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),di=v.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),Nd=v.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),oe=v.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ud=v.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:st,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Br)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Ot=v.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:v.getEnumType(Re)},{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:v.getEnumType(re)},{no:10,name:"layers",kind:"message",T:st,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:Ud,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:v.getEnumType(oe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Qr},{no:19,name:"audio_features",kind:"enum",T:v.getEnumType(de),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(Fr)}]),st=v.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(xn)},{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}]),Br=v.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),me=v.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:v.getEnumType(q)},{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:In,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Fd,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:$r,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Bd,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Id,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Fi,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:An,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Mn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:On,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Bi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ji,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:qi,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:jr,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),q=v.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),jr=v.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:v.getEnumType(oe)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),qr=v.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:In,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Fi,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:An,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Mn,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:On,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Bi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:ji,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:qi,oneof:"value"}]),Fd=v.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Vr,repeated:!0}]),Vr=v.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}]),In=v.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}]),$r=v.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Bd=v.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:jd,repeated:!0}]),jd=v.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}]),Fi=v.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}]),An=v.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}]),Mn=v.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),On=v.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:Wr,oneof:"value"}]),Wr=v.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}]),Gr=v.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Hr=v.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:v.getEnumType(zr)},{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}]),zr=v.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Kr=v.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:v.getEnumType(Jr)},{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}]),Jr=v.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"}]),Yr=v.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Xr},{no:2,name:"screen",kind:"message",T:Xr},{no:3,name:"resume_connection",kind:"enum",T:v.getEnumType(ci)},{no:4,name:"disabled_codecs",kind:"message",T:qd},{no:5,name:"force_relay",kind:"enum",T:v.getEnumType(ci)}]),Xr=v.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:v.getEnumType(ci)}]),qd=v.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Ui,repeated:!0},{no:2,name:"publish",kind:"message",T:Ui,repeated:!0}]),Qr=v.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Dn=v.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Zr=v.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:v.getEnumType(Dn)},{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"}),ea=v.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Bi=v.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:v.getEnumType(oe)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Zr,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:ea,oneof:"content_header"}],{localName:"DataStream_Header"}),ji=v.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"}),qi=v.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"}),Vd=v.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),xe=v.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ln=v.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),$d=v.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Wd=v.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:rt,oneof:"message"},{no:2,name:"answer",kind:"message",T:rt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Vi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:li,oneof:"message"},{no:5,name:"mute",kind:"message",T:$i,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Wi,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ia,oneof:"message"},{no:8,name:"leave",kind:"message",T:Gi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:sa,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:oa,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:qn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ne,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Bn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:la,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Fn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:na,oneof:"message"}]),ta=v.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Gd,oneof:"message"},{no:2,name:"answer",kind:"message",T:rt,oneof:"message"},{no:3,name:"offer",kind:"message",T:rt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Vi,oneof:"message"},{no:5,name:"update",kind:"message",T:Kd,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Un,oneof:"message"},{no:8,name:"leave",kind:"message",T:Gi,oneof:"message"},{no:9,name:"mute",kind:"message",T:$i,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Jd,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Yd,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Qd,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:el,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:il,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:sl,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:zd,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Hd,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:al,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:dl,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ll,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:ul,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:rl,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:ml,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:nl,oneof:"message"}]),Nn=v.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:st,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Br)}]),li=v.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:v.getEnumType(Re)},{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:v.getEnumType(re)},{no:9,name:"layers",kind:"message",T:st,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Nn,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:v.getEnumType(oe)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(Fr)},{no:17,name:"audio_features",kind:"enum",T:v.getEnumType(de),repeated:!0}]),Vi=v.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:v.getEnumType(xe)},{no:3,name:"final",kind:"scalar",T:8}]),$i=v.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Gd=v.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Ni},{no:2,name:"participant",kind:"message",T:yt},{no:3,name:"other_participants",kind:"message",T:yt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ra,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:Yr},{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:Hr},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ui,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Hd=v.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ra,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Yr},{no:3,name:"server_info",kind:"message",T:Hr},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Un=v.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ot}]),zd=v.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),rt=v.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},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),Kd=v.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:yt,repeated:!0}]),Wi=v.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:Gr,repeated:!0}]),ia=v.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:v.getEnumType(xn)},{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}]),Fn=v.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:v.getEnumType(de),repeated:!0}]),na=v.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}]),Gi=v.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:v.getEnumType(_e)},{no:3,name:"action",kind:"enum",T:v.getEnumType(Dt)},{no:4,name:"regions",kind:"message",T:ol}]),Dt=v.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),sa=v.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:st,repeated:!0}]),Bn=v.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}]),ra=v.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}]),Jd=v.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Vr,repeated:!0}]),Yd=v.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Ni}]),Xd=v.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:v.getEnumType(oi)},{no:3,name:"score",kind:"scalar",T:2}]),Qd=v.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Xd,repeated:!0}]),Zd=v.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:v.getEnumType(Ln)}]),el=v.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Zd,repeated:!0}]),jn=v.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(xn)},{no:2,name:"enabled",kind:"scalar",T:8}]),tl=v.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:jn,repeated:!0}]),il=v.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:jn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:tl,repeated:!0}]),nl=v.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Vd,repeated:!0}]),aa=v.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}]),oa=v.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:aa,repeated:!0}]),sl=v.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}]),rl=v.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Ni},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:yt},{no:4,name:"other_participants",kind:"message",T:yt,repeated:!0}]),qn=v.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:rt},{no:2,name:"subscription",kind:"message",T:Wi},{no:3,name:"publish_tracks",kind:"message",T:Un,repeated:!0},{no:4,name:"data_channels",kind:"message",T:da,repeated:!0},{no:5,name:"offer",kind:"message",T:rt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:ca,repeated:!0}]),ca=v.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),da=v.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:v.getEnumType(xe)}]),Ne=v.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:v.getEnumType($d),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"}]),la=v.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),al=v.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),ol=v.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:cl,repeated:!0}]),cl=v.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}]),dl=v.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:v.getEnumType(Dd)}]),ll=v.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:v.getEnumType(Vn)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Vi,oneof:"request"},{no:5,name:"add_track",kind:"message",T:li,oneof:"request"},{no:6,name:"mute",kind:"message",T:$i,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Bn,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Fn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:na,oneof:"request"}]),Vn=v.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),ul=v.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ua=v.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),hl=v.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Kr},{no:2,name:"connection_settings",kind:"message",T:ua},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:li,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:rt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:v.getEnumType(bt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:qn}]),pl=v.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:v.getEnumType(fl)},{no:2,name:"join_request",kind:"scalar",T:12}]),fl=v.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),ml=v.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function gl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Hi={exports:{}},vl=Hi.exports,ha;function bl(){return ha||(ha=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(vl,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(m,k){var S=m[k];if(typeof S.bind=="function")return S.bind(m);try{return Function.prototype.bind.call(S,m)}catch{return function(){return Function.prototype.apply.apply(S,[m,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 d(m){return m==="debug"&&(m="log"),typeof console===t?!1:m==="trace"&&i?c:console[m]!==void 0?a(console,m):console.log!==void 0?a(console,"log"):e}function l(){for(var m=this.getLevel(),k=0;k<s.length;k++){var S=s[k];this[S]=k<m?e:this.methodFactory(S,m,this.name)}if(this.log=this.debug,typeof console===t&&m<this.levels.SILENT)return"No console available for logging"}function u(m){return function(){typeof console!==t&&(l.call(this),this[m].apply(this,arguments))}}function h(m,k,S){return d(m)||u.apply(this,arguments)}function f(m,k){var S=this,R,I,b,y="loglevel";typeof m=="string"?y+=":"+m:typeof m=="symbol"&&(y=void 0);function E(L){var B=(s[L]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=B;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+B+";"}catch{}}}function A(){var L;if(!(typeof window===t||!y)){try{L=window.localStorage[y]}catch{}if(typeof L===t)try{var B=window.document.cookie,G=encodeURIComponent(y),se=B.indexOf(G+"=");se!==-1&&(L=/^([^;]+)/.exec(B.slice(se+G.length+1))[1])}catch{}return S.levels[L]===void 0&&(L=void 0),L}}function D(){if(!(typeof window===t||!y)){try{window.localStorage.removeItem(y)}catch{}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function M(L){var B=L;if(typeof B=="string"&&S.levels[B.toUpperCase()]!==void 0&&(B=S.levels[B.toUpperCase()]),typeof B=="number"&&B>=0&&B<=S.levels.SILENT)return B;throw new TypeError("log.setLevel() called with invalid level: "+L)}S.name=m,S.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},S.methodFactory=k||h,S.getLevel=function(){return b??I??R},S.setLevel=function(L,B){return b=M(L),B!==!1&&E(b),l.call(S)},S.setDefaultLevel=function(L){I=M(L),A()||S.setLevel(L,!1)},S.resetLevel=function(){b=null,D(),l.call(S)},S.enableAll=function(L){S.setLevel(S.levels.TRACE,L)},S.disableAll=function(L){S.setLevel(S.levels.SILENT,L)},S.rebuild=function(){if(o!==S&&(R=M(o.getLevel())),l.call(S),o===S)for(var L in r)r[L].rebuild()},R=M(o?o.getLevel():"WARN");var O=A();O!=null&&(b=M(O)),l.call(S)}o=new f,o.getLogger=function(k){if(typeof k!="symbol"&&typeof k!="string"||k==="")throw new TypeError("You must supply a name when creating a logger.");var S=r[k];return S||(S=r[k]=new f(k,o.methodFactory)),S};var g=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return r},o.default=o,o})})(Hi)),Hi.exports}var zi=bl(),$n;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})($n||($n={}));var Ie;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Ie||(Ie={}));let j=zi.getLogger("livekit");Object.values(Ie).map(n=>zi.getLogger(n)),j.setDefaultLevel($n.info);function We(n){const e=zi.getLogger(n);return e.setDefaultLevel(j.getLevel()),e}const yl=zi.getLogger("lk-e2ee"),ui=7e3,Sl=[0,300,4*300,9*300,16*300,ui,ui,ui,ui,ui];class kl{constructor(e){this._retryDelays=e!==void 0?[...e]:Sl}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Cl(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t}function p(n,e,t,i){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(l){try{d(i.next(l))}catch(u){o(u)}}function c(l){try{d(i.throw(l))}catch(u){o(u)}}function d(l){l.done?r(l.value):s(l.value).then(a,c)}d((i=i.apply(n,e||[])).next())})}function pa(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ge(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof pa=="function"?pa(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(o){return new Promise(function(a,c){o=n[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(d){r({value:d,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var Ki={exports:{}},fa;function Tl(){if(fa)return Ki.exports;fa=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(y,E,A){return Function.prototype.apply.call(y,E,A)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:t=function(y){return Object.getOwnPropertyNames(y)};function i(b){console&&console.warn&&console.warn(b)}var s=Number.isNaN||function(y){return y!==y};function r(){r.init.call(this)}Ki.exports=r,Ki.exports.once=S,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(b){if(typeof b!="number"||b<0||s(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");o=b}}),r.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},r.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function c(b){return b._maxListeners===void 0?r.defaultMaxListeners:b._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(y){for(var E=[],A=1;A<arguments.length;A++)E.push(arguments[A]);var D=y==="error",M=this._events;if(M!==void 0)D=D&&M.error===void 0;else if(!D)return!1;if(D){var O;if(E.length>0&&(O=E[0]),O instanceof Error)throw O;var L=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw L.context=O,L}var B=M[y];if(B===void 0)return!1;if(typeof B=="function")e(B,this,E);else for(var G=B.length,se=g(B,G),A=0;A<G;++A)e(se[A],this,E);return!0};function d(b,y,E,A){var D,M,O;if(a(E),M=b._events,M===void 0?(M=b._events=Object.create(null),b._eventsCount=0):(M.newListener!==void 0&&(b.emit("newListener",y,E.listener?E.listener:E),M=b._events),O=M[y]),O===void 0)O=M[y]=E,++b._eventsCount;else if(typeof O=="function"?O=M[y]=A?[E,O]:[O,E]:A?O.unshift(E):O.push(E),D=c(b),D>0&&O.length>D&&!O.warned){O.warned=!0;var L=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");L.name="MaxListenersExceededWarning",L.emitter=b,L.type=y,L.count=O.length,i(L)}return b}r.prototype.addListener=function(y,E){return d(this,y,E,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(y,E){return d(this,y,E,!0)};function l(){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(b,y,E){var A={fired:!1,wrapFn:void 0,target:b,type:y,listener:E},D=l.bind(A);return D.listener=E,A.wrapFn=D,D}r.prototype.once=function(y,E){return a(E),this.on(y,u(this,y,E)),this},r.prototype.prependOnceListener=function(y,E){return a(E),this.prependListener(y,u(this,y,E)),this},r.prototype.removeListener=function(y,E){var A,D,M,O,L;if(a(E),D=this._events,D===void 0)return this;if(A=D[y],A===void 0)return this;if(A===E||A.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete D[y],D.removeListener&&this.emit("removeListener",y,A.listener||E));else if(typeof A!="function"){for(M=-1,O=A.length-1;O>=0;O--)if(A[O]===E||A[O].listener===E){L=A[O].listener,M=O;break}if(M<0)return this;M===0?A.shift():m(A,M),A.length===1&&(D[y]=A[0]),D.removeListener!==void 0&&this.emit("removeListener",y,L||E)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(y){var E,A,D;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[y]),this;if(arguments.length===0){var M=Object.keys(A),O;for(D=0;D<M.length;++D)O=M[D],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=A[y],typeof E=="function")this.removeListener(y,E);else if(E!==void 0)for(D=E.length-1;D>=0;D--)this.removeListener(y,E[D]);return this};function h(b,y,E){var A=b._events;if(A===void 0)return[];var D=A[y];return D===void 0?[]:typeof D=="function"?E?[D.listener||D]:[D]:E?k(D):g(D,D.length)}r.prototype.listeners=function(y){return h(this,y,!0)},r.prototype.rawListeners=function(y){return h(this,y,!1)},r.listenerCount=function(b,y){return typeof b.listenerCount=="function"?b.listenerCount(y):f.call(b,y)},r.prototype.listenerCount=f;function f(b){var y=this._events;if(y!==void 0){var E=y[b];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(b,y){for(var E=new Array(y),A=0;A<y;++A)E[A]=b[A];return E}function m(b,y){for(;y+1<b.length;y++)b[y]=b[y+1];b.pop()}function k(b){for(var y=new Array(b.length),E=0;E<y.length;++E)y[E]=b[E].listener||b[E];return y}function S(b,y){return new Promise(function(E,A){function D(O){b.removeListener(y,M),A(O)}function M(){typeof b.removeListener=="function"&&b.removeListener("error",D),E([].slice.call(arguments))}I(b,y,M,{once:!0}),y!=="error"&&R(b,D,{once:!0})})}function R(b,y,E){typeof b.on=="function"&&I(b,"error",y,E)}function I(b,y,E,A){if(typeof b.on=="function")A.once?b.once(y,E):b.on(y,E);else if(typeof b.addEventListener=="function")b.addEventListener(y,function D(M){A.once&&b.removeEventListener(y,D),E(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Ki.exports}var Ue=Tl();let ma=!0,ga=!0;function hi(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function St(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.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,r.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 El(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(ma=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function wl(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(ga=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function va(){if(typeof window=="object"){if(ma)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Wn(n,e){ga&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Pl(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(hi(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(hi(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(hi(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=hi(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function ba(n){return Object.prototype.toString.call(n)==="[object Object]"}function ya(n){return ba(n)?Object.keys(n).reduce(function(e,t){const i=ba(n[t]),s=i?ya(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function Gn(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Gn(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{Gn(n,n.get(s),t)})}))}function Sa(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{n.forEach(a=>{a.type===i&&a.trackId===o.id&&Gn(n,a,s)})}),s}const ka=va;function Ca(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof a[d]=="object"?a[d]:{ideal:a[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};a=JSON.parse(JSON.stringify(a)),d(a.audio,"autoGainControl","googAutoGainControl"),d(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let d=a.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete a.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(m=>g.label.toLowerCase().includes(m)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=d.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=i(a.video),ka("chrome: "+JSON.stringify(a)),c(a)})}a.video=i(a.video)}return ka("chrome: "+JSON.stringify(a)),c(a)},r=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,d){s(a,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>a(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function Ta(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Ea(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else St(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function wa(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,c){let d=s.apply(this,arguments);return d||(d=e(this,a),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.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 Pa(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>Sa(o,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),St(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Sa(r,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===i&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===i&&(r?o=!0:r=a),a.track===i)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Ra(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.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 t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>a.indexOf(d)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.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]}),s.apply(this,arguments)}}function _a(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Ra(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,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(m=>m===l))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(m=>m.track===l))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(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const m=new n.MediaStream([l]);this._streams[u.id]=m,this._reverseStreams[m.id]=u,this.addStream(m)}return this.getSenders().find(m=>m.track===l)};function r(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],g=d._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function o(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],g=d._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[g=>{const m=r(this,g);h[0].apply(null,[m])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):l.apply(this,arguments).then(g=>r(this,g))}};n.RTCPeerConnection.prototype[d]=u[d]});const a=n.RTCPeerConnection.prototype.setLocalDescription;n.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(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:r(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._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(m=>l.track===m)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Hn(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function xa(n,e){St(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var Ia=Object.freeze({__proto__:null,fixNegotiationNeeded:xa,shimAddTrackRemoveTrack:_a,shimAddTrackRemoveTrackWithNative:Ra,shimGetSendersWithDtmf:wa,shimGetUserMedia:Ca,shimMediaStream:Ta,shimOnTrack:Ea,shimPeerConnection:Hn,shimSenderReceiverGetStats:Pa});function Aa(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){Wn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(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)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function Rl(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function Ma(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function zn(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=n.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(o,a)}}function Oa(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Da(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),St(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function La(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){Wn("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Na(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function Ua(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&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 r=e.apply(this,arguments);if(s){const{sender:o}=r,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 r})}function Fa(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Ba(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.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 ja(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.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 qa=Object.freeze({__proto__:null,shimAddTransceiver:Ua,shimCreateAnswer:ja,shimCreateOffer:Ba,shimGetDisplayMedia:Rl,shimGetParameters:Fa,shimGetUserMedia:Aa,shimOnTrack:Ma,shimPeerConnection:zn,shimRTCDataChannel:Na,shimReceiverGetStats:Da,shimRemoveStream:La,shimSenderGetStats:Oa});function Va(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function $a(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,i.dispatchEvent(o)})}),e.apply(i,arguments)}}}function Wa(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let a=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,d,l){const u=o.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=a}function Ga(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(Ha(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}).bind(e))}function Ha(n){return n&&n.video!==void 0?Object.assign({},n,{video:ya(n.video)}):n}function za(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(Wn("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(i.iceServers[o])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Ka(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ja(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!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.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!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.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ya(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Xa=Object.freeze({__proto__:null,shimAudioContext:Ya,shimCallbacksAPI:Wa,shimConstraints:Ha,shimCreateOfferLegacy:Ja,shimGetUserMedia:Ga,shimLocalStreamsAPI:Va,shimRTCIceServerUrls:za,shimRemoteStreamsAPI:$a,shimTrackEventTransceiver:Ka}),Kn={exports:{}},Qa;function _l(){return Qa||(Qa=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
204
209
  `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
205
210
  m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
206
211
  `)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(s=>s.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const s={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 r=8;r<i.length;r+=2)switch(i[r]){case"raddr":s.relatedAddress=i[r+1];break;case"rport":s.relatedPort=parseInt(i[r+1],10);break;case"tcptype":s.tcpType=i[r+1];break;case"ufrag":s.ufrag=i[r+1],s.usernameFragment=i[r+1];break;default:s[i[r]]===void 0&&(s[i[r]]=i[r+1]);break}return s},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const s=t.component;s==="rtp"?i.push(1):s==="rtcp"?i.push(2):i.push(s),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const r=t.type;return i.push("typ"),i.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const s={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),s.name=i[0],s.clockRate=parseInt(i[1],10),s.channels=i.length===3?parseInt(i[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
@@ -231,12 +236,12 @@ a=ice-pwd:`+t.password+`\r
231
236
  o=`+(s||"thisisadapterortc")+" "+r+" "+o+` IN IP4 127.0.0.1\r
232
237
  s=-\r
233
238
  t=0 0\r
234
- `},e.getDirection=function(t,i){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e})(Hn)),Hn.exports}var Xa=El(),Dt=hl(Xa),Pl=Dc({__proto__:null,default:Dt},[Xa]);function Ki(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.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 s=new e(i),r=Dt.parseCandidate(i.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,yt(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function zn(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||yt(n,"icecandidate",e=>{if(e.candidate){const t=Dt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ji(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=Dt.splitSections(a.sdp);return c.shift(),c.some(d=>{const l=Dt.parseMLine(d);return l&&l.kind==="application"&&l.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 d=parseInt(c[1],10);return d!==d?-1:d},s=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},r=function(a,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=Dt.matchPrefix(a.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},o=n.RTCPeerConnection.prototype.setRemoteDescription;n.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(t(arguments[0])){const c=i(arguments[0]),d=s(c),l=r(arguments[0],c);let u;d===0&&l===0?u=Number.POSITIVE_INFINITY:d===0||l===0?u=Math.max(d,l):u=Math.min(d,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function Yi(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(i.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(i,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},yt(n,"datachannel",i=>(e(i.channel,i.target),i))}function Kn(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.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(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Jn(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
239
+ `},e.getDirection=function(t,i){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e})(Kn)),Kn.exports}var Za=_l(),Lt=gl(Za),xl=Fc({__proto__:null,default:Lt},[Za]);function Ji(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.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 s=new e(i),r=Lt.parseCandidate(i.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,St(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Jn(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||St(n,"icecandidate",e=>{if(e.candidate){const t=Lt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Yi(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=Lt.splitSections(a.sdp);return c.shift(),c.some(d=>{const l=Lt.parseMLine(d);return l&&l.kind==="application"&&l.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 d=parseInt(c[1],10);return d!==d?-1:d},s=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},r=function(a,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=Lt.matchPrefix(a.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},o=n.RTCPeerConnection.prototype.setRemoteDescription;n.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(t(arguments[0])){const c=i(arguments[0]),d=s(c),l=r(arguments[0],c);let u;d===0&&l===0?u=Number.POSITIVE_INFINITY:d===0||l===0?u=Math.max(d,l):u=Math.min(d,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function Xi(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(i.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(i,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},St(n,"datachannel",i=>(e(i.channel,i.target),i))}function Yn(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.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(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Xn(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
235
240
  a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
236
241
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
237
- `);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Xi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.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():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Qi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var Rl=Object.freeze({__proto__:null,removeExtmapAllowMixed:Jn,shimAddIceCandidateNullOrEmpty:Xi,shimConnectionState:Kn,shimMaxMessageSize:Ji,shimParameterlessSetLocalDescription:Qi,shimRTCIceCandidate:Ki,shimRTCIceCandidateRelayProtocol:zn,shimSendThrowTypeError:Yi});function wl(){let{window:n}=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 t=ma,i=Tl(n),s={browserDetails:i,commonShim:Rl,extractVersion:ui,disableLog:Sl,disableWarnings:kl,sdp:Pl};switch(i.browser){case"chrome":if(!_a||!Wn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=_a,Xi(n,i),Qi(n),Sa(n,i),ka(n),Wn(n,i),Ta(n),Ra(n,i),Ca(n),Ea(n),wa(n,i),Ki(n),zn(n),Kn(n),Ji(n,i),Yi(n),Jn(n,i);break;case"firefox":if(!Ba||!Gn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=Ba,Xi(n,i),Qi(n),xa(n,i),Gn(n,i),Ia(n),Oa(n),Aa(n),Ma(n),Da(n),Na(n),La(n),Ua(n),Fa(n),Ki(n),Kn(n),Ji(n,i),Yi(n);break;case"safari":if(!Ja||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Ja,Xi(n,i),Qi(n),Ga(n),za(n),Va(n),ja(n),qa(n),Ha(n),$a(n),Ka(n),Ki(n),zn(n),Ji(n,i),Yi(n),Jn(n,i);break;default:t("Unsupported browser!");break}return s}wl({window:typeof window>"u"?void 0:window});class Se extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const _l=/version\/(\d+(\.?_?\d+)+)/i;let Yn;function ke(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Yn===void 0||e){const i=xl.find(s=>{let{test:r}=s;return r.test(t)});Yn=i==null?void 0:i.describe(t)}return Yn}const xl=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Zi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Xn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Zi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Xn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Zi(_l,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Xn(n)}}}];function Zi(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Xn(n){return n.includes("mac os")?Zi(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Il="2.17.0";const Al=Il,Ml=16;class Fe extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var K;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(K||(K={}));class U extends Fe{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=K[t]}static notAllowed(e,t,i){return new U(e,K.NotAllowed,t,i)}static timeout(e){return new U(e,K.Timeout)}static leaveRequest(e,t){return new U(e,K.LeaveRequest,void 0,t)}static internal(e,t){return new U(e,K.InternalError,void 0,t)}static cancelled(e){return new U(e,K.Cancelled)}static serverUnreachable(e,t){return new U(e,K.ServerUnreachable,t)}static websocket(e,t,i){return new U(e,K.WebSocket,t,i)}static serviceNotFound(e,t){return new U(e,K.ServiceNotFound,void 0,t)}}class Qn extends Fe{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class He extends Fe{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Ol extends Fe{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ie extends Fe{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Nt extends Fe{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Qa extends Fe{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Za extends Fe{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:jn[t]}}var ge;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(ge||(ge={}));class Ee extends Fe{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ge[t]}}class Lt extends Fe{constructor(e){super(18,e),this.name="SignalReconnectError"}}var en;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(en||(en={})),(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(en||(en={}));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)};var P;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(P||(P={}));var x;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(x||(x={}));var _;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(_||(_={}));var R;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(R||(R={}));function Dl(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class z{constructor(e,t,i,s,r){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(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};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 Nl=["vp8","h264"],Ll=["vp8","h264","vp9","av1","h265"];function Ul(n){return!!Nl.find(e=>e===n)}const Fl=Ul;var eo;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(eo||(eo={}));var Zn;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Zn||(Zn={}));const hi={h90:new z(160,90,9e4,20),h180:new z(320,180,16e4,20),h216:new z(384,216,18e4,20),h360:new z(640,360,45e4,20),h540:new z(960,540,8e5,25),h720:new z(1280,720,17e5,30),h1080:new z(1920,1080,3e6,30),h1440:new z(2560,1440,5e6,30),h2160:new z(3840,2160,8e6,30)},es={h120:new z(160,120,7e4,20),h180:new z(240,180,125e3,20),h240:new z(320,240,14e4,20),h360:new z(480,360,33e4,20),h480:new z(640,480,5e5,20),h540:new z(720,540,6e5,25),h720:new z(960,720,13e5,30),h1080:new z(1440,1080,23e5,30),h1440:new z(1920,1440,38e5,30)},ts={h360fps3:new z(640,360,2e5,3,"medium"),h360fps15:new z(640,360,4e5,15,"medium"),h720fps5:new z(1280,720,8e5,5,"medium"),h720fps15:new z(1280,720,15e5,15,"medium"),h720fps30:new z(1280,720,2e6,30,"medium"),h1080fps15:new z(1920,1080,25e5,15,"medium"),h1080fps30:new z(1920,1080,5e6,30,"medium"),original:new z(0,0,7e6,30,"medium")};function to(n,e,t){var i,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=so(n??{}),l=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(is(h.audio,e),(i=(r=h.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=c??l)),h.video&&(is(h.video,t),(s=(o=h.video).deviceId)!==null&&s!==void 0||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function is(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function ns(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const o={},a=o,c=n.video;Object.keys(c).forEach(d=>{switch(d){case"resolution":is(a,c.resolution);break;default:a[d]=c[d]}}),r.video=o,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function io(n){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=no();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield he(t),s.getByteTimeDomainData(o);const c=o.some(d=>d!==128&&d!==0);return i.close(),!c}return!1})()})}function no(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>p(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function Bl(n){return n==="audioinput"?T.Source.Microphone:n==="videoinput"?T.Source.Camera:T.Source.Unknown}function ss(n){return n===T.Source.Microphone?"audioinput":n===T.Source.Camera?"videoinput":void 0}function jl(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,kt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function pi(n){return n.split("/")[1].toLowerCase()}function ql(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Nn({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function V(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?V(n.track):{})}}function Vl(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function $l(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function so(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=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:t,videoProcessor:i,optionsWithoutProcessor:Dl(e)}}function Wl(n){switch(n){case se.CAMERA:return T.Source.Camera;case se.MICROPHONE:return T.Source.Microphone;case se.SCREEN_SHARE:return T.Source.ScreenShare;case se.SCREEN_SHARE_AUDIO:return T.Source.ScreenShareAudio;default:return T.Source.Unknown}}function ro(n,e){return n.width*n.height<e.width*e.height}function Gl(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const Hl=5e3,fi=[];var Ce;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ce||(Ce={}));class T extends Ue.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=T.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=B,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Hl):this.handleAppVisibilityChanged()},this.log=We((s=i.loggerName)!==null&&s!==void 0?s:Ie.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=T.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===T.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===T.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(fi.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&fi.splice(fi.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Ut(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?R.AudioPlaybackStarted:R.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?R.AudioPlaybackFailed:R.VideoPlaybackFailed,r):r.name==="AbortError"?B.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):B.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(R.ElementAttached,e),e}detach(e){try{if(e){Ft(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(R.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{Ft(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(R.ElementDetached,i)}),this.attachedElements=[],t}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=We(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),fi.forEach(i=>{i.parentElement||(t=!1)}),t&&fi.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===T.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Te()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Te()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Ut(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!kt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(kt()||St())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Ft(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return we.AUDIO;case e.Video:return we.VIDEO;default:return we.DATA}}n.kindToProto=s;function r(d){switch(d){case we.AUDIO:return e.Audio;case we.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function o(d){switch(d){case t.Camera:return se.CAMERA;case t.Microphone:return se.MICROPHONE;case t.ScreenShare:return se.SCREEN_SHARE;case t.ScreenShareAudio:return se.SCREEN_SHARE_AUDIO;default:return se.UNKNOWN}}n.sourceToProto=o;function a(d){switch(d){case se.CAMERA:return t.Camera;case se.MICROPHONE:return t.Microphone;case se.SCREEN_SHARE:return t.ScreenShare;case se.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=a;function c(d){switch(d){case On.ACTIVE:return i.Active;case On.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(T||(T={}));const zl="|",ao="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Kl(n){const e=n.split(zl);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function he(n){return new Se(e=>ue.setTimeout(e,n))}function rs(){return"addTransceiver"in RTCPeerConnection.prototype}function as(){return"addTrack"in RTCPeerConnection.prototype}function Jl(){if(!("getCapabilities"in RTCRtpSender)||kt()||St())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function Yl(){if(!("getCapabilities"in RTCRtpSender)||St())return!1;if(kt()){const t=ke();if(t!=null&&t.version&&je(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&je(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Ae(n){return n==="av1"||n==="vp9"}function os(n){return!document||mi()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function Xl(){return typeof RTCPeerConnection>"u"?!1:rs()||as()}function St(){var n;return((n=ke())===null||n===void 0?void 0:n.name)==="Firefox"}function oo(){const n=ke();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function kt(){var n;return((n=ke())===null||n===void 0?void 0:n.name)==="Safari"}function mi(){const n=ke();return(n==null?void 0:n.name)==="Safari"||(n==null?void 0:n.os)==="iOS"}function Ql(){const n=ke();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&je(n.osVersion,"17")>=0}function Zl(n){return n||(n=ke()),(n==null?void 0:n.name)==="Safari"&&je(n.version,"18.3")>0||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&je(n.osVersion,"18.3")>0}function co(){var n,e;return Te()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function eu(){const n=ke(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&je(n.osVersion,e)>=0?!0:n.name==="Safari"&&je(n.version,e)>=0}function Te(){return typeof document<"u"}function Be(){return navigator.product=="ReactNative"}function Bt(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function cs(n){return Bt(n)?n.hostname.split(".")[0]:null}function lo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function uo(){if(!Be())return;let n=lo();if(n)return n.platform}function ho(){if(Te())return window.devicePixelRatio;if(Be()){let n=lo();if(n)return n.devicePixelRatio}return 1}function je(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(i[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function tu(n){for(const e of n)e.target.handleResize(e)}function iu(n){for(const e of n)e.target.handleVisibilityChanged(e)}let ds=null;const po=()=>(ds||(ds=new ResizeObserver(tu)),ds);let ls=null;const fo=()=>(ls||(ls=new IntersectionObserver(iu,{root:null,rootMargin:"0px"})),ls);function nu(){var n;const e=new Hr({sdk:zr.JS,protocol:Ml,version:Al});return Be()&&(e.os=(n=uo())!==null&&n!==void 0?n:""),e}function mo(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let gi;function us(){if(!gi){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[gi]=i.stream.getAudioTracks(),!gi)throw Error("Could not get empty media stream audio track");gi.enabled=!1}return gi.clone()}class Pe{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>p(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function su(n){return Ll.includes(n)}function rt(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function ru(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function vi(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function au(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:o,endTime:a,final:c}=t;var d;const l=(d=e.get(i))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,l),{id:i,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function ou(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function go(n){switch(n.reason){case K.LeaveRequest:return n.context;case K.Cancelled:return _e.CLIENT_INITIATED;case K.NotAllowed:return _e.USER_REJECTED;case K.ServerUnreachable:return _e.JOIN_FAILURE;default:return _e.UNKNOWN_REASON}}function tn(n){return n!==void 0?Number(n):void 0}function Tt(n){return n!==void 0?BigInt(n):void 0}function jt(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function qe(n){return!!n&&n.kind==T.Kind.Audio}function at(n){return!!n&&n.kind==T.Kind.Video}function ot(n){return jt(n)&&at(n)}function ze(n){return jt(n)&&qe(n)}function hs(n){return!!n&&!n.isLocal}function cu(n){return!!n&&!n.isLocal}function ps(n){return hs(n)&&at(n)}function du(n){return n.isLocal}function lu(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function uu(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function hu(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=pu(n,e);return t?i:fs(i,"v1")}function pu(n,e){const t=new URL(ru(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),fs(t,"rtc")}function fu(n){const e=new URL(vi(n));return fs(e,"validate")}function vo(n){return n.endsWith("/")?n:"".concat(n,"/")}function fs(n,e){return n.pathname="".concat(vo(n.pathname)).concat(e),n}function bo(n){if(typeof n=="string")return Zr.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return Zr.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function mu(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const gu=10,bi="lk_e2ee",vu={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:gu,keyringSize:16};var ct;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(ct||(ct={}));var yo;(function(n){n.KeyRatcheted="keyRatcheted"})(yo||(yo={}));var dt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(dt||(dt={}));var So;(function(n){n.Error="cryptorError"})(So||(So={}));function bu(){return yu()||ms()}function ms(){return typeof window.RTCRtpScriptTransform<"u"}function yu(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Su(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new Br({value:n.value})}class _p extends Ue.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,s)=>{B.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},vu),e),this.on(ct.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(ct.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(ct.RatchetRequest,e,t)}}var ko;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(ko||(ko={}));class ku extends Ue.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const{kind:o,data:a}=i.data;switch(o){case"error":if(B.error(a.error.message),a.uuid){const l=this.decryptDataRequests.get(a.uuid);if(l!=null&&l.reject){l.reject(a.error);break}const u=this.encryptDataRequests.get(a.uuid);if(u!=null&&u.reject){u.reject(a.error);break}}this.emit(dt.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(dt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(dt.ParticipantEncryptionStatusChanged,a.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(ct.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(a.uuid);c!=null&&c.resolve&&c.resolve(a);break;case"encryptDataResponse":const d=this.encryptDataRequests.get(a.uuid);d!=null&&d.resolve&&d.resolve(a);break}},this.onWorkerError=i=>{B.error("e2ee worker encountered an error:",{error:i.error}),this.emit(dt.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!bu())throw new Qn("tried to setup end-to-end encryption on an unsupported browser");if(B.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:ml.getLevel()}};this.worker&&(B.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){B.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?B.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(_.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(P.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==ae.NONE,s.identity)),e.on(P.ConnectionStateChanged,i=>{i===H.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==ae.NONE,s.identity)})})}).on(P.TrackUnsubscribed,(i,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(P.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(P.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(x.LocalSenderCreated,(i,s)=>p(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(x.LocalTrackPublished,i=>{if(!at(i.track)||!mi())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:pi(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(ct.SetKey,i=>this.postKey(i)).on(ct.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Pe;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},a=new Pe;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(o),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.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 t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,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,t,e.kind==="video"?pi(i.mimeType):void 0)}}setupE2EESender(e,t){if(!jt(e)||!t){t||B.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return p(this,void 0,void 0,function*(){if(this.worker){if(ms()&&!oo()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(bi in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:i,isReuse:bi in e}};this.worker.postMessage(a,[o,r])}e[bi]=!0}})}handleSender(e,t,i){var s;if(!(bi in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ms()&&!oo()){B.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{B.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[r.readable,r.writable])}e[bi]=!0}}}const Tu=500,Cu=15e3;class qt{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new qt),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=cs(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,he(Math.min(Tu*Math.pow(2,r),Cu)))}getBackOffPromise(e){const t=new URL(e),i=t&&cs(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&cs(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}qt._instance=null;const gs="default";class de{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new de),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=de.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){B.debug("awaiting getUserMedia promise");try{t?yield de.userMediaPromiseMap.get(t):yield Promise.all(de.userMediaPromiseMap.values())}catch{B.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(kt()&&i.hasDeviceInUse(t))&&(o.filter(c=>c.kind===t).length===0||o.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,i){return p(this,void 0,void 0,function*(){if(t!==gs)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===gs);if(!r){B.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==gs&&a.groupId===(i??r.groupId));if(!o){B.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?de.userMediaPromiseMap.has(e):de.userMediaPromiseMap.size>0}}de.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],de.userMediaPromiseMap=new Map;var yi;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(yi||(yi={}));class Eu{constructor(){this.pendingTasks=new Map,this.taskMutex=new fe,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:yi.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=yi.RUNNING,yield e()}finally{t.status=yi.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Pu{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const o=function(){let{closeCode:a,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(a,c)};this.opened=new Se((a,c)=>{const d=()=>{c(U.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{a({readable:new ReadableStream({start(l){r.onmessage=u=>{let{data:h}=u;return l.enqueue(h)},r.onerror=u=>l.error(u)},cancel:o}),writable:new WritableStream({write(l){r.send(l)},abort(){r.close()},close:o}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),this.closed=new Se((a,c)=>{const d=()=>p(this,void 0,void 0,function*(){const l=new Se(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield Se.race([he(250),l]);u?a(u):c(U.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=l=>{let{code:u,reason:h}=l;a({closeCode:u,reason:h}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=o}}const Ru=["syncState","trickle","offer","answer","simulate","leave"];function wu(n){const e=Ru.indexOf(n.case)>=0;return B.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var J;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(J||(J={}));const _u=250;class vs{get currentState(){return this.state}get isDisconnected(){return this.state===J.DISCONNECTING||this.state===J.DISCONNECTED}get isEstablishingConnection(){return this.state===J.CONNECTING||this.state===J.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=J.DISCONNECTED,this.log=B,this._requestId=0,this.useV0SignalPath=!1,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.onMediaSectionsRequirement=void 0},this.log=We((i=t.loggerName)!==null&&i!==void 0?i:Ie.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Eu,this.queuedRequests=[],this.closingLock=new fe,this.connectionLock=new fe,this.state=J.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return p(this,arguments,void 0,function(r,o,a,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return d.state=J.CONNECTING,d.options=a,yield d.connect(r,o,a,c,l)})()})}reconnect(e,t,i,s){return p(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=J.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return p(this,arguments,void 0,function(r,o,a,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield d.connectionLock.lock();d.connectOptions=a,d.useV0SignalPath=l;const h=nu(),f=l?xu(o,h,a):Iu(o,h,a),g=hu(r,f,l).toString(),m=fu(g).toString();return new Promise((E,S)=>p(d,void 0,void 0,function*(){var w,I;try{let b=!1;const y=O=>p(this,void 0,void 0,function*(){if(b)return;b=!0;const N=O instanceof Event?O.currentTarget:O,F=mu(N,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(F)).catch(G=>{this.log.error(G),this.close()}):this.close(),C(),S(U.cancelled(F))});c==null||c.addEventListener("abort",y);const C=()=>{clearTimeout(A),c==null||c.removeEventListener("abort",y)},A=setTimeout(()=>{y(U.timeout("room connection has timed out (signal)"))},a.websocketTimeout),D=(O,N)=>{this.handleSignalConnected(O,A,N)},M=new URL(g);M.searchParams.has("access_token")&&M.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(M),Object.assign({reconnect:a.reconnect,reconnectReason:a.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Pu(g);try{this.ws.closed.then(re=>{var De;this.isEstablishingConnection&&S(U.internal("Websocket got closed during a (re)connection attempt: ".concat(re.reason))),re.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:re.reason,code:re.closeCode,wasClean:re.closeCode===1e3,state:this.state})),this.state===J.CONNECTED&&this.handleOnClose((De=re.reason)!==null&&De!==void 0?De:"Unexpected WS error"))}).catch(re=>{this.isEstablishingConnection&&S(U.internal("Websocket error during a (re)connection attempt: ".concat(re)))});const O=yield this.ws.opened.catch(re=>p(this,void 0,void 0,function*(){if(this.state!==J.CONNECTED){this.state=J.DISCONNECTED,clearTimeout(A);const De=yield this.handleConnectionError(re,m);S(De);return}this.handleWSError(re),S(re)}));if(clearTimeout(A),!O)return;const N=O.readable.getReader();this.streamWriter=O.writable.getWriter();const F=yield N.read();if(N.releaseLock(),!F.value)throw U.internal("no message received as first message");const G=bo(F.value),ne=this.validateFirstMessage(G,(w=a.reconnect)!==null&&w!==void 0?w:!1);if(!ne.isValid){S(ne.error);return}((I=G.message)===null||I===void 0?void 0:I.case)==="join"&&(this.pingTimeoutDuration=G.message.value.pingTimeout,this.pingIntervalDuration=G.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})));const be=ne.shouldProcessFirstMessage?G:void 0;D(O,be),E(ne.response)}catch(O){S(O)}finally{C()}}finally{u()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield he(this.signalLatency));const{done:i,value:s}=yield e.read();if(i)break;const r=bo(s);this.handleSignalResponse(r)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([J.DISCONNECTING||J.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=J.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,he(_u)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=J.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Vt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Vt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new qi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Vi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Un({requestId:a,metadata:i,name:s,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,t){return this.sendRequest({case:"updateLayers",value:new ia({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ra({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Y.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new ca({timestamp:Y.parse(Date.now()),rtt:Y.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Ln({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Wi({reason:_e.CLIENT_INITIATED,action:Ot.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!wu(t)&&i.state===J.RECONNECTING){i.queuedRequests.push(()=>p(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield he(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const o=new jd({message:t});try{i.useJSON?yield i.streamWriter.write(o.toJsonString()):yield i.streamWriter.write(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=To(s.value);this.onAnswer&&this.onAnswer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const o=To(s.value);this.onOffer&&this.onOffer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===J.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(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)}handleSignalConnected(e,t,i){this.state=J.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,o,a;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===J.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:U.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:U.internal("Unexpected first message")}:{isValid:!1,error:U.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return U.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return U.notAllowed(s,i.status);default:break}return e instanceof U?e:U.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof U?i:U.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function To(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Vt(n,e){return new st({sdp:n.sdp,type:n.type,id:e})}function xu(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Be()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function Iu(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new cl({clientInfo:e,connectionSettings:new da({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new dl({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class Co{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 t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Au{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.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[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[s,r]of i.entries())t.push(e(r,s,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var Me={},bs={},ys={exports:{}},Eo;function Ss(){if(Eo)return ys.exports;Eo=1;var n=ys.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 t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(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 t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),ys.exports}var Po;function Mu(){return Po||(Po=1,(function(n){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,d,l){if(l&&!d)c[l]=e(a[1]);else for(var u=0;u<d.length;u+=1)a[u+1]!=null&&(c[d[u]]=e(a[u+1]))},i=function(a,c,d){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:l?c[a.name]:c;t(d.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},s=Ss(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(a){var c={},d=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var m=s[h][g];if(m.reg.test(f))return i(m,l,f)}}),c.media=d,c};var o=function(a,c){var d=c.split(/=(.+)/,2);return d.length===2?a[d[0]]=e(d[1]):d.length===1&&c.length>1&&(a[d[0]]=void 0),a};n.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(a){return a.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(a){for(var c=[],d=a.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},n.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(bs)),bs}var ks,Ro;function Ou(){if(Ro)return ks;Ro=1;var n=Ss(),e=/%[sdv%]/g,t=function(o){var a=1,c=arguments,d=c.length;return o.replace(e,function(l){if(a>=d)return l;var u=c[a];switch(a+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(o,a,c){var d=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,l=[o+"="+d];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?l.push(c[a.name][h]):l.push(c[a.names[u]])}else l.push(c[a.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return ks=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||s,d=a.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in o&&o[h.name]!=null?l.push(i(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){l.push(i(u,h,f))})})}),o.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){l.push(i(h,f,g))})})})}),l.join(`\r
242
+ `);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Qi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.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():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Zi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var Il=Object.freeze({__proto__:null,removeExtmapAllowMixed:Xn,shimAddIceCandidateNullOrEmpty:Qi,shimConnectionState:Yn,shimMaxMessageSize:Yi,shimParameterlessSetLocalDescription:Zi,shimRTCIceCandidate:Ji,shimRTCIceCandidateRelayProtocol:Jn,shimSendThrowTypeError:Xi});function Al(){let{window:n}=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 t=va,i=Pl(n),s={browserDetails:i,commonShim:Il,extractVersion:hi,disableLog:El,disableWarnings:wl,sdp:xl};switch(i.browser){case"chrome":if(!Ia||!Hn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Ia,Qi(n,i),Zi(n),Ca(n,i),Ta(n),Hn(n,i),Ea(n),_a(n,i),wa(n),Pa(n),xa(n,i),Ji(n),Jn(n),Yn(n),Yi(n,i),Xi(n),Xn(n,i);break;case"firefox":if(!qa||!zn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=qa,Qi(n,i),Zi(n),Aa(n,i),zn(n,i),Ma(n),La(n),Oa(n),Da(n),Na(n),Ua(n),Fa(n),Ba(n),ja(n),Ji(n),Yn(n),Yi(n,i),Xi(n);break;case"safari":if(!Xa||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Xa,Qi(n,i),Zi(n),za(n),Ja(n),Wa(n),Va(n),$a(n),Ka(n),Ga(n),Ya(n),Ji(n),Jn(n),Yi(n,i),Xi(n),Xn(n,i);break;default:t("Unsupported browser!");break}return s}Al({window:typeof window>"u"?void 0:window});class Se extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const Ml=/version\/(\d+(\.?_?\d+)+)/i;let Qn;function ke(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Qn===void 0||e){const i=Ol.find(s=>{let{test:r}=s;return r.test(t)});Qn=i==null?void 0:i.describe(t)}return Qn}const Ol=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:en(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Zn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:en(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Zn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:en(Ml,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Zn(n)}}}];function en(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Zn(n){return n.includes("mac os")?en(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Dl="2.17.0";const Ll=Dl,Nl=16;class Fe extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var J;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(J||(J={}));class U extends Fe{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=J[t]}static notAllowed(e,t,i){return new U(e,J.NotAllowed,t,i)}static timeout(e){return new U(e,J.Timeout)}static leaveRequest(e,t){return new U(e,J.LeaveRequest,void 0,t)}static internal(e,t){return new U(e,J.InternalError,void 0,t)}static cancelled(e){return new U(e,J.Cancelled)}static serverUnreachable(e,t){return new U(e,J.ServerUnreachable,t)}static websocket(e,t,i){return new U(e,J.WebSocket,t,i)}static serviceNotFound(e,t){return new U(e,J.ServiceNotFound,void 0,t)}}class es extends Fe{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class He extends Fe{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Ul extends Fe{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ne extends Fe{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Nt extends Fe{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class eo extends Fe{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class to extends Fe{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Vn[t]}}var ge;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(ge||(ge={}));class Ee extends Fe{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ge[t]}}class Ut extends Fe{constructor(e){super(18,e),this.name="SignalReconnectError"}}var tn;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(tn||(tn={})),(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(tn||(tn={}));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)};var w;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(w||(w={}));var x;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(x||(x={}));var _;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(_||(_={}));var P;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(P||(P={}));function Fl(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class z{constructor(e,t,i,s,r){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(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};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 Bl=["vp8","h264"],jl=["vp8","h264","vp9","av1","h265"];function ql(n){return!!Bl.find(e=>e===n)}const Vl=ql;var io;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(io||(io={}));var ts;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(ts||(ts={}));const pi={h90:new z(160,90,9e4,20),h180:new z(320,180,16e4,20),h216:new z(384,216,18e4,20),h360:new z(640,360,45e4,20),h540:new z(960,540,8e5,25),h720:new z(1280,720,17e5,30),h1080:new z(1920,1080,3e6,30),h1440:new z(2560,1440,5e6,30),h2160:new z(3840,2160,8e6,30)},is={h120:new z(160,120,7e4,20),h180:new z(240,180,125e3,20),h240:new z(320,240,14e4,20),h360:new z(480,360,33e4,20),h480:new z(640,480,5e5,20),h540:new z(720,540,6e5,25),h720:new z(960,720,13e5,30),h1080:new z(1440,1080,23e5,30),h1440:new z(1920,1440,38e5,30)},ns={h360fps3:new z(640,360,2e5,3,"medium"),h360fps15:new z(640,360,4e5,15,"medium"),h720fps5:new z(1280,720,8e5,5,"medium"),h720fps15:new z(1280,720,15e5,15,"medium"),h720fps30:new z(1280,720,2e6,30,"medium"),h1080fps15:new z(1920,1080,25e5,15,"medium"),h1080fps30:new z(1920,1080,5e6,30,"medium"),original:new z(0,0,7e6,30,"medium")};function no(n,e,t){var i,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=ao(n??{}),l=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(ss(h.audio,e),(i=(r=h.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=c??l)),h.video&&(ss(h.video,t),(s=(o=h.video).deviceId)!==null&&s!==void 0||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function ss(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function rs(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const o={},a=o,c=n.video;Object.keys(c).forEach(d=>{switch(d){case"resolution":ss(a,c.resolution);break;default:a[d]=c[d]}}),r.video=o,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function so(n){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=ro();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield he(t),s.getByteTimeDomainData(o);const c=o.some(d=>d!==128&&d!==0);return i.close(),!c}return!1})()})}function ro(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>p(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function $l(n){return n==="audioinput"?T.Source.Microphone:n==="videoinput"?T.Source.Camera:T.Source.Unknown}function as(n){return n===T.Source.Microphone?"audioinput":n===T.Source.Camera?"videoinput":void 0}function Wl(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,Ct()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function fi(n){return n.split("/")[1].toLowerCase()}function Gl(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Un({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function V(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?V(n.track):{})}}function Hl(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function zl(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function ao(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=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:t,videoProcessor:i,optionsWithoutProcessor:Fl(e)}}function Kl(n){switch(n){case re.CAMERA:return T.Source.Camera;case re.MICROPHONE:return T.Source.Microphone;case re.SCREEN_SHARE:return T.Source.ScreenShare;case re.SCREEN_SHARE_AUDIO:return T.Source.ScreenShareAudio;default:return T.Source.Unknown}}function oo(n,e){return n.width*n.height<e.width*e.height}function Jl(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const Yl=5e3,mi=[];var Te;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Te||(Te={}));class T extends Ue.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=T.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=j,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Yl):this.handleAppVisibilityChanged()},this.log=We((s=i.loggerName)!==null&&s!==void 0?s:Ie.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=T.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===T.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===T.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(mi.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&mi.splice(mi.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Ft(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?P.AudioPlaybackStarted:P.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?P.AudioPlaybackFailed:P.VideoPlaybackFailed,r):r.name==="AbortError"?j.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):j.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){Bt(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(P.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{Bt(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(P.ElementDetached,i)}),this.attachedElements=[],t}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=We(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),mi.forEach(i=>{i.parentElement||(t=!1)}),t&&mi.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===T.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ce()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ce()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Ft(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!Ct()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Ct()||kt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Bt(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return Re.AUDIO;case e.Video:return Re.VIDEO;default:return Re.DATA}}n.kindToProto=s;function r(d){switch(d){case Re.AUDIO:return e.Audio;case Re.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function o(d){switch(d){case t.Camera:return re.CAMERA;case t.Microphone:return re.MICROPHONE;case t.ScreenShare:return re.SCREEN_SHARE;case t.ScreenShareAudio:return re.SCREEN_SHARE_AUDIO;default:return re.UNKNOWN}}n.sourceToProto=o;function a(d){switch(d){case re.CAMERA:return t.Camera;case re.MICROPHONE:return t.Microphone;case re.SCREEN_SHARE:return t.ScreenShare;case re.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=a;function c(d){switch(d){case Ln.ACTIVE:return i.Active;case Ln.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(T||(T={}));const Xl="|",co="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Ql(n){const e=n.split(Xl);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function he(n){return new Se(e=>ue.setTimeout(e,n))}function os(){return"addTransceiver"in RTCPeerConnection.prototype}function cs(){return"addTrack"in RTCPeerConnection.prototype}function Zl(){if(!("getCapabilities"in RTCRtpSender)||Ct()||kt())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function eu(){if(!("getCapabilities"in RTCRtpSender)||kt())return!1;if(Ct()){const t=ke();if(t!=null&&t.version&&je(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&je(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Ae(n){return n==="av1"||n==="vp9"}function ds(n){return!document||gi()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function tu(){return typeof RTCPeerConnection>"u"?!1:os()||cs()}function kt(){var n;return((n=ke())===null||n===void 0?void 0:n.name)==="Firefox"}function lo(){const n=ke();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function Ct(){var n;return((n=ke())===null||n===void 0?void 0:n.name)==="Safari"}function gi(){const n=ke();return(n==null?void 0:n.name)==="Safari"||(n==null?void 0:n.os)==="iOS"}function iu(){const n=ke();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&je(n.osVersion,"17")>=0}function nu(n){return n||(n=ke()),(n==null?void 0:n.name)==="Safari"&&je(n.version,"18.3")>0||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&je(n.osVersion,"18.3")>0}function uo(){var n,e;return Ce()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function su(){const n=ke(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&je(n.osVersion,e)>=0?!0:n.name==="Safari"&&je(n.version,e)>=0}function Ce(){return typeof document<"u"}function Be(){return navigator.product=="ReactNative"}function jt(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function ls(n){return jt(n)?n.hostname.split(".")[0]:null}function ho(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function po(){if(!Be())return;let n=ho();if(n)return n.platform}function fo(){if(Ce())return window.devicePixelRatio;if(Be()){let n=ho();if(n)return n.devicePixelRatio}return 1}function je(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(i[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function ru(n){for(const e of n)e.target.handleResize(e)}function au(n){for(const e of n)e.target.handleVisibilityChanged(e)}let us=null;const mo=()=>(us||(us=new ResizeObserver(ru)),us);let hs=null;const go=()=>(hs||(hs=new IntersectionObserver(au,{root:null,rootMargin:"0px"})),hs);function ou(){var n;const e=new Kr({sdk:Jr.JS,protocol:Nl,version:Ll});return Be()&&(e.os=(n=po())!==null&&n!==void 0?n:""),e}function vo(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let vi;function ps(){if(!vi){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[vi]=i.stream.getAudioTracks(),!vi)throw Error("Could not get empty media stream audio track");vi.enabled=!1}return vi.clone()}class we{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>p(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function cu(n){return jl.includes(n)}function at(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function du(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function bi(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function lu(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:o,endTime:a,final:c}=t;var d;const l=(d=e.get(i))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,l),{id:i,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function uu(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function bo(n){switch(n.reason){case J.LeaveRequest:return n.context;case J.Cancelled:return _e.CLIENT_INITIATED;case J.NotAllowed:return _e.USER_REJECTED;case J.ServerUnreachable:return _e.JOIN_FAILURE;default:return _e.UNKNOWN_REASON}}function nn(n){return n!==void 0?Number(n):void 0}function Tt(n){return n!==void 0?BigInt(n):void 0}function qt(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function qe(n){return!!n&&n.kind==T.Kind.Audio}function ot(n){return!!n&&n.kind==T.Kind.Video}function ct(n){return qt(n)&&ot(n)}function ze(n){return qt(n)&&qe(n)}function fs(n){return!!n&&!n.isLocal}function hu(n){return!!n&&!n.isLocal}function ms(n){return fs(n)&&ot(n)}function pu(n){return n.isLocal}function fu(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function mu(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function gu(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=vu(n,e);return t?i:gs(i,"v1")}function vu(n,e){const t=new URL(du(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),gs(t,"rtc")}function bu(n){const e=new URL(bi(n));return gs(e,"validate")}function yo(n){return n.endsWith("/")?n:"".concat(n,"/")}function gs(n,e){return n.pathname="".concat(yo(n.pathname)).concat(e),n}function So(n){if(typeof n=="string")return ta.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return ta.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function yu(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Su=10,yi="lk_e2ee",ku={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Su,keyringSize:16};var dt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(dt||(dt={}));var ko;(function(n){n.KeyRatcheted="keyRatcheted"})(ko||(ko={}));var lt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(lt||(lt={}));var Co;(function(n){n.Error="cryptorError"})(Co||(Co={}));function Cu(){return Tu()||vs()}function vs(){return typeof window.RTCRtpScriptTransform<"u"}function Tu(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Eu(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new qr({value:n.value})}class Dp extends Ue.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,s)=>{j.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},ku),e),this.on(dt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(dt.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(dt.RatchetRequest,e,t)}}var To;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(To||(To={}));class wu extends Ue.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const{kind:o,data:a}=i.data;switch(o){case"error":if(j.error(a.error.message),a.uuid){const l=this.decryptDataRequests.get(a.uuid);if(l!=null&&l.reject){l.reject(a.error);break}const u=this.encryptDataRequests.get(a.uuid);if(u!=null&&u.reject){u.reject(a.error);break}}this.emit(lt.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(lt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(lt.ParticipantEncryptionStatusChanged,a.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(dt.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(a.uuid);c!=null&&c.resolve&&c.resolve(a);break;case"encryptDataResponse":const d=this.encryptDataRequests.get(a.uuid);d!=null&&d.resolve&&d.resolve(a);break}},this.onWorkerError=i=>{j.error("e2ee worker encountered an error:",{error:i.error}),this.emit(lt.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Cu())throw new es("tried to setup end-to-end encryption on an unsupported browser");if(j.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:yl.getLevel()}};this.worker&&(j.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){j.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?j.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(_.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(w.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==oe.NONE,s.identity)),e.on(w.ConnectionStateChanged,i=>{i===H.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==oe.NONE,s.identity)})})}).on(w.TrackUnsubscribed,(i,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(w.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(w.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(x.LocalSenderCreated,(i,s)=>p(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(x.LocalTrackPublished,i=>{if(!ot(i.track)||!gi())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:fi(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(dt.SetKey,i=>this.postKey(i)).on(dt.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new we;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},a=new we;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(o),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.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 t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,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,t,e.kind==="video"?fi(i.mimeType):void 0)}}setupE2EESender(e,t){if(!qt(e)||!t){t||j.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return p(this,void 0,void 0,function*(){if(this.worker){if(vs()&&!lo()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(yi in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:i,isReuse:yi in e}};this.worker.postMessage(a,[o,r])}e[yi]=!0}})}handleSender(e,t,i){var s;if(!(yi in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(vs()&&!lo()){j.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{j.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[r.readable,r.writable])}e[yi]=!0}}}const Pu=500,Ru=15e3;class Vt{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Vt),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=ls(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,he(Math.min(Pu*Math.pow(2,r),Ru)))}getBackOffPromise(e){const t=new URL(e),i=t&&ls(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&ls(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Vt._instance=null;const bs="default";class le{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new le),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=le.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){j.debug("awaiting getUserMedia promise");try{t?yield le.userMediaPromiseMap.get(t):yield Promise.all(le.userMediaPromiseMap.values())}catch{j.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(Ct()&&i.hasDeviceInUse(t))&&(o.filter(c=>c.kind===t).length===0||o.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,i){return p(this,void 0,void 0,function*(){if(t!==bs)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===bs);if(!r){j.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==bs&&a.groupId===(i??r.groupId));if(!o){j.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?le.userMediaPromiseMap.has(e):le.userMediaPromiseMap.size>0}}le.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],le.userMediaPromiseMap=new Map;var Si;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Si||(Si={}));class _u{constructor(){this.pendingTasks=new Map,this.taskMutex=new fe,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Si.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Si.RUNNING,yield e()}finally{t.status=Si.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class xu{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const o=function(){let{closeCode:a,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(a,c)};this.opened=new Se((a,c)=>{const d=()=>{c(U.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{a({readable:new ReadableStream({start(l){r.onmessage=u=>{let{data:h}=u;return l.enqueue(h)},r.onerror=u=>l.error(u)},cancel:o}),writable:new WritableStream({write(l){r.send(l)},abort(){r.close()},close:o}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),this.closed=new Se((a,c)=>{const d=()=>p(this,void 0,void 0,function*(){const l=new Se(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield Se.race([he(250),l]);u?a(u):c(U.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=l=>{let{code:u,reason:h}=l;a({closeCode:u,reason:h}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=o}}const Iu=["syncState","trickle","offer","answer","simulate","leave"];function Au(n){const e=Iu.indexOf(n.case)>=0;return j.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Y;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Y||(Y={}));const Mu=250;class ys{get currentState(){return this.state}get isDisconnected(){return this.state===Y.DISCONNECTING||this.state===Y.DISCONNECTED}get isEstablishingConnection(){return this.state===Y.CONNECTING||this.state===Y.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Y.DISCONNECTED,this.log=j,this._requestId=0,this.useV0SignalPath=!1,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.onMediaSectionsRequirement=void 0},this.log=We((i=t.loggerName)!==null&&i!==void 0?i:Ie.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new _u,this.queuedRequests=[],this.closingLock=new fe,this.connectionLock=new fe,this.state=Y.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return p(this,arguments,void 0,function(r,o,a,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return d.state=Y.CONNECTING,d.options=a,yield d.connect(r,o,a,c,l)})()})}reconnect(e,t,i,s){return p(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=Y.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return p(this,arguments,void 0,function(r,o,a,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield d.connectionLock.lock();d.connectOptions=a,d.useV0SignalPath=l;const h=ou(),f=l?Ou(o,h,a):Du(o,h,a),g=gu(r,f,l).toString(),m=bu(g).toString();return new Promise((k,S)=>p(d,void 0,void 0,function*(){var R,I;try{let b=!1;const y=O=>p(this,void 0,void 0,function*(){if(b)return;b=!0;const L=O instanceof Event?O.currentTarget:O,B=yu(L,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(B)).catch(G=>{this.log.error(G),this.close()}):this.close(),E(),S(U.cancelled(B))});c==null||c.addEventListener("abort",y);const E=()=>{clearTimeout(A),c==null||c.removeEventListener("abort",y)},A=setTimeout(()=>{y(U.timeout("room connection has timed out (signal)"))},a.websocketTimeout),D=(O,L)=>{this.handleSignalConnected(O,A,L)},M=new URL(g);M.searchParams.has("access_token")&&M.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(M),Object.assign({reconnect:a.reconnect,reconnectReason:a.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new xu(g);try{this.ws.closed.then(ae=>{var De;this.isEstablishingConnection&&S(U.internal("Websocket got closed during a (re)connection attempt: ".concat(ae.reason))),ae.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:ae.reason,code:ae.closeCode,wasClean:ae.closeCode===1e3,state:this.state})),this.state===Y.CONNECTED&&this.handleOnClose((De=ae.reason)!==null&&De!==void 0?De:"Unexpected WS error"))}).catch(ae=>{this.isEstablishingConnection&&S(U.internal("Websocket error during a (re)connection attempt: ".concat(ae)))});const O=yield this.ws.opened.catch(ae=>p(this,void 0,void 0,function*(){if(this.state!==Y.CONNECTED){this.state=Y.DISCONNECTED,clearTimeout(A);const De=yield this.handleConnectionError(ae,m);S(De);return}this.handleWSError(ae),S(ae)}));if(clearTimeout(A),!O)return;const L=O.readable.getReader();this.streamWriter=O.writable.getWriter();const B=yield L.read();if(L.releaseLock(),!B.value)throw U.internal("no message received as first message");const G=So(B.value),se=this.validateFirstMessage(G,(R=a.reconnect)!==null&&R!==void 0?R:!1);if(!se.isValid){S(se.error);return}((I=G.message)===null||I===void 0?void 0:I.case)==="join"&&(this.pingTimeoutDuration=G.message.value.pingTimeout,this.pingIntervalDuration=G.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})));const be=se.shouldProcessFirstMessage?G:void 0;D(O,be),k(se.response)}catch(O){S(O)}finally{E()}}finally{u()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield he(this.signalLatency));const{done:i,value:s}=yield e.read();if(i)break;const r=So(s);this.handleSignalResponse(r)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([Y.DISCONNECTING||Y.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Y.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,he(Mu)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=Y.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:$t(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:$t(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Vi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new $i({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Bn({requestId:a,metadata:i,name:s,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,t){return this.sendRequest({case:"updateLayers",value:new sa({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new oa({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:X.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new la({timestamp:X.parse(Date.now()),rtt:X.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Fn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Gi({reason:_e.CLIENT_INITIATED,action:Dt.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!Au(t)&&i.state===Y.RECONNECTING){i.queuedRequests.push(()=>p(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield he(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const o=new Wd({message:t});try{i.useJSON?yield i.streamWriter.write(o.toJsonString()):yield i.streamWriter.write(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=Eo(s.value);this.onAnswer&&this.onAnswer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const o=Eo(s.value);this.onOffer&&this.onOffer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===Y.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(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)}handleSignalConnected(e,t,i){this.state=Y.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,o,a;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===Y.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:U.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:U.internal("Unexpected first message")}:{isValid:!1,error:U.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return U.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return U.notAllowed(s,i.status);default:break}return e instanceof U?e:U.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof U?i:U.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function Eo(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function $t(n,e){return new rt({sdp:n.sdp,type:n.type,id:e})}function Ou(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Be()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function Du(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new hl({clientInfo:e,connectionSettings:new ua({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new pl({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class wo{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 t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Lu{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.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[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[s,r]of i.entries())t.push(e(r,s,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var Me={},Ss={},ks={exports:{}},Po;function Cs(){if(Po)return ks.exports;Po=1;var n=ks.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 t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(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 t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),ks.exports}var Ro;function Nu(){return Ro||(Ro=1,(function(n){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,d,l){if(l&&!d)c[l]=e(a[1]);else for(var u=0;u<d.length;u+=1)a[u+1]!=null&&(c[d[u]]=e(a[u+1]))},i=function(a,c,d){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:l?c[a.name]:c;t(d.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},s=Cs(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(a){var c={},d=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var m=s[h][g];if(m.reg.test(f))return i(m,l,f)}}),c.media=d,c};var o=function(a,c){var d=c.split(/=(.+)/,2);return d.length===2?a[d[0]]=e(d[1]):d.length===1&&c.length>1&&(a[d[0]]=void 0),a};n.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(a){return a.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(a){for(var c=[],d=a.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},n.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(Ss)),Ss}var Ts,_o;function Uu(){if(_o)return Ts;_o=1;var n=Cs(),e=/%[sdv%]/g,t=function(o){var a=1,c=arguments,d=c.length;return o.replace(e,function(l){if(a>=d)return l;var u=c[a];switch(a+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(o,a,c){var d=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,l=[o+"="+d];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?l.push(c[a.name][h]):l.push(c[a.names[u]])}else l.push(c[a.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Ts=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||s,d=a.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in o&&o[h.name]!=null?l.push(i(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){l.push(i(u,h,f))})})}),o.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){l.push(i(h,f,g))})})})}),l.join(`\r
238
243
  `)+`\r
239
- `},ks}var wo;function Du(){if(wo)return Me;wo=1;var n=Mu(),e=Ou(),t=Ss();return Me.grammar=t,Me.write=e,Me.parse=n.parse,Me.parseParams=n.parseParams,Me.parseFmtpConfig=n.parseFmtpConfig,Me.parsePayloads=n.parsePayloads,Me.parseRemoteCandidates=n.parseRemoteCandidates,Me.parseImageAttributes=n.parseImageAttributes,Me.parseSimulcastStreamList=n.parseSimulcastStreamList,Me}var lt=Du();function Ts(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(i=t.isImmediate)!=null&&i,a=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(m,E){var S=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!o){var I=n.apply(g,f);a&&a(I),l.forEach(function(b){return(0,b.resolve)(I)}),l=[]}},u()),S){var w=n.apply(g,f);return a&&a(w),m(w)}l.push({resolve:m,reject:E})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(g){return(0,g.reject)(f)}),l=[]},h}const Nu=.7,Lu=20,$t={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class _o extends Ue.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=B,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ts(s=>p(this,void 0,void 0,function*(){this.emit($t.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Lu),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=We((i=t.loggerName)!==null&&i!==void 0?i:Ie.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new fe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:o}=Uu(e);this.remoteStereoMids=r,this.remoteNackMids=o}else if(e.type==="answer"){const r=lt.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(o=>{const a=Cs(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||a!=c.transceiver.mid)return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of o.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&o.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=lt.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit($t.NegotiationComplete),e.sdp&&lt.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit($t.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;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 s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const o=lt.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(a=>{Io(a),a.type==="audio"?xo(a,["all"],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(Ae(c.codec)&&!kt()&&this.ensureVideoDDExtensionForSVC(a,o),!Ae(c.codec)))return!0;const l=Math.round(c.maxbr*Nu);for(const u of a.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,lt.write(o)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=lt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{Io(s),s.type==="audio"&&xo(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,lt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ie("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new ie("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}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 p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),i.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;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(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,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 Nt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===ao))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(d=>{d.value>o&&(o=d.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:ao})}}}function xo(n,e,t){const i=Cs(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Uu(n){var e;const t=[],i=[],s=lt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;const c=Cs(o.mid);o.type==="audio"&&(o.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),o.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function Io(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Cs(n){return typeof n=="number"?n.toFixed(0):n}const Es="vp8",Fu={audioPreset:Zn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ts.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Es,backupCodec:!0,preConnectBuffer:!1},Ao={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Mo={deviceId:{ideal:"default"},resolution:hi.h720.resolution},Bu={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new vl,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Ps={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Z;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(Z||(Z={}));class ju{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Ps.peerConnectionTimeout,this.log=B,this.updateState=()=>{var r,o;const a=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=Z.CONNECTED:c.some(d=>d==="failed")?this.state=Z.FAILED:c.some(d=>d==="connecting")?this.state=Z.CONNECTING:c.every(d=>d==="closed")?this.state=Z.CLOSED:c.some(d=>d==="closed")?this.state=Z.CLOSING:c.every(d=>d==="new")&&(this.state=Z.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Z[a]," to ").concat(Z[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=We((s=i.loggerName)!==null&&s!==void 0?s:Ie.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new _o(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new _o(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,xe.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,xe.PUBLISHER)},this.publisher.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=(r,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r,o)},this.state=Z.NEW,this.connectionLock=new fe,this.remoteOfferLock=new fe}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===xe.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=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(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new Se((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new Nt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new Nt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once($t.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once($t.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),o instanceof Error?i(o):i(new Error(String(o)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i==null?void 0:i.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===xe.PUBLISHER?this.publisher.getConnectedAddress():e===xe.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),ue.clearTimeout(u),d(U.cancelled("room connection has been cancelled"))};s!=null&&s.signal.aborted&&l(),s==null||s.signal.addEventListener("abort",l);const u=ue.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",l),d(U.internal("could not establish pc connection"))},o);for(;this.state!==Z.CONNECTED;)if(yield he(50),s!=null&&s.signal.aborted){d(U.cancelled("room connection has been cancelled"));return}ue.clearTimeout(u),s==null||s.signal.removeEventListener("abort",l),c()}))})()})}}const Oo=5e3,qu=3e4;class W{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield W.fetchLock.lock();try{const r=yield fetch("".concat(Vu(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const o=uu(r.headers),a=o?o*1e3:Oo;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw r.status===401?U.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):U.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof U?r:i!=null&&i.aborted?U.cancelled("Region fetching was aborted"):U.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=W.settingsTimeouts.get(e.hostname);clearTimeout(s),W.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield W.fetchRegionSettings(e,t);W.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof U&&r.reason===K.NotAllowed){B.debug("token is not valid, cancelling auto region refresh");return}B.debug("auto refetching of region settings failed",{error:r}),W.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){W.cache.set(e.hostname,i),W.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=W.settingsTimeouts.get(e);t&&(clearTimeout(t),W.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=W.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=W.connectionTrackers.get(e);i&&i.connectionCount===0&&(B.debug("stopping region refetch after disconnect delay",{hostname:e}),W.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},qu))}static cancelCleanup(e){const t=W.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=W.connectionTrackers.get(e);t||(t={connectionCount:0},W.connectionTrackers.set(e,t)),t.connectionCount++,W.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=W.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&W.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Bt(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return W.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=W.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),W.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),B.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){W.updateCachedRegionSettings(this.serverUrl,this.token,e)}}W.cache=new Map,W.settingsTimeouts=new Map,W.connectionTrackers=new Map,W.fetchLock=new fe;function Vu(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ee extends Error{constructor(e,t,i){super(t),this.code=e,this.message=No(t,ee.MAX_MESSAGE_BYTES),this.data=i?No(i,ee.MAX_DATA_BYTES):void 0}static fromProto(e){return new ee(e.code,e.message,e.data)}toProto(){return new Vr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ee(ee.ErrorCode[e],ee.ErrorMessage[e],t)}}ee.MAX_MESSAGE_BYTES=256,ee.MAX_DATA_BYTES=15360,ee.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},ee.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 Do=15360;function Rs(n){return new TextEncoder().encode(n).length}function No(n,e){if(Rs(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const ws=2e3;function nn(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const _s=typeof MediaRecorder<"u";class $u{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Wu=_s?MediaRecorder:$u;class Gu extends Wu{constructor(e,t){if(!_s)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),s==null||s.close(),s=void 0},a=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function Hu(){return _s}const zu=1e3,Ku=1e4;class Lo extends T{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),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=Ts(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(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(R.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new fe,this.pauseUpstreamLock=new fe,this.trackChangeLock=new fe,this.trackChangeLock.lock().then(o=>p(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!==T.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Ft(this._mediaStreamTrack,r)}),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 s;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&&(Ut(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Ut(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:zu;return(function*(){var i;if(e.kind===T.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=ke())===null||i===void 0?void 0:i.os)==="iOS"&&(yield he(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield he(50)}throw new He("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===rt(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),rt(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===T.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===T.Kind.Audio?"audioinput":"videoinput";return t?de.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new He("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=bl(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===T.Kind.Video?o.video=i||s?{deviceId:i,facingMode:s}:!0:o.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{Ft(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===T.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(R.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}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?R.Muted:R.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 p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),co()&&(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 p(this,void 0,void 0,function*(){var e;const t=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(R.UpstreamPaused,this);const i=ke();if((i==null?void 0:i.name)==="Safari"&&je(i.version,"12.0")<0)throw new Qn("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{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=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(R.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(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 p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;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 t.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(Ut(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{a.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=a,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(Ft(i._mediaStreamTrack,d),Ut(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(R.TrackProcessorUpdate,i.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;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,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(R.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Hu()){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 t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Gu(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},Ku)}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 sn extends Lo{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,T.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(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=nn(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,ce.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,ce.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===T.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=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!==rt(this._constraints.deviceId);return this.source===T.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{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=ns({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){Te()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ws)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Be()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.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(R.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield io(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(R.AudioSilenceDetected)),e})}}function Ju(n,e,t){switch(n.kind){case"audio":return new sn(n,e,!1,void 0,t);case"video":return new rn(n,e,!1,t);default:throw new He("unsupported track type: ".concat(n.kind))}}const Yu=Object.values(hi),Xu=Object.values(es),Qu=Object.values(ts),Zu=[hi.h180,hi.h360],eh=[es.h180,es.h360],th=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new z(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),xs=["q","h","f"];function Is(n,e,t,i){var s,r;let o=i==null?void 0:i.videoEncoding;n&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,d=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=nh(n,e,t,d),B.debug("using video encoding",o));const l=o.maxFramerate,u=new z(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Ae(d)){const g=new Bo(c),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const E=ke();if(mi()||Be()||(E==null?void 0:E.name)==="Chrome"&&je(E==null?void 0:E.version,"113")<0){const S=g.suffix=="h"?2:3,w=Zl(E);for(let I=0;I<g.spatial;I+=1)m.push({rid:xs[2-I],maxBitrate:o.maxBitrate/Math.pow(S,I),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:w?Math.pow(2,I):void 0});m[0].scalabilityMode=c}else m.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(m[0].priority=u.encoding.priority,m[0].networkPriority=u.encoding.priority),B.debug("using svc encoding",{encodings:m}),m}if(!a)return[o];let h=[];n?h=(s=Fo(i==null?void 0:i.screenShareSimulcastLayers))!==null&&s!==void 0?s:Uo(n,u):h=(r=Fo(i==null?void 0:i.videoSimulcastLayers))!==null&&r!==void 0?r:Uo(n,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const m=Math.max(e,t);if(m>=960&&f)return As(e,t,[g,f,u],l);if(m>=480)return As(e,t,[g,u],l)}return As(e,t,[u])}function ih(n,e,t){var i,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&B.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=n.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=a.height)!==null&&r!==void 0?r:(o=n.dimensions)===null||o===void 0?void 0:o.height;return n.source===T.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Is(n.source===T.Source.ScreenShare,c,d,t)}function nh(n,e,t,i){const s=sh(n,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function sh(n,e,t){if(n)return Qu;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Yu:Xu}function Uo(n,e){if(n)return th(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?Zu:eh}function As(n,e,t,i){const s=[];if(t.forEach((r,o)=>{if(o>=xs.length)return;const a=Math.min(n,e),d={rid:xs[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=St()||o===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Be()&&uo()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var c;a.maxFramerate!=r&&(o&&(o=!1,B.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),B.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function Fo(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class Bo{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function rh(n){return n.source===T.Source.ScreenShare||n.constraints.height&&rt(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const ah=5e3;class rn extends Lo{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,T.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=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(r.map(c=>[c.rid,c])),a=r.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(R.CpuConstrained)),this.prevStats){let c=0;o.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=nn(d,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 t;if(this.signalClient=e,!Te())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ws))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=Ge(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;a=!0)r=d.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(l){i={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=Ge(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;a=!0){r=d.value,a=!1;const l=r;yield(o=l.sender)===null||o===void 0?void 0:o.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===T.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===T.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{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=i.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ce.LOW;i<=Ce.HIGH;i+=1)t.push(new Fn({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ae(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,o;let a;if(e){const u=ns({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,d=Ge(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;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&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=Ge(s.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)d=g.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(m){a={error:m}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){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:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},ah))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,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(Ae(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=Ge(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ae(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield jo(u.sender,u.encodings,l.qualities,this.senderLock,Ae(l.codec),this.log,this.logContext))}}}catch(l){o={error:l}}finally{try{!t&&!r&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return d})}setPublishingLayers(e,t){return p(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:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield jo(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(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 t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Ae(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),co()&&this.isInBackground&&this.source===T.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function jo(n,e,t,i,s,r,o){return p(this,void 0,void 0,function*(){const a=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var g;let m=(g=h.rid)!==null&&g!==void 0?g:"";m===""&&(m="q");const E=qo(m),S=t.find(w=>w.quality===E);S&&h.active!==S.enabled&&(l=!0,h.active=S.enabled,r.debug("setting layer ".concat(S.quality," to ").concat(h.active?"enabled":"disabled"),o),St()&&(S.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)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield n.setParameters(c))}finally{a()}})}function qo(n){switch(n){case"f":return Ce.HIGH;case"h":return Ce.MEDIUM;case"q":return Ce.LOW;default:return Ce.HIGH}}function Vo(n,e,t,i){if(!t)return[new nt({quality:Ce.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new Bo(s),o=[],a=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)o.push(new nt({quality:Math.min(Ce.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(a,d)),height:Math.ceil(e/Math.pow(a,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=qo((o=s.rid)!==null&&o!==void 0?o:"");return new nt({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const $o="_lossy",Wo="_reliable",oh=2*1e3,Ms="leave-reconnect",ch=3e4,dh=8*1024,lh=256*1024;var Re;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Re||(Re={}));class uh extends Ue.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ps.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Re.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=B,this.reliableDataSequence=1,this.reliableMessageBuffer=new Co,this.reliableReceivedState=new Au(ch),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:o}=s;return(function*(){if(o){if(o.label===Wo)r.reliableDCSub=o;else if(o.label===$o)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,o,a,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=me.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(_.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=Br.fromBinary(h.payload),g=new me({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((a=g.value)===null||a===void 0?void 0:a.case)==="user"&&Go(g,g.value.value),this.emit(_.DataPacketReceived,g,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&Go(u,u.value.value),this.emit(_.DataPacketReceived,u,ae.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?q.LOSSY:q.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(_.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}i===Ms&&(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(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Re.Connected&&i();const r=()=>{this.off(_.Disconnected,o),i()},o=()=>{this.off(_.Restarted,r),s()};this.once(_.Restarted,r),this.once(_.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===q.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(_.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(vi(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===J.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===J.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(vt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(vi(this.url),{method:"HEAD"}),he(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=We((t=e.loggerName)!==null&&t!==void 0?t:Ie.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new vs(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new fe,this.dataProcessLock=new fe,this.dcBufferStatus=new Map([[q.LOSSY,!0],[q.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(_.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(_.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(_.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(_.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(_.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(_.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(_.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(_.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,o,a,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=o,d.signalOpts=a,d.maxJoinAttempts=a.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,o,a,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{B.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(_.SignalConnected,u),u}catch(u){if(u instanceof U){if(u.reason===K.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,o,a,c,l)}else if(u.reason===K.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," – Retrying")),d.join(r,o,a,c,!0)}throw u}})()})}close(){return p(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(_.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(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 t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Co,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new He("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(U.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(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,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==Z.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new ju(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(_.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,a)=>{this.client.sendIceCandidate(o,a)},this.pcManager.onPublisherOffer=(o,a)=>{this.client.sendOffer(o,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,a,c)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),o===Z.CONNECTED){const u=this.pcState===Re.New;this.pcState=Re.Connected,u&&this.emit(_.Connected,e)}else o===Z.FAILED&&(this.pcState===Re.Connected||this.pcState===Re.Reconnecting)&&(this.pcState=Re.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?vt.RR_SUBSCRIBER_FAILED:vt.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===J.RECONNECTING,l=[Z.FAILED,Z.CLOSING,Z.CLOSED].includes(o);d&&l&&!this._isClosed&&this.emit(_.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(_.MediaTrackAdded,o.track,o.streams[0],o.receiver)},hh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.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(_.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(_.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(_.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(_.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(_.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",vt.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({updatedAtInMs:Date.now(),maxAgeInMs:Oo,regionSettings:e.regions})),e.action){case Ot.DISCONNECT:this.emit(_.Disconnected,e==null?void 0:e.reason),this.close();break;case Ot.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ms);break;case Ot.RESUME:this.handleDisconnect(Ms)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===oi.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($o,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Wo,{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,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(q.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,dh),lh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(rs())return yield this.createTransceiverRTCRtpSender(e,t,i);if(as())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ie("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(rs())return this.createSimulcastTransceiverSender(e,t,i,s);if(as())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ie("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ie("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),at(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ie("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ie("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){B.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===oi.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:Z.NEW)===Z.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof ie?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof Lt||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",vt.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(_.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new ie("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Lt;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof U&&o.reason===K.NotAllowed?new ie("could not reconnect, token might be expired"):new Lt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(_.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==J.CONNECTED)throw new Lt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(_.Restarted)}catch(r){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ie("could not reconnect, url or token not saved");if(!this.pcManager)throw new ie("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof U&&s.reason===K.NotAllowed?new ie("could not reconnect, token might be expired"):s instanceof U&&s.reason===K.LeaveRequest?s:new Lt(r)}if(this.emit(_.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),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!==J.CONNECTED)throw new Lt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(_.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ie("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Re.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield he(oh),!this.pcManager)throw new ie("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Re.Connected}catch(e){throw this.pcState=Re.Disconnected,U.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new me({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcResponse",value:new An({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,q.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new me({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcAck",value:new In({requestId:t})}});yield this.sendDataPacket(i,q.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Su(e);if(r){const o=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new Fr({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===q.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===q.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(q.RELIABLE);const t=this.dataChannelForKind(q.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(q.RELIABLE)})}waitForBufferStatusLow(e){return new Se((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new ie("engine closed"));for(this.once(_.Closing,s);!this.dcBufferStatus.get(e);)yield he(10);this.off(_.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new ie("PC manager is closed");const o=s?i.pcManager.subscriber:i.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw U.internal("".concat(a," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{B.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if((d==null?void 0:d.readyState)==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(o.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield he(50)}throw U.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Z.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new Se((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new Nt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new Nt("cannot negotiate on closed engine")),this.on(_.Closing,s),this.pcManager.publisher.once($t.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();su(c)&&o.set(a.payload,c)}),this.emit(_.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof Nt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",vt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(_.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===q.LOSSY)return this.lossyDCSub;if(e===q.RELIABLE)return this.reliableDCSub}else{if(e===q.LOSSY)return this.lossyDC;if(e===q.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,f=new Array;e.forEach(g=>{g.isDesired!==u&&h.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new Bn({answer:this.pcManager.mode==="publisher-only"?c?Vt({sdp:c.sdp,type:c.type}):void 0:l?Vt({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?a?Vt({sdp:a.sdp,type:a.type}):void 0:d?Vt({sdp:d.sdp,type:d.type}):void 0,subscription:new $i({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:ql(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,m)=>new aa({publisherSid:m,lastSeq:g}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new oa({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(q.LOSSY),xe.PUBLISHER),t(this.dataChannelForKind(q.RELIABLE),xe.PUBLISHER),t(this.dataChannelForKind(q.LOSSY,!0),xe.SUBSCRIBER),t(this.dataChannelForKind(q.RELIABLE,!0),xe.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ue.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Te()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Te()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[o]=r;return o===i});if(s)return s[1]}}}function hh(n){return n!==void 0&&n>13}function Go(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class Ho{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 Ee("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ge.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Ee("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ge.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class ph extends Ho{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Pe,i=null,s=null;if(this.signal){const o=this.signal;s=()=>{var a;(a=t.reject)===null||a===void 0||a.call(t,o.reason)},o.addEventListener("abort",s),i=o}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:d}=yield Promise.race([e.read(),t.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(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,o;let a=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=Ge(c),u;u=yield l.next(),i=u.done,!i;d=!0){o=u.value,d=!1;const h=o;a.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(a)})()})}}class fh extends Ho{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=tn(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new Pe,s=null,r=null;if(this.signal){const a=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,a.reason)},a.addEventListener("abort",r),s=a}const o=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,c;try{const{done:d,value:l}=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(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Ee("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),ge.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw o(),d}}),return(){return p(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,o;let a="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=Ge(c),u;u=yield l.next(),i=u.done,!i;d=!0)o=u.value,d=!1,a+=o}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return a})()})}}class mh{constructor(){this.log=B,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Ee('A text stream handler for topic "'.concat(e,'" has already been set.'),ge.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Ee('A byte stream handler for topic "'.concat(e,'" has already been set.'),ge.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;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 Ee("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ge.AbnormalEnd);for(const[d,l]of a)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of o)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;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 o;const a=new Pe;a.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:tn(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(o=l,this.textStreamControllers.has(e.streamId))throw new Ee("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ge.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new ph(c,d,tn(e.totalLength),a),{identity:t})}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 o;const a=new Pe;a.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(o=l,this.textStreamControllers.has(e.streamId))throw new Ee("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ge.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new fh(c,d,tn(e.totalLength),a),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ge.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ge.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ge.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ge.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class zo{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(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 gh extends zo{}class vh extends zo{}const Ko=15e3;class bh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const g=c.reduce((m,E)=>m+E,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},l=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:a,attributes:t==null?void 0:t.attributes});return yield l.write(e),d(1,0),yield l.close(),t!=null&&t.attachments&&a&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={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,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?ae.GCM:ae.NONE},a=new Fi({streamId:r,mimeType:o.mimeType,topic:o.topic,timestamp:Tt(o.timestamp),totalLength:Tt(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new Xr({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"?Mn.UPDATE:Mn.CREATE})}}),c=e==null?void 0:e.destinationIdentities,d=new me({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(d,q.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(m){return p(this,void 0,void 0,function*(){for(const E of lu(m,Ko)){const S=new Bi({content:E,streamId:r,chunkIndex:Tt(l)}),w=new me({destinationIdentities:c,value:{case:"streamChunk",value:S}});yield u.sendDataPacket(w,q.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const m=new ji({streamId:r}),E=new me({destinationIdentities:c,value:{case:"streamTrailer",value:m}});yield u.sendDataPacket(E,q.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let f=()=>p(this,void 0,void 0,function*(){yield g.close()});u.once(_.Closing,f);const g=new gh(h,o,()=>this.engine.off(_.Closing,f));return g})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i==null?void 0:i.mimeType)!==null&&s!==void 0?s:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,o,a;const c=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e==null?void 0:e.destinationIdentities,l={id:c,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?ae.GCM:ae.NONE},u=new Fi({totalLength:Tt((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:Tt(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Qr({name:l.name})}}),h=new me({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,q.RELIABLE);let f=0;const g=new fe,m=this.engine,E=this.log,S=new WritableStream({write(I){return p(this,void 0,void 0,function*(){const b=yield g.lock();let y=0;try{for(;y<I.byteLength;){const C=I.slice(y,y+Ko),A=new me({destinationIdentities:d,value:{case:"streamChunk",value:new Bi({content:C,streamId:c,chunkIndex:Tt(f)})}});yield m.sendDataPacket(A,q.RELIABLE),f+=1,y+=C.byteLength}}finally{b()}})},close(){return p(this,void 0,void 0,function*(){const I=new ji({streamId:c}),b=new me({destinationIdentities:d,value:{case:"streamTrailer",value:I}});yield m.sendDataPacket(b,q.RELIABLE)})},abort(I){E.error("Sink error:",I)}});return new vh(S,l)})}}class Jo extends T{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?R.Muted:R.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(R.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(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(),ws)),Vl()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(R.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class yh extends Jo{constructor(e,t,i,s,r,o){super(e,t,T.Kind.Audio,i,o),this.monitorReceiver=()=>p(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=nn(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Be()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Be())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(os(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&os(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(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 t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}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,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),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(R.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(R.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={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})}),t})}}const Os=100;class Sh extends Jo{constructor(e,t,i,s,r){super(e,t,T.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(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=nn(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Ts(()=>{this.updateDimensions()},Os),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===T.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Ft(this._mediaStreamTrack,t):Ut(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new kh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===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 t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,o=this.elementInfos.some(c=>c.pictureInPicture),a=this.elementInfos.some(c=>c.visible)&&!r||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-s<Os){ue.setTimeout(()=>{this.updateVisibility()},Os);return}this.lastVisible=a,this.emit(R.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>i+s&&(i=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(R.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?ho():t||(ho()>2?2:1)}}class kh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:o}=i;r===this.element&&(this.isIntersecting=o,this.isPiP=Si(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Si(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Si(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Ds(e),this.isPiP=Te()&&Si(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Ds(this.element),this.isPiP=Si(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,fo().observe(this.element),po().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=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=fo())===null||e===void 0||e.unobserve(this.element),(t=po())===null||t===void 0||t.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),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Si(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ds(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Ds(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,o=n.offsetHeight,{hidden:a}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&c!=="none"}class Ke extends Ue.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=ae.NONE,this.log=B,this.handleMuted=()=>{this.emit(R.Muted)},this.handleUnmuted=()=>{this.emit(R.Unmuted)},this.log=We((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Ie.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=T.Source.Unknown}setTrack(e){this.track&&(this.track.off(R.Muted,this.handleMuted),this.track.off(R.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(R.Muted,this.handleMuted),e.on(R.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==ae.NONE}get audioTrack(){if(qe(this.track))return this.track}get videoTrack(){if(at(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=T.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===T.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(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(Ke||(Ke={}));class Ns extends Ke{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(R.Ended)},this.handleCpuConstrained=()=>{this.track&&at(this.track)&&this.emit(R.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(R.Ended,this.handleTrackEnded),this.track.off(R.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(R.Ended,this.handleTrackEnded),e.on(R.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 p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(qe(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ce.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ce.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ce.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ce.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ce.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ce.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function an(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=so(n);let o=r.audio,a=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=to(r,Ao,Mo),d=ns(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(de.userMediaPromiseMap.set("audioinput",l),l.catch(()=>de.userMediaPromiseMap.delete("audioinput"))),r.video&&(de.userMediaPromiseMap.set("videoinput",l),l.catch(()=>de.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let m;const E=f?d.audio:d.video;typeof E!="boolean"&&(m=E);const S=h.getSettings().deviceId;m!=null&&m.deviceId&&rt(m.deviceId)!==S?m.deviceId=S:m||(m={deviceId:S});const w=Ju(h,m,e);return w.kind===T.Kind.Video?w.source=T.Source.Camera:w.kind===T.Kind.Audio&&(w.source=T.Source.Microphone),w.mediaStream=u,qe(w)&&i?yield w.setProcessor(i):at(w)&&s&&(yield w.setProcessor(s)),w})))}catch(u){if(!t)throw u;return an(Object.assign(Object.assign({},n),{audio:o,video:a}),e)}})}function Th(n){return p(this,void 0,void 0,function*(){return(yield an({audio:!1,video:!0}))[0]})}function Ch(n){return p(this,void 0,void 0,function*(){return(yield an({audio:!0,video:!1}))[0]})}var ut;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(ut||(ut={}));function Eh(n){switch(n){case ai.EXCELLENT:return ut.Excellent;case ai.GOOD:return ut.Good;case ai.POOR:return ut.Poor;case ai.LOST:return ut.Lost;default:return ut.Unknown}}class Yo extends Ue.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.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===ci.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===At.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ci.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ut.Unknown,this.log=B,this.log=We((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Ie.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Pe,this.once(x.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(T.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(T.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(T.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 t;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===At.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==At.ACTIVE&&this.emit(x.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(x.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(x.ParticipantNameChanged,e)}_setAttributes(e){const t=$l(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(x.AttributesChanged,t)}setPermissions(e){var t,i,s,r,o,a;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((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,d&&this.emit(x.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(x.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Eh(e),t!==this._connectionQuality&&this.emit(x.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>qe(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(R.Muted,()=>{this.emit(x.TrackMuted,e)}),e.on(R.Unmuted,()=>{this.emit(x.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case T.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case T.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Ph(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new sa({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Rh extends Yo{constructor(e,t,i,s,r,o){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ae.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Pe)},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,d,l,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,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("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,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,d;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Pe),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:d,message:l}=a,u=this.pendingSignalRequests.get(c);u&&(d!==jn.OK&&u.reject(new Za(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=ee.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);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=>Ph(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),V(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),V(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),V(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),V(c))),this.emit(x.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>p(this,void 0,void 0,function*(){var c,d,l,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 g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var m=!0,E=Ge(g),S;S=yield E.next(),c=S.done,!c;m=!0){u=S.value,m=!1;const w=u;Fl(w)&&(this.log.debug("publish ".concat(w," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),V(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,w,f.options))}}catch(w){d={error:w}}finally{try{!m&&!c&&(l=E.return)&&(yield l.call(E))}finally{if(d)throw d.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=>p(this,void 0,void 0,function*(){if(a.source===T.Source.ScreenShare||a.source===T.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),V(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(ze(a)||ot(a))try{if(Te())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===T.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),V(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),V(a))),ze(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),V(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ae.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(_.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(_.Connected,this.handleReconnected).on(_.SignalConnected,this.handleSignalConnected).on(_.SignalRestarted,this.handleReconnected).on(_.SignalResumed,this.handleReconnected).on(_.Restarting,this.handleReconnecting).on(_.Resuming,this.handleReconnecting).on(_.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(_.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(_.Closing,this.handleClosing).on(_.SignalRequestResponse,this.handleSignalRequestResponse).on(_.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:o}=t;return(function*(){return new Se((a,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(g=>{let[m,E]=g;return this.attributes[m]===E||E===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),a();return}yield he(50)}c(new Za("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(T.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(T.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(T.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?ae.GCM:ae.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d==null?void 0:d.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case T.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case T.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case T.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new He(e)}}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(x.MediaDevicesError,d,ss(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===T.Source.Microphone&&qe(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),V(u))),d.push(this.publishTrack(u,s));[a]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d}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===T.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(T.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(T.Source.Camera)||this.pendingPublishing.has(T.Source.Microphone))){this.pendingPublishing.add(T.Source.Camera),this.pendingPublishing.add(T.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(T.Source.Camera),this.pendingPublishing.delete(T.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=to(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield an(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(qe(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=T.Source.Microphone,this.emit(x.AudioStreamAcquired)),at(a)&&(this.cameraError=void 0,a.source=T.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Qn("getDisplayMedia not supported");e.resolution===void 0&&!Ql()&&(e.resolution=ts.h1080fps30.resolution);const t=jl(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new He("no video track found");const r=new rn(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=T.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(i.getAudioTracks().length>0){this.emit(x.AudioStreamAcquired);const a=new sn(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=T.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,d,l;ze(i)&&i.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),jt(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let S;switch(i.source){case T.Source.Microphone:S="audioinput";break;case T.Source.Camera:S="videoinput"}S&&r.activeDeviceMap.has(S)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(S)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new sn(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new rn(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new He("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(S=>{S.track&&S.track===i&&(h=S)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),V(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),g="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(c=f.forceStereo)!==null&&c!==void 0?c:g;m&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),V(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!eu()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const E=new Promise((S,w)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==J.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:V(i)}));let I=!1;const b=setTimeout(()=>{I=!0,i.stop(),w(new Qa("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),I)return;const y=yield this.publish(i,f,m);S(y)}else try{const I=yield this.publish(i,f,m);S(I)}catch(I){w(I)}}catch(I){w(I)}}));r.pendingPublishPromises.set(i,E);try{return yield E}catch(S){throw S}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Pe),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),V(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Wl(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),V(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,o,a,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Qa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>jt(e)&&M.source===e.source)&&e.source!==T.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),V(e))),t.stopMicTrackOnMute&&qe(e)&&(e.stopOnMute=!0),e.source===T.Source.ScreenShare&&St()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Jl()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Yl()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Es),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===pi(M.mime))||(t.videoCodec=pi(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(R.Muted,this.onTrackMuted),e.on(R.Unmuted,this.onTrackUnmuted),e.on(R.Ended,this.handleTrackEnded),e.on(R.UpstreamPaused,this.onTrackUpstreamPaused),e.on(R.UpstreamResumed,this.onTrackUpstreamResumed),e.on(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const E=[],S=!(!((s=t.dtx)!==null&&s!==void 0)||s),w=e.getSourceTrackSettings();w.autoGainControl&&E.push(ce.TF_AUTO_GAIN_CONTROL),w.echoCancellation&&E.push(ce.TF_ECHO_CANCELLATION),w.noiseSuppression&&E.push(ce.TF_NOISE_SUPPRESSION),w.channelCount&&w.channelCount>1&&E.push(ce.TF_STEREO),S&&E.push(ce.TF_NO_DTX),ze(e)&&e.hasPreConnectBuffer&&E.push(ce.TF_PRECONNECT_BUFFER);const I=new di({cid:e.mediaStreamTrack.id,name:t.name,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),disableDtx:S,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:E});let b;if(e.kind===T.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const N=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:hi.h720.resolution;M={width:N.width,height:N.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{dims:M}))}I.width=M.width,I.height=M.height,ot(e)&&(Ae(m)&&(e.source===T.Source.ScreenShare&&(t.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),V(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),I.simulcastCodecs=[new Dn({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Es}),t.backupCodec&&m!==t.backupCodec.codec&&I.encryption===ae.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),I.simulcastCodecs.push(new Dn({codec:t.backupCodec.codec,cid:""})))),b=Is(e.source===T.Source.ScreenShare,I.width,I.height,t),I.layers=Vo(I.width,I.height,b,Ae(t.videoCodec))}else e.kind===T.Kind.Audio&&(b=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new ie("cannot publish track when not connected");const y=()=>p(this,void 0,void 0,function*(){var M,O,N;if(!this.engine.pcManager)throw new ie("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(x.LocalSenderCreated,e.sender,e),ot(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=rh(e)),e.setDegradationPreference(t.degradationPreference)),b)if(St()&&e.kind===T.Kind.Audio){let F;for(const G of this.engine.pcManager.publisher.getTransceivers())if(G.sender===e.sender){F=G;break}F&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:F,codec:"opus",maxbr:!((O=b[0])===null||O===void 0)&&O.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&Ae(e.codec)&&(!((N=b[0])===null||N===void 0)&&N.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:I.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const A=new Promise((M,O)=>p(this,void 0,void 0,function*(){var N;try{C=yield this.engine.addTrack(I),M(C)}catch(F){e.sender&&(!((N=this.engine.pcManager)===null||N===void 0)&&N.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(G=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{error:G}))})),O(F)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([A,y()]))[0];else{C=yield A;let M;if(C.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===T.Kind.Video){const O=pi(M);O!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{codec:O})),t.videoCodec=O,b=Is(e.source===T.Source.ScreenShare,I.width,I.height,t))}yield y()}const D=new Ns(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(D.on(R.CpuConstrained,M=>this.onTrackCpuConstrained(M,D)),D.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:C})),ot(e)?e.startMonitor(this.engine.client):ze(e)&&e.startMonitor(),this.addTrackPublication(D),this.emit(x.LocalTrackPublished,D),ze(e)&&C.audioFeatures.includes(ce.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(x.LocalTrackSubscribed,N=>{if(N.trackSid===C.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),V(e))),e.stopPreConnectBuffer()}}),M&&new Promise((F,G)=>p(this,void 0,void 0,function*(){var ne,be,re,De,Gt,Ht;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),V(e)));const Xe=setTimeout(()=>{G(new Error("agent not active within 10 seconds"))},1e4),Ct=yield this.waitUntilActiveAgentPresent();clearTimeout(Xe),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),V(e)));const un=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ct.identity],attributes:{trackId:D.trackSid,sampleRate:String((Gt=w.sampleRate)!==null&&Gt!==void 0?Gt:"48000"),channels:String((Ht=w.channelCount)!==null&&Ht!==void 0?Ht:"1")}});try{for(var zt=!0,Je=Ge(M),Ye;Ye=yield Je.next(),ne=Ye.done,!ne;zt=!0){De=Ye.value,zt=!1;const Kt=De;yield un.write(Kt)}}catch(Kt){be={error:Kt}}finally{try{!zt&&!ne&&(re=Je.return)&&(yield re.call(Je))}finally{if(be)throw be.error}}yield un.close(),F()}catch(Xe){G(Xe)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),V(e)))}).catch(F=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{error:F}))})}return D})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==ae.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new He("track is not published");if(!ot(e))throw new He("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),a=ih(e,t,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),V(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const d=new di({cid:c.mediaStreamTrack.id,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=Vo(d.width,d.height,a),!this.engine||this.engine.isClosed)throw new ie("cannot publish track when not connected");const l=()=>p(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(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(jt(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),V(e))),yield d)}const r=this.getPublicationForTrack(e),o=r?V(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(R.Muted,this.onTrackMuted),e.off(R.Unmuted,this.onTrackUnmuted),e.off(R.Ended,this.handleTrackEnded),e.off(R.UpstreamPaused,this.onTrackUpstreamPaused),e.off(R.UpstreamResumed,this.onTrackUpstreamResumed),e.off(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Z.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),ot(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(a=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case T.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case T.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(x.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Se((r,o)=>p(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),a.push(c))}),yield Promise.all(a.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==T.Source.ScreenShare&&d.source!==T.Source.ScreenShareAudio&&(ze(d)||ot(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?q.RELIABLE:q.LOSSY,o=s.destinationIdentities,a=s.topic;let c=new _n({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:a});const d=new me({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new me({kind:q.RELIABLE,value:{case:"sipDtmf",value:new qr({code:e,digit:t})}});yield this.engine.sendDataPacket(i,q.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new me({value:{case:"chatMessage",value:new Ui(Object.assign(Object.assign({},i),{timestamp:Y.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(x.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new me({value:{case:"chatMessage",value:new Ui(Object.assign(Object.assign({},i),{timestamp:Y.parse(i.timestamp),editTimestamp:Y.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(x.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const o=7e3,a=o+1e3;return new Se((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if(Rs(s)>Do){d(ee.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&je((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(ee.builtIn("UNSUPPORTED_SERVER"));return}const g=Math.max(r,a),m=crypto.randomUUID();yield this.publishRpcRequest(t,m,i,s,g);const E=setTimeout(()=>{this.pendingAcks.delete(m),d(ee.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(m),clearTimeout(S)},o);this.pendingAcks.set(m,{resolve:()=>{clearTimeout(E)},participantIdentity:t});const S=setTimeout(()=>{this.pendingResponses.delete(m),d(ee.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(m,{resolve:(w,I)=>{clearTimeout(S),this.pendingAcks.has(m)&&(this.log.warn("RPC response received before ack",m),this.pendingAcks.delete(m),clearTimeout(E)),I?d(I):c(w??"")},participantIdentity:t})}))}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const o=new me({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcRequest",value:new xn({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,q.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ee.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),V(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Pe),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(ze(s)||ot(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield he(20)}})}}class wh extends Ke{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(R.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new $i({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new $r({participantSid:"",trackSids:[this.trackSid]})]});this.emit(R.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ke.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ke.SubscriptionStatus.Subscribed:Ke.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ke.PermissionStatus.Allowed:Ke.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 t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(ps(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ps(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ce.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(R.VisibilityChanged,this.handleVisibilityChange),s.off(R.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(R.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(R.VisibilityChanged,this.handleVisibilityChange),e.on(R.Ended,this.handleEnded),this.emit(R.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(R.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?R.Muted:R.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(R.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(R.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 ps(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ea({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===T.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)ro(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Gl(this.trackInfo,this.requestedMaxQuality);i&&ro(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.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:Ce.HIGH})),e.quality=Ce.HIGH)}this.emit(R.UpdateSettings,e)}}class on extends Yo{static fromParticipantInfo(e,t,i){return new on(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ci.STANDARD;super(t,i||"",s,r,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(R.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(R.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(R.SubscriptionPermissionChanged,t=>{this.emit(x.TrackSubscriptionPermissionChanged,e,t)}),e.on(R.SubscriptionStatusChanged,t=>{this.emit(x.TrackSubscriptionStatusChanged,e,t)}),e.on(R.Subscribed,t=>{this.emit(x.TrackSubscribed,t,e)}),e.on(R.Unsubscribed,t=>{this.emit(x.TrackUnsubscribed,t,e)}),e.on(R.SubscriptionFailed,t=>{this.emit(x.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:T.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:T.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(l=>{!a&&e.kind===l.kind.toString()&&(a=l)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(x.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,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),V(a))),this.emit(x.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new Sh(e,t,s,r):d=new yh(e,t,s,this.audioContext,this.audioOutput),d.source=a.source,d.isMuted=a.isMuted,d.setMediaStream(i),d.start(),a.setTrack(d),this.volumeMap.has(a.source)&&hs(d)&&qe(d)&&d.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 t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=T.kindFromProto(s.type);if(!c)return;a=new wh(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),i.set(s.sid,a);const d=Array.from(this.trackPublications.values()).find(l=>l.source===(a==null?void 0:a.source));d&&a.source!==T.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:V(d),newTrack:V(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),V(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(x.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case T.Kind.Audio:this.audioTrackPublications.delete(e);break;case T.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(x.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;qe(i.track)&&hs(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var H;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(H||(H={}));const _h=4*1e3;class Wt extends Ue.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,o;if(super(),t=this,this.state=H.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=B,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,c,d)=>p(this,void 0,void 0,function*(){var l;if(!Xl())throw Be()?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 u=yield this.disconnectLock.lock();if(this.state===H.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(H.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==vo(a)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Bt(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new W(a,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(g=>{var m;(m=this.regionUrlProvider)===null||m===void 0||m.setServerReportedRegions(g)}).catch(g=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:g}))}));const h=(g,m,E)=>p(this,void 0,void 0,function*(){var S,w;this.abortController&&this.abortController.abort();const I=new AbortController;this.abortController=I,u==null||u();try{if(yield qt.getInstance().getBackOffPromise(a),I.signal.aborted)throw U.cancelled("Connection attempt aborted");yield this.attemptConnection(E??a,c,d,I),this.abortController=void 0,g()}catch(b){if(this.regionUrlProvider&&b instanceof U&&b.reason!==K.Cancelled&&b.reason!==K.NotAllowed){let y=null;try{this.log.debug("Fetching next region"),y=yield this.regionUrlProvider.getNextBestRegionUrl((S=this.abortController)===null||S===void 0?void 0:S.signal)}catch(C){if(C instanceof U&&(C.status===401||C.reason===K.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(C);return}}[K.InternalError,K.ServerUnreachable,K.Timeout].includes(b.reason)&&(this.log.debug("Adding failed connection attempt to back off"),qt.getInstance().addFailedConnectionAttempt(a)),y&&!(!((w=this.abortController)===null||w===void 0)&&w.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(b.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield h(g,m,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,go(b)),m(b))}else{let y=_e.UNKNOWN_REASON;b instanceof U&&(y=go(b)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),m(b)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Pe((g,m)=>{h(g,m,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,g,m;const E=yield d.join(a,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let S=E.serverInfo;if(S||(S={version:E.serverVersion,region:E.serverRegion}),this.serverInfo=S,this.log.debug("connected to Livekit Server ".concat(Object.entries(S).map(w=>{let[I,b]=w;return"".concat(I,": ").concat(b)}).join(", ")),{room:(f=E.room)===null||f===void 0?void 0:f.name,roomSid:(g=E.room)===null||g===void 0?void 0:g.sid,identity:(m=E.participant)===null||m===void 0?void 0:m.identity}),!S.version)throw new Ol("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),E}),this.applyJoinResponse=a=>{const c=a.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===H.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ps),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(P.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const g=l.signal.aborted?U.cancelled("Signal connection aborted"):U.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(g.message="".concat(g.message,": ").concat(f.message)),f instanceof U&&(g.reason=f.reason,g.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),g}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),U.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Te()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Te()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(H.Connected),this.emit(P.Connected),qt.getInstance().resetFailedConnectionAttempts(a),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,g;const m=yield l.disconnectLock.lock();try{if(l.state===H.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===H.Connecting||l.state===H.Reconnecting||l.isResuming){const E="Abort connection attempt due to user initiated disconnect";l.log.warn(E,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(E),(g=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||g===void 0||g.call(f,U.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,_e.CLIENT_INITIATED),l.engine=void 0}finally{m()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const a=[],c=ke();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=us();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,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(P.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const a=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.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 a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(H.Reconnecting)&&this.emit(P.Reconnecting)},this.handleSignalRestarted=a=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(H.Connected),this.emit(P.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===At.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=a=>{const c=[],d={};a.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(P.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=a=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),a.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(P.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=T.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(x.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(P.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(a.trackSid);d&&d.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(a.trackSid);d&&d.setSubscriptionError(a.err)},this.handleDataPacket=(a,c)=>{const d=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(d,a.value.value,a.kind,c);else if(a.value.case==="transcription")this.handleTranscription(d,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(d,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(d,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,d);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a,c);else if(a.value.case==="rpcRequest"){const l=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(a,c,d,l)=>{this.emit(P.DataReceived,c.payload,a,d,c.topic,l),a==null||a.emit(x.DataReceived,c.payload,d,l)},this.handleSipDtmf=(a,c)=>{this.emit(P.SipDTMFReceived,c,a),a==null||a.emit(x.SipDTMFReceived,c)},this.handleTranscription=(a,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d==null?void 0:d.trackPublications.get(c.trackId),u=au(c,this.transcriptionReceivedTimes);l==null||l.emit(R.TranscriptionReceived,u),d==null||d.emit(x.TranscriptionReceived,u,l),this.emit(P.TranscriptionReceived,u,d,l)},this.handleChatMessage=(a,c)=>{const d=ou(c);this.emit(P.ChatMessage,d,a)},this.handleMetrics=(a,c)=>{this.emit(P.MetricsReceived,a,c)},this.handleDataStream=(a,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(a,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(P.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(P.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(P.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(P.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var a;((a=ke())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(P.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const c=this.roomInfo;this.roomInfo=a,c&&c.metadata!==a.metadata&&this.emitWhenConnected(P.RoomMetadataChanged,a.metadata),(c==null?void 0:c.activeRecording)!==a.activeRecording&&this.emitWhenConnected(P.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(P.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(P.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(P.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(P.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(P.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var c;(c=a==null?void 0:a.onPublish)===null||c===void 0||c.call(a,this)},this.onLocalTrackPublished=a=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=a.track)===null||c===void 0||c.on(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=a.track)===null||d===void 0||d.on(R.Restarted,this.onLocalTrackRestarted),(h=(u=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(P.LocalTrackPublished,a,this.localParticipant),ze(a.track)&&(yield a.track.checkForSilence())&&this.emit(P.LocalAudioSilenceDetected,a);const g=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),m=ss(a.source);m&&g&&g!==this.localParticipant.activeDeviceMap.get(m)&&(this.localParticipant.activeDeviceMap.set(m,g),this.emit(P.ActiveDeviceChanged,m,g))}),this.onLocalTrackUnpublished=a=>{var c,d;(c=a.track)===null||c===void 0||c.off(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=a.track)===null||d===void 0||d.off(R.Restarted,this.onLocalTrackRestarted),this.emit(P.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>p(this,void 0,void 0,function*(){const c=yield a.getDeviceId(!1),d=ss(a.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(P.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=a=>{this.emit(P.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,c)=>{this.emit(P.MediaDevicesError,a,c)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(P.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(P.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Bu),e),this.log=We((i=this.options.loggerName)!==null&&i!==void 0?i:Ie.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ao),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Mo),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Fu),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new mh,this.outgoingDataStreamManager=new bh(this.engine,this.log),this.disconnectLock=new fe,this.localParticipant=new Rh("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",rt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",rt(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",rt(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),Te()){const a=new AbortController;(o=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||o===void 0||o.call(r,"devicechange",this.handleDeviceChange,{signal:a.signal}),Wt.cleanupRegistry&&Wt.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(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;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new ku(i,t),this.e2eeManager.on(dt.ParticipantEncryptionStatusChanged,(s,r)=>{du(r)&&(this.isE2EEEnabled=s),this.emit(P.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(dt.EncryptionError,(s,r)=>{const o=r?this.getParticipantByIdentity(r):void 0;this.emit(P.EncryptionError,s,o)}),(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,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===H.Disconnected?Se.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Se.resolve(this.roomInfo.sid):new Se((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(_.RoomUpdate,i),e(s.sid))};this.engine.on(_.RoomUpdate,i),this.once(P.Disconnected,()=>{this.engine.off(_.RoomUpdate,i),t(new ie("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new uh(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(_.ParticipantUpdate,this.handleParticipantUpdates).on(_.RoomUpdate,this.handleRoomUpdate).on(_.SpeakersChanged,this.handleSpeakersChanged).on(_.StreamStateChanged,this.handleStreamStateUpdate).on(_.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(_.SubscriptionError,this.handleSubscriptionError).on(_.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(_.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(_.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(_.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(_.DataPacketReceived,this.handleDataPacket).on(_.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(H.SignalReconnecting)&&this.emit(P.SignalReconnecting)}).on(_.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(H.Connected)&&this.emit(P.Reconnected)}).on(_.SignalResumed,()=>{this.bufferedEvents=[],(this.state===H.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(_.Restarting,this.handleRestarting).on(_.SignalRestarted,this.handleSignalRestarted).on(_.Offline,()=>{this.setAndEmitConnectionState(H.Reconnecting)&&this.emit(P.Reconnecting)}).on(_.DCBufferStatusChanged,(e,t)=>{this.emit(P.DCBufferStatusChanged,e,t)}).on(_.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(x.LocalTrackSubscribed,t),this.emitWhenConnected(P.LocalTrackSubscribed,t,this.localParticipant)}).on(_.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(P.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 t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return de.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===H.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Bt(new URL(e))&&t){this.regionUrlProvider=new W(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===H.Disconnected&&(this.regionUrl=i,yield fetch(vi(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(vi(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,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Le({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Le({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Le({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Le({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=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Le({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Le({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":s=new Le({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Wi({reason:_e.CLIENT_INITIATED,action:Ot.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Le({scenario:{case:"subscriberBandwidth",value:Tt(t)}});break;case"leave-full-reconnect":s=new Le({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,d,l,u,h,f;let g=!0,m=!1;const E=o?{exact:s}:s;if(i==="audioinput"){m=r.localParticipant.audioTrackPublications.size===0;const S=(a=r.getActiveDevice(i))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=E;const w=Array.from(r.localParticipant.audioTrackPublications.values()).filter(b=>b.source===T.Source.Microphone);try{g=(yield Promise.all(w.map(b=>{var y;return(y=b.audioTrack)===null||y===void 0?void 0:y.setDeviceId(E)}))).every(b=>b===!0)}catch(b){throw r.options.audioCaptureDefaults.deviceId=S,b}const I=w.some(b=>{var y,C;return(C=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&C!==void 0?C:!1});g&&I&&(m=!0)}else if(i==="videoinput"){m=r.localParticipant.videoTrackPublications.size===0;const S=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=E;const w=Array.from(r.localParticipant.videoTrackPublications.values()).filter(b=>b.source===T.Source.Camera);try{g=(yield Promise.all(w.map(b=>{var y;return(y=b.videoTrack)===null||y===void 0?void 0:y.setDeviceId(E)}))).every(b=>b===!0)}catch(b){throw r.options.videoCaptureDefaults.deviceId=S,b}const I=w.some(b=>{var y,C;return(C=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&C!==void 0?C:!1});g&&I&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!os()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield de.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const S=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(w=>w.setAudioOutput({deviceId:s})))}catch(w){throw r.options.audioOutput.deviceId=S,w}}return m&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(P.ActiveDeviceChanged,i,s)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(x.AttributesChanged,this.onLocalAttributesChanged).on(x.TrackMuted,this.onLocalTrackMuted).on(x.TrackUnmuted,this.onLocalTrackUnmuted).on(x.LocalTrackPublished,this.onLocalTrackPublished).on(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(x.MediaDevicesError,this.onMediaDevicesError).on(x.AudioStreamAcquired,this.startAudio).on(x.ChatMessage,this.onLocalChatMessageSent).on(x.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,t,i){if(this.state===H.Connecting||this.state===H.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(P.Reconnected,u),this.off(P.Connected,u),this.off(P.Disconnected,h)};this.once(P.Reconnected,u),this.once(P.Connected,u),this.once(P.Disconnected,h);return}if(this.state===H.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 s=Kl(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!a.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}a=u}a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(o,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:o,trackId:a}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,a,t,i,d);l!=null&&l.isEncrypted&&!this.e2eeManager&&this.emit(P.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==H.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(o=>{r.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var o,a,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((o=r.track)===null||o===void 0||o.detach(),(a=r.track)===null||a===void 0||a.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(x.AttributesChanged,this.onLocalAttributesChanged).off(x.TrackMuted,this.onLocalTrackMuted).off(x.TrackUnmuted,this.onLocalTrackUnmuted).off(x.LocalTrackPublished,this.onLocalTrackPublished).off(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(x.MediaDevicesError,this.onMediaDevicesError).off(x.AudioStreamAcquired,this.startAudio).off(x.ChatMessage,this.onLocalChatMessageSent).off(x.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),Te()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(H.Disconnected),this.emit(P.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(P.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,o){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,ee.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,t,null,ee.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Rs(l)>Do?(c=ee.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ee?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ee.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=de.getInstance().previousDevices,r=yield de.getInstance().getDevices(void 0,!1),o=ke();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(P.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const d=Bl(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.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"&&!mi()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!mi())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;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=no())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),he(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(P.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=on.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new on(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(P.ParticipantConnected,i),i.on(x.TrackPublished,s=>{this.emitWhenConnected(P.TrackPublished,s,i)}).on(x.TrackSubscribed,(s,r)=>{s.kind===T.Kind.Audio?(s.on(R.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(R.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===T.Kind.Video&&(s.on(R.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(R.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(P.TrackSubscribed,s,r,i)}).on(x.TrackUnpublished,s=>{this.emit(P.TrackUnpublished,s,i)}).on(x.TrackUnsubscribed,(s,r)=>{this.emit(P.TrackUnsubscribed,s,r,i)}).on(x.TrackMuted,s=>{this.emitWhenConnected(P.TrackMuted,s,i)}).on(x.TrackUnmuted,s=>{this.emitWhenConnected(P.TrackUnmuted,s,i)}).on(x.ParticipantMetadataChanged,s=>{this.emitWhenConnected(P.ParticipantMetadataChanged,s,i)}).on(x.ParticipantNameChanged,s=>{this.emitWhenConnected(P.ParticipantNameChanged,s,i)}).on(x.AttributesChanged,s=>{this.emitWhenConnected(P.ParticipantAttributesChanged,s,i)}).on(x.ConnectionQualityChanged,s=>{this.emitWhenConnected(P.ConnectionQualityChanged,s,i)}).on(x.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(P.ParticipantPermissionsChanged,s,i)}).on(x.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionStatusChanged,s,r,i)}).on(x.TrackSubscriptionFailed,(s,r)=>{this.emit(P.TrackSubscriptionFailed,s,i,r)}).on(x.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionPermissionChanged,s,r,i)}).on(x.Active,()=>{this.emitWhenConnected(P.ParticipantActive,i),i.kind===ci.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&cu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}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,_e.STATE_MISMATCH))):e=0},_h)}clearConnectionReconcile(){this.connectionReconcileInterval&&ue.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(P.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===H.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===H.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ni({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Y.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new bt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(P.SignalConnected),this.emit(P.Connected),this.setAndEmitConnectionState(H.Connected),o.video){const c=new Ns(T.Kind.Video,new Mt({source:se.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO,name:"video-dummy"}),new rn(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:mo(160*((i=a.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(x.LocalTrackPublished,c)}if(o.audio){const c=new Ns(T.Kind.Audio,new Mt({source:se.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO}),new sn(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:us(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(x.LocalTrackPublished,c)}for(let c=0;c<a.count-1;c+=1){let d=new bt({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:At.ACTIVE,tracks:[],joinedAt:Y.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(a.video){const u=mo(160*((r=a.aspectRatios[c%a.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new Mt({source:se.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(a.audio){const u=us(),h=new Mt({source:se.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==P.ActiveSpeakersChanged&&e!==P.TranscriptionReceived){const r=Xo(i).filter(o=>o!==void 0);(e===P.TrackSubscribed||e===P.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Wt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Xo(n){return n.map(e=>{if(e)return Array.isArray(e)?Xo(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Oe;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Oe||(Oe={}));class ht extends Ue.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Oe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Wt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Oe.IDLE)throw Error("check is running already");this.setStatus(Oe.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Oe.SKIPPED&&this.setStatus(this.isSuccess()?Oe.SUCCESS:Oe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===H.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==H.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Oe.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(P.Reconnecting,()=>{t=!0}),this.room.once(P.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield he(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 xh extends ht{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new W(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){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")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,d="A".repeat(o),l=Date.now();for(let g=0;g<c;g++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Ls=1e4;class Ih extends ht{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):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/(Ls/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Ls/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Ls)),clearInterval(u),a.stop(),t.remove(),yield this.disconnect(),l})}}class Ah extends ht{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Ch();if(yield io(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.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 Mh extends ht{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Th();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,o,a,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(o=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=l.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const m=f.getImageData(0,0,d.width,d.height).data;let E=!0;for(let S=0;S<m.length;S+=4)if(m[S]!==0||m[S+1]!==0||m[S+2]!==0){E=!1;break}E?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class Oh extends ht{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const o=new Promise(d=>{setTimeout(d,5e3),r=d}),a=()=>{i=!0};t.on(P.SignalReconnecting,a).on(P.Reconnecting,a).on(P.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield o,i){if(!s||t.state!==H.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 Dh extends ht{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;Bt(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new W(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new vs,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,a=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(a=!0,c=!0):l.startsWith("turns:")&&(a=!0,c=!0,o=!0),l.startsWith("stun:")&&(c=!0);c?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Nh extends ht{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(P.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,o)=>{if(r.candidate){const a=new RTCIceCandidate(r);let c="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(Lh(a.address)?c+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,c+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,o)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(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(),B.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"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Lh(n){const e=n.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 t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Uh extends ht{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new vs,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(Bt(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const c=yield new W(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Gr.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class xp extends Ue.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Oe.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Oe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Uh)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Nh)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Dh)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Oh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ah)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Mh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Ih);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(xh)})}}function $(n,e,t){return(e=Bh(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Fh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Bh(n){var e=Fh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class ve extends Error{constructor(e,t){var i;super(e,t),$(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}$(ve,"code","ERR_JOSE_GENERIC");class jh extends ve{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),$(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),$(this,"claim",void 0),$(this,"reason",void 0),$(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}$(jh,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class qh extends ve{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),$(this,"code","ERR_JWT_EXPIRED"),$(this,"claim",void 0),$(this,"reason",void 0),$(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}$(qh,"code","ERR_JWT_EXPIRED");class Vh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}$(Vh,"code","ERR_JOSE_ALG_NOT_ALLOWED");class $h extends ve{constructor(){super(...arguments),$(this,"code","ERR_JOSE_NOT_SUPPORTED")}}$($h,"code","ERR_JOSE_NOT_SUPPORTED");class Wh extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWE_DECRYPTION_FAILED")}}$(Wh,"code","ERR_JWE_DECRYPTION_FAILED");class Gh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWE_INVALID")}}$(Gh,"code","ERR_JWE_INVALID");class Hh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWS_INVALID")}}$(Hh,"code","ERR_JWS_INVALID");class zh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWT_INVALID")}}$(zh,"code","ERR_JWT_INVALID");class Kh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWK_INVALID")}}$(Kh,"code","ERR_JWK_INVALID");class Jh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWKS_INVALID")}}$(Jh,"code","ERR_JWKS_INVALID");class Yh extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}$(Yh,"code","ERR_JWKS_NO_MATCHING_KEY");class Xh extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,Symbol.asyncIterator,void 0),$(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}$(Xh,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Qh extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWKS_TIMEOUT")}}$(Qh,"code","ERR_JWKS_TIMEOUT");class Zh extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}$(Zh,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class Qo extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??"https://voice.hanc.ai"}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e}){if(!(this.room&&this.room.state==="connected")){this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const t=new Wt;this.room=t,this.setupRoomEventListeners(t);const i=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now()}})});if(!i.ok){const c=await i.text();throw new Error(`Failed to get room token: ${i.status} ${c}`)}const{token:s,url:r,room_name:o,user_identity:a}=await i.json();this.roomName=o,this.userIdentity=a,await t.connect(r,s),this.updateStatus("connected"),this.isReady=!0,await this.enableMicrophone(t),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:o,identity:a}}))}catch(t){this.error=`Connection failed: ${t instanceof Error?t.message:String(t)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}setupRoomEventListeners(e){e.on(P.Connected,()=>{this.updateStatus("connected"),this.isReady=!0}),e.on(P.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(P.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const i=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");i&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:i}}))}),e.on(P.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const i=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");i&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:i}}))}),e.on(P.TrackSubscribed,(t,i,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}))}}),e.on(P.TrackUnsubscribed,(t,i,s)=>{t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(P.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(P.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(i=>i.includes("agent")||i.includes("voice-assistant")||i.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}async enableMicrophone(e){try{await e.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled"))}catch(t){this.error=`Failed to enable microphone: ${t instanceof Error?t.message:String(t)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),i=new TextEncoder().encode(e);await this.room.localParticipant.publishData(i,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");try{await this.room.disconnect(),this.room=null,this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.dispatchEvent(new CustomEvent("call-ended"))}catch(e){this.error=`Error ending call: ${e instanceof Error?e.message:String(e)}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}const ep=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,tp=/^rgba?\(([^)]+)\)$/i;function ki(n,e,t){return Math.min(t,Math.max(e,n))}function ip(n){const e=ep.exec(n);if(!e)return null;let t=e[1];t.length===3&&(t=t.split("").map(o=>o+o).join(""));const i=parseInt(t.slice(0,2),16),s=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);return{r:i,g:s,b:r}}function np(n){const e=tp.exec(n);if(!e)return null;const t=e[1].split(",").map(o=>o.trim());if(t.length<3)return null;const i=ki(Number.parseFloat(t[0]),0,255),s=ki(Number.parseFloat(t[1]),0,255),r=ki(Number.parseFloat(t[2]),0,255);return Number.isNaN(i)||Number.isNaN(s)||Number.isNaN(r)?null:{r:i,g:s,b:r}}function Us(n){const e=n.trim();return ip(e)||np(e)}function pe(n,e,t){const i=Us(n),s=Us(e);if(!i&&!s)return n;if(!i&&s)return`rgb(${s.r}, ${s.g}, ${s.b})`;if(i&&!s)return e;const r=ki(t,0,1),o=Math.round(i.r+(s.r-i.r)*r),a=Math.round(i.g+(s.g-i.g)*r),c=Math.round(i.b+(s.b-i.b)*r);return`rgb(${o}, ${a}, ${c})`}function Zo(n,e){const t=Us(n);if(!t)return n;const i=ki(e,0,1);return`rgba(${t.r}, ${t.g}, ${t.b}, ${i})`}const ec=Pt`
244
+ `},Ts}var xo;function Fu(){if(xo)return Me;xo=1;var n=Nu(),e=Uu(),t=Cs();return Me.grammar=t,Me.write=e,Me.parse=n.parse,Me.parseParams=n.parseParams,Me.parseFmtpConfig=n.parseFmtpConfig,Me.parsePayloads=n.parsePayloads,Me.parseRemoteCandidates=n.parseRemoteCandidates,Me.parseImageAttributes=n.parseImageAttributes,Me.parseSimulcastStreamList=n.parseSimulcastStreamList,Me}var ut=Fu();function Es(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(i=t.isImmediate)!=null&&i,a=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(m,k){var S=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!o){var I=n.apply(g,f);a&&a(I),l.forEach(function(b){return(0,b.resolve)(I)}),l=[]}},u()),S){var R=n.apply(g,f);return a&&a(R),m(R)}l.push({resolve:m,reject:k})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(g){return(0,g.reject)(f)}),l=[]},h}const Bu=.7,ju=20,Wt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Io extends Ue.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=j,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Es(s=>p(this,void 0,void 0,function*(){this.emit(Wt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),ju),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=We((i=t.loggerName)!==null&&i!==void 0?i:Ie.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new fe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:o}=qu(e);this.remoteStereoMids=r,this.remoteNackMids=o}else if(e.type==="answer"){const r=ut.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(o=>{const a=ws(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||a!=c.transceiver.mid)return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of o.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&o.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=ut.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Wt.NegotiationComplete),e.sdp&&ut.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Wt.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;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 s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const o=ut.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(a=>{Mo(a),a.type==="audio"?Ao(a,["all"],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(Ae(c.codec)&&!Ct()&&this.ensureVideoDDExtensionForSVC(a,o),!Ae(c.codec)))return!0;const l=Math.round(c.maxbr*Bu);for(const u of a.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,ut.write(o)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=ut.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{Mo(s),s.type==="audio"&&Ao(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,ut.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ne("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new ne("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}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 p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),i.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;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(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,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 Nt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===co))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(d=>{d.value>o&&(o=d.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:co})}}}function Ao(n,e,t){const i=ws(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function qu(n){var e;const t=[],i=[],s=ut.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;const c=ws(o.mid);o.type==="audio"&&(o.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),o.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function Mo(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function ws(n){return typeof n=="number"?n.toFixed(0):n}const Ps="vp8",Vu={audioPreset:ts.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ns.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ps,backupCodec:!0,preConnectBuffer:!1},Oo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Do={deviceId:{ideal:"default"},resolution:pi.h720.resolution},$u={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new kl,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Rs={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ee;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(ee||(ee={}));class Wu{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Rs.peerConnectionTimeout,this.log=j,this.updateState=()=>{var r,o;const a=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=ee.CONNECTED:c.some(d=>d==="failed")?this.state=ee.FAILED:c.some(d=>d==="connecting")?this.state=ee.CONNECTING:c.every(d=>d==="closed")?this.state=ee.CLOSED:c.some(d=>d==="closed")?this.state=ee.CLOSING:c.every(d=>d==="new")&&(this.state=ee.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(ee[a]," to ").concat(ee[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=We((s=i.loggerName)!==null&&s!==void 0?s:Ie.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new Io(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new Io(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,xe.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,xe.PUBLISHER)},this.publisher.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=(r,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r,o)},this.state=ee.NEW,this.connectionLock=new fe,this.remoteOfferLock=new fe}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===xe.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=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(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new Se((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new Nt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new Nt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(Wt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Wt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),o instanceof Error?i(o):i(new Error(String(o)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i==null?void 0:i.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===xe.PUBLISHER?this.publisher.getConnectedAddress():e===xe.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),ue.clearTimeout(u),d(U.cancelled("room connection has been cancelled"))};s!=null&&s.signal.aborted&&l(),s==null||s.signal.addEventListener("abort",l);const u=ue.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",l),d(U.internal("could not establish pc connection"))},o);for(;this.state!==ee.CONNECTED;)if(yield he(50),s!=null&&s.signal.aborted){d(U.cancelled("room connection has been cancelled"));return}ue.clearTimeout(u),s==null||s.signal.removeEventListener("abort",l),c()}))})()})}}const Lo=5e3,Gu=3e4;class W{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield W.fetchLock.lock();try{const r=yield fetch("".concat(Hu(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const o=mu(r.headers),a=o?o*1e3:Lo;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw r.status===401?U.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):U.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof U?r:i!=null&&i.aborted?U.cancelled("Region fetching was aborted"):U.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=W.settingsTimeouts.get(e.hostname);clearTimeout(s),W.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield W.fetchRegionSettings(e,t);W.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof U&&r.reason===J.NotAllowed){j.debug("token is not valid, cancelling auto region refresh");return}j.debug("auto refetching of region settings failed",{error:r}),W.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){W.cache.set(e.hostname,i),W.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=W.settingsTimeouts.get(e);t&&(clearTimeout(t),W.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=W.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=W.connectionTrackers.get(e);i&&i.connectionCount===0&&(j.debug("stopping region refetch after disconnect delay",{hostname:e}),W.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Gu))}static cancelCleanup(e){const t=W.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=W.connectionTrackers.get(e);t||(t={connectionCount:0},W.connectionTrackers.set(e,t)),t.connectionCount++,W.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=W.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&W.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return jt(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return W.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=W.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),W.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),j.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){W.updateCachedRegionSettings(this.serverUrl,this.token,e)}}W.cache=new Map,W.settingsTimeouts=new Map,W.connectionTrackers=new Map,W.fetchLock=new fe;function Hu(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class te extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Uo(t,te.MAX_MESSAGE_BYTES),this.data=i?Uo(i,te.MAX_DATA_BYTES):void 0}static fromProto(e){return new te(e.code,e.message,e.data)}toProto(){return new Wr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new te(te.ErrorCode[e],te.ErrorMessage[e],t)}}te.MAX_MESSAGE_BYTES=256,te.MAX_DATA_BYTES=15360,te.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},te.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 No=15360;function _s(n){return new TextEncoder().encode(n).length}function Uo(n,e){if(_s(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const xs=2e3;function sn(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const Is=typeof MediaRecorder<"u";class zu{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Ku=Is?MediaRecorder:zu;class Ju extends Ku{constructor(e,t){if(!Is)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),s==null||s.close(),s=void 0},a=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function Yu(){return Is}const Xu=1e3,Qu=1e4;class Fo extends T{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),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=Es(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(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(P.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new fe,this.pauseUpstreamLock=new fe,this.trackChangeLock=new fe,this.trackChangeLock.lock().then(o=>p(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!==T.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Bt(this._mediaStreamTrack,r)}),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 s;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&&(Ft(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Ft(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Xu;return(function*(){var i;if(e.kind===T.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=ke())===null||i===void 0?void 0:i.os)==="iOS"&&(yield he(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield he(50)}throw new He("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===at(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),at(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===T.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===T.Kind.Audio?"audioinput":"videoinput";return t?le.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new He("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=Cl(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===T.Kind.Video?o.video=i||s?{deviceId:i,facingMode:s}:!0:o.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{Bt(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===T.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(P.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}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?P.Muted:P.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 p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),uo()&&(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 p(this,void 0,void 0,function*(){var e;const t=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(P.UpstreamPaused,this);const i=ke();if((i==null?void 0:i.name)==="Safari"&&je(i.version,"12.0")<0)throw new es("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{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=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(P.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(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 p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;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 t.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(Ft(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{a.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=a,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(Bt(i._mediaStreamTrack,d),Ft(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(P.TrackProcessorUpdate,i.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;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,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(P.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Yu()){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 t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Ju(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},Qu)}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 rn extends Fo{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,T.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(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=sn(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,de.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,de.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===T.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=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!==at(this._constraints.deviceId);return this.source===T.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{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=rs({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){Ce()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},xs)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Be()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.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(P.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield so(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}}function Zu(n,e,t){switch(n.kind){case"audio":return new rn(n,e,!1,void 0,t);case"video":return new an(n,e,!1,t);default:throw new He("unsupported track type: ".concat(n.kind))}}const eh=Object.values(pi),th=Object.values(is),ih=Object.values(ns),nh=[pi.h180,pi.h360],sh=[is.h180,is.h360],rh=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new z(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),As=["q","h","f"];function Ms(n,e,t,i){var s,r;let o=i==null?void 0:i.videoEncoding;n&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,d=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=oh(n,e,t,d),j.debug("using video encoding",o));const l=o.maxFramerate,u=new z(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Ae(d)){const g=new qo(c),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const k=ke();if(gi()||Be()||(k==null?void 0:k.name)==="Chrome"&&je(k==null?void 0:k.version,"113")<0){const S=g.suffix=="h"?2:3,R=nu(k);for(let I=0;I<g.spatial;I+=1)m.push({rid:As[2-I],maxBitrate:o.maxBitrate/Math.pow(S,I),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:R?Math.pow(2,I):void 0});m[0].scalabilityMode=c}else m.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(m[0].priority=u.encoding.priority,m[0].networkPriority=u.encoding.priority),j.debug("using svc encoding",{encodings:m}),m}if(!a)return[o];let h=[];n?h=(s=jo(i==null?void 0:i.screenShareSimulcastLayers))!==null&&s!==void 0?s:Bo(n,u):h=(r=jo(i==null?void 0:i.videoSimulcastLayers))!==null&&r!==void 0?r:Bo(n,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const m=Math.max(e,t);if(m>=960&&f)return Os(e,t,[g,f,u],l);if(m>=480)return Os(e,t,[g,u],l)}return Os(e,t,[u])}function ah(n,e,t){var i,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&j.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=n.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=a.height)!==null&&r!==void 0?r:(o=n.dimensions)===null||o===void 0?void 0:o.height;return n.source===T.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Ms(n.source===T.Source.ScreenShare,c,d,t)}function oh(n,e,t,i){const s=ch(n,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function ch(n,e,t){if(n)return ih;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?eh:th}function Bo(n,e){if(n)return rh(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?nh:sh}function Os(n,e,t,i){const s=[];if(t.forEach((r,o)=>{if(o>=As.length)return;const a=Math.min(n,e),d={rid:As[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=kt()||o===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Be()&&po()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var c;a.maxFramerate!=r&&(o&&(o=!1,j.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),j.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function jo(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class qo{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function dh(n){return n.source===T.Source.ScreenShare||n.constraints.height&&at(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const lh=5e3;class an extends Fo{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,T.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=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(r.map(c=>[c.rid,c])),a=r.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(P.CpuConstrained)),this.prevStats){let c=0;o.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=sn(d,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 t;if(this.signalClient=e,!Ce())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},xs))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=Ge(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;a=!0)r=d.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(l){i={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=Ge(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;a=!0){r=d.value,a=!1;const l=r;yield(o=l.sender)===null||o===void 0?void 0:o.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===T.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===T.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{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=i.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Te.LOW;i<=Te.HIGH;i+=1)t.push(new jn({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ae(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,o;let a;if(e){const u=rs({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,d=Ge(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;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&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=Ge(s.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)d=g.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(m){a={error:m}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){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:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},lh))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,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(Ae(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=Ge(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ae(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield Vo(u.sender,u.encodings,l.qualities,this.senderLock,Ae(l.codec),this.log,this.logContext))}}}catch(l){o={error:l}}finally{try{!t&&!r&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return d})}setPublishingLayers(e,t){return p(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:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Vo(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(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 t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Ae(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),uo()&&this.isInBackground&&this.source===T.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Vo(n,e,t,i,s,r,o){return p(this,void 0,void 0,function*(){const a=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var g;let m=(g=h.rid)!==null&&g!==void 0?g:"";m===""&&(m="q");const k=$o(m),S=t.find(R=>R.quality===k);S&&h.active!==S.enabled&&(l=!0,h.active=S.enabled,r.debug("setting layer ".concat(S.quality," to ").concat(h.active?"enabled":"disabled"),o),kt()&&(S.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)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield n.setParameters(c))}finally{a()}})}function $o(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function Wo(n,e,t,i){if(!t)return[new st({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new qo(s),o=[],a=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)o.push(new st({quality:Math.min(Te.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(a,d)),height:Math.ceil(e/Math.pow(a,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=$o((o=s.rid)!==null&&o!==void 0?o:"");return new st({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Go="_lossy",Ho="_reliable",uh=2*1e3,Ds="leave-reconnect",hh=3e4,ph=8*1024,fh=256*1024;var Pe;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Pe||(Pe={}));class mh extends Ue.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Rs.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Pe.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=j,this.reliableDataSequence=1,this.reliableMessageBuffer=new wo,this.reliableReceivedState=new Lu(hh),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:o}=s;return(function*(){if(o){if(o.label===Ho)r.reliableDCSub=o;else if(o.label===Go)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,o,a,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=me.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(_.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=qr.fromBinary(h.payload),g=new me({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((a=g.value)===null||a===void 0?void 0:a.case)==="user"&&zo(g,g.value.value),this.emit(_.DataPacketReceived,g,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&zo(u,u.value.value),this.emit(_.DataPacketReceived,u,oe.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?q.LOSSY:q.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(_.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}i===Ds&&(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(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Pe.Connected&&i();const r=()=>{this.off(_.Disconnected,o),i()},o=()=>{this.off(_.Restarted,r),s()};this.once(_.Restarted,r),this.once(_.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===q.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(_.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(bi(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Y.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Y.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(bt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(bi(this.url),{method:"HEAD"}),he(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=We((t=e.loggerName)!==null&&t!==void 0?t:Ie.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ys(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new fe,this.dataProcessLock=new fe,this.dcBufferStatus=new Map([[q.LOSSY,!0],[q.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(_.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(_.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(_.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(_.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(_.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(_.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(_.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(_.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,o,a,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=o,d.signalOpts=a,d.maxJoinAttempts=a.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,o,a,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{j.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(_.SignalConnected,u),u}catch(u){if(u instanceof U){if(u.reason===J.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,o,a,c,l)}else if(u.reason===J.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," – Retrying")),d.join(r,o,a,c,!0)}throw u}})()})}close(){return p(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(_.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(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 t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new wo,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new He("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(U.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(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,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==ee.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new Wu(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(_.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,a)=>{this.client.sendIceCandidate(o,a)},this.pcManager.onPublisherOffer=(o,a)=>{this.client.sendOffer(o,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,a,c)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),o===ee.CONNECTED){const u=this.pcState===Pe.New;this.pcState=Pe.Connected,u&&this.emit(_.Connected,e)}else o===ee.FAILED&&(this.pcState===Pe.Connected||this.pcState===Pe.Reconnecting)&&(this.pcState=Pe.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?bt.RR_SUBSCRIBER_FAILED:bt.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Y.RECONNECTING,l=[ee.FAILED,ee.CLOSING,ee.CLOSED].includes(o);d&&l&&!this._isClosed&&this.emit(_.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(_.MediaTrackAdded,o.track,o.streams[0],o.receiver)},gh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.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(_.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(_.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(_.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(_.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(_.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",bt.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({updatedAtInMs:Date.now(),maxAgeInMs:Lo,regionSettings:e.regions})),e.action){case Dt.DISCONNECT:this.emit(_.Disconnected,e==null?void 0:e.reason),this.close();break;case Dt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ds);break;case Dt.RESUME:this.handleDisconnect(Ds)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ci.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(Go,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ho,{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,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(q.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,ph),fh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(os())return yield this.createTransceiverRTCRtpSender(e,t,i);if(cs())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ne("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(os())return this.createSimulcastTransceiverSender(e,t,i,s);if(cs())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ne("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ne("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),ot(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ne("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ne("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){j.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===ci.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:ee.NEW)===ee.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof ne?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof Ut||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",bt.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(_.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new ne("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ut;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof U&&o.reason===J.NotAllowed?new ne("could not reconnect, token might be expired"):new Ut}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(_.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Y.CONNECTED)throw new Ut("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(_.Restarted)}catch(r){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ne("could not reconnect, url or token not saved");if(!this.pcManager)throw new ne("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof U&&s.reason===J.NotAllowed?new ne("could not reconnect, token might be expired"):s instanceof U&&s.reason===J.LeaveRequest?s:new Ut(r)}if(this.emit(_.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),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!==Y.CONNECTED)throw new Ut("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(_.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ne("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Pe.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield he(uh),!this.pcManager)throw new ne("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Pe.Connected}catch(e){throw this.pcState=Pe.Disconnected,U.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new me({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcResponse",value:new On({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,q.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new me({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcAck",value:new Mn({requestId:t})}});yield this.sendDataPacket(i,q.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Eu(e);if(r){const o=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new jr({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===q.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===q.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(q.RELIABLE);const t=this.dataChannelForKind(q.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(q.RELIABLE)})}waitForBufferStatusLow(e){return new Se((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new ne("engine closed"));for(this.once(_.Closing,s);!this.dcBufferStatus.get(e);)yield he(10);this.off(_.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new ne("PC manager is closed");const o=s?i.pcManager.subscriber:i.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw U.internal("".concat(a," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{j.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if((d==null?void 0:d.readyState)==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(o.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield he(50)}throw U.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ee.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new Se((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new Nt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new Nt("cannot negotiate on closed engine")),this.on(_.Closing,s),this.pcManager.publisher.once(Wt.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();cu(c)&&o.set(a.payload,c)}),this.emit(_.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof Nt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",bt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(_.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===q.LOSSY)return this.lossyDCSub;if(e===q.RELIABLE)return this.reliableDCSub}else{if(e===q.LOSSY)return this.lossyDC;if(e===q.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,f=new Array;e.forEach(g=>{g.isDesired!==u&&h.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new qn({answer:this.pcManager.mode==="publisher-only"?c?$t({sdp:c.sdp,type:c.type}):void 0:l?$t({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?a?$t({sdp:a.sdp,type:a.type}):void 0:d?$t({sdp:d.sdp,type:d.type}):void 0,subscription:new Wi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Gl(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,m)=>new ca({publisherSid:m,lastSeq:g}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new da({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(q.LOSSY),xe.PUBLISHER),t(this.dataChannelForKind(q.RELIABLE),xe.PUBLISHER),t(this.dataChannelForKind(q.LOSSY,!0),xe.SUBSCRIBER),t(this.dataChannelForKind(q.RELIABLE,!0),xe.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ue.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ce()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Ce()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[o]=r;return o===i});if(s)return s[1]}}}function gh(n){return n!==void 0&&n>13}function zo(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class Ko{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 Ee("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ge.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Ee("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ge.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class vh extends Ko{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new we,i=null,s=null;if(this.signal){const o=this.signal;s=()=>{var a;(a=t.reject)===null||a===void 0||a.call(t,o.reason)},o.addEventListener("abort",s),i=o}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:d}=yield Promise.race([e.read(),t.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(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,o;let a=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=Ge(c),u;u=yield l.next(),i=u.done,!i;d=!0){o=u.value,d=!1;const h=o;a.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(a)})()})}}class bh extends Ko{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=nn(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new we,s=null,r=null;if(this.signal){const a=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,a.reason)},a.addEventListener("abort",r),s=a}const o=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,c;try{const{done:d,value:l}=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(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Ee("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),ge.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw o(),d}}),return(){return p(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,o;let a="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=Ge(c),u;u=yield l.next(),i=u.done,!i;d=!0)o=u.value,d=!1,a+=o}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return a})()})}}class yh{constructor(){this.log=j,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Ee('A text stream handler for topic "'.concat(e,'" has already been set.'),ge.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Ee('A byte stream handler for topic "'.concat(e,'" has already been set.'),ge.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;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 Ee("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ge.AbnormalEnd);for(const[d,l]of a)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of o)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;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 o;const a=new we;a.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:nn(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(o=l,this.textStreamControllers.has(e.streamId))throw new Ee("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ge.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new vh(c,d,nn(e.totalLength),a),{identity:t})}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 o;const a=new we;a.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(o=l,this.textStreamControllers.has(e.streamId))throw new Ee("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ge.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new bh(c,d,nn(e.totalLength),a),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ge.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ge.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ge.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Ee("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ge.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Jo{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(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 Sh extends Jo{}class kh extends Jo{}const Yo=15e3;class Ch{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const g=c.reduce((m,k)=>m+k,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},l=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:a,attributes:t==null?void 0:t.attributes});return yield l.write(e),d(1,0),yield l.close(),t!=null&&t.attachments&&a&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={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,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?oe.GCM:oe.NONE},a=new Bi({streamId:r,mimeType:o.mimeType,topic:o.topic,timestamp:Tt(o.timestamp),totalLength:Tt(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new Zr({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"?Dn.UPDATE:Dn.CREATE})}}),c=e==null?void 0:e.destinationIdentities,d=new me({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(d,q.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(m){return p(this,void 0,void 0,function*(){for(const k of fu(m,Yo)){const S=new ji({content:k,streamId:r,chunkIndex:Tt(l)}),R=new me({destinationIdentities:c,value:{case:"streamChunk",value:S}});yield u.sendDataPacket(R,q.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const m=new qi({streamId:r}),k=new me({destinationIdentities:c,value:{case:"streamTrailer",value:m}});yield u.sendDataPacket(k,q.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let f=()=>p(this,void 0,void 0,function*(){yield g.close()});u.once(_.Closing,f);const g=new Sh(h,o,()=>this.engine.off(_.Closing,f));return g})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i==null?void 0:i.mimeType)!==null&&s!==void 0?s:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,o,a;const c=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e==null?void 0:e.destinationIdentities,l={id:c,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?oe.GCM:oe.NONE},u=new Bi({totalLength:Tt((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:Tt(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new ea({name:l.name})}}),h=new me({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,q.RELIABLE);let f=0;const g=new fe,m=this.engine,k=this.log,S=new WritableStream({write(I){return p(this,void 0,void 0,function*(){const b=yield g.lock();let y=0;try{for(;y<I.byteLength;){const E=I.slice(y,y+Yo),A=new me({destinationIdentities:d,value:{case:"streamChunk",value:new ji({content:E,streamId:c,chunkIndex:Tt(f)})}});yield m.sendDataPacket(A,q.RELIABLE),f+=1,y+=E.byteLength}}finally{b()}})},close(){return p(this,void 0,void 0,function*(){const I=new qi({streamId:c}),b=new me({destinationIdentities:d,value:{case:"streamTrailer",value:I}});yield m.sendDataPacket(b,q.RELIABLE)})},abort(I){k.error("Sink error:",I)}});return new kh(S,l)})}}class Xo extends T{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?P.Muted:P.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(P.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(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(),xs)),Hl()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(P.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Th extends Xo{constructor(e,t,i,s,r,o){super(e,t,T.Kind.Audio,i,o),this.monitorReceiver=()=>p(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=sn(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Be()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Be())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(ds(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&ds(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(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 t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}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,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),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(P.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(P.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={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})}),t})}}const Ls=100;class Eh extends Xo{constructor(e,t,i,s,r){super(e,t,T.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(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=sn(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Es(()=>{this.updateDimensions()},Ls),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===T.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Bt(this._mediaStreamTrack,t):Ft(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new wh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===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 t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,o=this.elementInfos.some(c=>c.pictureInPicture),a=this.elementInfos.some(c=>c.visible)&&!r||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-s<Ls){ue.setTimeout(()=>{this.updateVisibility()},Ls);return}this.lastVisible=a,this.emit(P.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>i+s&&(i=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(P.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?fo():t||(fo()>2?2:1)}}class wh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:o}=i;r===this.element&&(this.isIntersecting=o,this.isPiP=ki(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ki(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=ki(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Ns(e),this.isPiP=Ce()&&ki(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Ns(this.element),this.isPiP=ki(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,go().observe(this.element),mo().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=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=go())===null||e===void 0||e.unobserve(this.element),(t=mo())===null||t===void 0||t.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),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function ki(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ns(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Ns(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,o=n.offsetHeight,{hidden:a}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&c!=="none"}class Ke extends Ue.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=oe.NONE,this.log=j,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=We((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Ie.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=T.Source.Unknown}setTrack(e){this.track&&(this.track.off(P.Muted,this.handleMuted),this.track.off(P.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(P.Muted,this.handleMuted),e.on(P.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==oe.NONE}get audioTrack(){if(qe(this.track))return this.track}get videoTrack(){if(ot(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=T.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===T.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(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(Ke||(Ke={}));class Us extends Ke{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(P.Ended)},this.handleCpuConstrained=()=>{this.track&&ot(this.track)&&this.emit(P.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(P.Ended,this.handleTrackEnded),this.track.off(P.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(P.Ended,this.handleTrackEnded),e.on(P.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 p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(qe(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(de.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(de.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(de.TF_NOISE_SUPPRESSION),t.channelCount&&t.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 on(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=ao(n);let o=r.audio,a=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=no(r,Oo,Do),d=rs(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(le.userMediaPromiseMap.set("audioinput",l),l.catch(()=>le.userMediaPromiseMap.delete("audioinput"))),r.video&&(le.userMediaPromiseMap.set("videoinput",l),l.catch(()=>le.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let m;const k=f?d.audio:d.video;typeof k!="boolean"&&(m=k);const S=h.getSettings().deviceId;m!=null&&m.deviceId&&at(m.deviceId)!==S?m.deviceId=S:m||(m={deviceId:S});const R=Zu(h,m,e);return R.kind===T.Kind.Video?R.source=T.Source.Camera:R.kind===T.Kind.Audio&&(R.source=T.Source.Microphone),R.mediaStream=u,qe(R)&&i?yield R.setProcessor(i):ot(R)&&s&&(yield R.setProcessor(s)),R})))}catch(u){if(!t)throw u;return on(Object.assign(Object.assign({},n),{audio:o,video:a}),e)}})}function Ph(n){return p(this,void 0,void 0,function*(){return(yield on({audio:!1,video:!0}))[0]})}function Rh(n){return p(this,void 0,void 0,function*(){return(yield on({audio:!0,video:!1}))[0]})}var ht;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(ht||(ht={}));function _h(n){switch(n){case oi.EXCELLENT:return ht.Excellent;case oi.GOOD:return ht.Good;case oi.POOR:return ht.Poor;case oi.LOST:return ht.Lost;default:return ht.Unknown}}class Qo extends Ue.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.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===di.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Mt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:di.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ht.Unknown,this.log=j,this.log=We((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Ie.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new we,this.once(x.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(T.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(T.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(T.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 t;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===Mt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Mt.ACTIVE&&this.emit(x.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(x.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(x.ParticipantNameChanged,e)}_setAttributes(e){const t=zl(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(x.AttributesChanged,t)}setPermissions(e){var t,i,s,r,o,a;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((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,d&&this.emit(x.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(x.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=_h(e),t!==this._connectionQuality&&this.emit(x.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>qe(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(P.Muted,()=>{this.emit(x.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(x.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case T.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case T.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function xh(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new aa({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Ih extends Qo{constructor(e,t,i,s,r,o){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=oe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new we)},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,d,l,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,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("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,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,d;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new we),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:d,message:l}=a,u=this.pendingSignalRequests.get(c);u&&(d!==Vn.OK&&u.reject(new to(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=te.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);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=>xh(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),V(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),V(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),V(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),V(c))),this.emit(x.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>p(this,void 0,void 0,function*(){var c,d,l,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 g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var m=!0,k=Ge(g),S;S=yield k.next(),c=S.done,!c;m=!0){u=S.value,m=!1;const R=u;Vl(R)&&(this.log.debug("publish ".concat(R," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),V(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,R,f.options))}}catch(R){d={error:R}}finally{try{!m&&!c&&(l=k.return)&&(yield l.call(k))}finally{if(d)throw d.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=>p(this,void 0,void 0,function*(){if(a.source===T.Source.ScreenShare||a.source===T.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),V(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(ze(a)||ct(a))try{if(Ce())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===T.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),V(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),V(a))),ze(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),V(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==oe.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(_.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(_.Connected,this.handleReconnected).on(_.SignalConnected,this.handleSignalConnected).on(_.SignalRestarted,this.handleReconnected).on(_.SignalResumed,this.handleReconnected).on(_.Restarting,this.handleReconnecting).on(_.Resuming,this.handleReconnecting).on(_.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(_.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(_.Closing,this.handleClosing).on(_.SignalRequestResponse,this.handleSignalRequestResponse).on(_.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:o}=t;return(function*(){return new Se((a,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(g=>{let[m,k]=g;return this.attributes[m]===k||k===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),a();return}yield he(50)}c(new to("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(T.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(T.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(T.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?oe.GCM:oe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d==null?void 0:d.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case T.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case T.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case T.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new He(e)}}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(x.MediaDevicesError,d,as(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===T.Source.Microphone&&qe(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),V(u))),d.push(this.publishTrack(u,s));[a]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d}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===T.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(T.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(T.Source.Camera)||this.pendingPublishing.has(T.Source.Microphone))){this.pendingPublishing.add(T.Source.Camera),this.pendingPublishing.add(T.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(T.Source.Camera),this.pendingPublishing.delete(T.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=no(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield on(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(qe(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=T.Source.Microphone,this.emit(x.AudioStreamAcquired)),ot(a)&&(this.cameraError=void 0,a.source=T.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new es("getDisplayMedia not supported");e.resolution===void 0&&!iu()&&(e.resolution=ns.h1080fps30.resolution);const t=Wl(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new He("no video track found");const r=new an(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=T.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(i.getAudioTracks().length>0){this.emit(x.AudioStreamAcquired);const a=new rn(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=T.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,d,l;ze(i)&&i.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),qt(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let S;switch(i.source){case T.Source.Microphone:S="audioinput";break;case T.Source.Camera:S="videoinput"}S&&r.activeDeviceMap.has(S)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(S)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new rn(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new an(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new He("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(S=>{S.track&&S.track===i&&(h=S)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),V(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),g="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(c=f.forceStereo)!==null&&c!==void 0?c:g;m&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),V(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!su()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const k=new Promise((S,R)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Y.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:V(i)}));let I=!1;const b=setTimeout(()=>{I=!0,i.stop(),R(new eo("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),I)return;const y=yield this.publish(i,f,m);S(y)}else try{const I=yield this.publish(i,f,m);S(I)}catch(I){R(I)}}catch(I){R(I)}}));r.pendingPublishPromises.set(i,k);try{return yield k}catch(S){throw S}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new we),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),V(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Kl(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),V(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,o,a,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new eo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>qt(e)&&M.source===e.source)&&e.source!==T.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),V(e))),t.stopMicTrackOnMute&&qe(e)&&(e.stopOnMute=!0),e.source===T.Source.ScreenShare&&kt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Zl()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!eu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Ps),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===fi(M.mime))||(t.videoCodec=fi(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(P.Muted,this.onTrackMuted),e.on(P.Unmuted,this.onTrackUnmuted),e.on(P.Ended,this.handleTrackEnded),e.on(P.UpstreamPaused,this.onTrackUpstreamPaused),e.on(P.UpstreamResumed,this.onTrackUpstreamResumed),e.on(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const k=[],S=!(!((s=t.dtx)!==null&&s!==void 0)||s),R=e.getSourceTrackSettings();R.autoGainControl&&k.push(de.TF_AUTO_GAIN_CONTROL),R.echoCancellation&&k.push(de.TF_ECHO_CANCELLATION),R.noiseSuppression&&k.push(de.TF_NOISE_SUPPRESSION),R.channelCount&&R.channelCount>1&&k.push(de.TF_STEREO),S&&k.push(de.TF_NO_DTX),ze(e)&&e.hasPreConnectBuffer&&k.push(de.TF_PRECONNECT_BUFFER);const I=new li({cid:e.mediaStreamTrack.id,name:t.name,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),disableDtx:S,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:k});let b;if(e.kind===T.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const L=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:pi.h720.resolution;M={width:L.width,height:L.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{dims:M}))}I.width=M.width,I.height=M.height,ct(e)&&(Ae(m)&&(e.source===T.Source.ScreenShare&&(t.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),V(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),I.simulcastCodecs=[new Nn({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Ps}),t.backupCodec&&m!==t.backupCodec.codec&&I.encryption===oe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),I.simulcastCodecs.push(new Nn({codec:t.backupCodec.codec,cid:""})))),b=Ms(e.source===T.Source.ScreenShare,I.width,I.height,t),I.layers=Wo(I.width,I.height,b,Ae(t.videoCodec))}else e.kind===T.Kind.Audio&&(b=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new ne("cannot publish track when not connected");const y=()=>p(this,void 0,void 0,function*(){var M,O,L;if(!this.engine.pcManager)throw new ne("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(x.LocalSenderCreated,e.sender,e),ct(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=dh(e)),e.setDegradationPreference(t.degradationPreference)),b)if(kt()&&e.kind===T.Kind.Audio){let B;for(const G of this.engine.pcManager.publisher.getTransceivers())if(G.sender===e.sender){B=G;break}B&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:B,codec:"opus",maxbr:!((O=b[0])===null||O===void 0)&&O.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&Ae(e.codec)&&(!((L=b[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:I.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let E;const A=new Promise((M,O)=>p(this,void 0,void 0,function*(){var L;try{E=yield this.engine.addTrack(I),M(E)}catch(B){e.sender&&(!((L=this.engine.pcManager)===null||L===void 0)&&L.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(G=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{error:G}))})),O(B)}}));if(this.enabledPublishVideoCodecs.length>0)E=(yield Promise.all([A,y()]))[0];else{E=yield A;let M;if(E.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===T.Kind.Video){const O=fi(M);O!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{codec:O})),t.videoCodec=O,b=Ms(e.source===T.Source.ScreenShare,I.width,I.height,t))}yield y()}const D=new Us(e.kind,E,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(D.on(P.CpuConstrained,M=>this.onTrackCpuConstrained(M,D)),D.options=t,e.sid=E.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:E})),ct(e)?e.startMonitor(this.engine.client):ze(e)&&e.startMonitor(),this.addTrackPublication(D),this.emit(x.LocalTrackPublished,D),ze(e)&&E.audioFeatures.includes(de.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(x.LocalTrackSubscribed,L=>{if(L.trackSid===E.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),V(e))),e.stopPreConnectBuffer()}}),M&&new Promise((B,G)=>p(this,void 0,void 0,function*(){var se,be,ae,De,Ht,zt;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),V(e)));const Qe=setTimeout(()=>{G(new Error("agent not active within 10 seconds"))},1e4),Et=yield this.waitUntilActiveAgentPresent();clearTimeout(Qe),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),V(e)));const pn=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Et.identity],attributes:{trackId:D.trackSid,sampleRate:String((Ht=R.sampleRate)!==null&&Ht!==void 0?Ht:"48000"),channels:String((zt=R.channelCount)!==null&&zt!==void 0?zt:"1")}});try{for(var Kt=!0,Ye=Ge(M),Xe;Xe=yield Ye.next(),se=Xe.done,!se;Kt=!0){De=Xe.value,Kt=!1;const Jt=De;yield pn.write(Jt)}}catch(Jt){be={error:Jt}}finally{try{!Kt&&!se&&(ae=Ye.return)&&(yield ae.call(Ye))}finally{if(be)throw be.error}}yield pn.close(),B()}catch(Qe){G(Qe)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),V(e)))}).catch(B=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{error:B}))})}return D})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==oe.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new He("track is not published");if(!ct(e))throw new He("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),a=ah(e,t,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),V(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const d=new li({cid:c.mediaStreamTrack.id,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=Wo(d.width,d.height,a),!this.engine||this.engine.isClosed)throw new ne("cannot publish track when not connected");const l=()=>p(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(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(qt(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),V(e))),yield d)}const r=this.getPublicationForTrack(e),o=r?V(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(P.Muted,this.onTrackMuted),e.off(P.Unmuted,this.onTrackUnmuted),e.off(P.Ended,this.handleTrackEnded),e.off(P.UpstreamPaused,this.onTrackUpstreamPaused),e.off(P.UpstreamResumed,this.onTrackUpstreamResumed),e.off(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ee.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),ct(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(a=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case T.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case T.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(x.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Se((r,o)=>p(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),a.push(c))}),yield Promise.all(a.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==T.Source.ScreenShare&&d.source!==T.Source.ScreenShareAudio&&(ze(d)||ct(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?q.RELIABLE:q.LOSSY,o=s.destinationIdentities,a=s.topic;let c=new In({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:a});const d=new me({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new me({kind:q.RELIABLE,value:{case:"sipDtmf",value:new $r({code:e,digit:t})}});yield this.engine.sendDataPacket(i,q.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new me({value:{case:"chatMessage",value:new Fi(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(x.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new me({value:{case:"chatMessage",value:new Fi(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp),editTimestamp:X.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(x.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const o=7e3,a=o+1e3;return new Se((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if(_s(s)>No){d(te.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&je((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(te.builtIn("UNSUPPORTED_SERVER"));return}const g=Math.max(r,a),m=crypto.randomUUID();yield this.publishRpcRequest(t,m,i,s,g);const k=setTimeout(()=>{this.pendingAcks.delete(m),d(te.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(m),clearTimeout(S)},o);this.pendingAcks.set(m,{resolve:()=>{clearTimeout(k)},participantIdentity:t});const S=setTimeout(()=>{this.pendingResponses.delete(m),d(te.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(m,{resolve:(R,I)=>{clearTimeout(S),this.pendingAcks.has(m)&&(this.log.warn("RPC response received before ack",m),this.pendingAcks.delete(m),clearTimeout(k)),I?d(I):c(R??"")},participantIdentity:t})}))}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const o=new me({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcRequest",value:new An({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,q.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,te.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),V(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new we),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(ze(s)||ct(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield he(20)}})}}class Ah extends Ke{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(P.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new Wi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Gr({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ke.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ke.SubscriptionStatus.Subscribed:Ke.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ke.PermissionStatus.Allowed:Ke.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 t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(ms(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ms(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Te.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(P.VisibilityChanged,this.handleVisibilityChange),s.off(P.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(P.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(P.VisibilityChanged,this.handleVisibilityChange),e.on(P.Ended,this.handleEnded),this.emit(P.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(P.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?P.Muted:P.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(P.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(P.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 ms(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ia({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===T.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)oo(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Jl(this.trackInfo,this.requestedMaxQuality);i&&oo(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.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:Te.HIGH})),e.quality=Te.HIGH)}this.emit(P.UpdateSettings,e)}}class cn extends Qo{static fromParticipantInfo(e,t,i){return new cn(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:di.STANDARD;super(t,i||"",s,r,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(P.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(P.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(P.SubscriptionPermissionChanged,t=>{this.emit(x.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(x.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(x.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(x.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(x.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:T.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:T.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(l=>{!a&&e.kind===l.kind.toString()&&(a=l)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(x.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,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),V(a))),this.emit(x.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new Eh(e,t,s,r):d=new Th(e,t,s,this.audioContext,this.audioOutput),d.source=a.source,d.isMuted=a.isMuted,d.setMediaStream(i),d.start(),a.setTrack(d),this.volumeMap.has(a.source)&&fs(d)&&qe(d)&&d.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 t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=T.kindFromProto(s.type);if(!c)return;a=new Ah(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),i.set(s.sid,a);const d=Array.from(this.trackPublications.values()).find(l=>l.source===(a==null?void 0:a.source));d&&a.source!==T.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:V(d),newTrack:V(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),V(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(x.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case T.Kind.Audio:this.audioTrackPublications.delete(e);break;case T.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(x.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;qe(i.track)&&fs(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var H;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(H||(H={}));const Mh=4*1e3;class Gt extends Ue.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,o;if(super(),t=this,this.state=H.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=j,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,c,d)=>p(this,void 0,void 0,function*(){var l;if(!tu())throw Be()?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 u=yield this.disconnectLock.lock();if(this.state===H.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(H.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==yo(a)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),jt(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new W(a,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(g=>{var m;(m=this.regionUrlProvider)===null||m===void 0||m.setServerReportedRegions(g)}).catch(g=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:g}))}));const h=(g,m,k)=>p(this,void 0,void 0,function*(){var S,R;this.abortController&&this.abortController.abort();const I=new AbortController;this.abortController=I,u==null||u();try{if(yield Vt.getInstance().getBackOffPromise(a),I.signal.aborted)throw U.cancelled("Connection attempt aborted");yield this.attemptConnection(k??a,c,d,I),this.abortController=void 0,g()}catch(b){if(this.regionUrlProvider&&b instanceof U&&b.reason!==J.Cancelled&&b.reason!==J.NotAllowed){let y=null;try{this.log.debug("Fetching next region"),y=yield this.regionUrlProvider.getNextBestRegionUrl((S=this.abortController)===null||S===void 0?void 0:S.signal)}catch(E){if(E instanceof U&&(E.status===401||E.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(E);return}}[J.InternalError,J.ServerUnreachable,J.Timeout].includes(b.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Vt.getInstance().addFailedConnectionAttempt(a)),y&&!(!((R=this.abortController)===null||R===void 0)&&R.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(b.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield h(g,m,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,bo(b)),m(b))}else{let y=_e.UNKNOWN_REASON;b instanceof U&&(y=bo(b)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),m(b)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new we((g,m)=>{h(g,m,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,g,m;const k=yield d.join(a,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let S=k.serverInfo;if(S||(S={version:k.serverVersion,region:k.serverRegion}),this.serverInfo=S,this.log.debug("connected to Livekit Server ".concat(Object.entries(S).map(R=>{let[I,b]=R;return"".concat(I,": ").concat(b)}).join(", ")),{room:(f=k.room)===null||f===void 0?void 0:f.name,roomSid:(g=k.room)===null||g===void 0?void 0:g.sid,identity:(m=k.participant)===null||m===void 0?void 0:m.identity}),!S.version)throw new Ul("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),k}),this.applyJoinResponse=a=>{const c=a.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===H.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Rs),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const g=l.signal.aborted?U.cancelled("Signal connection aborted"):U.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(g.message="".concat(g.message,": ").concat(f.message)),f instanceof U&&(g.reason=f.reason,g.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),g}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),U.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Ce()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ce()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(H.Connected),this.emit(w.Connected),Vt.getInstance().resetFailedConnectionAttempts(a),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,g;const m=yield l.disconnectLock.lock();try{if(l.state===H.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===H.Connecting||l.state===H.Reconnecting||l.isResuming){const k="Abort connection attempt due to user initiated disconnect";l.log.warn(k,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(k),(g=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||g===void 0||g.call(f,U.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,_e.CLIENT_INITIATED),l.engine=void 0}finally{m()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const a=[],c=ke();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=ps();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,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(w.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const a=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.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 a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(H.Reconnecting)&&this.emit(w.Reconnecting)},this.handleSignalRestarted=a=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(H.Connected),this.emit(w.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===Mt.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=a=>{const c=[],d={};a.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(w.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=a=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),a.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(w.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=T.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(x.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(w.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(a.trackSid);d&&d.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(a.trackSid);d&&d.setSubscriptionError(a.err)},this.handleDataPacket=(a,c)=>{const d=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(d,a.value.value,a.kind,c);else if(a.value.case==="transcription")this.handleTranscription(d,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(d,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(d,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,d);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a,c);else if(a.value.case==="rpcRequest"){const l=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(a,c,d,l)=>{this.emit(w.DataReceived,c.payload,a,d,c.topic,l),a==null||a.emit(x.DataReceived,c.payload,d,l)},this.handleSipDtmf=(a,c)=>{this.emit(w.SipDTMFReceived,c,a),a==null||a.emit(x.SipDTMFReceived,c)},this.handleTranscription=(a,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d==null?void 0:d.trackPublications.get(c.trackId),u=lu(c,this.transcriptionReceivedTimes);l==null||l.emit(P.TranscriptionReceived,u),d==null||d.emit(x.TranscriptionReceived,u,l),this.emit(w.TranscriptionReceived,u,d,l)},this.handleChatMessage=(a,c)=>{const d=uu(c);this.emit(w.ChatMessage,d,a)},this.handleMetrics=(a,c)=>{this.emit(w.MetricsReceived,a,c)},this.handleDataStream=(a,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(a,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(w.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(w.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(w.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(w.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var a;((a=ke())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(w.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const c=this.roomInfo;this.roomInfo=a,c&&c.metadata!==a.metadata&&this.emitWhenConnected(w.RoomMetadataChanged,a.metadata),(c==null?void 0:c.activeRecording)!==a.activeRecording&&this.emitWhenConnected(w.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(w.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(w.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(w.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(w.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(w.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var c;(c=a==null?void 0:a.onPublish)===null||c===void 0||c.call(a,this)},this.onLocalTrackPublished=a=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=a.track)===null||c===void 0||c.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=a.track)===null||d===void 0||d.on(P.Restarted,this.onLocalTrackRestarted),(h=(u=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(w.LocalTrackPublished,a,this.localParticipant),ze(a.track)&&(yield a.track.checkForSilence())&&this.emit(w.LocalAudioSilenceDetected,a);const g=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),m=as(a.source);m&&g&&g!==this.localParticipant.activeDeviceMap.get(m)&&(this.localParticipant.activeDeviceMap.set(m,g),this.emit(w.ActiveDeviceChanged,m,g))}),this.onLocalTrackUnpublished=a=>{var c,d;(c=a.track)===null||c===void 0||c.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=a.track)===null||d===void 0||d.off(P.Restarted,this.onLocalTrackRestarted),this.emit(w.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>p(this,void 0,void 0,function*(){const c=yield a.getDeviceId(!1),d=as(a.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(w.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=a=>{this.emit(w.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,c)=>{this.emit(w.MediaDevicesError,a,c)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(w.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(w.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},$u),e),this.log=We((i=this.options.loggerName)!==null&&i!==void 0?i:Ie.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Oo),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Do),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Vu),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new yh,this.outgoingDataStreamManager=new Ch(this.engine,this.log),this.disconnectLock=new fe,this.localParticipant=new Ih("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",at(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",at(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",at(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),Ce()){const a=new AbortController;(o=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||o===void 0||o.call(r,"devicechange",this.handleDeviceChange,{signal:a.signal}),Gt.cleanupRegistry&&Gt.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(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;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new wu(i,t),this.e2eeManager.on(lt.ParticipantEncryptionStatusChanged,(s,r)=>{pu(r)&&(this.isE2EEEnabled=s),this.emit(w.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(lt.EncryptionError,(s,r)=>{const o=r?this.getParticipantByIdentity(r):void 0;this.emit(w.EncryptionError,s,o)}),(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,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===H.Disconnected?Se.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Se.resolve(this.roomInfo.sid):new Se((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(_.RoomUpdate,i),e(s.sid))};this.engine.on(_.RoomUpdate,i),this.once(w.Disconnected,()=>{this.engine.off(_.RoomUpdate,i),t(new ne("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new mh(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(_.ParticipantUpdate,this.handleParticipantUpdates).on(_.RoomUpdate,this.handleRoomUpdate).on(_.SpeakersChanged,this.handleSpeakersChanged).on(_.StreamStateChanged,this.handleStreamStateUpdate).on(_.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(_.SubscriptionError,this.handleSubscriptionError).on(_.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(_.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(_.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(_.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(_.DataPacketReceived,this.handleDataPacket).on(_.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(H.SignalReconnecting)&&this.emit(w.SignalReconnecting)}).on(_.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(H.Connected)&&this.emit(w.Reconnected)}).on(_.SignalResumed,()=>{this.bufferedEvents=[],(this.state===H.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(_.Restarting,this.handleRestarting).on(_.SignalRestarted,this.handleSignalRestarted).on(_.Offline,()=>{this.setAndEmitConnectionState(H.Reconnecting)&&this.emit(w.Reconnecting)}).on(_.DCBufferStatusChanged,(e,t)=>{this.emit(w.DCBufferStatusChanged,e,t)}).on(_.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(x.LocalTrackSubscribed,t),this.emitWhenConnected(w.LocalTrackSubscribed,t,this.localParticipant)}).on(_.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(w.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 t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return le.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===H.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(jt(new URL(e))&&t){this.regionUrlProvider=new W(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===H.Disconnected&&(this.regionUrl=i,yield fetch(bi(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(bi(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,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Ne({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ne({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ne({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ne({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=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({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":s=new Ne({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Gi({reason:_e.CLIENT_INITIATED,action:Dt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ne({scenario:{case:"subscriberBandwidth",value:Tt(t)}});break;case"leave-full-reconnect":s=new Ne({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,d,l,u,h,f;let g=!0,m=!1;const k=o?{exact:s}:s;if(i==="audioinput"){m=r.localParticipant.audioTrackPublications.size===0;const S=(a=r.getActiveDevice(i))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=k;const R=Array.from(r.localParticipant.audioTrackPublications.values()).filter(b=>b.source===T.Source.Microphone);try{g=(yield Promise.all(R.map(b=>{var y;return(y=b.audioTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(b=>b===!0)}catch(b){throw r.options.audioCaptureDefaults.deviceId=S,b}const I=R.some(b=>{var y,E;return(E=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&E!==void 0?E:!1});g&&I&&(m=!0)}else if(i==="videoinput"){m=r.localParticipant.videoTrackPublications.size===0;const S=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=k;const R=Array.from(r.localParticipant.videoTrackPublications.values()).filter(b=>b.source===T.Source.Camera);try{g=(yield Promise.all(R.map(b=>{var y;return(y=b.videoTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(b=>b===!0)}catch(b){throw r.options.videoCaptureDefaults.deviceId=S,b}const I=R.some(b=>{var y,E;return(E=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&E!==void 0?E:!1});g&&I&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!ds()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield le.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const S=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(R=>R.setAudioOutput({deviceId:s})))}catch(R){throw r.options.audioOutput.deviceId=S,R}}return m&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(w.ActiveDeviceChanged,i,s)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(x.AttributesChanged,this.onLocalAttributesChanged).on(x.TrackMuted,this.onLocalTrackMuted).on(x.TrackUnmuted,this.onLocalTrackUnmuted).on(x.LocalTrackPublished,this.onLocalTrackPublished).on(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(x.MediaDevicesError,this.onMediaDevicesError).on(x.AudioStreamAcquired,this.startAudio).on(x.ChatMessage,this.onLocalChatMessageSent).on(x.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,t,i){if(this.state===H.Connecting||this.state===H.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(w.Reconnected,u),this.off(w.Connected,u),this.off(w.Disconnected,h)};this.once(w.Reconnected,u),this.once(w.Connected,u),this.once(w.Disconnected,h);return}if(this.state===H.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 s=Ql(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!a.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}a=u}a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(o,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:o,trackId:a}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,a,t,i,d);l!=null&&l.isEncrypted&&!this.e2eeManager&&this.emit(w.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==H.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(o=>{r.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var o,a,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((o=r.track)===null||o===void 0||o.detach(),(a=r.track)===null||a===void 0||a.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(x.AttributesChanged,this.onLocalAttributesChanged).off(x.TrackMuted,this.onLocalTrackMuted).off(x.TrackUnmuted,this.onLocalTrackUnmuted).off(x.LocalTrackPublished,this.onLocalTrackPublished).off(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(x.MediaDevicesError,this.onMediaDevicesError).off(x.AudioStreamAcquired,this.startAudio).off(x.ChatMessage,this.onLocalChatMessageSent).off(x.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),Ce()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(H.Disconnected),this.emit(w.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(w.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,o){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,te.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,t,null,te.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});_s(l)>No?(c=te.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof te?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=te.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=le.getInstance().previousDevices,r=yield le.getInstance().getDevices(void 0,!1),o=ke();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(w.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const d=$l(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.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"&&!gi()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!gi())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;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=ro())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),he(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(w.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=cn.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new cn(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(w.ParticipantConnected,i),i.on(x.TrackPublished,s=>{this.emitWhenConnected(w.TrackPublished,s,i)}).on(x.TrackSubscribed,(s,r)=>{s.kind===T.Kind.Audio?(s.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===T.Kind.Video&&(s.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(w.TrackSubscribed,s,r,i)}).on(x.TrackUnpublished,s=>{this.emit(w.TrackUnpublished,s,i)}).on(x.TrackUnsubscribed,(s,r)=>{this.emit(w.TrackUnsubscribed,s,r,i)}).on(x.TrackMuted,s=>{this.emitWhenConnected(w.TrackMuted,s,i)}).on(x.TrackUnmuted,s=>{this.emitWhenConnected(w.TrackUnmuted,s,i)}).on(x.ParticipantMetadataChanged,s=>{this.emitWhenConnected(w.ParticipantMetadataChanged,s,i)}).on(x.ParticipantNameChanged,s=>{this.emitWhenConnected(w.ParticipantNameChanged,s,i)}).on(x.AttributesChanged,s=>{this.emitWhenConnected(w.ParticipantAttributesChanged,s,i)}).on(x.ConnectionQualityChanged,s=>{this.emitWhenConnected(w.ConnectionQualityChanged,s,i)}).on(x.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(w.ParticipantPermissionsChanged,s,i)}).on(x.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionStatusChanged,s,r,i)}).on(x.TrackSubscriptionFailed,(s,r)=>{this.emit(w.TrackSubscriptionFailed,s,i,r)}).on(x.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionPermissionChanged,s,r,i)}).on(x.Active,()=>{this.emitWhenConnected(w.ParticipantActive,i),i.kind===di.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&hu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}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,_e.STATE_MISMATCH))):e=0},Mh)}clearConnectionReconcile(){this.connectionReconcileInterval&&ue.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(w.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===H.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===H.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ni({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:X.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new yt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected),this.emit(w.Connected),this.setAndEmitConnectionState(H.Connected),o.video){const c=new Us(T.Kind.Video,new Ot({source:re.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO,name:"video-dummy"}),new an(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:vo(160*((i=a.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(x.LocalTrackPublished,c)}if(o.audio){const c=new Us(T.Kind.Audio,new Ot({source:re.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO}),new rn(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ps(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(x.LocalTrackPublished,c)}for(let c=0;c<a.count-1;c+=1){let d=new yt({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:Mt.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(a.video){const u=vo(160*((r=a.aspectRatios[c%a.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new Ot({source:re.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(a.audio){const u=ps(),h=new Ot({source:re.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==w.ActiveSpeakersChanged&&e!==w.TranscriptionReceived){const r=Zo(i).filter(o=>o!==void 0);(e===w.TrackSubscribed||e===w.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Gt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Zo(n){return n.map(e=>{if(e)return Array.isArray(e)?Zo(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Oe;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Oe||(Oe={}));class pt extends Ue.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Oe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Gt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Oe.IDLE)throw Error("check is running already");this.setStatus(Oe.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Oe.SKIPPED&&this.setStatus(this.isSuccess()?Oe.SUCCESS:Oe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===H.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==H.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Oe.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(w.Reconnecting,()=>{t=!0}),this.room.once(w.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield he(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 Oh extends pt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new W(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){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")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,d="A".repeat(o),l=Date.now();for(let g=0;g<c;g++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Fs=1e4;class Dh extends pt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):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/(Fs/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Fs/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Fs)),clearInterval(u),a.stop(),t.remove(),yield this.disconnect(),l})}}class Lh extends pt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Rh();if(yield so(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.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 Nh extends pt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Ph();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,o,a,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(o=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=l.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const m=f.getImageData(0,0,d.width,d.height).data;let k=!0;for(let S=0;S<m.length;S+=4)if(m[S]!==0||m[S+1]!==0||m[S+2]!==0){k=!1;break}k?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class Uh extends pt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const o=new Promise(d=>{setTimeout(d,5e3),r=d}),a=()=>{i=!0};t.on(w.SignalReconnecting,a).on(w.Reconnecting,a).on(w.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield o,i){if(!s||t.state!==H.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 Fh extends pt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;jt(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new W(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new ys,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,a=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(a=!0,c=!0):l.startsWith("turns:")&&(a=!0,c=!0,o=!0),l.startsWith("stun:")&&(c=!0);c?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Bh extends pt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(w.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,o)=>{if(r.candidate){const a=new RTCIceCandidate(r);let c="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(jh(a.address)?c+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,c+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,o)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(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(),j.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"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function jh(n){const e=n.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 t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class qh extends pt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new ys,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(jt(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const c=yield new W(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===zr.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class Lp extends Ue.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Oe.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Oe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(qh)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Bh)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Fh)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Uh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Lh)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Nh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Dh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Oh)})}}function $(n,e,t){return(e=$h(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Vh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function $h(n){var e=Vh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class ve extends Error{constructor(e,t){var i;super(e,t),$(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}$(ve,"code","ERR_JOSE_GENERIC");class Wh extends ve{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),$(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),$(this,"claim",void 0),$(this,"reason",void 0),$(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}$(Wh,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Gh extends ve{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),$(this,"code","ERR_JWT_EXPIRED"),$(this,"claim",void 0),$(this,"reason",void 0),$(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}$(Gh,"code","ERR_JWT_EXPIRED");class Hh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}$(Hh,"code","ERR_JOSE_ALG_NOT_ALLOWED");class zh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JOSE_NOT_SUPPORTED")}}$(zh,"code","ERR_JOSE_NOT_SUPPORTED");class Kh extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWE_DECRYPTION_FAILED")}}$(Kh,"code","ERR_JWE_DECRYPTION_FAILED");class Jh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWE_INVALID")}}$(Jh,"code","ERR_JWE_INVALID");class Yh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWS_INVALID")}}$(Yh,"code","ERR_JWS_INVALID");class Xh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWT_INVALID")}}$(Xh,"code","ERR_JWT_INVALID");class Qh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWK_INVALID")}}$(Qh,"code","ERR_JWK_INVALID");class Zh extends ve{constructor(){super(...arguments),$(this,"code","ERR_JWKS_INVALID")}}$(Zh,"code","ERR_JWKS_INVALID");class ep extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}$(ep,"code","ERR_JWKS_NO_MATCHING_KEY");class tp extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,Symbol.asyncIterator,void 0),$(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}$(tp,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class ip extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWKS_TIMEOUT")}}$(ip,"code","ERR_JWKS_TIMEOUT");class np extends ve{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),$(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}$(np,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class ec extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??"https://voice.hanc.ai"}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e}){if(!(this.room&&this.room.state==="connected")){this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const t=new Gt;this.room=t,this.setupRoomEventListeners(t);const i=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now()}})});if(!i.ok){const c=await i.text();throw new Error(`Failed to get room token: ${i.status} ${c}`)}const{token:s,url:r,room_name:o,user_identity:a}=await i.json();this.roomName=o,this.userIdentity=a,await t.connect(r,s),this.updateStatus("connected"),this.isReady=!0,await this.enableMicrophone(t),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:o,identity:a}}))}catch(t){this.error=`Connection failed: ${t instanceof Error?t.message:String(t)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}setupRoomEventListeners(e){e.on(w.Connected,()=>{this.updateStatus("connected"),this.isReady=!0}),e.on(w.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(w.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const i=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");i&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:i}}))}),e.on(w.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const i=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");i&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:i}}))}),e.on(w.TrackSubscribed,(t,i,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}))}}),e.on(w.TrackUnsubscribed,(t,i,s)=>{t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(w.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(w.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(i=>i.includes("agent")||i.includes("voice-assistant")||i.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}async enableMicrophone(e){try{await e.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled"))}catch(t){this.error=`Failed to enable microphone: ${t instanceof Error?t.message:String(t)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),i=new TextEncoder().encode(e);await this.room.localParticipant.publishData(i,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");try{await this.room.disconnect(),this.room=null,this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.dispatchEvent(new CustomEvent("call-ended"))}catch(e){this.error=`Error ending call: ${e instanceof Error?e.message:String(e)}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}const sp=/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,rp=/^rgba?\(([^)]+)\)$/i,ap=/^hsla?\(([^)]+)\)$/i;let Bs=null;function Je(n,e,t){return Math.min(t,Math.max(e,n))}function tc(n){const e=sp.exec(n);if(!e)return null;let t=e[1];if((t.length===3||t.length===4)&&(t=t.split("").map(o=>o+o).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const i=parseInt(t.slice(0,2),16),s=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);return{r:i,g:s,b:r}}function ic(n){const e=rp.exec(n);if(!e)return null;const t=e[1].trim(),s=(t.includes("/")?t.split("/")[0].trim():t).split(/[\s,]+/).map(d=>d.trim()).filter(Boolean);if(s.length<3)return null;const r=d=>{if(d.endsWith("%")){const l=Number.parseFloat(d);return Je(l/100*255,0,255)}return Je(Number.parseFloat(d),0,255)},o=r(s[0]),a=r(s[1]),c=r(s[2]);return Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(c)?null:{r:o,g:a,b:c}}function op(n){const e=ap.exec(n);if(!e)return null;const t=e[1].trim(),s=(t.includes("/")?t.split("/")[0].trim():t).split(/[\s,]+/).map(k=>k.trim()).filter(Boolean);if(s.length<3)return null;const r=Number.parseFloat(s[0]);if(Number.isNaN(r))return null;const o=k=>{const S=Number.parseFloat(k);return Number.isNaN(S)?null:k.endsWith("%")||S>1?Je(S/100,0,1):Je(S,0,1)},a=o(s[1]),c=o(s[2]);if(a===null||c===null)return null;const d=(r%360+360)%360,l=(1-Math.abs(2*c-1))*a,u=l*(1-Math.abs(d/60%2-1)),h=c-l/2;let f=0,g=0,m=0;return d<60?(f=l,g=u):d<120?(f=u,g=l):d<180?(g=l,m=u):d<240?(g=u,m=l):d<300?(f=u,m=l):(f=l,m=u),{r:Math.round(Je((f+h)*255,0,255)),g:Math.round(Je((g+h)*255,0,255)),b:Math.round(Je((m+h)*255,0,255))}}function cp(){if(Bs)return Bs;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(Bs=e,e):null}function dp(n){const e=cp();if(!e||typeof CSS<"u"&&CSS.supports&&!CSS.supports("color",n))return null;e.fillStyle="#000000",e.fillStyle=n;const t=e.fillStyle.toString();return tc(t)||ic(t)}function dn(n){const e=n.trim();return tc(e)||ic(e)||op(e)||dp(e)}function nc(n){const e=dn(n);if(!e)return null;const t=o=>{const a=o/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)},i=t(e.r),s=t(e.g),r=t(e.b);return .2126*i+.7152*s+.0722*r}function pe(n,e,t){const i=dn(n),s=dn(e);if(!i&&!s)return n;if(!i&&s)return`rgb(${s.r}, ${s.g}, ${s.b})`;if(i&&!s)return e;const r=Je(t,0,1),o=Math.round(i.r+(s.r-i.r)*r),a=Math.round(i.g+(s.g-i.g)*r),c=Math.round(i.b+(s.b-i.b)*r);return`rgb(${o}, ${a}, ${c})`}function sc(n,e){const t=dn(n);if(!t)return n;const i=Je(e,0,1);return`rgba(${t.r}, ${t.g}, ${t.b}, ${i})`}const rc=Pt`
240
245
  <svg
241
246
  xmlns="http://www.w3.org/2000/svg"
242
247
  width="22"
@@ -257,7 +262,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
257
262
  0 0 2.81.7A2 2 0 0 1 22 16.92z"
258
263
  />
259
264
  </svg>
260
- `,tc=Pt`
265
+ `,ac=Pt`
261
266
  <svg
262
267
  xmlns="http://www.w3.org/2000/svg"
263
268
  width="22"
@@ -280,8 +285,8 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
280
285
  />
281
286
  <line x1="22" x2="2" y1="2" y2="22" />
282
287
  </svg>
283
- `,sp={primary:"#8b5cf6",secondary:"#6366f1",accent:"#a855f7",glow:"#8b5cf6",background:"rgba(255, 255, 255, 0.03)",text:"rgba(255, 255, 255, 0.9)",statusText:"rgba(167, 139, 250, 0.9)",button:"#8b5cf6",buttonText:"#ffffff",buttonHover:"#7c3aed",buttonActive:"#ef4444"},rp={orbDiameter:180,widgetWidth:320,widgetPadding:24,borderRadius:28,buttonHeight:52,buttonRadius:14},ap={intensity:"medium",idleSpeed:.5,responseSpeed:.7,particlesCount:20,glowIntensity:.6,smoothing:.08,idleAnimation:!0},op={title:"AI Assistant",statusIdle:"Ready to connect",statusConnecting:"Connecting...",statusActive:"Listening...",statusError:"Connection error",buttonStart:"Start Call",buttonConnecting:"Connecting...",buttonEnd:"End Call"},cp={showTitle:!0,showStatus:!0,showGlow:!0,compactMode:!1,darkMode:!0},dp={placement:"bottom-right",offsetX:24,offsetY:24},ic={"liquid-purple":{style:"liquid-glass",colors:{primary:"#8b5cf6",secondary:"#6366f1",accent:"#a855f7",glow:"#8b5cf6",statusText:"rgba(167, 139, 250, 0.9)",button:"#8b5cf6",buttonHover:"#7c3aed"}},"liquid-cyan":{style:"liquid-glass",colors:{primary:"#06b6d4",secondary:"#0891b2",accent:"#22d3ee",glow:"#06b6d4",statusText:"rgba(34, 211, 238, 0.9)",button:"#06b6d4",buttonHover:"#0891b2"}},"liquid-pink":{style:"liquid-glass-premium",colors:{primary:"#ec4899",secondary:"#db2777",accent:"#f472b6",glow:"#ec4899",statusText:"rgba(244, 114, 182, 0.9)",button:"#ec4899",buttonHover:"#db2777"}},"neural-green":{style:"neural-liquid",colors:{primary:"#22c55e",secondary:"#16a34a",accent:"#4ade80",glow:"#22c55e",statusText:"rgba(74, 222, 128, 0.9)",button:"#22c55e",buttonHover:"#16a34a"}},"neural-blue":{style:"neural-liquid",colors:{primary:"#3b82f6",secondary:"#2563eb",accent:"#60a5fa",glow:"#3b82f6",statusText:"rgba(96, 165, 250, 0.9)",button:"#3b82f6",buttonHover:"#2563eb"}},"orbit-blue":{style:"neural-orbit",colors:{primary:"#0ea5e9",secondary:"#0284c7",accent:"#38bdf8",glow:"#0ea5e9",statusText:"rgba(56, 189, 248, 0.9)",button:"#0ea5e9",buttonHover:"#0284c7"}},"synaptic-purple":{style:"synaptic-core",colors:{primary:"#a855f7",secondary:"#9333ea",accent:"#c084fc",glow:"#a855f7",statusText:"rgba(192, 132, 252, 0.9)",button:"#a855f7",buttonHover:"#9333ea"}},"minimal-dark":{style:"liquid-glass",colors:{primary:"#ffffff",secondary:"#a1a1aa",accent:"#f4f4f5",glow:"rgba(255, 255, 255, 0.3)",background:"rgba(0, 0, 0, 0.8)",text:"#ffffff",statusText:"rgba(255, 255, 255, 0.6)",button:"#ffffff",buttonText:"#18181b",buttonHover:"#e4e4e7"},display:{darkMode:!0}},"minimal-light":{style:"liquid-glass",colors:{primary:"#18181b",secondary:"#52525b",accent:"#3f3f46",glow:"rgba(0, 0, 0, 0.2)",background:"rgba(255, 255, 255, 0.9)",text:"#18181b",statusText:"rgba(24, 24, 27, 0.6)",button:"#18181b",buttonText:"#ffffff",buttonHover:"#27272a"},display:{darkMode:!1}}};function cn(n){return ic[n]||ic["liquid-purple"]}function nc(n){return{agentId:n.agentId||"",style:n.style||"liquid-glass",colors:{...sp,...n.colors||{}},size:{...rp,...n.size||{}},animation:{...ap,...n.animation||{}},text:{...op,...n.text||{}},display:{...cp,...n.display||{}},position:{...dp,...n.position||{}}}}const lp=.3,up=.4,hp=.4,pp=.15,fp="135deg",mp=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,gp=/^rgba?\(([^)]+)\)$/i;function dn(n,e){const t=n.trim(),i=mp.exec(t);if(i){let r=i[1];r.length===3&&(r=r.split("").map(d=>d+d).join(""));const o=parseInt(r.slice(0,2),16),a=parseInt(r.slice(2,4),16),c=parseInt(r.slice(4,6),16);return`rgba(${o}, ${a}, ${c}, ${e})`}const s=gp.exec(t);if(s){const r=s[1].split(",").map(o=>o.trim());if(r.length>=3){const[o,a,c]=r;return`rgba(${o}, ${a}, ${c}, ${e})`}}return n}function Fs(n,e){return`linear-gradient(${fp}, ${n} 0%, ${e} 100%)`}function ln(n,e){const t=e.button,i=e.buttonHover,s=e.buttonActive;n.style.setProperty("--hanc-button",Fs(t,i)),n.style.setProperty("--hanc-button-hover",Fs(i,t)),n.style.setProperty("--hanc-button-active",Fs(s,s)),n.style.setProperty("--hanc-button-text",e.buttonText),n.style.setProperty("--hanc-button-shadow",dn(t,lp)),n.style.setProperty("--hanc-button-shadow-hover",dn(t,up)),n.style.setProperty("--hanc-button-shadow-active",dn(s,hp)),n.style.setProperty("--hanc-glow-shadow",dn(e.glow,pp))}class Ti{constructor(e,t,i,s){this.colorTransitionSpeed=.08,this.time=0,this.audioLevel=0,this.targetAudioLevel=0,this.isActive=!1,this.animationId=null,this.animate=()=>{this.update(),this.render(),this.animationId=requestAnimationFrame(this.animate)},this.canvas=e;const r=e.getContext("2d");if(!r)throw new Error("Could not get 2D context");this.ctx=r,this.size=t,this.centerX=t/2,this.centerY=t/2,this.colors={...i},this.targetColors={...i},this.animation=s,this.setupCanvas()}setupCanvas(){const e=window.devicePixelRatio||1;this.canvas.width=this.size*e,this.canvas.height=this.size*e,this.ctx.scale(e,e)}setColors(e){this.targetColors={...e}}setAnimation(e){this.animation=e}setAudioLevel(e){this.targetAudioLevel=Math.max(0,Math.min(1,e))}setActive(e){this.isActive=e,e||(this.targetAudioLevel=0)}start(){this.animationId===null&&this.animate()}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}update(){this.updateColors();const e=this.animation.smoothing;this.audioLevel+=(this.targetAudioLevel-this.audioLevel)*e;const t=this.animation.idleSpeed*.012,i=this.animation.responseSpeed*.025;this.time+=this.isActive?t+this.audioLevel*i:t}getSpeedMultiplier(){return this.isActive?1+this.audioLevel*2:.5}clear(){this.ctx.clearRect(0,0,this.size,this.size)}colorWithAlpha(e,t){if(e.startsWith("#")){const i=e.slice(1),s=parseInt(i.slice(0,2),16),r=parseInt(i.slice(2,4),16),o=parseInt(i.slice(4,6),16);return`rgba(${s}, ${r}, ${o}, ${t})`}if(e.startsWith("rgb")){const i=e.match(/[\d.]+/g);if(i&&i.length>=3)return`rgba(${i[0]}, ${i[1]}, ${i[2]}, ${t})`}return e}getIntensityMultiplier(){switch(this.animation.intensity){case"low":return .5;case"medium":return 1;case"high":return 1.5;default:return 1}}destroy(){this.stop()}updateColors(){if(!this.targetColors)return;const e=this.colorTransitionSpeed;this.colors={...this.colors,primary:pe(this.colors.primary,this.targetColors.primary,e),secondary:pe(this.colors.secondary,this.targetColors.secondary,e),accent:pe(this.colors.accent,this.targetColors.accent,e),glow:pe(this.colors.glow,this.targetColors.glow,e),background:this.targetColors.background,text:this.targetColors.text,statusText:this.targetColors.statusText,button:this.targetColors.button,buttonText:this.targetColors.buttonText,buttonHover:this.targetColors.buttonHover,buttonActive:this.targetColors.buttonActive}}}class sc extends Ti{constructor(e,t,i,s){super(e,t,i,s),this.bubbles=[],this.sphereRadius=t*.38,this.initBubbles()}initBubbles(){const e=Math.floor(this.animation.particlesCount*.5);this.bubbles=[];for(let t=0;t<e;t++)this.bubbles.push({x:this.centerX+(Math.random()-.5)*this.sphereRadius,y:this.centerY+Math.random()*this.sphereRadius*.5,radius:2+Math.random()*4,speed:.3+Math.random()*.5,wobble:Math.random()*3,phase:Math.random()*Math.PI*2})}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawOuterGlow(t),this.drawGlassSphere(),this.drawLiquidWaves(t),this.drawBubbles(t),this.drawCaustics(t),this.drawReflections(t)}drawOuterGlow(e){if(!this.animation.glowIntensity)return;const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.sphereRadius*.7,this.centerX,this.centerY,this.sphereRadius*1.4),i=(.2+e*.3)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.glow,i)),t.addColorStop(.5,this.colorWithAlpha(this.colors.glow,i*.4)),t.addColorStop(1,this.colorWithAlpha(this.colors.glow,0)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius*1.4,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill()}drawGlassSphere(){const e=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.2,this.centerY-this.sphereRadius*.25,0,this.centerX,this.centerY,this.sphereRadius);e.addColorStop(0,"rgba(255, 255, 255, 0.15)"),e.addColorStop(.4,this.colorWithAlpha(this.colors.primary,.08)),e.addColorStop(.8,this.colorWithAlpha(this.colors.secondary,.05)),e.addColorStop(1,this.colorWithAlpha(this.colors.primary,.1)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius,0,Math.PI*2),this.ctx.fillStyle=e,this.ctx.fill();const t=this.ctx.createRadialGradient(this.centerX,this.centerY+this.sphereRadius*.1,0,this.centerX,this.centerY,this.sphereRadius*.9);t.addColorStop(0,"rgba(15, 15, 30, 0.5)"),t.addColorStop(.7,"rgba(15, 15, 30, 0.2)"),t.addColorStop(1,"rgba(15, 15, 30, 0)"),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius*.9,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill()}drawLiquidWaves(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip(),[{yOffset:15,amplitude:4,frequency:.08,speed:1.2,alpha:.5},{yOffset:5,amplitude:5,frequency:.1,speed:1.5,alpha:.4},{yOffset:-5,amplitude:6,frequency:.12,speed:1.8,alpha:.3}].forEach((i,s)=>{this.drawWaveLayer(i,e,s)}),this.ctx.restore()}drawWaveLayer(e,t,i){const s=this.getSpeedMultiplier(),r=this.centerY+e.yOffset+Math.sin(this.time*e.speed*s)*5,o=e.amplitude*(.3+t*2+(this.isActive?.7:0));this.ctx.beginPath(),this.ctx.moveTo(this.centerX-this.sphereRadius,r);for(let c=-this.sphereRadius;c<=this.sphereRadius;c+=2){const d=Math.abs(c)/this.sphereRadius,l=Math.sqrt(1-d*d)*this.sphereRadius,u=Math.sin(c*e.frequency+this.time*e.speed*8*s)*o,h=Math.sin(c*e.frequency*.5+this.time*e.speed*5*s)*o*.5,f=r+u+h;f>this.centerY-l&&f<this.centerY+l&&this.ctx.lineTo(this.centerX+c,f)}for(let c=this.sphereRadius;c>=-this.sphereRadius;c-=2){const d=Math.abs(c)/this.sphereRadius,l=Math.sqrt(1-d*d)*this.sphereRadius;this.ctx.lineTo(this.centerX+c,this.centerY+l)}this.ctx.closePath();const a=[this.colors.primary,this.colors.secondary,this.colors.accent];this.ctx.fillStyle=this.colorWithAlpha(a[i%a.length],e.alpha+t*.2),this.ctx.fill()}drawBubbles(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();this.bubbles.forEach(i=>{i.y-=i.speed*t*(.3+e*2),i.x+=Math.sin(this.time*2*t+i.phase)*i.wobble*.05,i.y<this.centerY-this.sphereRadius*.8&&(i.y=this.centerY+this.sphereRadius*.6,i.x=this.centerX+(Math.random()-.5)*this.sphereRadius);const s=this.ctx.createRadialGradient(i.x-i.radius*.3,i.y-i.radius*.3,0,i.x,i.y,i.radius);s.addColorStop(0,"rgba(255, 255, 255, 0.8)"),s.addColorStop(.5,"rgba(255, 255, 255, 0.2)"),s.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.arc(i.x,i.y,i.radius*(1+e*.3),0,Math.PI*2),this.ctx.fillStyle=s,this.ctx.fill()}),this.ctx.restore()}drawCaustics(e){const i=this.getSpeedMultiplier();for(let s=0;s<5;s++){const r=s/5*Math.PI*2+this.time*.5*i,o=this.sphereRadius*.4+Math.sin(this.time*2*i+s)*10*(.3+e),a=this.centerX+Math.cos(r)*o,c=this.centerY+this.sphereRadius*.25+Math.sin(r)*o*.3,d=this.ctx.createRadialGradient(a,c,0,a,c,15+e*10),l=.2+e*.35;d.addColorStop(0,this.colorWithAlpha(this.colors.accent,l)),d.addColorStop(.5,this.colorWithAlpha(this.colors.primary,l*.5)),d.addColorStop(1,this.colorWithAlpha(this.colors.primary,0)),this.ctx.beginPath(),this.ctx.arc(a,c,15+e*10,0,Math.PI*2),this.ctx.fillStyle=d,this.ctx.fill()}}drawReflections(e){const t=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.25,this.centerY-this.sphereRadius*.3,0,this.centerX-this.sphereRadius*.25,this.centerY-this.sphereRadius*.3,this.sphereRadius*.35);t.addColorStop(0,`rgba(255, 255, 255, ${.6+e*.2})`),t.addColorStop(.3,"rgba(255, 255, 255, 0.2)"),t.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.ellipse(this.centerX-this.sphereRadius*.25,this.centerY-this.sphereRadius*.3,this.sphereRadius*.2,this.sphereRadius*.12,-.5,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(this.centerX+this.sphereRadius*.3,this.centerY-this.sphereRadius*.2,this.sphereRadius*.08,0,Math.PI*2);const i=this.ctx.createRadialGradient(this.centerX+this.sphereRadius*.3,this.centerY-this.sphereRadius*.2,0,this.centerX+this.sphereRadius*.3,this.centerY-this.sphereRadius*.2,this.sphereRadius*.08);i.addColorStop(0,"rgba(255, 255, 255, 0.5)"),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=i,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-1,0,Math.PI*2),this.ctx.strokeStyle=`rgba(255, 255, 255, ${.15+e*.1})`,this.ctx.lineWidth=1.5,this.ctx.stroke()}}class vp extends Ti{constructor(e,t,i,s){super(e,t,i,s),this.nodes=[],this.sphereRadius=t*.38,this.initNodes()}initNodes(){this.nodes=[],this.nodes.push(this.createNode(0,0,0));const e=5;for(let i=0;i<e;i++){const s=i/e*Math.PI*2;this.nodes.push(this.createNode(s,this.sphereRadius*.35,1))}const t=8;for(let i=0;i<t;i++){const s=i/t*Math.PI*2+Math.PI/t;this.nodes.push(this.createNode(s,this.sphereRadius*.7,2))}for(let i=1;i<=e;i++)this.nodes[0].connections.push(i);for(let i=1;i<=e;i++){const s=e+1+(i-1)*2%t,r=e+1+((i-1)*2+1)%t;this.nodes[i].connections.push(s),this.nodes[i].connections.push(r)}for(let i=1;i<=e;i++)this.nodes[i].connections.push(i%e+1)}createNode(e,t,i){return{angle:e,baseDist:t,layer:i,radius:3+Math.random()*2,pulseOffset:Math.random()*Math.PI*2,connections:[],activity:0,targetActivity:0,floatSpeed:.5+Math.random()*.5,floatOffset:Math.random()*Math.PI*2}}getNodePosition(e){const t=this.audioLevel,i=this.getSpeedMultiplier(),s=this.isActive?0:6,r=Math.sin(this.time*e.floatSpeed*i+e.floatOffset)*(4+s+t*10),o=Math.cos(this.time*e.floatSpeed*.7*i+e.floatOffset)*(3+s*.7+t*5),a=e.baseDist+Math.sin(this.time*i+e.pulseOffset)*5*(.7+t);return{x:this.centerX+Math.cos(e.angle)*a+o,y:this.centerY+Math.sin(e.angle)*a+r}}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawGlassSphere(t),this.drawLiquidBackground(t),this.updateNodes(t),this.drawConnections(t),this.drawNodes(t),this.drawReflections(t)}drawGlassSphere(e){const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.sphereRadius*.7,this.centerX,this.centerY,this.sphereRadius*1.3),i=(.15+e*.2)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.glow,i)),t.addColorStop(.5,this.colorWithAlpha(this.colors.glow,i*.5)),t.addColorStop(1,this.colorWithAlpha(this.colors.glow,0)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius*1.3,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill();const s=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.2,this.centerY-this.sphereRadius*.2,0,this.centerX,this.centerY,this.sphereRadius);s.addColorStop(0,"rgba(200, 255, 220, 0.1)"),s.addColorStop(.5,this.colorWithAlpha(this.colors.primary,.05)),s.addColorStop(1,this.colorWithAlpha(this.colors.secondary,.08)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius,0,Math.PI*2),this.ctx.fillStyle=s,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius,0,Math.PI*2),this.ctx.strokeStyle=this.colorWithAlpha(this.colors.accent,.2+e*.15),this.ctx.lineWidth=1.5,this.ctx.stroke()}drawLiquidBackground(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();for(let i=0;i<3;i++){const s=20-i*15,r=3+(this.isActive?0:3.5)+e*8,o=(1+i*.3)*t;this.ctx.beginPath(),this.ctx.moveTo(this.centerX-this.sphereRadius,this.centerY+s);for(let c=-this.sphereRadius;c<=this.sphereRadius;c+=3){if(Math.abs(c)/this.sphereRadius>.95)continue;const l=Math.sin(c*.08+this.time*o*3)*r+Math.sin(c*.05+this.time*o*2)*r*.5,u=this.centerY+s+l;this.ctx.lineTo(this.centerX+c,u)}this.ctx.lineTo(this.centerX+this.sphereRadius*.95,this.centerY+this.sphereRadius*.9),this.ctx.lineTo(this.centerX-this.sphereRadius*.95,this.centerY+this.sphereRadius*.9),this.ctx.closePath();const a=.12-i*.03+e*.08;this.ctx.fillStyle=this.colorWithAlpha(this.colors.secondary,a),this.ctx.fill()}this.ctx.restore()}updateNodes(e){this.nodes.forEach((t,i)=>{t.activity+=(t.targetActivity-t.activity)*.1,this.isActive?t.targetActivity=.5+Math.sin(this.time*2+i*.7)*.3+e*.5:t.targetActivity=.15})}drawConnections(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();this.nodes.forEach((i,s)=>{const r=this.getNodePosition(i);i.connections.forEach(o=>{const a=this.nodes[o],c=this.getNodePosition(a),d=(i.activity+a.activity)/2,l=(r.x+c.x)/2+Math.sin(this.time*2*t)*3*e,u=(r.y+c.y)/2+Math.cos(this.time*2.5*t)*3*e,h=this.ctx.createLinearGradient(r.x,r.y,c.x,c.y),f=.15+d*.4+e*.3;if(h.addColorStop(0,this.colorWithAlpha(this.colors.primary,f)),h.addColorStop(.5,this.colorWithAlpha(this.colors.accent,f*1.3)),h.addColorStop(1,this.colorWithAlpha(this.colors.primary,f)),this.ctx.beginPath(),this.ctx.moveTo(r.x,r.y),this.ctx.quadraticCurveTo(l,u,c.x,c.y),this.ctx.strokeStyle=h,this.ctx.lineWidth=1.5+d*2+e*1.5,this.ctx.stroke(),this.isActive&&(d>.2||e>.2)){const m=(this.time*1.5*t+i.pulseOffset)%1,E=(1-m)*(1-m)*r.x+2*(1-m)*m*l+m*m*c.x,S=(1-m)*(1-m)*r.y+2*(1-m)*m*u+m*m*c.y;this.ctx.beginPath(),this.ctx.arc(E,S,2.5+e*2,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.8+e*.2),this.ctx.fill()}})}),this.ctx.restore()}drawNodes(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();this.nodes.forEach(i=>{const s=this.getNodePosition(i),r=Math.sin(this.time*3*t+i.pulseOffset)*.15+.85,o=i.radius*(1+i.activity*.5+e*.5),a=o*(3+i.activity*2+e*3),c=this.ctx.createRadialGradient(s.x,s.y,0,s.x,s.y,a),d=.4+i.activity*.4+e*.3;c.addColorStop(0,this.colorWithAlpha(this.colors.primary,d)),c.addColorStop(.4,this.colorWithAlpha(this.colors.secondary,d*.5)),c.addColorStop(1,this.colorWithAlpha(this.colors.primary,0)),this.ctx.beginPath(),this.ctx.arc(s.x,s.y,a,0,Math.PI*2),this.ctx.fillStyle=c,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(s.x,s.y,o*r,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.9),this.ctx.fill()}),this.ctx.restore()}drawReflections(e){const t=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.22,this.centerY-this.sphereRadius*.28,0,this.centerX-this.sphereRadius*.22,this.centerY-this.sphereRadius*.28,this.sphereRadius*.3);t.addColorStop(0,`rgba(255, 255, 255, ${.6+e*.2})`),t.addColorStop(.4,"rgba(255, 255, 255, 0.2)"),t.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.ellipse(this.centerX-this.sphereRadius*.22,this.centerY-this.sphereRadius*.28,this.sphereRadius*.18,this.sphereRadius*.1,-.4,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill()}}let rc=class{constructor(e=Math.random()*1e4){this.p=new Uint8Array(256);for(let i=0;i<256;i++)this.p[i]=i;let t=e;for(let i=255;i>0;i--){t=t*16807%2147483647;const s=t%(i+1);[this.p[i],this.p[s]]=[this.p[s],this.p[i]]}this.perm=new Uint8Array(512);for(let i=0;i<512;i++)this.perm[i]=this.p[i&255]}noise2D(e,t){const i=.5*(Math.sqrt(3)-1),s=(3-Math.sqrt(3))/6,r=(e+t)*i,o=Math.floor(e+r),a=Math.floor(t+r),c=(o+a)*s,d=e-(o-c),l=t-(a-c),u=d>l?1:0,h=d>l?0:1,f=d-u+s,g=l-h+s,m=d-1+2*s,E=l-1+2*s,S=o&255,w=a&255,I=(O,N,F)=>{const G=O&7,ne=G<4?N:F,be=G<4?F:N;return(G&1?-ne:ne)+(G&2?-2*be:2*be)};let b=0,y=0,C=0,A=.5-d*d-l*l;A>=0&&(A*=A,b=A*A*I(this.perm[S+this.perm[w]],d,l));let D=.5-f*f-g*g;D>=0&&(D*=D,y=D*D*I(this.perm[S+u+this.perm[w+h]],f,g));let M=.5-m*m-E*E;return M>=0&&(M*=M,C=M*M*I(this.perm[S+1+this.perm[w+1]],m,E)),70*(b+y+C)}noise3D(e,t,i){return(this.noise2D(e,t)+this.noise2D(e+100,i)+this.noise2D(t+200,i))/3}};class bp extends Ti{constructor(e,t,i,s){super(e,t,i,s),this.noise1=new rc(42),this.noise2=new rc(137),this.baseRadius=t*.38}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawGlow(t);const i=this.createShape(t);this.drawShape(i),this.drawHighlight(i,t)}createShape(e){const t=[],s=this.getSpeedMultiplier(),r=8+e*25+(this.isActive?0:10),o=5+e*15+(this.isActive?0:6);for(let a=0;a<=120;a++){const c=a/120*Math.PI*2,d=Math.cos(c),l=Math.sin(c),u=this.noise1.noise3D(d*.8,l*.8,this.time*.3*s),h=this.noise2.noise3D(d*1.5,l*1.5,this.time*.5*s),f=Math.sin(c*4+this.time*2*s)*e*8,g=u*r+h*o*.5+f,m=this.baseRadius+g;t.push({x:this.centerX+d*m,y:this.centerY+l*m})}return t}drawGlow(e){const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.baseRadius*.3,this.centerX,this.centerY,this.baseRadius*1.2+e*30),i=(.3+e*.4)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.glow,i)),t.addColorStop(1,this.colorWithAlpha(this.colors.glow,0)),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,this.size,this.size)}drawShape(e){const t=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.2,this.centerY-this.baseRadius*.2,0,this.centerX,this.centerY,this.baseRadius);t.addColorStop(0,this.colorWithAlpha(this.colors.accent,.95)),t.addColorStop(.5,this.colorWithAlpha(this.colors.primary,.9)),t.addColorStop(1,this.colorWithAlpha(this.colors.secondary,.85)),this.ctx.beginPath(),this.ctx.moveTo(e[0].x,e[0].y);for(let i=1;i<e.length-1;i++){const s=(e[i].x+e[i+1].x)/2,r=(e[i].y+e[i+1].y)/2;this.ctx.quadraticCurveTo(e[i].x,e[i].y,s,r)}this.ctx.closePath(),this.ctx.fillStyle=t,this.ctx.fill()}drawHighlight(e,t){const i=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.2,this.centerY-this.baseRadius*.2,0,this.centerX-this.baseRadius*.15,this.centerY-this.baseRadius*.15,this.baseRadius*.6);i.addColorStop(0,`rgba(255, 255, 255, ${.5+t*.3})`),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.moveTo(e[0].x,e[0].y);for(let s=1;s<e.length-1;s++){const r=(e[s].x+e[s+1].x)/2,o=(e[s].y+e[s+1].y)/2;this.ctx.quadraticCurveTo(e[s].x,e[s].y,r,o)}this.ctx.closePath(),this.ctx.fillStyle=i,this.ctx.fill()}}class ac extends Ti{constructor(e,t,i,s){super(e,t,i,s),this.nodes=[],this.initNetwork()}initNetwork(){this.nodes=[];const e=this.size*.35;this.nodes.push(this.createNode(this.centerX,this.centerY,0));for(let t=0;t<6;t++){const i=t/6*Math.PI*2-Math.PI/2,s=e*.5;this.nodes.push(this.createNode(this.centerX+Math.cos(i)*s,this.centerY+Math.sin(i)*s,1))}for(let t=0;t<12;t++){const i=t/12*Math.PI*2,s=e;this.nodes.push(this.createNode(this.centerX+Math.cos(i)*s,this.centerY+Math.sin(i)*s,2))}for(let t=1;t<=6;t++)this.nodes[0].connections.push(t);for(let t=1;t<=6;t++){const i=7+(t-1)*2;this.nodes[t].connections.push(i%12+7),this.nodes[t].connections.push((i+1)%12+7)}for(let t=1;t<=6;t++)this.nodes[t].connections.push(t%6+1)}createNode(e,t,i){return{x:e,y:t,baseX:e,baseY:t,layer:i,radius:3+Math.random()*2,pulseOffset:Math.random()*Math.PI*2,connections:[],activity:0,targetActivity:0}}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.updateNodes(t),this.drawConnections(t),this.drawNodes(t),this.size<=200&&this.applyEdgeFade()}updateNodes(e){const t=this.getSpeedMultiplier(),i=this.time*(this.isActive?.9:1.35),s=this.isActive?0:this.size*.01,r=this.isActive?0:this.size*.012;this.nodes.forEach((o,a)=>{const c=this.isActive?5+e*10:6,d=this.isActive?0:Math.sin(i+(o.baseX+o.baseY)*.04),l=this.isActive?0:Math.sin(i*.95+(o.baseX-o.baseY)*.045);o.x=o.baseX+Math.sin(this.time*.5*t+o.pulseOffset)*c+d*s,o.y=o.baseY+Math.cos(this.time*.7*t+o.pulseOffset)*c+l*r,o.activity+=(o.targetActivity-o.activity)*.1,this.isActive?o.targetActivity=.5+Math.sin(this.time*2*t+a*.5)*.3+e*.5:o.targetActivity=.22+Math.sin(this.time*t*1.25+a*.3)*.12+d*.08})}drawConnections(e){const t=this.getSpeedMultiplier(),i=this.isActive?2*t:2*t*1.6;this.nodes.forEach(s=>{s.connections.forEach(r=>{const o=this.nodes[r],a=(s.activity+o.activity)/2,c=this.ctx.createLinearGradient(s.x,s.y,o.x,o.y),d=.1+a*.4+e*.3;if(c.addColorStop(0,this.colorWithAlpha(this.colors.primary,d)),c.addColorStop(.5,this.colorWithAlpha(this.colors.accent,d*1.2)),c.addColorStop(1,this.colorWithAlpha(this.colors.primary,d)),this.ctx.beginPath(),this.ctx.moveTo(s.x,s.y),this.ctx.lineTo(o.x,o.y),this.ctx.strokeStyle=c,this.ctx.lineWidth=1+a*2+e,this.ctx.stroke(),a>.15||e>.15||!this.isActive){const l=(this.time*i+s.pulseOffset)%1,u=s.x+(o.x-s.x)*l,h=s.y+(o.y-s.y)*l;this.ctx.beginPath(),this.ctx.arc(u,h,2+e*2,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.5+a*.3+e*.2),this.ctx.fill()}})})}drawNodes(e){const t=this.getSpeedMultiplier(),i=this.getGlowScale(),s=this.isActive?1:.95+Math.sin(this.time*.9)*.05;this.nodes.forEach(r=>{const o=Math.sin(this.time*3*t+r.pulseOffset)*.3+.7,a=r.radius*(1+r.activity*.5+e*.5)*s,c=a*(2+r.activity*3+e*2)*i,d=this.ctx.createRadialGradient(r.x,r.y,0,r.x,r.y,c),l=(.3+r.activity*.5+e*.3)*i;d.addColorStop(0,this.colorWithAlpha(this.colors.primary,l)),d.addColorStop(.5,this.colorWithAlpha(this.colors.primary,l*.3)),d.addColorStop(1,this.colorWithAlpha(this.colors.primary,0)),this.ctx.beginPath(),this.ctx.arc(r.x,r.y,c,0,Math.PI*2),this.ctx.fillStyle=d,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(r.x,r.y,a*o,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.9),this.ctx.fill()})}getGlowScale(){return Math.min(1,this.size/180)}applyEdgeFade(){const e=this.size*.48,t=this.size*.12,i=this.ctx.createRadialGradient(this.centerX,this.centerY,Math.max(0,e-t),this.centerX,this.centerY,e);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.save(),this.ctx.globalCompositeOperation="destination-in",this.ctx.fillStyle=i,this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,e,0,Math.PI*2),this.ctx.fill(),this.ctx.restore()}}class yp{constructor(e=Math.random()*1e4){this.p=new Uint8Array(256);for(let i=0;i<256;i++)this.p[i]=i;let t=e;for(let i=255;i>0;i--){t=t*16807%2147483647;const s=t%(i+1);[this.p[i],this.p[s]]=[this.p[s],this.p[i]]}this.perm=new Uint8Array(512);for(let i=0;i<512;i++)this.perm[i]=this.p[i&255]}noise3D(e,t,i){const s=.3333333333333333,r=1/6,o=(e+t+i)*s,a=Math.floor(e+o),c=Math.floor(t+o),d=Math.floor(i+o),l=(a+c+d)*r,u=e-(a-l),h=t-(c-l),f=i-(d-l);let g,m,E,S,w,I;u>=h?h>=f?(g=1,m=0,E=0,S=1,w=1,I=0):u>=f?(g=1,m=0,E=0,S=1,w=0,I=1):(g=0,m=0,E=1,S=1,w=0,I=1):h<f?(g=0,m=0,E=1,S=0,w=1,I=1):u<f?(g=0,m=1,E=0,S=0,w=1,I=1):(g=0,m=1,E=0,S=1,w=1,I=0);const b=u-g+r,y=h-m+r,C=f-E+r,A=u-S+2*r,D=h-w+2*r,M=f-I+2*r,O=u-1+3*r,N=h-1+3*r,F=f-1+3*r,G=a&255,ne=c&255,be=d&255,re=(un,Kt,dc,Rp)=>{const Jt=un&15,lc=Jt<8?Kt:dc,uc=Jt<4?dc:Jt===12||Jt===14?Kt:Rp;return(Jt&1?-lc:lc)+(Jt&2?-uc:uc)};let De=0,Gt=0,Ht=0,zt=0,Je=.6-u*u-h*h-f*f;Je>=0&&(Je*=Je,De=Je*Je*re(this.perm[G+this.perm[ne+this.perm[be]]],u,h,f));let Ye=.6-b*b-y*y-C*C;Ye>=0&&(Ye*=Ye,Gt=Ye*Ye*re(this.perm[G+g+this.perm[ne+m+this.perm[be+E]]],b,y,C));let Xe=.6-A*A-D*D-M*M;Xe>=0&&(Xe*=Xe,Ht=Xe*Xe*re(this.perm[G+S+this.perm[ne+w+this.perm[be+I]]],A,D,M));let Ct=.6-O*O-N*N-F*F;return Ct>=0&&(Ct*=Ct,zt=Ct*Ct*re(this.perm[G+1+this.perm[ne+1+this.perm[be+1]]],O,N,F)),32*(De+Gt+Ht+zt)}}class Sp extends Ti{constructor(e,t,i,s){super(e,t,i,s),this.rotationX=0,this.rotationY=0,this.noise=new yp(42),this.baseRadius=t*.35}update(){super.update();const e=this.getSpeedMultiplier();this.rotationX+=.003*e,this.rotationY+=.005*e}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawOuterGlow(t),this.drawBlob(t),this.drawIridescentHighlights(t),this.drawReflection(t)}drawOuterGlow(e){const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.baseRadius*.5,this.centerX,this.centerY,this.baseRadius*1.8),i=(.25+e*.35)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.primary,i)),t.addColorStop(.4,this.colorWithAlpha(this.colors.secondary,i*.5)),t.addColorStop(.7,this.colorWithAlpha(this.colors.accent,i*.2)),t.addColorStop(1,"rgba(0, 0, 0, 0)"),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,this.size,this.size)}drawBlob(e){const s=.15+e*.35+(this.isActive?0:.08),r=this.getSpeedMultiplier();for(let o=0;o<3;o++){const a=o*.1,c=1-o*.2;this.ctx.beginPath();for(let u=0;u<=72;u++){const h=u/72*Math.PI*2,f=Math.cos(h),g=Math.sin(h),m=this.noise.noise3D(f*1.5+this.rotationX,g*1.5+this.rotationY,this.time*.5*r+a),E=Math.sin(this.time*3*r+h*2)*e*.1,S=this.baseRadius*(1+m*s+E),w=this.centerX+Math.cos(h)*S,I=this.centerY+Math.sin(h)*S;u===0?this.ctx.moveTo(w,I):this.ctx.lineTo(w,I)}this.ctx.closePath();const d=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.3,this.centerY-this.baseRadius*.3,0,this.centerX,this.centerY,this.baseRadius*1.2),l=Math.sin(this.time*.3*r)*30;d.addColorStop(0,this.shiftHue(this.colors.accent,l,c*.9)),d.addColorStop(.4,this.shiftHue(this.colors.primary,l+20,c*.8)),d.addColorStop(.7,this.shiftHue(this.colors.secondary,l+40,c*.7)),d.addColorStop(1,this.shiftHue(this.colors.primary,l+60,c*.5)),this.ctx.fillStyle=d,this.ctx.fill()}}drawIridescentHighlights(e){const t=this.getSpeedMultiplier();for(let i=0;i<3;i++){const s=this.time*.5*t+i*(Math.PI*2/3),r=this.baseRadius*.4,o=this.centerX+Math.cos(s)*r,a=this.centerY+Math.sin(s)*r*.6,c=this.ctx.createRadialGradient(o,a,0,o,a,this.baseRadius*.4),d=(this.time*50*t+i*120)%360;c.addColorStop(0,`hsla(${d}, 80%, 70%, ${.3+e*.3})`),c.addColorStop(.5,`hsla(${d+30}, 70%, 60%, ${.15+e*.15})`),c.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=c,this.ctx.beginPath(),this.ctx.arc(o,a,this.baseRadius*.4,0,Math.PI*2),this.ctx.fill()}}drawReflection(e){const t=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.25,this.centerY-this.baseRadius*.3,0,this.centerX-this.baseRadius*.25,this.centerY-this.baseRadius*.3,this.baseRadius*.4);t.addColorStop(0,`rgba(255, 255, 255, ${.7+e*.2})`),t.addColorStop(.3,`rgba(255, 255, 255, ${.3+e*.1})`),t.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=t,this.ctx.beginPath(),this.ctx.ellipse(this.centerX-this.baseRadius*.25,this.centerY-this.baseRadius*.3,this.baseRadius*.25,this.baseRadius*.15,-.4,0,Math.PI*2),this.ctx.fill();const i=this.ctx.createRadialGradient(this.centerX,this.centerY,this.baseRadius*.8,this.centerX,this.centerY,this.baseRadius*1.1);i.addColorStop(0,"rgba(255, 255, 255, 0)"),i.addColorStop(.5,`rgba(255, 255, 255, ${.1+e*.1})`),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=i,this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.baseRadius*1.1,0,Math.PI*2),this.ctx.fill()}shiftHue(e,t,i){if(!e.startsWith("#"))return this.colorWithAlpha(e,i);const s=e.slice(1),r=parseInt(s.slice(0,2),16)/255,o=parseInt(s.slice(2,4),16)/255,a=parseInt(s.slice(4,6),16)/255,c=Math.max(r,o,a),d=Math.min(r,o,a);let l=0;const u=(c+d)/2,h=c===d?0:u>.5?(c-d)/(2-c-d):(c-d)/(c+d);return c!==d&&(c===r?l=(o-a)/(c-d)%6:c===o?l=(a-r)/(c-d)+2:l=(r-o)/(c-d)+4,l*=60,l<0&&(l+=360)),l=(l+t)%360,l<0&&(l+=360),`hsla(${l}, ${h*100}%, ${u*100}%, ${i})`}}function oc(n,e,t,i,s){switch(n){case"liquid-glass":case"liquid-glass-premium":return new sc(e,t,i,s);case"neural-liquid":return new vp(e,t,i,s);case"neural-orbit":case"neural-network":return new ac(e,t,i,s);case"synaptic-core":return new ac(e,t,i,s);case"organic-sphere":return new bp(e,t,i,s);case"morphing-blob":return new Sp(e,t,i,s);default:return new sc(e,t,i,s)}}var kp=Object.defineProperty,Tp=Object.getOwnPropertyDescriptor,le=(n,e,t,i)=>{for(var s=i>1?void 0:i?Tp(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&kp(e,t,s),s};L.InlineCall=class extends _t{constructor(){super(...arguments),this.callManager=new Qo,this.theme="neural-blue",this.visualStyle="neural-network",this.orbSize=400,this.hideButton=!1,this.buttonPosition="bottom",this.callStatus="idle",this.renderer=null,this.audioSimTimer=null,this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,this.baseColors=null,this.themeColors=null,this.baseAnimation=null,this.buttonStartText="Start Call",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.handleStatusChange=e=>{switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="idle";break}},this.toggleCall=async()=>{if(!this.agentId)return new Error("Agent ID is required to make a call.");this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callManager.hangUp()}}get callState(){switch(this.callStatus){case"connecting":return"connecting";case"connected":return"active";default:return"idle"}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.callManager.addEventListener("status-changed",this.handleStatusChange)}disconnectedCallback(){var e;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.hangUp(),(e=this.renderer)==null||e.destroy(),this.renderer=null,this.stopAudioSimulation()}updated(e){var t;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("visualStyle")||e.has("theme")||e.has("orbSize")||e.has("orbColor"))&&this.setupRenderer(),e.has("callStatus")&&((t=this.renderer)==null||t.setActive(this.callState==="active"),this.callState==="active"?this.startAudioSimulation():this.stopAudioSimulation(),this.syncOrbAppearance()),e.has("activeOrbColor")&&this.syncOrbAppearance(),(e.has("buttonColor")||e.has("buttonHoverColor")||e.has("buttonActiveColor")||e.has("buttonTextColor"))&&this.updateButtonThemeVars()}firstUpdated(){this.setupRenderer()}setupRenderer(){var s;const e=this.renderRoot.querySelector("#orb-canvas");if(!e)return;const t=this.theme==="custom"?cn("liquid-purple"):cn(this.theme),i=nc({...t,style:this.visualStyle,size:{...t.size,orbDiameter:this.orbSize}});this.themeColors=i.colors,this.baseColors=this.getBaseOrbColors(i.colors),this.baseAnimation=i.animation,this.style.setProperty("--hanc-orb-size",`${i.size.orbDiameter}px`),this.updateButtonThemeVars(),(s=this.renderer)==null||s.destroy(),this.renderer=oc(i.style,e,i.size.orbDiameter,this.baseColors,i.animation),this.renderer.setActive(this.callState==="active"),this.renderer.start(),this.syncOrbAppearance()}clamp(e,t,i){return Math.min(i,Math.max(t,e))}buildOrbPalette(e,t){return{...t,primary:e,secondary:pe(e,"#000000",.18),accent:pe(e,"#ffffff",.25),glow:pe(e,"#ffffff",.45)}}getBaseOrbColors(e){var i;const t=(i=this.orbColor)==null?void 0:i.trim();return t?this.buildOrbPalette(t,e):e}getActiveSeedColor(e){var i;const t=(i=this.activeOrbColor)==null?void 0:i.trim();return t||pe(e.primary,"#ffffff",.25)}getActiveColors(e){const t=this.getActiveSeedColor(e);return this.buildOrbPalette(t,e)}getButtonColors(e){var o,a,c,d;const t=((o=this.buttonColor)==null?void 0:o.trim())||e.button,i=((a=this.buttonHoverColor)==null?void 0:a.trim())||pe(t,"#000000",.12),s=((c=this.buttonActiveColor)==null?void 0:c.trim())||pe(t,"#000000",.35),r=((d=this.buttonTextColor)==null?void 0:d.trim())||e.buttonText;return{...e,button:t,buttonHover:i,buttonActive:s,buttonText:r}}updateButtonThemeVars(){if(!this.themeColors)return;if(!(!!this.buttonColor||!!this.buttonHoverColor||!!this.buttonActiveColor||!!this.buttonTextColor)){this.theme!=="custom"&&ln(this,this.themeColors);return}ln(this,this.getButtonColors(this.themeColors))}getAnimationForState(){const e=this.baseAnimation,t=this.isActive,i=1.2,s=1.4,r=t?1.5:1.2,o=t?s:i,a=t?1.3:1.05;return{...e,idleSpeed:this.clamp(e.idleSpeed*o,.05,1),responseSpeed:this.clamp(e.responseSpeed*a,.05,1),glowIntensity:this.clamp(e.glowIntensity*r,0,1)}}syncOrbAppearance(){if(!this.renderer||!this.baseColors||!this.baseAnimation)return;const e=this.getActiveSeedColor(this.baseColors);if(this.style.setProperty("--hanc-orb-active-glow",Zo(e,.45)),this.renderer.setAnimation(this.getAnimationForState()),this.isActive){this.renderer.setColors(this.getActiveColors(this.baseColors));return}this.renderer.setColors(this.baseColors)}startAudioSimulation(){if(this.audioSimTimer!==null)return;this.simulatedTargetLevel=.25,this.audioSimTimer=window.setInterval(()=>{const t=(Math.random()-.5)*.25,i=this.simulatedTargetLevel+t;this.simulatedTargetLevel=Math.min(.85,Math.max(.12,i))},180);const e=()=>{var t;this.audioSimTimer!==null&&(this.simulatedCurrentLevel+=(this.simulatedTargetLevel-this.simulatedCurrentLevel)*.12,(t=this.renderer)==null||t.setAudioLevel(this.simulatedCurrentLevel),requestAnimationFrame(e))};requestAnimationFrame(e)}stopAudioSimulation(){var e;this.audioSimTimer!==null&&(clearInterval(this.audioSimTimer),this.audioSimTimer=null),this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,(e=this.renderer)==null||e.setAudioLevel(0)}get isActive(){return this.callStatus==="connected"}get buttonText(){switch(this.callStatus){case"connecting":return this.buttonConnectingText;case"connected":return this.buttonEndText;default:return this.buttonStartText}}render(){return Pt`
284
- <div class="widget" part="wrapper">
288
+ `,lp={primary:"#8b5cf6",secondary:"#6366f1",accent:"#a855f7",glow:"#8b5cf6",background:"rgba(255, 255, 255, 0.03)",text:"rgba(255, 255, 255, 0.9)",statusText:"rgba(167, 139, 250, 0.9)",button:"#8b5cf6",buttonText:"#ffffff",buttonHover:"#7c3aed",buttonActive:"#ef4444"},up={orbDiameter:180,widgetWidth:320,widgetPadding:24,borderRadius:28,buttonHeight:52,buttonRadius:14},hp={intensity:"medium",idleSpeed:.5,responseSpeed:.7,particlesCount:20,glowIntensity:.6,smoothing:.08,idleAnimation:!0},pp={title:"AI Assistant",statusIdle:"Ready to connect",statusConnecting:"Connecting...",statusActive:"Listening...",statusError:"Connection error",buttonStart:"Start Call",buttonConnecting:"Connecting...",buttonEnd:"End Call"},fp={showTitle:!0,showStatus:!0,showGlow:!0,compactMode:!1,darkMode:!0},mp={placement:"bottom-right",offsetX:24,offsetY:24},oc={"liquid-purple":{style:"liquid-glass",colors:{primary:"#8b5cf6",secondary:"#6366f1",accent:"#a855f7",glow:"#8b5cf6",statusText:"rgba(167, 139, 250, 0.9)",button:"#8b5cf6",buttonHover:"#7c3aed"}},"liquid-cyan":{style:"liquid-glass",colors:{primary:"#06b6d4",secondary:"#0891b2",accent:"#22d3ee",glow:"#06b6d4",statusText:"rgba(34, 211, 238, 0.9)",button:"#06b6d4",buttonHover:"#0891b2"}},"liquid-pink":{style:"liquid-glass-premium",colors:{primary:"#ec4899",secondary:"#db2777",accent:"#f472b6",glow:"#ec4899",statusText:"rgba(244, 114, 182, 0.9)",button:"#ec4899",buttonHover:"#db2777"}},"neural-green":{style:"neural-liquid",colors:{primary:"#22c55e",secondary:"#16a34a",accent:"#4ade80",glow:"#22c55e",statusText:"rgba(74, 222, 128, 0.9)",button:"#22c55e",buttonHover:"#16a34a"}},"neural-blue":{style:"neural-liquid",colors:{primary:"#3b82f6",secondary:"#2563eb",accent:"#60a5fa",glow:"#3b82f6",statusText:"rgba(96, 165, 250, 0.9)",button:"#3b82f6",buttonHover:"#2563eb"}},"orbit-blue":{style:"neural-orbit",colors:{primary:"#0ea5e9",secondary:"#0284c7",accent:"#38bdf8",glow:"#0ea5e9",statusText:"rgba(56, 189, 248, 0.9)",button:"#0ea5e9",buttonHover:"#0284c7"}},"synaptic-purple":{style:"synaptic-core",colors:{primary:"#a855f7",secondary:"#9333ea",accent:"#c084fc",glow:"#a855f7",statusText:"rgba(192, 132, 252, 0.9)",button:"#a855f7",buttonHover:"#9333ea"}},"minimal-dark":{style:"liquid-glass",colors:{primary:"#ffffff",secondary:"#a1a1aa",accent:"#f4f4f5",glow:"rgba(255, 255, 255, 0.3)",background:"rgba(0, 0, 0, 0.8)",text:"#ffffff",statusText:"rgba(255, 255, 255, 0.6)",button:"#ffffff",buttonText:"#18181b",buttonHover:"#e4e4e7"},display:{darkMode:!0}},"minimal-light":{style:"liquid-glass",colors:{primary:"#18181b",secondary:"#52525b",accent:"#3f3f46",glow:"rgba(0, 0, 0, 0.2)",background:"rgba(255, 255, 255, 0.9)",text:"#18181b",statusText:"rgba(24, 24, 27, 0.6)",button:"#18181b",buttonText:"#ffffff",buttonHover:"#27272a"},display:{darkMode:!1}}};function ln(n){return oc[n]||oc["liquid-purple"]}function cc(n){return{agentId:n.agentId||"",style:n.style||"liquid-glass",colors:{...lp,...n.colors||{}},size:{...up,...n.size||{}},animation:{...hp,...n.animation||{}},text:{...pp,...n.text||{}},display:{...fp,...n.display||{}},position:{...mp,...n.position||{}}}}const gp=.3,vp=.4,bp=.4,yp=.15,Sp="135deg",kp=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,Cp=/^rgba?\(([^)]+)\)$/i;function un(n,e){const t=n.trim(),i=kp.exec(t);if(i){let r=i[1];r.length===3&&(r=r.split("").map(d=>d+d).join(""));const o=parseInt(r.slice(0,2),16),a=parseInt(r.slice(2,4),16),c=parseInt(r.slice(4,6),16);return`rgba(${o}, ${a}, ${c}, ${e})`}const s=Cp.exec(t);if(s){const r=s[1].split(",").map(o=>o.trim());if(r.length>=3){const[o,a,c]=r;return`rgba(${o}, ${a}, ${c}, ${e})`}}return n}function js(n,e){return`linear-gradient(${Sp}, ${n} 0%, ${e} 100%)`}function hn(n,e){const t=e.button,i=e.buttonHover,s=e.buttonActive;n.style.setProperty("--hanc-button",js(t,i)),n.style.setProperty("--hanc-button-hover",js(i,t)),n.style.setProperty("--hanc-button-active",js(s,s)),n.style.setProperty("--hanc-button-text",e.buttonText),n.style.setProperty("--hanc-button-shadow",un(t,gp)),n.style.setProperty("--hanc-button-shadow-hover",un(t,vp)),n.style.setProperty("--hanc-button-shadow-active",un(s,bp)),n.style.setProperty("--hanc-glow-shadow",un(e.glow,yp))}class Ci{constructor(e,t,i,s){this.colorTransitionSpeed=.08,this.time=0,this.audioLevel=0,this.targetAudioLevel=0,this.isActive=!1,this.animationId=null,this.lastFrameTime=null,this.frameDelta=1,this.animate=o=>{if(this.lastFrameTime===null)this.lastFrameTime=o,this.frameDelta=1;else{const a=o-this.lastFrameTime;this.lastFrameTime=o;const c=a/16.6667;this.frameDelta=Math.min(2.5,Math.max(.5,c))}this.update(),this.render(),this.animationId=requestAnimationFrame(this.animate)},this.canvas=e;const r=e.getContext("2d");if(!r)throw new Error("Could not get 2D context");this.ctx=r,this.size=t,this.centerX=t/2,this.centerY=t/2,this.colors={...i},this.targetColors={...i},this.animation=s,this.setupCanvas()}setupCanvas(){const e=window.devicePixelRatio||1;this.canvas.width=this.size*e,this.canvas.height=this.size*e,this.ctx.scale(e,e)}setColors(e){this.targetColors={...e}}setAnimation(e){this.animation=e}setAudioLevel(e){this.targetAudioLevel=Math.max(0,Math.min(1,e))}setActive(e){this.isActive=e,e||(this.targetAudioLevel=0)}start(){this.animationId===null&&(this.lastFrameTime=null,this.animationId=requestAnimationFrame(this.animate))}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.lastFrameTime=null}update(){this.updateColors();const e=1-Math.pow(1-this.animation.smoothing,this.frameDelta);this.audioLevel+=(this.targetAudioLevel-this.audioLevel)*e;const t=this.animation.idleSpeed*.012,i=this.animation.responseSpeed*.025,s=this.isActive?t+this.audioLevel*i:t;this.time+=s*this.frameDelta}getSpeedMultiplier(){return this.isActive?1+this.audioLevel*2:.5}clear(){this.ctx.clearRect(0,0,this.size,this.size)}colorWithAlpha(e,t){if(e.startsWith("#")){const i=e.slice(1),s=parseInt(i.slice(0,2),16),r=parseInt(i.slice(2,4),16),o=parseInt(i.slice(4,6),16);return`rgba(${s}, ${r}, ${o}, ${t})`}if(e.startsWith("rgb")){const i=e.match(/[\d.]+/g);if(i&&i.length>=3)return`rgba(${i[0]}, ${i[1]}, ${i[2]}, ${t})`}return e}getIntensityMultiplier(){switch(this.animation.intensity){case"low":return .5;case"medium":return 1;case"high":return 1.5;default:return 1}}destroy(){this.stop()}resetDynamics(){this.audioLevel=0,this.targetAudioLevel=0}updateColors(){if(!this.targetColors)return;const e=this.colorTransitionSpeed;this.colors={...this.colors,primary:pe(this.colors.primary,this.targetColors.primary,e),secondary:pe(this.colors.secondary,this.targetColors.secondary,e),accent:pe(this.colors.accent,this.targetColors.accent,e),glow:pe(this.colors.glow,this.targetColors.glow,e),background:this.targetColors.background,text:this.targetColors.text,statusText:this.targetColors.statusText,button:this.targetColors.button,buttonText:this.targetColors.buttonText,buttonHover:this.targetColors.buttonHover,buttonActive:this.targetColors.buttonActive}}}class dc extends Ci{constructor(e,t,i,s){super(e,t,i,s),this.bubbles=[],this.sphereRadius=t*.38,this.initBubbles()}initBubbles(){const e=Math.floor(this.animation.particlesCount*.5);this.bubbles=[];for(let t=0;t<e;t++)this.bubbles.push({x:this.centerX+(Math.random()-.5)*this.sphereRadius,y:this.centerY+Math.random()*this.sphereRadius*.5,radius:2+Math.random()*4,speed:.3+Math.random()*.5,wobble:Math.random()*3,phase:Math.random()*Math.PI*2})}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawOuterGlow(t),this.drawGlassSphere(),this.drawLiquidWaves(t),this.drawBubbles(t),this.drawCaustics(t),this.drawReflections(t)}drawOuterGlow(e){if(!this.animation.glowIntensity)return;const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.sphereRadius*.7,this.centerX,this.centerY,this.sphereRadius*1.4),i=(.2+e*.3)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.glow,i)),t.addColorStop(.5,this.colorWithAlpha(this.colors.glow,i*.4)),t.addColorStop(1,this.colorWithAlpha(this.colors.glow,0)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius*1.4,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill()}drawGlassSphere(){const e=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.2,this.centerY-this.sphereRadius*.25,0,this.centerX,this.centerY,this.sphereRadius);e.addColorStop(0,"rgba(255, 255, 255, 0.15)"),e.addColorStop(.4,this.colorWithAlpha(this.colors.primary,.08)),e.addColorStop(.8,this.colorWithAlpha(this.colors.secondary,.05)),e.addColorStop(1,this.colorWithAlpha(this.colors.primary,.1)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius,0,Math.PI*2),this.ctx.fillStyle=e,this.ctx.fill();const t=this.ctx.createRadialGradient(this.centerX,this.centerY+this.sphereRadius*.1,0,this.centerX,this.centerY,this.sphereRadius*.9);t.addColorStop(0,"rgba(15, 15, 30, 0.5)"),t.addColorStop(.7,"rgba(15, 15, 30, 0.2)"),t.addColorStop(1,"rgba(15, 15, 30, 0)"),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius*.9,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill()}drawLiquidWaves(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip(),[{yOffset:15,amplitude:4,frequency:.08,speed:1.2,alpha:.5},{yOffset:5,amplitude:5,frequency:.1,speed:1.5,alpha:.4},{yOffset:-5,amplitude:6,frequency:.12,speed:1.8,alpha:.3}].forEach((i,s)=>{this.drawWaveLayer(i,e,s)}),this.ctx.restore()}drawWaveLayer(e,t,i){const s=this.getSpeedMultiplier(),r=this.centerY+e.yOffset+Math.sin(this.time*e.speed*s)*5,o=e.amplitude*(.3+t*2+(this.isActive?.7:0));this.ctx.beginPath(),this.ctx.moveTo(this.centerX-this.sphereRadius,r);for(let c=-this.sphereRadius;c<=this.sphereRadius;c+=2){const d=Math.abs(c)/this.sphereRadius,l=Math.sqrt(1-d*d)*this.sphereRadius,u=Math.sin(c*e.frequency+this.time*e.speed*8*s)*o,h=Math.sin(c*e.frequency*.5+this.time*e.speed*5*s)*o*.5,f=r+u+h;f>this.centerY-l&&f<this.centerY+l&&this.ctx.lineTo(this.centerX+c,f)}for(let c=this.sphereRadius;c>=-this.sphereRadius;c-=2){const d=Math.abs(c)/this.sphereRadius,l=Math.sqrt(1-d*d)*this.sphereRadius;this.ctx.lineTo(this.centerX+c,this.centerY+l)}this.ctx.closePath();const a=[this.colors.primary,this.colors.secondary,this.colors.accent];this.ctx.fillStyle=this.colorWithAlpha(a[i%a.length],e.alpha+t*.2),this.ctx.fill()}drawBubbles(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();this.bubbles.forEach(i=>{i.y-=i.speed*t*(.3+e*2),i.x+=Math.sin(this.time*2*t+i.phase)*i.wobble*.05,i.y<this.centerY-this.sphereRadius*.8&&(i.y=this.centerY+this.sphereRadius*.6,i.x=this.centerX+(Math.random()-.5)*this.sphereRadius);const s=this.ctx.createRadialGradient(i.x-i.radius*.3,i.y-i.radius*.3,0,i.x,i.y,i.radius);s.addColorStop(0,"rgba(255, 255, 255, 0.8)"),s.addColorStop(.5,"rgba(255, 255, 255, 0.2)"),s.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.arc(i.x,i.y,i.radius*(1+e*.3),0,Math.PI*2),this.ctx.fillStyle=s,this.ctx.fill()}),this.ctx.restore()}drawCaustics(e){const i=this.getSpeedMultiplier();for(let s=0;s<5;s++){const r=s/5*Math.PI*2+this.time*.5*i,o=this.sphereRadius*.4+Math.sin(this.time*2*i+s)*10*(.3+e),a=this.centerX+Math.cos(r)*o,c=this.centerY+this.sphereRadius*.25+Math.sin(r)*o*.3,d=this.ctx.createRadialGradient(a,c,0,a,c,15+e*10),l=.2+e*.35;d.addColorStop(0,this.colorWithAlpha(this.colors.accent,l)),d.addColorStop(.5,this.colorWithAlpha(this.colors.primary,l*.5)),d.addColorStop(1,this.colorWithAlpha(this.colors.primary,0)),this.ctx.beginPath(),this.ctx.arc(a,c,15+e*10,0,Math.PI*2),this.ctx.fillStyle=d,this.ctx.fill()}}drawReflections(e){const t=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.25,this.centerY-this.sphereRadius*.3,0,this.centerX-this.sphereRadius*.25,this.centerY-this.sphereRadius*.3,this.sphereRadius*.35);t.addColorStop(0,`rgba(255, 255, 255, ${.6+e*.2})`),t.addColorStop(.3,"rgba(255, 255, 255, 0.2)"),t.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.ellipse(this.centerX-this.sphereRadius*.25,this.centerY-this.sphereRadius*.3,this.sphereRadius*.2,this.sphereRadius*.12,-.5,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(this.centerX+this.sphereRadius*.3,this.centerY-this.sphereRadius*.2,this.sphereRadius*.08,0,Math.PI*2);const i=this.ctx.createRadialGradient(this.centerX+this.sphereRadius*.3,this.centerY-this.sphereRadius*.2,0,this.centerX+this.sphereRadius*.3,this.centerY-this.sphereRadius*.2,this.sphereRadius*.08);i.addColorStop(0,"rgba(255, 255, 255, 0.5)"),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=i,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-1,0,Math.PI*2),this.ctx.strokeStyle=`rgba(255, 255, 255, ${.15+e*.1})`,this.ctx.lineWidth=1.5,this.ctx.stroke()}}class Tp extends Ci{constructor(e,t,i,s){super(e,t,i,s),this.nodes=[],this.sphereRadius=t*.38,this.initNodes()}initNodes(){this.nodes=[],this.nodes.push(this.createNode(0,0,0));const e=5;for(let i=0;i<e;i++){const s=i/e*Math.PI*2;this.nodes.push(this.createNode(s,this.sphereRadius*.35,1))}const t=8;for(let i=0;i<t;i++){const s=i/t*Math.PI*2+Math.PI/t;this.nodes.push(this.createNode(s,this.sphereRadius*.7,2))}for(let i=1;i<=e;i++)this.nodes[0].connections.push(i);for(let i=1;i<=e;i++){const s=e+1+(i-1)*2%t,r=e+1+((i-1)*2+1)%t;this.nodes[i].connections.push(s),this.nodes[i].connections.push(r)}for(let i=1;i<=e;i++)this.nodes[i].connections.push(i%e+1)}createNode(e,t,i){return{angle:e,baseDist:t,layer:i,radius:3+Math.random()*2,pulseOffset:Math.random()*Math.PI*2,connections:[],activity:0,targetActivity:0,floatSpeed:.5+Math.random()*.5,floatOffset:Math.random()*Math.PI*2}}getNodePosition(e){const t=this.audioLevel,i=this.getSpeedMultiplier(),s=this.isActive?0:6,r=Math.sin(this.time*e.floatSpeed*i+e.floatOffset)*(4+s+t*10),o=Math.cos(this.time*e.floatSpeed*.7*i+e.floatOffset)*(3+s*.7+t*5),a=e.baseDist+Math.sin(this.time*i+e.pulseOffset)*5*(.7+t);return{x:this.centerX+Math.cos(e.angle)*a+o,y:this.centerY+Math.sin(e.angle)*a+r}}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawGlassSphere(t),this.drawLiquidBackground(t),this.updateNodes(t),this.drawConnections(t),this.drawNodes(t),this.drawReflections(t)}drawGlassSphere(e){const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.sphereRadius*.7,this.centerX,this.centerY,this.sphereRadius*1.3),i=(.15+e*.2)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.glow,i)),t.addColorStop(.5,this.colorWithAlpha(this.colors.glow,i*.5)),t.addColorStop(1,this.colorWithAlpha(this.colors.glow,0)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius*1.3,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill();const s=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.2,this.centerY-this.sphereRadius*.2,0,this.centerX,this.centerY,this.sphereRadius);s.addColorStop(0,"rgba(200, 255, 220, 0.1)"),s.addColorStop(.5,this.colorWithAlpha(this.colors.primary,.05)),s.addColorStop(1,this.colorWithAlpha(this.colors.secondary,.08)),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius,0,Math.PI*2),this.ctx.fillStyle=s,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius,0,Math.PI*2),this.ctx.strokeStyle=this.colorWithAlpha(this.colors.accent,.2+e*.15),this.ctx.lineWidth=1.5,this.ctx.stroke()}drawLiquidBackground(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();for(let i=0;i<3;i++){const s=20-i*15,r=3+(this.isActive?0:3.5)+e*8,o=(1+i*.3)*t;this.ctx.beginPath(),this.ctx.moveTo(this.centerX-this.sphereRadius,this.centerY+s);for(let c=-this.sphereRadius;c<=this.sphereRadius;c+=3){if(Math.abs(c)/this.sphereRadius>.95)continue;const l=Math.sin(c*.08+this.time*o*3)*r+Math.sin(c*.05+this.time*o*2)*r*.5,u=this.centerY+s+l;this.ctx.lineTo(this.centerX+c,u)}this.ctx.lineTo(this.centerX+this.sphereRadius*.95,this.centerY+this.sphereRadius*.9),this.ctx.lineTo(this.centerX-this.sphereRadius*.95,this.centerY+this.sphereRadius*.9),this.ctx.closePath();const a=.12-i*.03+e*.08;this.ctx.fillStyle=this.colorWithAlpha(this.colors.secondary,a),this.ctx.fill()}this.ctx.restore()}updateNodes(e){this.nodes.forEach((t,i)=>{t.activity+=(t.targetActivity-t.activity)*.1,this.isActive?t.targetActivity=.5+Math.sin(this.time*2+i*.7)*.3+e*.5:t.targetActivity=.15})}drawConnections(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();this.nodes.forEach((i,s)=>{const r=this.getNodePosition(i);i.connections.forEach(o=>{const a=this.nodes[o],c=this.getNodePosition(a),d=(i.activity+a.activity)/2,l=(r.x+c.x)/2+Math.sin(this.time*2*t)*3*e,u=(r.y+c.y)/2+Math.cos(this.time*2.5*t)*3*e,h=this.ctx.createLinearGradient(r.x,r.y,c.x,c.y),f=.15+d*.4+e*.3;if(h.addColorStop(0,this.colorWithAlpha(this.colors.primary,f)),h.addColorStop(.5,this.colorWithAlpha(this.colors.accent,f*1.3)),h.addColorStop(1,this.colorWithAlpha(this.colors.primary,f)),this.ctx.beginPath(),this.ctx.moveTo(r.x,r.y),this.ctx.quadraticCurveTo(l,u,c.x,c.y),this.ctx.strokeStyle=h,this.ctx.lineWidth=1.5+d*2+e*1.5,this.ctx.stroke(),this.isActive&&(d>.2||e>.2)){const m=(this.time*1.5*t+i.pulseOffset)%1,k=(1-m)*(1-m)*r.x+2*(1-m)*m*l+m*m*c.x,S=(1-m)*(1-m)*r.y+2*(1-m)*m*u+m*m*c.y;this.ctx.beginPath(),this.ctx.arc(k,S,2.5+e*2,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.8+e*.2),this.ctx.fill()}})}),this.ctx.restore()}drawNodes(e){this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.sphereRadius-2,0,Math.PI*2),this.ctx.clip();const t=this.getSpeedMultiplier();this.nodes.forEach(i=>{const s=this.getNodePosition(i),r=Math.sin(this.time*3*t+i.pulseOffset)*.15+.85,o=i.radius*(1+i.activity*.5+e*.5),a=o*(3+i.activity*2+e*3),c=this.ctx.createRadialGradient(s.x,s.y,0,s.x,s.y,a),d=.4+i.activity*.4+e*.3;c.addColorStop(0,this.colorWithAlpha(this.colors.primary,d)),c.addColorStop(.4,this.colorWithAlpha(this.colors.secondary,d*.5)),c.addColorStop(1,this.colorWithAlpha(this.colors.primary,0)),this.ctx.beginPath(),this.ctx.arc(s.x,s.y,a,0,Math.PI*2),this.ctx.fillStyle=c,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(s.x,s.y,o*r,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.9),this.ctx.fill()}),this.ctx.restore()}drawReflections(e){const t=this.ctx.createRadialGradient(this.centerX-this.sphereRadius*.22,this.centerY-this.sphereRadius*.28,0,this.centerX-this.sphereRadius*.22,this.centerY-this.sphereRadius*.28,this.sphereRadius*.3);t.addColorStop(0,`rgba(255, 255, 255, ${.6+e*.2})`),t.addColorStop(.4,"rgba(255, 255, 255, 0.2)"),t.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.ellipse(this.centerX-this.sphereRadius*.22,this.centerY-this.sphereRadius*.28,this.sphereRadius*.18,this.sphereRadius*.1,-.4,0,Math.PI*2),this.ctx.fillStyle=t,this.ctx.fill()}}let lc=class{constructor(e=Math.random()*1e4){this.p=new Uint8Array(256);for(let i=0;i<256;i++)this.p[i]=i;let t=e;for(let i=255;i>0;i--){t=t*16807%2147483647;const s=t%(i+1);[this.p[i],this.p[s]]=[this.p[s],this.p[i]]}this.perm=new Uint8Array(512);for(let i=0;i<512;i++)this.perm[i]=this.p[i&255]}noise2D(e,t){const i=.5*(Math.sqrt(3)-1),s=(3-Math.sqrt(3))/6,r=(e+t)*i,o=Math.floor(e+r),a=Math.floor(t+r),c=(o+a)*s,d=e-(o-c),l=t-(a-c),u=d>l?1:0,h=d>l?0:1,f=d-u+s,g=l-h+s,m=d-1+2*s,k=l-1+2*s,S=o&255,R=a&255,I=(O,L,B)=>{const G=O&7,se=G<4?L:B,be=G<4?B:L;return(G&1?-se:se)+(G&2?-2*be:2*be)};let b=0,y=0,E=0,A=.5-d*d-l*l;A>=0&&(A*=A,b=A*A*I(this.perm[S+this.perm[R]],d,l));let D=.5-f*f-g*g;D>=0&&(D*=D,y=D*D*I(this.perm[S+u+this.perm[R+h]],f,g));let M=.5-m*m-k*k;return M>=0&&(M*=M,E=M*M*I(this.perm[S+1+this.perm[R+1]],m,k)),70*(b+y+E)}noise3D(e,t,i){return(this.noise2D(e,t)+this.noise2D(e+100,i)+this.noise2D(t+200,i))/3}};class Ep extends Ci{constructor(e,t,i,s){super(e,t,i,s),this.noise1=new lc(42),this.noise2=new lc(137),this.baseRadius=t*.38}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawGlow(t);const i=this.createShape(t);this.drawShape(i),this.drawHighlight(i,t)}createShape(e){const t=[],s=this.getSpeedMultiplier(),r=8+e*25+(this.isActive?0:10),o=5+e*15+(this.isActive?0:6);for(let a=0;a<=120;a++){const c=a/120*Math.PI*2,d=Math.cos(c),l=Math.sin(c),u=this.noise1.noise3D(d*.8,l*.8,this.time*.3*s),h=this.noise2.noise3D(d*1.5,l*1.5,this.time*.5*s),f=Math.sin(c*4+this.time*2*s)*e*8,g=u*r+h*o*.5+f,m=this.baseRadius+g;t.push({x:this.centerX+d*m,y:this.centerY+l*m})}return t}drawGlow(e){const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.baseRadius*.3,this.centerX,this.centerY,this.baseRadius*1.2+e*30),i=(.3+e*.4)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.glow,i)),t.addColorStop(1,this.colorWithAlpha(this.colors.glow,0)),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,this.size,this.size)}drawShape(e){const t=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.2,this.centerY-this.baseRadius*.2,0,this.centerX,this.centerY,this.baseRadius);t.addColorStop(0,this.colorWithAlpha(this.colors.accent,.95)),t.addColorStop(.5,this.colorWithAlpha(this.colors.primary,.9)),t.addColorStop(1,this.colorWithAlpha(this.colors.secondary,.85)),this.ctx.beginPath(),this.ctx.moveTo(e[0].x,e[0].y);for(let i=1;i<e.length-1;i++){const s=(e[i].x+e[i+1].x)/2,r=(e[i].y+e[i+1].y)/2;this.ctx.quadraticCurveTo(e[i].x,e[i].y,s,r)}this.ctx.closePath(),this.ctx.fillStyle=t,this.ctx.fill()}drawHighlight(e,t){const i=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.2,this.centerY-this.baseRadius*.2,0,this.centerX-this.baseRadius*.15,this.centerY-this.baseRadius*.15,this.baseRadius*.6);i.addColorStop(0,`rgba(255, 255, 255, ${.5+t*.3})`),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.beginPath(),this.ctx.moveTo(e[0].x,e[0].y);for(let s=1;s<e.length-1;s++){const r=(e[s].x+e[s+1].x)/2,o=(e[s].y+e[s+1].y)/2;this.ctx.quadraticCurveTo(e[s].x,e[s].y,r,o)}this.ctx.closePath(),this.ctx.fillStyle=i,this.ctx.fill()}}class qs extends Ci{constructor(e,t,i,s){super(e,t,i,s),this.nodes=[],this.thicknessScale=1,this.glowRadiusScale=1,this.activeBlend=0,this.initNetwork()}setThicknessScale(e){this.thicknessScale=Math.min(1.6,Math.max(.8,e))}setGlowRadiusScale(e){this.glowRadiusScale=Math.min(1.2,Math.max(.5,e))}resetDynamics(){super.resetDynamics(),this.activeBlend=0,this.nodes.forEach(e=>{e.activity=0,e.targetActivity=0})}initNetwork(){this.nodes=[];const e=this.size*.35;this.nodes.push(this.createNode(this.centerX,this.centerY,0));for(let t=0;t<6;t++){const i=t/6*Math.PI*2-Math.PI/2,s=e*.5;this.nodes.push(this.createNode(this.centerX+Math.cos(i)*s,this.centerY+Math.sin(i)*s,1))}for(let t=0;t<12;t++){const i=t/12*Math.PI*2,s=e;this.nodes.push(this.createNode(this.centerX+Math.cos(i)*s,this.centerY+Math.sin(i)*s,2))}for(let t=1;t<=6;t++)this.nodes[0].connections.push(t);for(let t=1;t<=6;t++){const i=7+(t-1)*2;this.nodes[t].connections.push(i%12+7),this.nodes[t].connections.push((i+1)%12+7)}for(let t=1;t<=6;t++)this.nodes[t].connections.push(t%6+1)}createNode(e,t,i){return{x:e,y:t,baseX:e,baseY:t,layer:i,radius:3+Math.random()*2,pulseOffset:Math.random()*Math.PI*2,connections:[],activity:0,targetActivity:0}}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e,i=this.activeBlend;this.updateNodes(t,i),this.drawConnections(t,i),this.drawNodes(t,i),this.size<=200&&this.applyEdgeFade()}update(){this.updateColors();const e=1-Math.pow(1-this.animation.smoothing,this.frameDelta);this.audioLevel+=(this.targetAudioLevel-this.audioLevel)*e;const t=this.animation.idleSpeed*.012,i=this.animation.responseSpeed*.025,s=this.isActive?1:0,o=1-Math.pow(1-.12,this.frameDelta);this.activeBlend+=(s-this.activeBlend)*o;const a=t+(i-t)*this.activeBlend;this.time+=a*this.frameDelta}getSpeedMultiplier(e=this.activeBlend){return .6+(1.5-.6)*e}updateNodes(e,t){const i=this.getSpeedMultiplier(t),s=this.time*(1.35-.45*t),r=this.size*.01*(1-t),o=this.size*.012*(1-t),a=7,c=8+e*12,d=a+(c-a)*t;this.nodes.forEach((l,u)=>{const h=Math.sin(s+(l.baseX+l.baseY)*.04)*(1-t),f=Math.sin(s*.95+(l.baseX-l.baseY)*.045)*(1-t);l.x=l.baseX+Math.sin(this.time*.5*i+l.pulseOffset)*d+h*r,l.y=l.baseY+Math.cos(this.time*.7*i+l.pulseOffset)*d+f*o,l.activity+=(l.targetActivity-l.activity)*.1;const g=.5+Math.sin(this.time*2*i+u*.5)*.3+e*.5,m=.22+Math.sin(this.time*i*1.25+u*.3)*.12+h*.08;l.targetActivity=m+(g-m)*t})}drawConnections(e,t){const s=2*this.getSpeedMultiplier(t)*(1+.6*(1-t));this.nodes.forEach(r=>{r.connections.forEach(o=>{const a=this.nodes[o],c=(r.activity+a.activity)/2,d=this.ctx.createLinearGradient(r.x,r.y,a.x,a.y),l=.1+c*.4+e*.3;d.addColorStop(0,this.colorWithAlpha(this.colors.primary,l)),d.addColorStop(.5,this.colorWithAlpha(this.colors.accent,l*1.2)),d.addColorStop(1,this.colorWithAlpha(this.colors.primary,l)),this.ctx.beginPath(),this.ctx.moveTo(r.x,r.y),this.ctx.lineTo(a.x,a.y),this.ctx.strokeStyle=d,this.ctx.lineWidth=(1+c*2+e)*this.thicknessScale,this.ctx.stroke();const u=1-t;if(c>.15||e>.15||u>.4){const h=(this.time*s+r.pulseOffset)%1,f=r.x+(a.x-r.x)*h,g=r.y+(a.y-r.y)*h;this.ctx.beginPath(),this.ctx.arc(f,g,(2+e*2)*this.thicknessScale,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.5+c*.3+e*.2),this.ctx.fill()}})})}drawNodes(e,t){const i=this.getSpeedMultiplier(t),s=this.getGlowScale(),r=.95+Math.sin(this.time*.9)*.05,o=r+(1-r)*t;this.nodes.forEach(a=>{const c=Math.sin(this.time*3*i+a.pulseOffset)*.3+.7,d=a.radius*(1+a.activity*.5+e*.5)*o,l=d*this.thicknessScale,u=d*(2+a.activity*3+e*2)*s*this.glowRadiusScale,h=this.ctx.createRadialGradient(a.x,a.y,0,a.x,a.y,u),f=(.3+a.activity*.5+e*.3)*s;h.addColorStop(0,this.colorWithAlpha(this.colors.primary,f)),h.addColorStop(.5,this.colorWithAlpha(this.colors.primary,f*.3)),h.addColorStop(1,this.colorWithAlpha(this.colors.primary,0)),this.ctx.beginPath(),this.ctx.arc(a.x,a.y,u,0,Math.PI*2),this.ctx.fillStyle=h,this.ctx.fill(),this.ctx.beginPath(),this.ctx.arc(a.x,a.y,l*c,0,Math.PI*2),this.ctx.fillStyle=this.colorWithAlpha(this.colors.accent,.9),this.ctx.fill()})}getGlowScale(){return Math.min(1,this.size/180)}applyEdgeFade(){const e=this.size*.48,t=this.size*.12,i=this.ctx.createRadialGradient(this.centerX,this.centerY,Math.max(0,e-t),this.centerX,this.centerY,e);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.save(),this.ctx.globalCompositeOperation="destination-in",this.ctx.fillStyle=i,this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,e,0,Math.PI*2),this.ctx.fill(),this.ctx.restore()}}class wp{constructor(e=Math.random()*1e4){this.p=new Uint8Array(256);for(let i=0;i<256;i++)this.p[i]=i;let t=e;for(let i=255;i>0;i--){t=t*16807%2147483647;const s=t%(i+1);[this.p[i],this.p[s]]=[this.p[s],this.p[i]]}this.perm=new Uint8Array(512);for(let i=0;i<512;i++)this.perm[i]=this.p[i&255]}noise3D(e,t,i){const s=.3333333333333333,r=1/6,o=(e+t+i)*s,a=Math.floor(e+o),c=Math.floor(t+o),d=Math.floor(i+o),l=(a+c+d)*r,u=e-(a-l),h=t-(c-l),f=i-(d-l);let g,m,k,S,R,I;u>=h?h>=f?(g=1,m=0,k=0,S=1,R=1,I=0):u>=f?(g=1,m=0,k=0,S=1,R=0,I=1):(g=0,m=0,k=1,S=1,R=0,I=1):h<f?(g=0,m=0,k=1,S=0,R=1,I=1):u<f?(g=0,m=1,k=0,S=0,R=1,I=1):(g=0,m=1,k=0,S=1,R=1,I=0);const b=u-g+r,y=h-m+r,E=f-k+r,A=u-S+2*r,D=h-R+2*r,M=f-I+2*r,O=u-1+3*r,L=h-1+3*r,B=f-1+3*r,G=a&255,se=c&255,be=d&255,ae=(pn,Jt,pc,Mp)=>{const Yt=pn&15,fc=Yt<8?Jt:pc,mc=Yt<4?pc:Yt===12||Yt===14?Jt:Mp;return(Yt&1?-fc:fc)+(Yt&2?-mc:mc)};let De=0,Ht=0,zt=0,Kt=0,Ye=.6-u*u-h*h-f*f;Ye>=0&&(Ye*=Ye,De=Ye*Ye*ae(this.perm[G+this.perm[se+this.perm[be]]],u,h,f));let Xe=.6-b*b-y*y-E*E;Xe>=0&&(Xe*=Xe,Ht=Xe*Xe*ae(this.perm[G+g+this.perm[se+m+this.perm[be+k]]],b,y,E));let Qe=.6-A*A-D*D-M*M;Qe>=0&&(Qe*=Qe,zt=Qe*Qe*ae(this.perm[G+S+this.perm[se+R+this.perm[be+I]]],A,D,M));let Et=.6-O*O-L*L-B*B;return Et>=0&&(Et*=Et,Kt=Et*Et*ae(this.perm[G+1+this.perm[se+1+this.perm[be+1]]],O,L,B)),32*(De+Ht+zt+Kt)}}class Pp extends Ci{constructor(e,t,i,s){super(e,t,i,s),this.rotationX=0,this.rotationY=0,this.noise=new wp(42),this.baseRadius=t*.35}update(){super.update();const e=this.getSpeedMultiplier();this.rotationX+=.003*e,this.rotationY+=.005*e}render(){this.clear();const e=this.getIntensityMultiplier(),t=this.audioLevel*e;this.drawOuterGlow(t),this.drawBlob(t),this.drawIridescentHighlights(t),this.drawReflection(t)}drawOuterGlow(e){const t=this.ctx.createRadialGradient(this.centerX,this.centerY,this.baseRadius*.5,this.centerX,this.centerY,this.baseRadius*1.8),i=(.25+e*.35)*this.animation.glowIntensity;t.addColorStop(0,this.colorWithAlpha(this.colors.primary,i)),t.addColorStop(.4,this.colorWithAlpha(this.colors.secondary,i*.5)),t.addColorStop(.7,this.colorWithAlpha(this.colors.accent,i*.2)),t.addColorStop(1,"rgba(0, 0, 0, 0)"),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,this.size,this.size)}drawBlob(e){const s=.15+e*.35+(this.isActive?0:.08),r=this.getSpeedMultiplier();for(let o=0;o<3;o++){const a=o*.1,c=1-o*.2;this.ctx.beginPath();for(let u=0;u<=72;u++){const h=u/72*Math.PI*2,f=Math.cos(h),g=Math.sin(h),m=this.noise.noise3D(f*1.5+this.rotationX,g*1.5+this.rotationY,this.time*.5*r+a),k=Math.sin(this.time*3*r+h*2)*e*.1,S=this.baseRadius*(1+m*s+k),R=this.centerX+Math.cos(h)*S,I=this.centerY+Math.sin(h)*S;u===0?this.ctx.moveTo(R,I):this.ctx.lineTo(R,I)}this.ctx.closePath();const d=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.3,this.centerY-this.baseRadius*.3,0,this.centerX,this.centerY,this.baseRadius*1.2),l=Math.sin(this.time*.3*r)*30;d.addColorStop(0,this.shiftHue(this.colors.accent,l,c*.9)),d.addColorStop(.4,this.shiftHue(this.colors.primary,l+20,c*.8)),d.addColorStop(.7,this.shiftHue(this.colors.secondary,l+40,c*.7)),d.addColorStop(1,this.shiftHue(this.colors.primary,l+60,c*.5)),this.ctx.fillStyle=d,this.ctx.fill()}}drawIridescentHighlights(e){const t=this.getSpeedMultiplier();for(let i=0;i<3;i++){const s=this.time*.5*t+i*(Math.PI*2/3),r=this.baseRadius*.4,o=this.centerX+Math.cos(s)*r,a=this.centerY+Math.sin(s)*r*.6,c=this.ctx.createRadialGradient(o,a,0,o,a,this.baseRadius*.4),d=(this.time*50*t+i*120)%360;c.addColorStop(0,`hsla(${d}, 80%, 70%, ${.3+e*.3})`),c.addColorStop(.5,`hsla(${d+30}, 70%, 60%, ${.15+e*.15})`),c.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=c,this.ctx.beginPath(),this.ctx.arc(o,a,this.baseRadius*.4,0,Math.PI*2),this.ctx.fill()}}drawReflection(e){const t=this.ctx.createRadialGradient(this.centerX-this.baseRadius*.25,this.centerY-this.baseRadius*.3,0,this.centerX-this.baseRadius*.25,this.centerY-this.baseRadius*.3,this.baseRadius*.4);t.addColorStop(0,`rgba(255, 255, 255, ${.7+e*.2})`),t.addColorStop(.3,`rgba(255, 255, 255, ${.3+e*.1})`),t.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=t,this.ctx.beginPath(),this.ctx.ellipse(this.centerX-this.baseRadius*.25,this.centerY-this.baseRadius*.3,this.baseRadius*.25,this.baseRadius*.15,-.4,0,Math.PI*2),this.ctx.fill();const i=this.ctx.createRadialGradient(this.centerX,this.centerY,this.baseRadius*.8,this.centerX,this.centerY,this.baseRadius*1.1);i.addColorStop(0,"rgba(255, 255, 255, 0)"),i.addColorStop(.5,`rgba(255, 255, 255, ${.1+e*.1})`),i.addColorStop(1,"rgba(255, 255, 255, 0)"),this.ctx.fillStyle=i,this.ctx.beginPath(),this.ctx.arc(this.centerX,this.centerY,this.baseRadius*1.1,0,Math.PI*2),this.ctx.fill()}shiftHue(e,t,i){if(!e.startsWith("#"))return this.colorWithAlpha(e,i);const s=e.slice(1),r=parseInt(s.slice(0,2),16)/255,o=parseInt(s.slice(2,4),16)/255,a=parseInt(s.slice(4,6),16)/255,c=Math.max(r,o,a),d=Math.min(r,o,a);let l=0;const u=(c+d)/2,h=c===d?0:u>.5?(c-d)/(2-c-d):(c-d)/(c+d);return c!==d&&(c===r?l=(o-a)/(c-d)%6:c===o?l=(a-r)/(c-d)+2:l=(r-o)/(c-d)+4,l*=60,l<0&&(l+=360)),l=(l+t)%360,l<0&&(l+=360),`hsla(${l}, ${h*100}%, ${u*100}%, ${i})`}}function uc(n,e,t,i,s){switch(n){case"liquid-glass":case"liquid-glass-premium":return new dc(e,t,i,s);case"neural-liquid":return new Tp(e,t,i,s);case"neural-orbit":case"neural-network":return new qs(e,t,i,s);case"synaptic-core":return new qs(e,t,i,s);case"organic-sphere":return new Ep(e,t,i,s);case"morphing-blob":return new Pp(e,t,i,s);default:return new dc(e,t,i,s)}}var Rp=Object.defineProperty,_p=Object.getOwnPropertyDescriptor,Q=(n,e,t,i)=>{for(var s=i>1?void 0:i?_p(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Rp(e,t,s),s};N.InlineCall=class extends xt{constructor(){super(...arguments),this.callManager=new ec,this.theme="neural-blue",this.visualStyle="neural-network",this.orbSize=400,this.hideButton=!1,this.buttonPosition="bottom",this.callStatus="idle",this.prefersLightScheme=!1,this.colorSchemeQuery=null,this.renderer=null,this.audioSimTimer=null,this.audioSimFrameId=null,this.audioSimPhase=0,this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,this.baseColors=null,this.themeColors=null,this.baseAnimation=null,this.buttonStartText="Start Call",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.handleColorSchemeChange=e=>{this.prefersLightScheme=e.matches},this.handleStatusChange=e=>{switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="idle";break}},this.toggleCall=async()=>{if(!this.agentId)return new Error("Agent ID is required to make a call.");this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callManager.hangUp()}}get callState(){switch(this.callStatus){case"connecting":return"connecting";case"connected":return"active";default:return"idle"}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.setupColorSchemeListener()}disconnectedCallback(){var e;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.hangUp(),this.teardownColorSchemeListener(),(e=this.renderer)==null||e.destroy(),this.renderer=null,this.stopAudioSimulation()}updated(e){var t;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("visualStyle")||e.has("theme")||e.has("orbSize")||e.has("orbColor")||e.has("orbColorLight")||e.has("orbColorDark")||e.has("prefersLightScheme"))&&this.setupRenderer(),e.has("callStatus")&&((t=this.renderer)==null||t.setActive(this.callState==="active"),this.callState==="active"?this.startAudioSimulation():this.stopAudioSimulation(),this.syncOrbAppearance()),(e.has("activeOrbColor")||e.has("activeOrbColorLight")||e.has("activeOrbColorDark"))&&this.syncOrbAppearance(),(e.has("buttonColor")||e.has("buttonHoverColor")||e.has("buttonActiveColor")||e.has("buttonTextColor"))&&this.updateButtonThemeVars()}firstUpdated(){this.setupRenderer()}setupRenderer(){var s;const e=this.renderRoot.querySelector("#orb-canvas");if(!e)return;const t=this.theme==="custom"?ln("liquid-purple"):ln(this.theme),i=cc({...t,style:this.visualStyle,size:{...t.size,orbDiameter:this.orbSize}});this.themeColors=i.colors,this.baseColors=this.getBaseOrbColors(i.colors),this.baseAnimation=i.animation,this.style.setProperty("--hanc-orb-size",`${i.size.orbDiameter}px`),this.updateButtonThemeVars(),(s=this.renderer)==null||s.destroy(),this.renderer=uc(i.style,e,i.size.orbDiameter,this.baseColors,i.animation),this.applyNeuralNetworkTuning(),this.renderer.setActive(this.callState==="active"),this.renderer.start(),this.syncOrbAppearance()}setupColorSchemeListener(){typeof window>"u"||!window.matchMedia||(this.colorSchemeQuery=window.matchMedia("(prefers-color-scheme: light)"),this.prefersLightScheme=this.colorSchemeQuery.matches,this.colorSchemeQuery.addEventListener?this.colorSchemeQuery.addEventListener("change",this.handleColorSchemeChange):this.colorSchemeQuery.addListener&&this.colorSchemeQuery.addListener(this.handleColorSchemeChange))}teardownColorSchemeListener(){this.colorSchemeQuery&&(this.colorSchemeQuery.removeEventListener?this.colorSchemeQuery.removeEventListener("change",this.handleColorSchemeChange):this.colorSchemeQuery.removeListener&&this.colorSchemeQuery.removeListener(this.handleColorSchemeChange),this.colorSchemeQuery=null)}clamp(e,t,i){return Math.min(i,Math.max(t,e))}resolveColorValue(e){var a;const t=e==null?void 0:e.trim();if(!t)return;if(!t.startsWith("var(")||typeof window>"u"||!window.getComputedStyle)return t;const i=t.match(/^var\(\s*(--[^,\s)]+)\s*(?:,\s*([^)]+)\s*)?\)$/);if(!i)return;const s=i[1],r=(a=i[2])==null?void 0:a.trim(),o=getComputedStyle(this).getPropertyValue(s).trim()||getComputedStyle(document.documentElement).getPropertyValue(s).trim();return o||r||void 0}buildOrbPalette(e,t){if(nc(e)===null)return{...t,primary:e};const s=this.prefersLightScheme,r=s?.28:.18,o=s?"#000000":"#ffffff",a=s?.4:.25,c=s?"#000000":"#ffffff",d=s?.22:.45;return{...t,primary:e,secondary:pe(e,"#000000",r),accent:pe(e,o,a),glow:pe(e,c,d)}}getBaseOrbColors(e){var r,o,a;const i=(this.prefersLightScheme?(r=this.orbColorLight)==null?void 0:r.trim():(o=this.orbColorDark)==null?void 0:o.trim())||((a=this.orbColor)==null?void 0:a.trim()),s=this.resolveColorValue(i);return s?this.buildOrbPalette(s,e):e}getActiveSeedColor(e){var a,c,d;const i=(this.prefersLightScheme?(a=this.activeOrbColorLight)==null?void 0:a.trim():(c=this.activeOrbColorDark)==null?void 0:c.trim())||((d=this.activeOrbColor)==null?void 0:d.trim()),s=this.resolveColorValue(i);if(s)return s;const r=this.prefersLightScheme?"#000000":"#ffffff",o=this.prefersLightScheme?.2:.25;return pe(e.primary,r,o)}getActiveColors(e){const t=this.getActiveSeedColor(e);return this.buildOrbPalette(t,e)}getButtonColors(e){var o,a,c,d;const t=((o=this.buttonColor)==null?void 0:o.trim())||e.button,i=((a=this.buttonHoverColor)==null?void 0:a.trim())||pe(t,"#000000",.12),s=((c=this.buttonActiveColor)==null?void 0:c.trim())||pe(t,"#000000",.35),r=((d=this.buttonTextColor)==null?void 0:d.trim())||e.buttonText;return{...e,button:t,buttonHover:i,buttonActive:s,buttonText:r}}updateButtonThemeVars(){if(!this.themeColors)return;if(!(!!this.buttonColor||!!this.buttonHoverColor||!!this.buttonActiveColor||!!this.buttonTextColor)){this.theme!=="custom"&&hn(this,this.themeColors);return}hn(this,this.getButtonColors(this.themeColors))}getAnimationForState(){const e=this.baseAnimation,t=this.isActive,i=1.2,s=1.4,r=t?1.5:1.2,o=this.prefersLightScheme?.85:1,a=t?s:i,c=t?1.3:1.05;return{...e,idleSpeed:this.clamp(e.idleSpeed*a,.05,1),responseSpeed:this.clamp(e.responseSpeed*c,.05,1),glowIntensity:this.clamp(e.glowIntensity*r*o,0,1)}}syncOrbAppearance(){if(!this.renderer||!this.baseColors||!this.baseAnimation)return;const e=this.getActiveSeedColor(this.baseColors),t=this.prefersLightScheme?.3:.45;if(this.style.setProperty("--hanc-orb-active-glow",sc(e,t)),this.renderer.setAnimation(this.getAnimationForState()),this.isActive){this.renderer.setColors(this.getActiveColors(this.baseColors));return}this.renderer.setColors(this.baseColors)}applyNeuralNetworkTuning(){if(!(this.renderer instanceof qs))return;if(this.visualStyle!=="neural-network"){this.renderer.setThicknessScale(1),this.renderer.setGlowRadiusScale(1);return}const e=this.prefersLightScheme?1.35:1,t=this.prefersLightScheme?.7:1;this.renderer.setThicknessScale(e),this.renderer.setGlowRadiusScale(t)}startAudioSimulation(){if(this.audioSimTimer!==null||this.audioSimFrameId!==null)return;this.audioSimPhase=Math.random()*Math.PI*2,this.simulatedTargetLevel=.32,this.simulatedCurrentLevel=this.simulatedTargetLevel,this.audioSimTimer=window.setInterval(()=>{const t=Math.sin(this.audioSimPhase)*.18,i=(Math.random()-.5)*.08,s=.32+t+i;this.simulatedTargetLevel=this.clamp(s,.12,.6),this.audioSimPhase+=.35+Math.random()*.12},180);const e=()=>{var t;if(this.audioSimTimer===null){this.audioSimFrameId=null;return}this.simulatedCurrentLevel+=(this.simulatedTargetLevel-this.simulatedCurrentLevel)*.12,(t=this.renderer)==null||t.setAudioLevel(this.simulatedCurrentLevel),this.audioSimFrameId=requestAnimationFrame(e)};this.audioSimFrameId=requestAnimationFrame(e)}stopAudioSimulation(){var e;this.audioSimTimer!==null&&(clearInterval(this.audioSimTimer),this.audioSimTimer=null),this.audioSimFrameId!==null&&(cancelAnimationFrame(this.audioSimFrameId),this.audioSimFrameId=null),this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,(e=this.renderer)==null||e.setAudioLevel(0)}get isActive(){return this.callStatus==="connected"}get buttonText(){switch(this.callStatus){case"connecting":return this.buttonConnectingText;case"connected":return this.buttonEndText;default:return this.buttonStartText}}render(){return Pt`
289
+ <div class="widget" part="wrapper" data-state=${this.callStatus}>
285
290
  <div
286
291
  class="orb-container"
287
292
  part="orb-container"
@@ -300,12 +305,12 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
300
305
  data-calling=${String(this.isActive)}
301
306
  ?disabled=${this.callStatus==="connecting"}
302
307
  >
303
- ${this.callStatus==="connected"?tc:ec}
308
+ ${this.callStatus==="connected"?ac:rc}
304
309
  <span part="button-text">${this.buttonText}</span>
305
310
  </button>
306
311
  `}
307
312
  </div>
308
- `}},L.InlineCall.styles=[nr,Oc],le([j({type:String,attribute:"agent-id"})],L.InlineCall.prototype,"agentId",2),le([j({type:String,attribute:"voice-service-url"})],L.InlineCall.prototype,"voiceServiceUrl",2),le([j({type:String})],L.InlineCall.prototype,"theme",2),le([j({type:String,attribute:"visual-style"})],L.InlineCall.prototype,"visualStyle",2),le([j({type:Number,attribute:"orb-size"})],L.InlineCall.prototype,"orbSize",2),le([j({type:String,attribute:"orb-color"})],L.InlineCall.prototype,"orbColor",2),le([j({type:Boolean,attribute:"hide-button"})],L.InlineCall.prototype,"hideButton",2),le([j({type:String,attribute:"button-position",reflect:!0})],L.InlineCall.prototype,"buttonPosition",2),le([j({type:String,attribute:"active-orb-color"})],L.InlineCall.prototype,"activeOrbColor",2),le([j({type:String,attribute:"button-color"})],L.InlineCall.prototype,"buttonColor",2),le([j({type:String,attribute:"button-hover-color"})],L.InlineCall.prototype,"buttonHoverColor",2),le([j({type:String,attribute:"button-active-color"})],L.InlineCall.prototype,"buttonActiveColor",2),le([j({type:String,attribute:"button-text-color"})],L.InlineCall.prototype,"buttonTextColor",2),le([ir()],L.InlineCall.prototype,"callStatus",2),le([j({type:String,attribute:"button-start-text"})],L.InlineCall.prototype,"buttonStartText",2),le([j({type:String,attribute:"button-connecting-text"})],L.InlineCall.prototype,"buttonConnectingText",2),le([j({type:String,attribute:"button-end-text"})],L.InlineCall.prototype,"buttonEndText",2),L.InlineCall=le([tr("hanc-ai-inline-call")],L.InlineCall);const Cp=fn`
313
+ `}},N.InlineCall.styles=[rr,Uc],Q([F({type:String,attribute:"agent-id"})],N.InlineCall.prototype,"agentId",2),Q([F({type:String,attribute:"voice-service-url"})],N.InlineCall.prototype,"voiceServiceUrl",2),Q([F({type:String})],N.InlineCall.prototype,"theme",2),Q([F({type:String,attribute:"visual-style"})],N.InlineCall.prototype,"visualStyle",2),Q([F({type:Number,attribute:"orb-size"})],N.InlineCall.prototype,"orbSize",2),Q([F({type:String,attribute:"orb-color"})],N.InlineCall.prototype,"orbColor",2),Q([F({type:String,attribute:"orb-color-light"})],N.InlineCall.prototype,"orbColorLight",2),Q([F({type:String,attribute:"orb-color-dark"})],N.InlineCall.prototype,"orbColorDark",2),Q([F({type:Boolean,attribute:"hide-button"})],N.InlineCall.prototype,"hideButton",2),Q([F({type:String,attribute:"button-position",reflect:!0})],N.InlineCall.prototype,"buttonPosition",2),Q([F({type:String,attribute:"active-orb-color"})],N.InlineCall.prototype,"activeOrbColor",2),Q([F({type:String,attribute:"active-orb-color-light"})],N.InlineCall.prototype,"activeOrbColorLight",2),Q([F({type:String,attribute:"active-orb-color-dark"})],N.InlineCall.prototype,"activeOrbColorDark",2),Q([F({type:String,attribute:"button-color"})],N.InlineCall.prototype,"buttonColor",2),Q([F({type:String,attribute:"button-hover-color"})],N.InlineCall.prototype,"buttonHoverColor",2),Q([F({type:String,attribute:"button-active-color"})],N.InlineCall.prototype,"buttonActiveColor",2),Q([F({type:String,attribute:"button-text-color"})],N.InlineCall.prototype,"buttonTextColor",2),Q([Pi()],N.InlineCall.prototype,"callStatus",2),Q([Pi()],N.InlineCall.prototype,"prefersLightScheme",2),Q([F({type:String,attribute:"button-start-text"})],N.InlineCall.prototype,"buttonStartText",2),Q([F({type:String,attribute:"button-connecting-text"})],N.InlineCall.prototype,"buttonConnectingText",2),Q([F({type:String,attribute:"button-end-text"})],N.InlineCall.prototype,"buttonEndText",2),N.InlineCall=Q([sr("hanc-ai-inline-call")],N.InlineCall);const xp=gn`
309
314
  :host {
310
315
  display: block;
311
316
  position: fixed;
@@ -349,10 +354,15 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
349
354
  box-shadow:
350
355
  0 20px 40px rgba(0, 0, 0, 0.4),
351
356
  0 0 60px var(--hanc-glow-shadow, rgba(139, 92, 246, 0.1));
352
- transition: box-shadow 0.3s ease, transform 0.3s ease;
357
+ transition:
358
+ box-shadow 0.3s ease,
359
+ transform 0.3s ease;
353
360
  overflow: visible;
354
361
  }
355
362
 
363
+ .widget[data-state='connecting'] {
364
+ cursor: not-allowed;
365
+ }
356
366
  .widget:hover {
357
367
  transform: translateY(-4px);
358
368
  box-shadow:
@@ -381,10 +391,19 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
381
391
  animation: orb-twist-active 11s ease-in-out infinite;
382
392
  }
383
393
 
394
+ .orb-container[data-state='connecting'] {
395
+ pointer-events: none;
396
+ opacity: 0.75;
397
+ filter: saturate(0.7) brightness(0.9);
398
+ }
399
+
384
400
  .orb-container[data-active='true'] {
385
- filter:
386
- drop-shadow(0 0 14px var(--hanc-orb-active-glow, rgba(139, 92, 246, 0.35)))
387
- drop-shadow(0 0 32px var(--hanc-orb-active-glow, rgba(139, 92, 246, 0.25)));
401
+ filter: drop-shadow(
402
+ 0 0 14px var(--hanc-orb-active-glow, rgba(139, 92, 246, 0.35))
403
+ )
404
+ drop-shadow(
405
+ 0 0 32px var(--hanc-orb-active-glow, rgba(139, 92, 246, 0.25))
406
+ );
388
407
  }
389
408
 
390
409
  canvas {
@@ -432,10 +451,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
432
451
  .button:hover {
433
452
  background: var(
434
453
  --hanc-button-hover,
435
- var(
436
- --hanc-button,
437
- linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%)
438
- )
454
+ var(--hanc-button, linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%))
439
455
  );
440
456
  transform: translateY(-2px);
441
457
  box-shadow: 0 8px 25px
@@ -517,8 +533,8 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
517
533
  animation: none;
518
534
  }
519
535
  }
520
- `;var Ep=Object.defineProperty,Pp=Object.getOwnPropertyDescriptor,X=(n,e,t,i)=>{for(var s=i>1?void 0:i?Pp(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ep(e,t,s),s};L.FloatingCall=class extends _t{constructor(){super(...arguments),this.callManager=new Qo,this.theme="neural-blue",this.visualStyle="neural-network",this.position="bottom-right",this.offsetX=24,this.offsetY=24,this.orbSize=120,this.hideButton=!1,this.buttonPosition="bottom",this.minimized=!1,this.callStatus="idle",this.renderer=null,this.audioSimTimer=null,this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,this.baseColors=null,this.themeColors=null,this.baseAnimation=null,this.labelText="Need a help?",this.buttonStartText="Start Call",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.handleStatusChange=e=>{switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="idle";break}},this.toggleCall=async()=>{if(!this.agentId)return new Error("Agent ID is required to make a call.");this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callManager.hangUp()}}get callState(){switch(this.callStatus){case"connecting":return"connecting";case"connected":return"active";default:return"idle"}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.style.setProperty("--hanc-offset-x",`${this.offsetX}px`),this.style.setProperty("--hanc-offset-y",`${this.offsetY}px`)}disconnectedCallback(){var e;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.hangUp(),(e=this.renderer)==null||e.destroy(),this.renderer=null,this.stopAudioSimulation()}updated(e){var t;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&(this.callManager.serviceUrl=this.voiceServiceUrl),e.has("offsetX")&&this.style.setProperty("--hanc-offset-x",`${this.offsetX}px`),e.has("offsetY")&&this.style.setProperty("--hanc-offset-y",`${this.offsetY}px`),(e.has("visualStyle")||e.has("theme")||e.has("orbSize")||e.has("orbColor"))&&this.setupRenderer(),e.has("callStatus")&&((t=this.renderer)==null||t.setActive(this.callState==="active"),this.callState==="active"?this.startAudioSimulation():this.stopAudioSimulation(),this.syncOrbAppearance()),e.has("activeOrbColor")&&this.syncOrbAppearance(),(e.has("buttonColor")||e.has("buttonHoverColor")||e.has("buttonActiveColor")||e.has("buttonTextColor"))&&this.updateButtonThemeVars()}firstUpdated(){this.setupRenderer()}setupRenderer(){var s;const e=this.renderRoot.querySelector("#orb-canvas");if(!e)return;const t=this.theme==="custom"?cn("liquid-purple"):cn(this.theme),i=nc({...t,style:this.visualStyle,size:{...t.size,orbDiameter:this.orbSize}});this.themeColors=i.colors,this.baseColors=this.getBaseOrbColors(i.colors),this.baseAnimation=i.animation,this.style.setProperty("--hanc-orb-size",`${i.size.orbDiameter}px`),this.updateButtonThemeVars(),(s=this.renderer)==null||s.destroy(),this.renderer=oc(i.style,e,i.size.orbDiameter,this.baseColors,i.animation),this.renderer.setActive(this.callState==="active"),this.renderer.start(),this.syncOrbAppearance()}clamp(e,t,i){return Math.min(i,Math.max(t,e))}buildOrbPalette(e,t){return{...t,primary:e,secondary:pe(e,"#000000",.18),accent:pe(e,"#ffffff",.25),glow:pe(e,"#ffffff",.45)}}getBaseOrbColors(e){var i;const t=(i=this.orbColor)==null?void 0:i.trim();return t?this.buildOrbPalette(t,e):e}getActiveSeedColor(e){var i;const t=(i=this.activeOrbColor)==null?void 0:i.trim();return t||pe(e.primary,"#ffffff",.25)}getActiveColors(e){const t=this.getActiveSeedColor(e);return this.buildOrbPalette(t,e)}getButtonColors(e){var o,a,c,d;const t=((o=this.buttonColor)==null?void 0:o.trim())||e.button,i=((a=this.buttonHoverColor)==null?void 0:a.trim())||pe(t,"#000000",.12),s=((c=this.buttonActiveColor)==null?void 0:c.trim())||pe(t,"#000000",.35),r=((d=this.buttonTextColor)==null?void 0:d.trim())||e.buttonText;return{...e,button:t,buttonHover:i,buttonActive:s,buttonText:r}}updateButtonThemeVars(){if(!this.themeColors)return;if(!(!!this.buttonColor||!!this.buttonHoverColor||!!this.buttonActiveColor||!!this.buttonTextColor)){this.theme!=="custom"&&ln(this,this.themeColors);return}ln(this,this.getButtonColors(this.themeColors))}getAnimationForState(){const e=this.baseAnimation,t=this.isActive,i=1.2,s=1.4,r=t?1.5:1.2,o=t?s:i,a=t?1.3:1.05;return{...e,idleSpeed:this.clamp(e.idleSpeed*o,.05,1),responseSpeed:this.clamp(e.responseSpeed*a,.05,1),glowIntensity:this.clamp(e.glowIntensity*r,0,1)}}syncOrbAppearance(){if(!this.renderer||!this.baseColors||!this.baseAnimation)return;const e=this.getActiveSeedColor(this.baseColors);if(this.style.setProperty("--hanc-orb-active-glow",Zo(e,.45)),this.renderer.setAnimation(this.getAnimationForState()),this.isActive){this.renderer.setColors(this.getActiveColors(this.baseColors));return}this.renderer.setColors(this.baseColors)}startAudioSimulation(){if(this.audioSimTimer!==null)return;this.simulatedTargetLevel=.25,this.audioSimTimer=window.setInterval(()=>{const t=(Math.random()-.5)*.25,i=this.simulatedTargetLevel+t;this.simulatedTargetLevel=Math.min(.85,Math.max(.12,i))},180);const e=()=>{var t;this.audioSimTimer!==null&&(this.simulatedCurrentLevel+=(this.simulatedTargetLevel-this.simulatedCurrentLevel)*.12,(t=this.renderer)==null||t.setAudioLevel(this.simulatedCurrentLevel),requestAnimationFrame(e))};requestAnimationFrame(e)}stopAudioSimulation(){var e;this.audioSimTimer!==null&&(clearInterval(this.audioSimTimer),this.audioSimTimer=null),this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,(e=this.renderer)==null||e.setAudioLevel(0)}get isActive(){return this.callStatus==="connected"}get buttonText(){switch(this.callStatus){case"connecting":return this.buttonConnectingText;case"connected":return this.buttonEndText;default:return this.buttonStartText}}render(){return Pt`
521
- <div class="widget" part="root">
536
+ `;var Ip=Object.defineProperty,Ap=Object.getOwnPropertyDescriptor,K=(n,e,t,i)=>{for(var s=i>1?void 0:i?Ap(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ip(e,t,s),s};N.FloatingCall=class extends xt{constructor(){super(...arguments),this.callManager=new ec,this.theme="neural-blue",this.visualStyle="neural-network",this.position="bottom-right",this.offsetX=24,this.offsetY=24,this.orbSize=120,this.hideButton=!1,this.buttonPosition="bottom",this.minimized=!1,this.callStatus="idle",this.prefersLightScheme=!1,this.colorSchemeQuery=null,this.renderer=null,this.audioSimTimer=null,this.audioSimFrameId=null,this.audioSimPhase=0,this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,this.baseColors=null,this.themeColors=null,this.baseAnimation=null,this.labelText="Need a help?",this.buttonStartText="Start Call",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.handleColorSchemeChange=e=>{this.prefersLightScheme=e.matches},this.handleStatusChange=e=>{switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="idle";break}},this.toggleCall=async()=>{if(!this.agentId)return new Error("Agent ID is required to make a call.");this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callManager.hangUp()}}get callState(){switch(this.callStatus){case"connecting":return"connecting";case"connected":return"active";default:return"idle"}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.setupColorSchemeListener(),this.style.setProperty("--hanc-offset-x",`${this.offsetX}px`),this.style.setProperty("--hanc-offset-y",`${this.offsetY}px`)}disconnectedCallback(){var e;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.hangUp(),this.teardownColorSchemeListener(),(e=this.renderer)==null||e.destroy(),this.renderer=null,this.stopAudioSimulation()}updated(e){var t;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&(this.callManager.serviceUrl=this.voiceServiceUrl),e.has("offsetX")&&this.style.setProperty("--hanc-offset-x",`${this.offsetX}px`),e.has("offsetY")&&this.style.setProperty("--hanc-offset-y",`${this.offsetY}px`),(e.has("visualStyle")||e.has("theme")||e.has("orbSize")||e.has("orbColor")||e.has("orbColorLight")||e.has("orbColorDark")||e.has("prefersLightScheme"))&&this.setupRenderer(),e.has("callStatus")&&((t=this.renderer)==null||t.setActive(this.callState==="active"),this.callState==="active"?this.startAudioSimulation():this.stopAudioSimulation(),this.syncOrbAppearance()),(e.has("activeOrbColor")||e.has("activeOrbColorLight")||e.has("activeOrbColorDark"))&&this.syncOrbAppearance(),(e.has("buttonColor")||e.has("buttonHoverColor")||e.has("buttonActiveColor")||e.has("buttonTextColor"))&&this.updateButtonThemeVars()}firstUpdated(){this.setupRenderer()}setupRenderer(){var s;const e=this.renderRoot.querySelector("#orb-canvas");if(!e)return;const t=this.theme==="custom"?ln("liquid-purple"):ln(this.theme),i=cc({...t,style:this.visualStyle,size:{...t.size,orbDiameter:this.orbSize}});this.themeColors=i.colors,this.baseColors=this.getBaseOrbColors(i.colors),this.baseAnimation=i.animation,this.style.setProperty("--hanc-orb-size",`${i.size.orbDiameter}px`),this.updateButtonThemeVars(),(s=this.renderer)==null||s.destroy(),this.renderer=uc(i.style,e,i.size.orbDiameter,this.baseColors,i.animation),this.renderer.setActive(this.callState==="active"),this.renderer.start(),this.syncOrbAppearance()}setupColorSchemeListener(){typeof window>"u"||!window.matchMedia||(this.colorSchemeQuery=window.matchMedia("(prefers-color-scheme: light)"),this.prefersLightScheme=this.colorSchemeQuery.matches,this.colorSchemeQuery.addEventListener?this.colorSchemeQuery.addEventListener("change",this.handleColorSchemeChange):this.colorSchemeQuery.addListener&&this.colorSchemeQuery.addListener(this.handleColorSchemeChange))}teardownColorSchemeListener(){this.colorSchemeQuery&&(this.colorSchemeQuery.removeEventListener?this.colorSchemeQuery.removeEventListener("change",this.handleColorSchemeChange):this.colorSchemeQuery.removeListener&&this.colorSchemeQuery.removeListener(this.handleColorSchemeChange),this.colorSchemeQuery=null)}clamp(e,t,i){return Math.min(i,Math.max(t,e))}resolveColorValue(e){var a;const t=e==null?void 0:e.trim();if(!t)return;if(!t.startsWith("var(")||typeof window>"u"||!window.getComputedStyle)return t;const i=t.match(/^var\(\s*(--[^,\s)]+)\s*(?:,\s*([^)]+)\s*)?\)$/);if(!i)return;const s=i[1],r=(a=i[2])==null?void 0:a.trim(),o=getComputedStyle(this).getPropertyValue(s).trim()||getComputedStyle(document.documentElement).getPropertyValue(s).trim();return o||r||void 0}buildOrbPalette(e,t){return nc(e)===null?{...t,primary:e}:{...t,primary:e,secondary:pe(e,"#000000",.18),accent:pe(e,"#ffffff",.25),glow:pe(e,"#ffffff",.45)}}getBaseOrbColors(e){var r,o,a;const i=(this.prefersLightScheme?(r=this.orbColorLight)==null?void 0:r.trim():(o=this.orbColorDark)==null?void 0:o.trim())||((a=this.orbColor)==null?void 0:a.trim()),s=this.resolveColorValue(i);return s?this.buildOrbPalette(s,e):e}getActiveSeedColor(e){var r,o,a;const i=(this.prefersLightScheme?(r=this.activeOrbColorLight)==null?void 0:r.trim():(o=this.activeOrbColorDark)==null?void 0:o.trim())||((a=this.activeOrbColor)==null?void 0:a.trim()),s=this.resolveColorValue(i);return s||pe(e.primary,"#ffffff",.25)}getActiveColors(e){const t=this.getActiveSeedColor(e);return this.buildOrbPalette(t,e)}getButtonColors(e){var o,a,c,d;const t=((o=this.buttonColor)==null?void 0:o.trim())||e.button,i=((a=this.buttonHoverColor)==null?void 0:a.trim())||pe(t,"#000000",.12),s=((c=this.buttonActiveColor)==null?void 0:c.trim())||pe(t,"#000000",.35),r=((d=this.buttonTextColor)==null?void 0:d.trim())||e.buttonText;return{...e,button:t,buttonHover:i,buttonActive:s,buttonText:r}}updateButtonThemeVars(){if(!this.themeColors)return;if(!(!!this.buttonColor||!!this.buttonHoverColor||!!this.buttonActiveColor||!!this.buttonTextColor)){this.theme!=="custom"&&hn(this,this.themeColors);return}hn(this,this.getButtonColors(this.themeColors))}getAnimationForState(){const e=this.baseAnimation,t=this.isActive,i=1.2,s=1.4,r=t?1.5:1.2,o=t?s:i,a=t?1.3:1.05;return{...e,idleSpeed:this.clamp(e.idleSpeed*o,.05,1),responseSpeed:this.clamp(e.responseSpeed*a,.05,1),glowIntensity:this.clamp(e.glowIntensity*r,0,1)}}syncOrbAppearance(){if(!this.renderer||!this.baseColors||!this.baseAnimation)return;const e=this.getActiveSeedColor(this.baseColors);if(this.style.setProperty("--hanc-orb-active-glow",sc(e,.45)),this.renderer.setAnimation(this.getAnimationForState()),this.isActive){this.renderer.setColors(this.getActiveColors(this.baseColors));return}this.renderer.setColors(this.baseColors)}startAudioSimulation(){if(this.audioSimTimer!==null||this.audioSimFrameId!==null)return;this.audioSimPhase=Math.random()*Math.PI*2,this.simulatedTargetLevel=.32,this.simulatedCurrentLevel=this.simulatedTargetLevel,this.audioSimTimer=window.setInterval(()=>{const t=Math.sin(this.audioSimPhase)*.18,i=(Math.random()-.5)*.08,s=.32+t+i;this.simulatedTargetLevel=this.clamp(s,.12,.6),this.audioSimPhase+=.35+Math.random()*.12},180);const e=()=>{var t;if(this.audioSimTimer===null){this.audioSimFrameId=null;return}this.simulatedCurrentLevel+=(this.simulatedTargetLevel-this.simulatedCurrentLevel)*.12,(t=this.renderer)==null||t.setAudioLevel(this.simulatedCurrentLevel),this.audioSimFrameId=requestAnimationFrame(e)};this.audioSimFrameId=requestAnimationFrame(e)}stopAudioSimulation(){var e;this.audioSimTimer!==null&&(clearInterval(this.audioSimTimer),this.audioSimTimer=null),this.audioSimFrameId!==null&&(cancelAnimationFrame(this.audioSimFrameId),this.audioSimFrameId=null),this.simulatedTargetLevel=0,this.simulatedCurrentLevel=0,(e=this.renderer)==null||e.setAudioLevel(0)}get isActive(){return this.callStatus==="connected"}get buttonText(){switch(this.callStatus){case"connecting":return this.buttonConnectingText;case"connected":return this.buttonEndText;default:return this.buttonStartText}}render(){return Pt`
537
+ <div class="widget" part="root" data-state=${this.callStatus}>
522
538
  <div
523
539
  class="orb-container"
524
540
  part="avatar-wrapper"
@@ -540,10 +556,10 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
540
556
  data-calling=${String(this.isActive)}
541
557
  ?disabled=${this.callStatus==="connecting"}
542
558
  >
543
- ${this.callStatus==="connected"?tc:ec}
559
+ ${this.callStatus==="connected"?ac:rc}
544
560
  <span part="button-text">${this.buttonText}</span>
545
561
  </button>
546
562
  `}
547
563
  </div>
548
564
  </div>
549
- `}},L.FloatingCall.styles=[nr,Cp],X([j({type:String,attribute:"agent-id"})],L.FloatingCall.prototype,"agentId",2),X([j({type:String,attribute:"voice-service-url"})],L.FloatingCall.prototype,"voiceServiceUrl",2),X([j({type:String})],L.FloatingCall.prototype,"theme",2),X([j({type:String,attribute:"visual-style"})],L.FloatingCall.prototype,"visualStyle",2),X([j({type:String,reflect:!0})],L.FloatingCall.prototype,"position",2),X([j({type:Number,attribute:"offset-x"})],L.FloatingCall.prototype,"offsetX",2),X([j({type:Number,attribute:"offset-y"})],L.FloatingCall.prototype,"offsetY",2),X([j({type:Number,attribute:"orb-size"})],L.FloatingCall.prototype,"orbSize",2),X([j({type:String,attribute:"orb-color"})],L.FloatingCall.prototype,"orbColor",2),X([j({type:Boolean,attribute:"hide-button"})],L.FloatingCall.prototype,"hideButton",2),X([j({type:String,attribute:"button-position",reflect:!0})],L.FloatingCall.prototype,"buttonPosition",2),X([j({type:String,attribute:"active-orb-color"})],L.FloatingCall.prototype,"activeOrbColor",2),X([j({type:String,attribute:"button-color"})],L.FloatingCall.prototype,"buttonColor",2),X([j({type:String,attribute:"button-hover-color"})],L.FloatingCall.prototype,"buttonHoverColor",2),X([j({type:String,attribute:"button-active-color"})],L.FloatingCall.prototype,"buttonActiveColor",2),X([j({type:String,attribute:"button-text-color"})],L.FloatingCall.prototype,"buttonTextColor",2),X([j({type:Boolean,reflect:!0})],L.FloatingCall.prototype,"minimized",2),X([ir()],L.FloatingCall.prototype,"callStatus",2),X([j({type:String,attribute:"label-text"})],L.FloatingCall.prototype,"labelText",2),X([j({type:String,attribute:"button-start-text"})],L.FloatingCall.prototype,"buttonStartText",2),X([j({type:String,attribute:"button-connecting-text"})],L.FloatingCall.prototype,"buttonConnectingText",2),X([j({type:String,attribute:"button-end-text"})],L.FloatingCall.prototype,"buttonEndText",2),L.FloatingCall=X([tr("hanc-ai-floating-call")],L.FloatingCall),Object.defineProperty(L,Symbol.toStringTag,{value:"Module"})}));
565
+ `}},N.FloatingCall.styles=[rr,xp],K([F({type:String,attribute:"agent-id"})],N.FloatingCall.prototype,"agentId",2),K([F({type:String,attribute:"voice-service-url"})],N.FloatingCall.prototype,"voiceServiceUrl",2),K([F({type:String})],N.FloatingCall.prototype,"theme",2),K([F({type:String,attribute:"visual-style"})],N.FloatingCall.prototype,"visualStyle",2),K([F({type:String,reflect:!0})],N.FloatingCall.prototype,"position",2),K([F({type:Number,attribute:"offset-x"})],N.FloatingCall.prototype,"offsetX",2),K([F({type:Number,attribute:"offset-y"})],N.FloatingCall.prototype,"offsetY",2),K([F({type:Number,attribute:"orb-size"})],N.FloatingCall.prototype,"orbSize",2),K([F({type:String,attribute:"orb-color"})],N.FloatingCall.prototype,"orbColor",2),K([F({type:String,attribute:"orb-color-light"})],N.FloatingCall.prototype,"orbColorLight",2),K([F({type:String,attribute:"orb-color-dark"})],N.FloatingCall.prototype,"orbColorDark",2),K([F({type:Boolean,attribute:"hide-button"})],N.FloatingCall.prototype,"hideButton",2),K([F({type:String,attribute:"button-position",reflect:!0})],N.FloatingCall.prototype,"buttonPosition",2),K([F({type:String,attribute:"active-orb-color"})],N.FloatingCall.prototype,"activeOrbColor",2),K([F({type:String,attribute:"active-orb-color-light"})],N.FloatingCall.prototype,"activeOrbColorLight",2),K([F({type:String,attribute:"active-orb-color-dark"})],N.FloatingCall.prototype,"activeOrbColorDark",2),K([F({type:String,attribute:"button-color"})],N.FloatingCall.prototype,"buttonColor",2),K([F({type:String,attribute:"button-hover-color"})],N.FloatingCall.prototype,"buttonHoverColor",2),K([F({type:String,attribute:"button-active-color"})],N.FloatingCall.prototype,"buttonActiveColor",2),K([F({type:String,attribute:"button-text-color"})],N.FloatingCall.prototype,"buttonTextColor",2),K([F({type:Boolean,reflect:!0})],N.FloatingCall.prototype,"minimized",2),K([Pi()],N.FloatingCall.prototype,"callStatus",2),K([Pi()],N.FloatingCall.prototype,"prefersLightScheme",2),K([F({type:String,attribute:"label-text"})],N.FloatingCall.prototype,"labelText",2),K([F({type:String,attribute:"button-start-text"})],N.FloatingCall.prototype,"buttonStartText",2),K([F({type:String,attribute:"button-connecting-text"})],N.FloatingCall.prototype,"buttonConnectingText",2),K([F({type:String,attribute:"button-end-text"})],N.FloatingCall.prototype,"buttonEndText",2),N.FloatingCall=K([sr("hanc-ai-floating-call")],N.FloatingCall),Object.defineProperty(N,Symbol.toStringTag,{value:"Module"})}));