obi-sdk 0.1.6 → 0.1.8

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.
@@ -2,19 +2,19 @@
2
2
  * @license
3
3
  * Copyright 2019 Google LLC
4
4
  * SPDX-License-Identifier: BSD-3-Clause
5
- */const un=globalThis,hs=un.ShadowRoot&&(un.ShadyCSS===void 0||un.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Hr=Symbol(),Zr=new WeakMap;let bd=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==Hr)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(hs&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=Zr.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Zr.set(t,e))}return e}toString(){return this.cssText}};const kd=n=>new bd(typeof n=="string"?n:n+"",void 0,Hr),Td=(n,e)=>{if(hs)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),s=un.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=t.cssText,n.appendChild(i)}},Jr=hs?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return kd(t)})(n):n;/**
5
+ */const hn=globalThis,ps=hn.ShadowRoot&&(hn.ShadyCSS===void 0||hn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Jr=Symbol(),Yr=new WeakMap;let Sd=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==Jr)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(ps&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=Yr.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Yr.set(t,e))}return e}toString(){return this.cssText}};const Cd=n=>new Sd(typeof n=="string"?n:n+"",void 0,Jr),_d=(n,e)=>{if(ps)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),s=hn.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=t.cssText,n.appendChild(i)}},Qr=ps?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return Cd(t)})(n):n;/**
6
6
  * @license
7
7
  * Copyright 2017 Google LLC
8
8
  * SPDX-License-Identifier: BSD-3-Clause
9
- */const{is:Sd,defineProperty:Cd,getOwnPropertyDescriptor:_d,getOwnPropertyNames:Ed,getOwnPropertySymbols:wd,getPrototypeOf:Pd}=Object,ht=globalThis,Yr=ht.trustedTypes,Rd=Yr?Yr.emptyScript:"",fs=ht.reactiveElementPolyfillSupport,_i=(n,e)=>n,hn={toAttribute(n,e){switch(e){case Boolean:n=n?Rd: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}},ps=(n,e)=>!Sd(n,e),Qr={attribute:!0,type:String,converter:hn,reflect:!1,useDefault:!1,hasChanged:ps};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ht.litPropertyMetadata??(ht.litPropertyMetadata=new WeakMap);let Ei=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=Qr){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&&Cd(this.prototype,e,s)}}static getPropertyDescriptor(e,t,i){const{get:s,set:r}=_d(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:s,set(a){const o=s==null?void 0:s.call(this);r==null||r.call(this,a),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Qr}static _$Ei(){if(this.hasOwnProperty(_i("elementProperties")))return;const e=Pd(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(_i("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(_i("properties"))){const t=this.properties,i=[...Ed(t),...wd(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(Jr(s))}else e!==void 0&&t.push(Jr(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 Td(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 a=(((r=i.converter)==null?void 0:r.toAttribute)!==void 0?i.converter:hn).toAttribute(t,i.type);this._$Em=e,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(e,t){var r,a;const i=this.constructor,s=i._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const o=i.getPropertyOptions(s),c=typeof o.converter=="function"?{fromAttribute:o.converter}:((r=o.converter)==null?void 0:r.fromAttribute)!==void 0?o.converter:hn;this._$Em=s,this[s]=c.fromAttribute(t,o.type)??((a=this._$Ej)==null?void 0:a.get(s))??null,this._$Em=null}}requestUpdate(e,t,i){var s;if(e!==void 0){const r=this.constructor,a=this[e];if(i??(i=r.getPropertyOptions(e)),!((i.hasChanged??ps)(a,t)||i.useDefault&&i.reflect&&a===((s=this._$Ej)==null?void 0:s.get(e))&&!this.hasAttribute(r._$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},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),r!==!0||a!==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,a]of this._$Ep)this[r]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,a]of s){const{wrapped:o}=a,c=this[r];o!==!0||this._$AL.has(r)||c===void 0||this.C(r,void 0,a,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){}};Ei.elementStyles=[],Ei.shadowRootOptions={mode:"open"},Ei[_i("elementProperties")]=new Map,Ei[_i("finalized")]=new Map,fs==null||fs({ReactiveElement:Ei}),(ht.reactiveElementVersions??(ht.reactiveElementVersions=[])).push("2.1.0");/**
9
+ */const{is:Ed,defineProperty:wd,getOwnPropertyDescriptor:Pd,getOwnPropertyNames:Rd,getOwnPropertySymbols:xd,getPrototypeOf:Id}=Object,ft=globalThis,Xr=ft.trustedTypes,Ad=Xr?Xr.emptyScript:"",ms=ft.reactiveElementPolyfillSupport,Ei=(n,e)=>n,fn={toAttribute(n,e){switch(e){case Boolean:n=n?Ad: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}},gs=(n,e)=>!Ed(n,e),ea={attribute:!0,type:String,converter:fn,reflect:!1,useDefault:!1,hasChanged:gs};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ft.litPropertyMetadata??(ft.litPropertyMetadata=new WeakMap);let wi=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=ea){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&&wd(this.prototype,e,s)}}static getPropertyDescriptor(e,t,i){const{get:s,set:r}=Pd(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:s,set(a){const o=s==null?void 0:s.call(this);r==null||r.call(this,a),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??ea}static _$Ei(){if(this.hasOwnProperty(Ei("elementProperties")))return;const e=Id(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Ei("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ei("properties"))){const t=this.properties,i=[...Rd(t),...xd(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(Qr(s))}else e!==void 0&&t.push(Qr(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 _d(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 a=(((r=i.converter)==null?void 0:r.toAttribute)!==void 0?i.converter:fn).toAttribute(t,i.type);this._$Em=e,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(e,t){var r,a;const i=this.constructor,s=i._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const o=i.getPropertyOptions(s),c=typeof o.converter=="function"?{fromAttribute:o.converter}:((r=o.converter)==null?void 0:r.fromAttribute)!==void 0?o.converter:fn;this._$Em=s,this[s]=c.fromAttribute(t,o.type)??((a=this._$Ej)==null?void 0:a.get(s))??null,this._$Em=null}}requestUpdate(e,t,i){var s;if(e!==void 0){const r=this.constructor,a=this[e];if(i??(i=r.getPropertyOptions(e)),!((i.hasChanged??gs)(a,t)||i.useDefault&&i.reflect&&a===((s=this._$Ej)==null?void 0:s.get(e))&&!this.hasAttribute(r._$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},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),r!==!0||a!==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,a]of this._$Ep)this[r]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,a]of s){const{wrapped:o}=a,c=this[r];o!==!0||this._$AL.has(r)||c===void 0||this.C(r,void 0,a,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){}};wi.elementStyles=[],wi.shadowRootOptions={mode:"open"},wi[Ei("elementProperties")]=new Map,wi[Ei("finalized")]=new Map,ms==null||ms({ReactiveElement:wi}),(ft.reactiveElementVersions??(ft.reactiveElementVersions=[])).push("2.1.0");/**
10
10
  * @license
11
11
  * Copyright 2017 Google LLC
12
12
  * SPDX-License-Identifier: BSD-3-Clause
13
- */const xd={attribute:!0,type:String,converter:hn,reflect:!1,hasChanged:ps},Id=(n=xd,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:a}=t;return{set(o){const c=e.get.call(this);e.set.call(this,o),this.requestUpdate(a,c,n)},init(o){return o!==void 0&&this.C(a,void 0,n,o),o}}}if(i==="setter"){const{name:a}=t;return function(o){const c=this[a];e.call(this,o),this.requestUpdate(a,c,n)}}throw Error("Unsupported decorator location: "+i)};function Y(n){return(e,t)=>typeof t=="object"?Id(n,e,t):((i,s,r)=>{const a=s.hasOwnProperty(r);return s.constructor.createProperty(r,i),a?Object.getOwnPropertyDescriptor(s,r):void 0})(n,e,t)}/**
13
+ */const Od={attribute:!0,type:String,converter:fn,reflect:!1,hasChanged:gs},Dd=(n=Od,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:a}=t;return{set(o){const c=e.get.call(this);e.set.call(this,o),this.requestUpdate(a,c,n)},init(o){return o!==void 0&&this.C(a,void 0,n,o),o}}}if(i==="setter"){const{name:a}=t;return function(o){const c=this[a];e.call(this,o),this.requestUpdate(a,c,n)}}throw Error("Unsupported decorator location: "+i)};function Y(n){return(e,t)=>typeof t=="object"?Dd(n,e,t):((i,s,r)=>{const a=s.hasOwnProperty(r);return s.constructor.createProperty(r,i),a?Object.getOwnPropertyDescriptor(s,r):void 0})(n,e,t)}/**
14
14
  * @license
15
15
  * Copyright 2017 Google LLC
16
16
  * SPDX-License-Identifier: BSD-3-Clause
17
- */function ft(n){return Y({...n,state:!0,attribute:!1})}const ke=Symbol.for("@ts-pattern/matcher"),Xr=Symbol.for("@ts-pattern/isVariadic"),fn="@ts-pattern/anonymous-select-key",ms=n=>!!(n&&typeof n=="object"),pn=n=>n&&!!n[ke],me=(n,e,t)=>{if(pn(n)){const i=n[ke](),{matched:s,selections:r}=i.match(e);return s&&r&&Object.keys(r).forEach(a=>t(a,r[a])),s}if(ms(n)){if(!ms(e))return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;let i=[],s=[],r=[];for(const a of n.keys()){const o=n[a];pn(o)&&o[Xr]?r.push(o):r.length?s.push(o):i.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<i.length+s.length)return!1;const a=e.slice(0,i.length),o=s.length===0?[]:e.slice(-s.length),c=e.slice(i.length,s.length===0?1/0:-s.length);return i.every((d,l)=>me(d,a[l],t))&&s.every((d,l)=>me(d,o[l],t))&&(r.length===0||me(r[0],c,t))}return n.length===e.length&&n.every((a,o)=>me(a,e[o],t))}return Reflect.ownKeys(n).every(i=>{const s=n[i];return(i in e||pn(r=s)&&r[ke]().matcherType==="optional")&&me(s,e[i],t);var r})}return Object.is(e,n)},Pe=n=>{var e,t,i;return ms(n)?pn(n)?(e=(t=(i=n[ke]()).getSelectionKeys)==null?void 0:t.call(i))!=null?e:[]:Array.isArray(n)?wi(n,Pe):wi(Object.values(n),Pe):[]},wi=(n,e)=>n.reduce((t,i)=>t.concat(e(i)),[]);function Ad(...n){if(n.length===1){const[e]=n;return t=>me(e,t,()=>{})}if(n.length===2){const[e,t]=n;return me(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${n.length}.`)}function ge(n){return Object.assign(n,{optional:()=>vs(n),and:e=>ie(n,e),or:e=>ea(n,e),select:e=>e===void 0?Pi(n):Pi(e,n)})}function gs(n){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const i=[{value:Object.assign(e,{[Xr]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var s;return(s=i[t++])!=null?s:i.at(-1)}}}}))(n),{optional:()=>gs(vs(n)),select:e=>gs(e===void 0?Pi(n):Pi(e,n))})}function vs(n){return ge({[ke]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return e===void 0?(Pe(n).forEach(s=>i(s,void 0)),{matched:!0,selections:t}):{matched:me(n,e,i),selections:t}},getSelectionKeys:()=>Pe(n),matcherType:"optional"})})}const Od=(n,e)=>{for(const t of n)if(!e(t))return!1;return!0},Dd=(n,e)=>{for(const[t,i]of n.entries())if(!e(i,t))return!1;return!0};function ie(...n){return ge({[ke]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return{matched:n.every(s=>me(s,e,i)),selections:t}},getSelectionKeys:()=>wi(n,Pe),matcherType:"and"})})}function ea(...n){return ge({[ke]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return wi(n,Pe).forEach(s=>i(s,void 0)),{matched:n.some(s=>me(s,e,i)),selections:t}},getSelectionKeys:()=>wi(n,Pe),matcherType:"or"})})}function W(n){return{[ke]:()=>({match:e=>({matched:!!n(e)})})}}function Pi(...n){const e=typeof n[0]=="string"?n[0]:void 0,t=n.length===2?n[1]:typeof n[0]=="string"?void 0:n[0];return ge({[ke]:()=>({match:i=>{let s={[e??fn]:i};return{matched:t===void 0||me(t,i,(r,a)=>{s[r]=a}),selections:s}},getSelectionKeys:()=>[e??fn].concat(t===void 0?[]:Pe(t))})})}function qe(n){return typeof n=="number"}function pt(n){return typeof n=="string"}function mt(n){return typeof n=="bigint"}const ta=ge(W(function(n){return!0})),Md=ta,gt=n=>Object.assign(ge(n),{startsWith:e=>{return gt(ie(n,(t=e,W(i=>pt(i)&&i.startsWith(t)))));var t},endsWith:e=>{return gt(ie(n,(t=e,W(i=>pt(i)&&i.endsWith(t)))));var t},minLength:e=>gt(ie(n,(t=>W(i=>pt(i)&&i.length>=t))(e))),length:e=>gt(ie(n,(t=>W(i=>pt(i)&&i.length===t))(e))),maxLength:e=>gt(ie(n,(t=>W(i=>pt(i)&&i.length<=t))(e))),includes:e=>{return gt(ie(n,(t=e,W(i=>pt(i)&&i.includes(t)))));var t},regex:e=>{return gt(ie(n,(t=e,W(i=>pt(i)&&!!i.match(t)))));var t}}),Nd=gt(W(pt)),ze=n=>Object.assign(ge(n),{between:(e,t)=>ze(ie(n,((i,s)=>W(r=>qe(r)&&i<=r&&s>=r))(e,t))),lt:e=>ze(ie(n,(t=>W(i=>qe(i)&&i<t))(e))),gt:e=>ze(ie(n,(t=>W(i=>qe(i)&&i>t))(e))),lte:e=>ze(ie(n,(t=>W(i=>qe(i)&&i<=t))(e))),gte:e=>ze(ie(n,(t=>W(i=>qe(i)&&i>=t))(e))),int:()=>ze(ie(n,W(e=>qe(e)&&Number.isInteger(e)))),finite:()=>ze(ie(n,W(e=>qe(e)&&Number.isFinite(e)))),positive:()=>ze(ie(n,W(e=>qe(e)&&e>0))),negative:()=>ze(ie(n,W(e=>qe(e)&&e<0)))}),Ld=ze(W(qe)),vt=n=>Object.assign(ge(n),{between:(e,t)=>vt(ie(n,((i,s)=>W(r=>mt(r)&&i<=r&&s>=r))(e,t))),lt:e=>vt(ie(n,(t=>W(i=>mt(i)&&i<t))(e))),gt:e=>vt(ie(n,(t=>W(i=>mt(i)&&i>t))(e))),lte:e=>vt(ie(n,(t=>W(i=>mt(i)&&i<=t))(e))),gte:e=>vt(ie(n,(t=>W(i=>mt(i)&&i>=t))(e))),positive:()=>vt(ie(n,W(e=>mt(e)&&e>0))),negative:()=>vt(ie(n,W(e=>mt(e)&&e<0)))}),Ud=vt(W(mt)),jd=ge(W(function(n){return typeof n=="boolean"})),Fd=ge(W(function(n){return typeof n=="symbol"})),$d=ge(W(function(n){return n==null})),Bd=ge(W(function(n){return n!=null}));var Vd={__proto__:null,matcher:ke,optional:vs,array:function(...n){return gs({[ke]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(n.length===0)return{matched:!0};const t=n[0];let i={};if(e.length===0)return Pe(t).forEach(r=>{i[r]=[]}),{matched:!0,selections:i};const s=(r,a)=>{i[r]=(i[r]||[]).concat([a])};return{matched:e.every(r=>me(t,r,s)),selections:i}},getSelectionKeys:()=>n.length===0?[]:Pe(n[0])})})},set:function(...n){return ge({[ke]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(n.length===0)return{matched:!0};const i=(r,a)=>{t[r]=(t[r]||[]).concat([a])},s=n[0];return{matched:Od(e,r=>me(s,r,i)),selections:t}},getSelectionKeys:()=>n.length===0?[]:Pe(n[0])})})},map:function(...n){return ge({[ke]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const i=(o,c)=>{t[o]=(t[o]||[]).concat([c])};if(n.length===0)return{matched:!0};var s;if(n.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(s=n[0])==null?void 0:s.toString()}`);const[r,a]=n;return{matched:Dd(e,(o,c)=>{const d=me(r,c,i),l=me(a,o,i);return d&&l}),selections:t}},getSelectionKeys:()=>n.length===0?[]:[...Pe(n[0]),...Pe(n[1])]})})},intersection:ie,union:ea,not:function(n){return ge({[ke]:()=>({match:e=>({matched:!me(n,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:W,select:Pi,any:ta,_:Md,string:Nd,number:Ld,bigint:Ud,boolean:jd,symbol:Fd,nullish:$d,nonNullable:Bd,instanceOf:function(n){return ge(W(function(e){return t=>t instanceof e}(n)))},shape:function(n){return ge(W(Ad(n)))}};class qd extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const ys={matched:!1,value:void 0};function mn(n){return new zd(n,ys)}let zd=class Wr{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],i=[e[0]];let s;e.length===3&&typeof e[1]=="function"?s=e[1]:e.length>2&&i.push(...e.slice(1,e.length-1));let r=!1,a={};const o=(d,l)=>{r=!0,a[d]=l},c=!i.some(d=>me(d,this.input,o))||s&&!s(this.input)?ys:{matched:!0,value:t(r?fn in a?a[fn]:a:this.input,this.input)};return new Wr(this.input,c)}when(e,t){if(this.state.matched)return this;const i=!!e(this.input);return new Wr(this.input,i?{matched:!0,value:t(this.input,this.input)}:ys)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=Kd){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function Kd(n){throw new qd(n)}var H;(function(n){n.assertEqual=s=>s;function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const r={};for(const a of s)r[a]=a;return r},n.getValidEnumValues=s=>{const r=n.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of r)a[o]=s[o];return n.objectValues(a)},n.objectValues=s=>n.objectKeys(s).map(function(r){return s[r]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const r=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&r.push(a);return r},n.find=(s,r)=>{for(const a of s)if(r(a))return a},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,r=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(r)}n.joinValues=i,n.jsonStringifyReplacer=(s,r)=>typeof r=="bigint"?r.toString():r})(H||(H={}));var bs;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(bs||(bs={}));const O=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),et=n=>{switch(typeof n){case"undefined":return O.undefined;case"string":return O.string;case"number":return isNaN(n)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(n)?O.array:n===null?O.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?O.promise:typeof Map<"u"&&n instanceof Map?O.map:typeof Set<"u"&&n instanceof Set?O.set:typeof Date<"u"&&n instanceof Date?O.date:O.object;default:return O.unknown}},_=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gd=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");class Re extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(r){return r.message},i={_errors:[]},s=r=>{for(const a of r.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)i._errors.push(t(a));else{let o=i,c=0;for(;c<a.path.length;){const d=a.path[c];c===a.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(t(a))):o[d]=o[d]||{_errors:[]},o=o[d],c++}}};return s(this),i}static assert(e){if(!(e instanceof Re))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Re.create=n=>new Re(n);const Xt=(n,e)=>{let t;switch(n.code){case _.invalid_type:n.received===O.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case _.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,H.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:t=`Unrecognized key(s) in object: ${H.joinValues(n.keys,", ")}`;break;case _.invalid_union:t="Invalid input";break;case _.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${H.joinValues(n.options)}`;break;case _.invalid_enum_value:t=`Invalid enum value. Expected ${H.joinValues(n.options)}, received '${n.received}'`;break;case _.invalid_arguments:t="Invalid function arguments";break;case _.invalid_return_type:t="Invalid function return type";break;case _.invalid_date:t="Invalid date";break;case _.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:H.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case _.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case _.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case _.custom:t="Invalid input";break;case _.invalid_intersection_types:t="Intersection results could not be merged";break;case _.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case _.not_finite:t="Number must be finite";break;default:t=e.defaultError,H.assertNever(n)}return{message:t}};let ia=Xt;function Wd(n){ia=n}function gn(){return ia}const vn=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,r=[...t,...s.path||[]],a={...s,path:r};if(s.message!==void 0)return{...s,path:r,message:s.message};let o="";const c=i.filter(d=>!!d).slice().reverse();for(const d of c)o=d(a,{data:e,defaultError:o}).message;return{...s,path:r,message:o}},Hd=[];function I(n,e){const t=gn(),i=vn({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Xt?void 0:Xt].filter(s=>!!s)});n.common.issues.push(i)}class ye{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return F;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const r=await s.key,a=await s.value;i.push({key:r,value:a})}return ye.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:r,value:a}=s;if(r.status==="aborted"||a.status==="aborted")return F;r.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),r.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(i[r.value]=a.value)}return{status:e.value,value:i}}}const F=Object.freeze({status:"aborted"}),ei=n=>({status:"dirty",value:n}),be=n=>({status:"valid",value:n}),ks=n=>n.status==="aborted",Ts=n=>n.status==="dirty",Lt=n=>n.status==="valid",Ri=n=>typeof Promise<"u"&&n instanceof Promise;function yn(n,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(n):i?i.value:e.get(n)}function na(n,e,t,i,s){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}typeof SuppressedError=="function"&&SuppressedError;var N;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(N||(N={}));var xi,Ii;class Ke{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const sa=(n,e)=>{if(Lt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Re(n.common.issues);return this._error=t,this._error}}};function B(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{var c,d;const{message:l}=n;return a.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:(c=l??i)!==null&&c!==void 0?c:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(d=l??t)!==null&&d!==void 0?d:o.defaultError}},description:s}}class V{get description(){return this._def.description}_getType(e){return et(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ri(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const s={common:{issues:[],async:(i=t==null?void 0:t.async)!==null&&i!==void 0?i:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:et(e)},r=this._parseSync({data:e,path:s.path,parent:s});return sa(s,r)}"~validate"(e){var t,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:et(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:s});return Lt(r)?{value:r.value}:{issues:s.common.issues}}catch(r){!((i=(t=r==null?void 0:r.message)===null||t===void 0?void 0:t.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then(r=>Lt(r)?{value:r.value}:{issues:s.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:et(e)},s=this._parse({data:e,path:i.path,parent:i}),r=await(Ri(s)?s:Promise.resolve(s));return sa(i,r)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,r)=>{const a=e(s),o=()=>r.addIssue({code:_.custom,...i(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new Me({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return We.create(this,this._def)}nullable(){return Tt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return De.create(this)}promise(){return si.create(this,this._def)}or(e){return Mi.create([this,e],this._def)}and(e){return Ni.create(this,e,this._def)}transform(e){return new Me({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new $i({...B(this._def),innerType:this,defaultValue:t,typeName:j.ZodDefault})}brand(){return new _s({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Bi({...B(this._def),innerType:this,catchValue:t,typeName:j.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Vi.create(this,e)}readonly(){return qi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Zd=/^c[^\s-]{8,}$/i,Jd=/^[0-9a-z]+$/,Yd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Qd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Xd=/^[a-z0-9_-]{21}$/i,el=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tl=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,il=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ss;const sl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,al=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ol=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ra="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ll=new RegExp(`^${ra}$`);function aa(n){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`),e}function ul(n){return new RegExp(`^${aa(n)}$`)}function oa(n){let e=`${ra}T${aa(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function hl(n,e){return!!((e==="v4"||!e)&&sl.test(n)||(e==="v6"||!e)&&al.test(n))}function fl(n,e){if(!el.test(n))return!1;try{const[t]=n.split("."),i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||e&&s.alg!==e)}catch{return!1}}function pl(n,e){return!!((e==="v4"||!e)&&rl.test(n)||(e==="v6"||!e)&&ol.test(n))}class Oe extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_type,expected:O.string,received:r.parsedType}),F}const i=new ye;let s;for(const r of this._def.checks)if(r.kind==="min")e.data.length<r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")e.data.length>r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){const a=e.data.length>r.value,o=e.data.length<r.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?I(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&I(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")il.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"email",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")Ss||(Ss=new RegExp(nl,"u")),Ss.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"emoji",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")Qd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"uuid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")Xd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"nanoid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")Zd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")Jd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid2",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")Yd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ulid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),I(s,{validation:"url",code:_.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"regex",code:_.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?e.data=e.data.trim():r.kind==="includes"?e.data.includes(r.value,r.position)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?e.data=e.data.toLowerCase():r.kind==="toUpperCase"?e.data=e.data.toUpperCase():r.kind==="startsWith"?e.data.startsWith(r.value)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?e.data.endsWith(r.value)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?oa(r).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?ll.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?ul(r).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?tl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"duration",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?hl(e.data,r.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ip",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?fl(e.data,r.alg)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"jwt",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?pl(e.data,r.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cidr",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?cl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?dl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64url",code:_.invalid_string,message:r.message}),i.dirty()):H.assertNever(r);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:_.invalid_string,...N.errToObj(i)})}_addCheck(e){return new Oe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){var t,i;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(i=e==null?void 0:e.local)!==null&&i!==void 0?i:!1,...N.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...N.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...N.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errToObj(t)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new Oe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Oe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Oe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Oe.create=n=>{var e;return new Oe({checks:[],typeName:j.ZodString,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...B(n)})};function ml(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,r=parseInt(n.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return r%a/Math.pow(10,s)}class yt extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_type,expected:O.number,received:r.parsedType}),F}let i;const s=new ye;for(const r of this._def.checks)r.kind==="int"?H.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),I(i,{code:_.invalid_type,expected:"integer",received:"float",message:r.message}),s.dirty()):r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):r.kind==="multipleOf"?ml(e.data,r.value)!==0&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):r.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),I(i,{code:_.not_finite,message:r.message}),s.dirty()):H.assertNever(r);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,i,s){return new yt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:N.toString(s)}]})}_addCheck(e){return new yt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&H.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}yt.create=n=>new yt({checks:[],typeName:j.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...B(n)});class bt extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let i;const s=new ye;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):r.kind==="multipleOf"?e.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):H.assertNever(r);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return I(t,{code:_.invalid_type,expected:O.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,i,s){return new bt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:N.toString(s)}]})}_addCheck(e){return new bt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}bt.create=n=>{var e;return new bt({checks:[],typeName:j.ZodBigInt,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...B(n)})};class Ai extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.boolean,received:i.parsedType}),F}return be(e.data)}}Ai.create=n=>new Ai({typeName:j.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...B(n)});class Ut extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_type,expected:O.date,received:r.parsedType}),F}if(isNaN(e.data.getTime())){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_date}),F}const i=new ye;let s;for(const r of this._def.checks)r.kind==="min"?e.data.getTime()<r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?e.data.getTime()>r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):H.assertNever(r);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ut({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Ut.create=n=>new Ut({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:j.ZodDate,...B(n)});class bn extends V{_parse(e){if(this._getType(e)!==O.symbol){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.symbol,received:i.parsedType}),F}return be(e.data)}}bn.create=n=>new bn({typeName:j.ZodSymbol,...B(n)});class Oi extends V{_parse(e){if(this._getType(e)!==O.undefined){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.undefined,received:i.parsedType}),F}return be(e.data)}}Oi.create=n=>new Oi({typeName:j.ZodUndefined,...B(n)});class Di extends V{_parse(e){if(this._getType(e)!==O.null){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.null,received:i.parsedType}),F}return be(e.data)}}Di.create=n=>new Di({typeName:j.ZodNull,...B(n)});class ti extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return be(e.data)}}ti.create=n=>new ti({typeName:j.ZodAny,...B(n)});class jt extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return be(e.data)}}jt.create=n=>new jt({typeName:j.ZodUnknown,...B(n)});class tt extends V{_parse(e){const t=this._getOrReturnCtx(e);return I(t,{code:_.invalid_type,expected:O.never,received:t.parsedType}),F}}tt.create=n=>new tt({typeName:j.ZodNever,...B(n)});class kn extends V{_parse(e){if(this._getType(e)!==O.undefined){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.void,received:i.parsedType}),F}return be(e.data)}}kn.create=n=>new kn({typeName:j.ZodVoid,...B(n)});class De extends V{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==O.array)return I(t,{code:_.invalid_type,expected:O.array,received:t.parsedType}),F;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(I(t,{code:a?_.too_big:_.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(I(t,{code:_.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(I(t,{code:_.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new Ke(t,a,t.path,o)))).then(a=>ye.mergeArray(i,a));const r=[...t.data].map((a,o)=>s.type._parseSync(new Ke(t,a,t.path,o)));return ye.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new De({...this._def,minLength:{value:e,message:N.toString(t)}})}max(e,t){return new De({...this._def,maxLength:{value:e,message:N.toString(t)}})}length(e,t){return new De({...this._def,exactLength:{value:e,message:N.toString(t)}})}nonempty(e){return this.min(1,e)}}De.create=(n,e)=>new De({type:n,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(e)});function ii(n){if(n instanceof re){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=We.create(ii(i))}return new re({...n._def,shape:()=>e})}else return n instanceof De?new De({...n._def,type:ii(n.element)}):n instanceof We?We.create(ii(n.unwrap())):n instanceof Tt?Tt.create(ii(n.unwrap())):n instanceof Ge?Ge.create(n.items.map(e=>ii(e))):n}class re extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=H.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==O.object){const d=this._getOrReturnCtx(e);return I(d,{code:_.invalid_type,expected:O.object,received:d.parsedType}),F}const{status:i,ctx:s}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||o.push(d);const c=[];for(const d of a){const l=r[d],u=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Ke(s,u,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof tt){const d=this._def.unknownKeys;if(d==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(d==="strict")o.length>0&&(I(s,{code:_.unrecognized_keys,keys:o}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const l of o){const u=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Ke(s,u,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const l of c){const u=await l.key,h=await l.value;d.push({key:u,value:h,alwaysSet:l.alwaysSet})}return d}).then(d=>ye.mergeObjectSync(i,d)):ye.mergeObjectSync(i,c)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new re({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var s,r,a,o;const c=(a=(r=(s=this._def).errorMap)===null||r===void 0?void 0:r.call(s,t,i).message)!==null&&a!==void 0?a:i.defaultError;return t.code==="unrecognized_keys"?{message:(o=N.errToObj(e).message)!==null&&o!==void 0?o:c}:{message:c}}}:{}})}strip(){return new re({...this._def,unknownKeys:"strip"})}passthrough(){return new re({...this._def,unknownKeys:"passthrough"})}extend(e){return new re({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new re({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:j.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new re({...this._def,catchall:e})}pick(e){const t={};return H.objectKeys(e).forEach(i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])}),new re({...this._def,shape:()=>t})}omit(e){const t={};return H.objectKeys(this.shape).forEach(i=>{e[i]||(t[i]=this.shape[i])}),new re({...this._def,shape:()=>t})}deepPartial(){return ii(this)}partial(e){const t={};return H.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}),new re({...this._def,shape:()=>t})}required(e){const t={};return H.objectKeys(this.shape).forEach(i=>{if(e&&!e[i])t[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof We;)r=r._def.innerType;t[i]=r}}),new re({...this._def,shape:()=>t})}keyof(){return ca(H.objectKeys(this.shape))}}re.create=(n,e)=>new re({shape:()=>n,unknownKeys:"strip",catchall:tt.create(),typeName:j.ZodObject,...B(e)}),re.strictCreate=(n,e)=>new re({shape:()=>n,unknownKeys:"strict",catchall:tt.create(),typeName:j.ZodObject,...B(e)}),re.lazycreate=(n,e)=>new re({shape:n,unknownKeys:"strip",catchall:tt.create(),typeName:j.ZodObject,...B(e)});class Mi extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(r){for(const o of r)if(o.result.status==="valid")return o.result;for(const o of r)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=r.map(o=>new Re(o.ctx.common.issues));return I(t,{code:_.invalid_union,unionErrors:a}),F}if(t.common.async)return Promise.all(i.map(async r=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let r;const a=[];for(const c of i){const d={...t,common:{...t.common,issues:[]},parent:null},l=c._parseSync({data:t.data,path:t.path,parent:d});if(l.status==="valid")return l;l.status==="dirty"&&!r&&(r={result:l,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;const o=a.map(c=>new Re(c));return I(t,{code:_.invalid_union,unionErrors:o}),F}}get options(){return this._def.options}}Mi.create=(n,e)=>new Mi({options:n,typeName:j.ZodUnion,...B(e)});const it=n=>n instanceof Ui?it(n.schema):n instanceof Me?it(n.innerType()):n instanceof ji?[n.value]:n instanceof kt?n.options:n instanceof Fi?H.objectValues(n.enum):n instanceof $i?it(n._def.innerType):n instanceof Oi?[void 0]:n instanceof Di?[null]:n instanceof We?[void 0,...it(n.unwrap())]:n instanceof Tt?[null,...it(n.unwrap())]:n instanceof _s||n instanceof qi?it(n.unwrap()):n instanceof Bi?it(n._def.innerType):[];class Tn extends V{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.object)return I(t,{code:_.invalid_type,expected:O.object,received:t.parsedType}),F;const i=this.discriminator,s=t.data[i],r=this.optionsMap.get(s);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(I(t,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),F)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const s=new Map;for(const r of t){const a=it(r.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,r)}}return new Tn({typeName:j.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(i)})}}function Cs(n,e){const t=et(n),i=et(e);if(n===e)return{valid:!0,data:n};if(t===O.object&&i===O.object){const s=H.objectKeys(e),r=H.objectKeys(n).filter(o=>s.indexOf(o)!==-1),a={...n,...e};for(const o of r){const c=Cs(n[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===O.array&&i===O.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let r=0;r<n.length;r++){const a=n[r],o=e[r],c=Cs(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===O.date&&i===O.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Ni extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(r,a)=>{if(ks(r)||ks(a))return F;const o=Cs(r.value,a.value);return o.valid?((Ts(r)||Ts(a))&&t.dirty(),{status:t.value,value:o.data}):(I(i,{code:_.invalid_intersection_types}),F)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,a])=>s(r,a)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Ni.create=(n,e,t)=>new Ni({left:n,right:e,typeName:j.ZodIntersection,...B(t)});class Ge extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.array)return I(i,{code:_.invalid_type,expected:O.array,received:i.parsedType}),F;if(i.data.length<this._def.items.length)return I(i,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F;!this._def.rest&&i.data.length>this._def.items.length&&(I(i,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...i.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Ke(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(r).then(a=>ye.mergeArray(t,a)):ye.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Ge({...this._def,rest:e})}}Ge.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ge({items:n,typeName:j.ZodTuple,rest:null,...B(e)})};class Li extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.object)return I(i,{code:_.invalid_type,expected:O.object,received:i.parsedType}),F;const s=[],r=this._def.keyType,a=this._def.valueType;for(const o in i.data)s.push({key:r._parse(new Ke(i,o,i.path,o)),value:a._parse(new Ke(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?ye.mergeObjectAsync(t,s):ye.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof V?new Li({keyType:e,valueType:t,typeName:j.ZodRecord,...B(i)}):new Li({keyType:Oe.create(),valueType:e,typeName:j.ZodRecord,...B(t)})}}class Sn extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.map)return I(i,{code:_.invalid_type,expected:O.map,received:i.parsedType}),F;const s=this._def.keyType,r=this._def.valueType,a=[...i.data.entries()].map(([o,c],d)=>({key:s._parse(new Ke(i,o,i.path,[d,"key"])),value:r._parse(new Ke(i,c,i.path,[d,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const d=await c.key,l=await c.value;if(d.status==="aborted"||l.status==="aborted")return F;(d.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(d.value,l.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of a){const d=c.key,l=c.value;if(d.status==="aborted"||l.status==="aborted")return F;(d.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(d.value,l.value)}return{status:t.value,value:o}}}}Sn.create=(n,e,t)=>new Sn({valueType:e,keyType:n,typeName:j.ZodMap,...B(t)});class Ft extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.set)return I(i,{code:_.invalid_type,expected:O.set,received:i.parsedType}),F;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(I(i,{code:_.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(I(i,{code:_.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const r=this._def.valueType;function a(c){const d=new Set;for(const l of c){if(l.status==="aborted")return F;l.status==="dirty"&&t.dirty(),d.add(l.value)}return{status:t.value,value:d}}const o=[...i.data.values()].map((c,d)=>r._parse(new Ke(i,c,i.path,d)));return i.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new Ft({...this._def,minSize:{value:e,message:N.toString(t)}})}max(e,t){return new Ft({...this._def,maxSize:{value:e,message:N.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ft.create=(n,e)=>new Ft({valueType:n,minSize:null,maxSize:null,typeName:j.ZodSet,...B(e)});class ni extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.function)return I(t,{code:_.invalid_type,expected:O.function,received:t.parsedType}),F;function i(o,c){return vn({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,gn(),Xt].filter(d=>!!d),issueData:{code:_.invalid_arguments,argumentsError:c}})}function s(o,c){return vn({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,gn(),Xt].filter(d=>!!d),issueData:{code:_.invalid_return_type,returnTypeError:c}})}const r={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof si){const o=this;return be(async function(...c){const d=new Re([]),l=await o._def.args.parseAsync(c,r).catch(p=>{throw d.addIssue(i(c,p)),d}),u=await Reflect.apply(a,this,l);return await o._def.returns._def.type.parseAsync(u,r).catch(p=>{throw d.addIssue(s(u,p)),d})})}else{const o=this;return be(function(...c){const d=o._def.args.safeParse(c,r);if(!d.success)throw new Re([i(c,d.error)]);const l=Reflect.apply(a,this,d.data),u=o._def.returns.safeParse(l,r);if(!u.success)throw new Re([s(l,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ni({...this._def,args:Ge.create(e).rest(jt.create())})}returns(e){return new ni({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new ni({args:e||Ge.create([]).rest(jt.create()),returns:t||jt.create(),typeName:j.ZodFunction,...B(i)})}}class Ui extends V{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ui.create=(n,e)=>new Ui({getter:n,typeName:j.ZodLazy,...B(e)});class ji extends V{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:_.invalid_literal,expected:this._def.value}),F}return{status:"valid",value:e.data}}get value(){return this._def.value}}ji.create=(n,e)=>new ji({value:n,typeName:j.ZodLiteral,...B(e)});function ca(n,e){return new kt({values:n,typeName:j.ZodEnum,...B(e)})}class kt extends V{constructor(){super(...arguments),xi.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return I(t,{expected:H.joinValues(i),received:t.parsedType,code:_.invalid_type}),F}if(yn(this,xi,"f")||na(this,xi,new Set(this._def.values),"f"),!yn(this,xi,"f").has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return I(t,{received:t.data,code:_.invalid_enum_value,options:i}),F}return be(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return kt.create(e,{...this._def,...t})}exclude(e,t=this._def){return kt.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}xi=new WeakMap,kt.create=ca;class Fi extends V{constructor(){super(...arguments),Ii.set(this,void 0)}_parse(e){const t=H.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==O.string&&i.parsedType!==O.number){const s=H.objectValues(t);return I(i,{expected:H.joinValues(s),received:i.parsedType,code:_.invalid_type}),F}if(yn(this,Ii,"f")||na(this,Ii,new Set(H.getValidEnumValues(this._def.values)),"f"),!yn(this,Ii,"f").has(e.data)){const s=H.objectValues(t);return I(i,{received:i.data,code:_.invalid_enum_value,options:s}),F}return be(e.data)}get enum(){return this._def.values}}Ii=new WeakMap,Fi.create=(n,e)=>new Fi({values:n,typeName:j.ZodNativeEnum,...B(e)});class si extends V{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.promise&&t.common.async===!1)return I(t,{code:_.invalid_type,expected:O.promise,received:t.parsedType}),F;const i=t.parsedType===O.promise?t.data:Promise.resolve(t.data);return be(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}si.create=(n,e)=>new si({type:n,typeName:j.ZodPromise,...B(e)});class Me extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,r={addIssue:a=>{I(i,a),a.fatal?t.abort():t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),s.type==="preprocess"){const a=s.transform(i.data,r);if(i.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return F;const c=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return c.status==="aborted"?F:c.status==="dirty"||t.value==="dirty"?ei(c.value):c});{if(t.value==="aborted")return F;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?F:o.status==="dirty"||t.value==="dirty"?ei(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,r);if(i.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?F:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?F:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Lt(a))return a;const o=s.transform(a.value,r);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>Lt(a)?Promise.resolve(s.transform(a.value,r)).then(o=>({status:t.value,value:o})):a);H.assertNever(s)}}Me.create=(n,e,t)=>new Me({schema:n,typeName:j.ZodEffects,effect:e,...B(t)}),Me.createWithPreprocess=(n,e,t)=>new Me({schema:e,effect:{type:"preprocess",transform:n},typeName:j.ZodEffects,...B(t)});class We extends V{_parse(e){return this._getType(e)===O.undefined?be(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}We.create=(n,e)=>new We({innerType:n,typeName:j.ZodOptional,...B(e)});class Tt extends V{_parse(e){return this._getType(e)===O.null?be(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Tt.create=(n,e)=>new Tt({innerType:n,typeName:j.ZodNullable,...B(e)});class $i extends V{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===O.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}$i.create=(n,e)=>new $i({innerType:n,typeName:j.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});class Bi extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Ri(s)?s.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Re(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Re(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Bi.create=(n,e)=>new Bi({innerType:n,typeName:j.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});class Cn extends V{_parse(e){if(this._getType(e)!==O.nan){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.nan,received:i.parsedType}),F}return{status:"valid",value:e.data}}}Cn.create=n=>new Cn({typeName:j.ZodNaN,...B(n)});const gl=Symbol("zod_brand");class _s extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Vi extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?F:r.status==="dirty"?(t.dirty(),ei(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?F:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new Vi({in:e,out:t,typeName:j.ZodPipeline})}}class qi extends V{_parse(e){const t=this._def.innerType._parse(e),i=s=>(Lt(s)&&(s.value=Object.freeze(s.value)),s);return Ri(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}qi.create=(n,e)=>new qi({innerType:n,typeName:j.ZodReadonly,...B(e)});function da(n,e){const t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function la(n,e={},t){return n?ti.create().superRefine((i,s)=>{var r,a;const o=n(i);if(o instanceof Promise)return o.then(c=>{var d,l;if(!c){const u=da(e,i),h=(l=(d=u.fatal)!==null&&d!==void 0?d:t)!==null&&l!==void 0?l:!0;s.addIssue({code:"custom",...u,fatal:h})}});if(!o){const c=da(e,i),d=(a=(r=c.fatal)!==null&&r!==void 0?r:t)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...c,fatal:d})}}):ti.create()}const vl={object:re.lazycreate};var j;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(j||(j={}));const yl=(n,e={message:`Input not instance of ${n.name}`})=>la(t=>t instanceof n,e),ua=Oe.create,ha=yt.create,bl=Cn.create,kl=bt.create,fa=Ai.create,Tl=Ut.create,Sl=bn.create,Cl=Oi.create,_l=Di.create,El=ti.create,wl=jt.create,Pl=tt.create,Rl=kn.create,xl=De.create,Il=re.create,Al=re.strictCreate,Ol=Mi.create,Dl=Tn.create,Ml=Ni.create,Nl=Ge.create,Ll=Li.create,Ul=Sn.create,jl=Ft.create,Fl=ni.create,$l=Ui.create,Bl=ji.create,Vl=kt.create,ql=Fi.create,zl=si.create,pa=Me.create,Kl=We.create,Gl=Tt.create,Wl=Me.createWithPreprocess,Hl=Vi.create;var nt=Object.freeze({__proto__:null,defaultErrorMap:Xt,setErrorMap:Wd,getErrorMap:gn,makeIssue:vn,EMPTY_PATH:Hd,addIssueToContext:I,ParseStatus:ye,INVALID:F,DIRTY:ei,OK:be,isAborted:ks,isDirty:Ts,isValid:Lt,isAsync:Ri,get util(){return H},get objectUtil(){return bs},ZodParsedType:O,getParsedType:et,ZodType:V,datetimeRegex:oa,ZodString:Oe,ZodNumber:yt,ZodBigInt:bt,ZodBoolean:Ai,ZodDate:Ut,ZodSymbol:bn,ZodUndefined:Oi,ZodNull:Di,ZodAny:ti,ZodUnknown:jt,ZodNever:tt,ZodVoid:kn,ZodArray:De,ZodObject:re,ZodUnion:Mi,ZodDiscriminatedUnion:Tn,ZodIntersection:Ni,ZodTuple:Ge,ZodRecord:Li,ZodMap:Sn,ZodSet:Ft,ZodFunction:ni,ZodLazy:Ui,ZodLiteral:ji,ZodEnum:kt,ZodNativeEnum:Fi,ZodPromise:si,ZodEffects:Me,ZodTransformer:Me,ZodOptional:We,ZodNullable:Tt,ZodDefault:$i,ZodCatch:Bi,ZodNaN:Cn,BRAND:gl,ZodBranded:_s,ZodPipeline:Vi,ZodReadonly:qi,custom:la,Schema:V,ZodSchema:V,late:vl,get ZodFirstPartyTypeKind(){return j},coerce:{string:n=>Oe.create({...n,coerce:!0}),number:n=>yt.create({...n,coerce:!0}),boolean:n=>Ai.create({...n,coerce:!0}),bigint:n=>bt.create({...n,coerce:!0}),date:n=>Ut.create({...n,coerce:!0})},any:El,array:xl,bigint:kl,boolean:fa,date:Tl,discriminatedUnion:Dl,effect:pa,enum:Vl,function:Fl,instanceof:yl,intersection:Ml,lazy:$l,literal:Bl,map:Ul,nan:bl,nativeEnum:ql,never:Pl,null:_l,nullable:Gl,number:ha,object:Il,oboolean:()=>fa().optional(),onumber:()=>ha().optional(),optional:Kl,ostring:()=>ua().optional(),pipeline:Hl,preprocess:Wl,promise:zl,record:Ll,set:jl,strictObject:Al,string:ua,symbol:Sl,transformer:pa,tuple:Nl,undefined:Cl,union:Ol,unknown:wl,void:Rl,NEVER:F,ZodIssueCode:_,quotelessJson:Gd,ZodError:Re});const ma="https://iamobi.ai/api",Zl=nt.object({apiKey:nt.string().optional(),enableVoice:nt.boolean().default(!0),enableScreenCapture:nt.boolean().default(!0),debug:nt.boolean().default(!1),user:nt.object({id:nt.string(),email:nt.string().optional(),metadata:nt.any().optional()}).optional()});var st=(n=>(n.READY="ready",n.ERROR="error",n.VOICE_START="voice:start",n.VOICE_STOP="voice:stop",n.SCREEN_CAPTURE_START="screen:start",n.SCREEN_CAPTURE_STOP="screen:stop",n.STATE_CHANGE="state:change",n))(st||{}),$=(n=>(n.READY="ready",n.ERROR="error",n.PAUSED="paused",n.LOADING="loading",n.THINKING="thinking",n.RESEARCHING="researching",n.AGENT_SPEAKING="agent_speaking",n.USER_SPEAKING="user_speaking",n.AWAITING_USER_INPUT="awaiting_user_input",n))($||{}),Jl=Object.defineProperty,Yl=Object.getOwnPropertyDescriptor,_n=(n,e,t,i)=>{for(var s=i>1?void 0:i?Yl(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Jl(e,t,s),s};class ri extends L.LitElement{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return L.html`
17
+ */function pt(n){return Y({...n,state:!0,attribute:!1})}const ke=Symbol.for("@ts-pattern/matcher"),ta=Symbol.for("@ts-pattern/isVariadic"),pn="@ts-pattern/anonymous-select-key",vs=n=>!!(n&&typeof n=="object"),mn=n=>n&&!!n[ke],me=(n,e,t)=>{if(mn(n)){const i=n[ke](),{matched:s,selections:r}=i.match(e);return s&&r&&Object.keys(r).forEach(a=>t(a,r[a])),s}if(vs(n)){if(!vs(e))return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;let i=[],s=[],r=[];for(const a of n.keys()){const o=n[a];mn(o)&&o[ta]?r.push(o):r.length?s.push(o):i.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<i.length+s.length)return!1;const a=e.slice(0,i.length),o=s.length===0?[]:e.slice(-s.length),c=e.slice(i.length,s.length===0?1/0:-s.length);return i.every((d,l)=>me(d,a[l],t))&&s.every((d,l)=>me(d,o[l],t))&&(r.length===0||me(r[0],c,t))}return n.length===e.length&&n.every((a,o)=>me(a,e[o],t))}return Reflect.ownKeys(n).every(i=>{const s=n[i];return(i in e||mn(r=s)&&r[ke]().matcherType==="optional")&&me(s,e[i],t);var r})}return Object.is(e,n)},Pe=n=>{var e,t,i;return vs(n)?mn(n)?(e=(t=(i=n[ke]()).getSelectionKeys)==null?void 0:t.call(i))!=null?e:[]:Array.isArray(n)?Pi(n,Pe):Pi(Object.values(n),Pe):[]},Pi=(n,e)=>n.reduce((t,i)=>t.concat(e(i)),[]);function Md(...n){if(n.length===1){const[e]=n;return t=>me(e,t,()=>{})}if(n.length===2){const[e,t]=n;return me(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${n.length}.`)}function ge(n){return Object.assign(n,{optional:()=>bs(n),and:e=>ie(n,e),or:e=>ia(n,e),select:e=>e===void 0?Ri(n):Ri(e,n)})}function ys(n){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const i=[{value:Object.assign(e,{[ta]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var s;return(s=i[t++])!=null?s:i.at(-1)}}}}))(n),{optional:()=>ys(bs(n)),select:e=>ys(e===void 0?Ri(n):Ri(e,n))})}function bs(n){return ge({[ke]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return e===void 0?(Pe(n).forEach(s=>i(s,void 0)),{matched:!0,selections:t}):{matched:me(n,e,i),selections:t}},getSelectionKeys:()=>Pe(n),matcherType:"optional"})})}const Nd=(n,e)=>{for(const t of n)if(!e(t))return!1;return!0},Ld=(n,e)=>{for(const[t,i]of n.entries())if(!e(i,t))return!1;return!0};function ie(...n){return ge({[ke]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return{matched:n.every(s=>me(s,e,i)),selections:t}},getSelectionKeys:()=>Pi(n,Pe),matcherType:"and"})})}function ia(...n){return ge({[ke]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return Pi(n,Pe).forEach(s=>i(s,void 0)),{matched:n.some(s=>me(s,e,i)),selections:t}},getSelectionKeys:()=>Pi(n,Pe),matcherType:"or"})})}function W(n){return{[ke]:()=>({match:e=>({matched:!!n(e)})})}}function Ri(...n){const e=typeof n[0]=="string"?n[0]:void 0,t=n.length===2?n[1]:typeof n[0]=="string"?void 0:n[0];return ge({[ke]:()=>({match:i=>{let s={[e??pn]:i};return{matched:t===void 0||me(t,i,(r,a)=>{s[r]=a}),selections:s}},getSelectionKeys:()=>[e??pn].concat(t===void 0?[]:Pe(t))})})}function ze(n){return typeof n=="number"}function mt(n){return typeof n=="string"}function gt(n){return typeof n=="bigint"}const na=ge(W(function(n){return!0})),Ud=na,vt=n=>Object.assign(ge(n),{startsWith:e=>{return vt(ie(n,(t=e,W(i=>mt(i)&&i.startsWith(t)))));var t},endsWith:e=>{return vt(ie(n,(t=e,W(i=>mt(i)&&i.endsWith(t)))));var t},minLength:e=>vt(ie(n,(t=>W(i=>mt(i)&&i.length>=t))(e))),length:e=>vt(ie(n,(t=>W(i=>mt(i)&&i.length===t))(e))),maxLength:e=>vt(ie(n,(t=>W(i=>mt(i)&&i.length<=t))(e))),includes:e=>{return vt(ie(n,(t=e,W(i=>mt(i)&&i.includes(t)))));var t},regex:e=>{return vt(ie(n,(t=e,W(i=>mt(i)&&!!i.match(t)))));var t}}),Fd=vt(W(mt)),Ke=n=>Object.assign(ge(n),{between:(e,t)=>Ke(ie(n,((i,s)=>W(r=>ze(r)&&i<=r&&s>=r))(e,t))),lt:e=>Ke(ie(n,(t=>W(i=>ze(i)&&i<t))(e))),gt:e=>Ke(ie(n,(t=>W(i=>ze(i)&&i>t))(e))),lte:e=>Ke(ie(n,(t=>W(i=>ze(i)&&i<=t))(e))),gte:e=>Ke(ie(n,(t=>W(i=>ze(i)&&i>=t))(e))),int:()=>Ke(ie(n,W(e=>ze(e)&&Number.isInteger(e)))),finite:()=>Ke(ie(n,W(e=>ze(e)&&Number.isFinite(e)))),positive:()=>Ke(ie(n,W(e=>ze(e)&&e>0))),negative:()=>Ke(ie(n,W(e=>ze(e)&&e<0)))}),jd=Ke(W(ze)),yt=n=>Object.assign(ge(n),{between:(e,t)=>yt(ie(n,((i,s)=>W(r=>gt(r)&&i<=r&&s>=r))(e,t))),lt:e=>yt(ie(n,(t=>W(i=>gt(i)&&i<t))(e))),gt:e=>yt(ie(n,(t=>W(i=>gt(i)&&i>t))(e))),lte:e=>yt(ie(n,(t=>W(i=>gt(i)&&i<=t))(e))),gte:e=>yt(ie(n,(t=>W(i=>gt(i)&&i>=t))(e))),positive:()=>yt(ie(n,W(e=>gt(e)&&e>0))),negative:()=>yt(ie(n,W(e=>gt(e)&&e<0)))}),$d=yt(W(gt)),Bd=ge(W(function(n){return typeof n=="boolean"})),Vd=ge(W(function(n){return typeof n=="symbol"})),qd=ge(W(function(n){return n==null})),zd=ge(W(function(n){return n!=null}));var Kd={__proto__:null,matcher:ke,optional:bs,array:function(...n){return ys({[ke]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(n.length===0)return{matched:!0};const t=n[0];let i={};if(e.length===0)return Pe(t).forEach(r=>{i[r]=[]}),{matched:!0,selections:i};const s=(r,a)=>{i[r]=(i[r]||[]).concat([a])};return{matched:e.every(r=>me(t,r,s)),selections:i}},getSelectionKeys:()=>n.length===0?[]:Pe(n[0])})})},set:function(...n){return ge({[ke]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(n.length===0)return{matched:!0};const i=(r,a)=>{t[r]=(t[r]||[]).concat([a])},s=n[0];return{matched:Nd(e,r=>me(s,r,i)),selections:t}},getSelectionKeys:()=>n.length===0?[]:Pe(n[0])})})},map:function(...n){return ge({[ke]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const i=(o,c)=>{t[o]=(t[o]||[]).concat([c])};if(n.length===0)return{matched:!0};var s;if(n.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(s=n[0])==null?void 0:s.toString()}`);const[r,a]=n;return{matched:Ld(e,(o,c)=>{const d=me(r,c,i),l=me(a,o,i);return d&&l}),selections:t}},getSelectionKeys:()=>n.length===0?[]:[...Pe(n[0]),...Pe(n[1])]})})},intersection:ie,union:ia,not:function(n){return ge({[ke]:()=>({match:e=>({matched:!me(n,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:W,select:Ri,any:na,_:Ud,string:Fd,number:jd,bigint:$d,boolean:Bd,symbol:Vd,nullish:qd,nonNullable:zd,instanceOf:function(n){return ge(W(function(e){return t=>t instanceof e}(n)))},shape:function(n){return ge(W(Md(n)))}};class Gd extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const ks={matched:!1,value:void 0};function gn(n){return new Wd(n,ks)}let Wd=class Zr{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],i=[e[0]];let s;e.length===3&&typeof e[1]=="function"?s=e[1]:e.length>2&&i.push(...e.slice(1,e.length-1));let r=!1,a={};const o=(d,l)=>{r=!0,a[d]=l},c=!i.some(d=>me(d,this.input,o))||s&&!s(this.input)?ks:{matched:!0,value:t(r?pn in a?a[pn]:a:this.input,this.input)};return new Zr(this.input,c)}when(e,t){if(this.state.matched)return this;const i=!!e(this.input);return new Zr(this.input,i?{matched:!0,value:t(this.input,this.input)}:ks)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=Hd){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function Hd(n){throw new Gd(n)}var H;(function(n){n.assertEqual=s=>s;function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const r={};for(const a of s)r[a]=a;return r},n.getValidEnumValues=s=>{const r=n.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of r)a[o]=s[o];return n.objectValues(a)},n.objectValues=s=>n.objectKeys(s).map(function(r){return s[r]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const r=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&r.push(a);return r},n.find=(s,r)=>{for(const a of s)if(r(a))return a},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,r=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(r)}n.joinValues=i,n.jsonStringifyReplacer=(s,r)=>typeof r=="bigint"?r.toString():r})(H||(H={}));var Ts;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Ts||(Ts={}));const O=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tt=n=>{switch(typeof n){case"undefined":return O.undefined;case"string":return O.string;case"number":return isNaN(n)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(n)?O.array:n===null?O.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?O.promise:typeof Map<"u"&&n instanceof Map?O.map:typeof Set<"u"&&n instanceof Set?O.set:typeof Date<"u"&&n instanceof Date?O.date:O.object;default:return O.unknown}},_=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Zd=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");class Re extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(r){return r.message},i={_errors:[]},s=r=>{for(const a of r.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)i._errors.push(t(a));else{let o=i,c=0;for(;c<a.path.length;){const d=a.path[c];c===a.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(t(a))):o[d]=o[d]||{_errors:[]},o=o[d],c++}}};return s(this),i}static assert(e){if(!(e instanceof Re))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Re.create=n=>new Re(n);const ei=(n,e)=>{let t;switch(n.code){case _.invalid_type:n.received===O.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case _.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,H.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:t=`Unrecognized key(s) in object: ${H.joinValues(n.keys,", ")}`;break;case _.invalid_union:t="Invalid input";break;case _.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${H.joinValues(n.options)}`;break;case _.invalid_enum_value:t=`Invalid enum value. Expected ${H.joinValues(n.options)}, received '${n.received}'`;break;case _.invalid_arguments:t="Invalid function arguments";break;case _.invalid_return_type:t="Invalid function return type";break;case _.invalid_date:t="Invalid date";break;case _.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:H.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case _.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case _.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case _.custom:t="Invalid input";break;case _.invalid_intersection_types:t="Intersection results could not be merged";break;case _.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case _.not_finite:t="Number must be finite";break;default:t=e.defaultError,H.assertNever(n)}return{message:t}};let sa=ei;function Jd(n){sa=n}function vn(){return sa}const yn=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,r=[...t,...s.path||[]],a={...s,path:r};if(s.message!==void 0)return{...s,path:r,message:s.message};let o="";const c=i.filter(d=>!!d).slice().reverse();for(const d of c)o=d(a,{data:e,defaultError:o}).message;return{...s,path:r,message:o}},Yd=[];function I(n,e){const t=vn(),i=yn({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ei?void 0:ei].filter(s=>!!s)});n.common.issues.push(i)}class ye{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return j;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const r=await s.key,a=await s.value;i.push({key:r,value:a})}return ye.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:r,value:a}=s;if(r.status==="aborted"||a.status==="aborted")return j;r.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),r.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(i[r.value]=a.value)}return{status:e.value,value:i}}}const j=Object.freeze({status:"aborted"}),ti=n=>({status:"dirty",value:n}),be=n=>({status:"valid",value:n}),Ss=n=>n.status==="aborted",Cs=n=>n.status==="dirty",Ut=n=>n.status==="valid",xi=n=>typeof Promise<"u"&&n instanceof Promise;function bn(n,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(n):i?i.value:e.get(n)}function ra(n,e,t,i,s){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}typeof SuppressedError=="function"&&SuppressedError;var N;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(N||(N={}));var Ii,Ai;class Ge{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const aa=(n,e)=>{if(Ut(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Re(n.common.issues);return this._error=t,this._error}}};function B(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{var c,d;const{message:l}=n;return a.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:(c=l??i)!==null&&c!==void 0?c:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(d=l??t)!==null&&d!==void 0?d:o.defaultError}},description:s}}class V{get description(){return this._def.description}_getType(e){return tt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(xi(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const s={common:{issues:[],async:(i=t==null?void 0:t.async)!==null&&i!==void 0?i:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},r=this._parseSync({data:e,path:s.path,parent:s});return aa(s,r)}"~validate"(e){var t,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:s});return Ut(r)?{value:r.value}:{issues:s.common.issues}}catch(r){!((i=(t=r==null?void 0:r.message)===null||t===void 0?void 0:t.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then(r=>Ut(r)?{value:r.value}:{issues:s.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},s=this._parse({data:e,path:i.path,parent:i}),r=await(xi(s)?s:Promise.resolve(s));return aa(i,r)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,r)=>{const a=e(s),o=()=>r.addIssue({code:_.custom,...i(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new Me({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return He.create(this,this._def)}nullable(){return St.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return De.create(this)}promise(){return ri.create(this,this._def)}or(e){return Ni.create([this,e],this._def)}and(e){return Li.create(this,e,this._def)}transform(e){return new Me({...B(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Bi({...B(this._def),innerType:this,defaultValue:t,typeName:F.ZodDefault})}brand(){return new ws({typeName:F.ZodBranded,type:this,...B(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Vi({...B(this._def),innerType:this,catchValue:t,typeName:F.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return qi.create(this,e)}readonly(){return zi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Qd=/^c[^\s-]{8,}$/i,Xd=/^[0-9a-z]+$/,el=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tl=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,il=/^[a-z0-9_-]{21}$/i,nl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sl=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,al="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let _s;const ol=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,cl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,dl=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ll=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ul=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oa="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fl=new RegExp(`^${oa}$`);function ca(n){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`),e}function pl(n){return new RegExp(`^${ca(n)}$`)}function da(n){let e=`${oa}T${ca(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function ml(n,e){return!!((e==="v4"||!e)&&ol.test(n)||(e==="v6"||!e)&&dl.test(n))}function gl(n,e){if(!nl.test(n))return!1;try{const[t]=n.split("."),i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||e&&s.alg!==e)}catch{return!1}}function vl(n,e){return!!((e==="v4"||!e)&&cl.test(n)||(e==="v6"||!e)&&ll.test(n))}class Oe extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_type,expected:O.string,received:r.parsedType}),j}const i=new ye;let s;for(const r of this._def.checks)if(r.kind==="min")e.data.length<r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")e.data.length>r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){const a=e.data.length>r.value,o=e.data.length<r.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?I(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&I(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")rl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"email",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")_s||(_s=new RegExp(al,"u")),_s.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"emoji",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")tl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"uuid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")il.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"nanoid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")Qd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")Xd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid2",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")el.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ulid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),I(s,{validation:"url",code:_.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"regex",code:_.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?e.data=e.data.trim():r.kind==="includes"?e.data.includes(r.value,r.position)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?e.data=e.data.toLowerCase():r.kind==="toUpperCase"?e.data=e.data.toUpperCase():r.kind==="startsWith"?e.data.startsWith(r.value)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?e.data.endsWith(r.value)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?da(r).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?fl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?pl(r).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:_.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?sl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"duration",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?ml(e.data,r.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ip",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?gl(e.data,r.alg)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"jwt",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?vl(e.data,r.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cidr",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?ul.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?hl.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64url",code:_.invalid_string,message:r.message}),i.dirty()):H.assertNever(r);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:_.invalid_string,...N.errToObj(i)})}_addCheck(e){return new Oe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){var t,i;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(i=e==null?void 0:e.local)!==null&&i!==void 0?i:!1,...N.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...N.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...N.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errToObj(t)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new Oe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Oe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Oe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Oe.create=n=>{var e;return new Oe({checks:[],typeName:F.ZodString,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...B(n)})};function yl(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,r=parseInt(n.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return r%a/Math.pow(10,s)}class bt extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_type,expected:O.number,received:r.parsedType}),j}let i;const s=new ye;for(const r of this._def.checks)r.kind==="int"?H.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),I(i,{code:_.invalid_type,expected:"integer",received:"float",message:r.message}),s.dirty()):r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):r.kind==="multipleOf"?yl(e.data,r.value)!==0&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):r.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),I(i,{code:_.not_finite,message:r.message}),s.dirty()):H.assertNever(r);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,i,s){return new bt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:N.toString(s)}]})}_addCheck(e){return new bt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&H.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}bt.create=n=>new bt({checks:[],typeName:F.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...B(n)});class kt extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let i;const s=new ye;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):r.kind==="multipleOf"?e.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),I(i,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):H.assertNever(r);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return I(t,{code:_.invalid_type,expected:O.bigint,received:t.parsedType}),j}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,i,s){return new kt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:N.toString(s)}]})}_addCheck(e){return new kt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}kt.create=n=>{var e;return new kt({checks:[],typeName:F.ZodBigInt,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...B(n)})};class Oi extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.boolean,received:i.parsedType}),j}return be(e.data)}}Oi.create=n=>new Oi({typeName:F.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...B(n)});class Ft extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_type,expected:O.date,received:r.parsedType}),j}if(isNaN(e.data.getTime())){const r=this._getOrReturnCtx(e);return I(r,{code:_.invalid_date}),j}const i=new ye;let s;for(const r of this._def.checks)r.kind==="min"?e.data.getTime()<r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?e.data.getTime()>r.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:_.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):H.assertNever(r);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ft({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Ft.create=n=>new Ft({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:F.ZodDate,...B(n)});class kn extends V{_parse(e){if(this._getType(e)!==O.symbol){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.symbol,received:i.parsedType}),j}return be(e.data)}}kn.create=n=>new kn({typeName:F.ZodSymbol,...B(n)});class Di extends V{_parse(e){if(this._getType(e)!==O.undefined){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.undefined,received:i.parsedType}),j}return be(e.data)}}Di.create=n=>new Di({typeName:F.ZodUndefined,...B(n)});class Mi extends V{_parse(e){if(this._getType(e)!==O.null){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.null,received:i.parsedType}),j}return be(e.data)}}Mi.create=n=>new Mi({typeName:F.ZodNull,...B(n)});class ii extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return be(e.data)}}ii.create=n=>new ii({typeName:F.ZodAny,...B(n)});class jt extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return be(e.data)}}jt.create=n=>new jt({typeName:F.ZodUnknown,...B(n)});class it extends V{_parse(e){const t=this._getOrReturnCtx(e);return I(t,{code:_.invalid_type,expected:O.never,received:t.parsedType}),j}}it.create=n=>new it({typeName:F.ZodNever,...B(n)});class Tn extends V{_parse(e){if(this._getType(e)!==O.undefined){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.void,received:i.parsedType}),j}return be(e.data)}}Tn.create=n=>new Tn({typeName:F.ZodVoid,...B(n)});class De extends V{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==O.array)return I(t,{code:_.invalid_type,expected:O.array,received:t.parsedType}),j;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(I(t,{code:a?_.too_big:_.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(I(t,{code:_.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(I(t,{code:_.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new Ge(t,a,t.path,o)))).then(a=>ye.mergeArray(i,a));const r=[...t.data].map((a,o)=>s.type._parseSync(new Ge(t,a,t.path,o)));return ye.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new De({...this._def,minLength:{value:e,message:N.toString(t)}})}max(e,t){return new De({...this._def,maxLength:{value:e,message:N.toString(t)}})}length(e,t){return new De({...this._def,exactLength:{value:e,message:N.toString(t)}})}nonempty(e){return this.min(1,e)}}De.create=(n,e)=>new De({type:n,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...B(e)});function ni(n){if(n instanceof re){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=He.create(ni(i))}return new re({...n._def,shape:()=>e})}else return n instanceof De?new De({...n._def,type:ni(n.element)}):n instanceof He?He.create(ni(n.unwrap())):n instanceof St?St.create(ni(n.unwrap())):n instanceof We?We.create(n.items.map(e=>ni(e))):n}class re extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=H.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==O.object){const d=this._getOrReturnCtx(e);return I(d,{code:_.invalid_type,expected:O.object,received:d.parsedType}),j}const{status:i,ctx:s}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof it&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||o.push(d);const c=[];for(const d of a){const l=r[d],u=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Ge(s,u,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof it){const d=this._def.unknownKeys;if(d==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(d==="strict")o.length>0&&(I(s,{code:_.unrecognized_keys,keys:o}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const l of o){const u=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Ge(s,u,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const l of c){const u=await l.key,h=await l.value;d.push({key:u,value:h,alwaysSet:l.alwaysSet})}return d}).then(d=>ye.mergeObjectSync(i,d)):ye.mergeObjectSync(i,c)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new re({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var s,r,a,o;const c=(a=(r=(s=this._def).errorMap)===null||r===void 0?void 0:r.call(s,t,i).message)!==null&&a!==void 0?a:i.defaultError;return t.code==="unrecognized_keys"?{message:(o=N.errToObj(e).message)!==null&&o!==void 0?o:c}:{message:c}}}:{}})}strip(){return new re({...this._def,unknownKeys:"strip"})}passthrough(){return new re({...this._def,unknownKeys:"passthrough"})}extend(e){return new re({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new re({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new re({...this._def,catchall:e})}pick(e){const t={};return H.objectKeys(e).forEach(i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])}),new re({...this._def,shape:()=>t})}omit(e){const t={};return H.objectKeys(this.shape).forEach(i=>{e[i]||(t[i]=this.shape[i])}),new re({...this._def,shape:()=>t})}deepPartial(){return ni(this)}partial(e){const t={};return H.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}),new re({...this._def,shape:()=>t})}required(e){const t={};return H.objectKeys(this.shape).forEach(i=>{if(e&&!e[i])t[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof He;)r=r._def.innerType;t[i]=r}}),new re({...this._def,shape:()=>t})}keyof(){return la(H.objectKeys(this.shape))}}re.create=(n,e)=>new re({shape:()=>n,unknownKeys:"strip",catchall:it.create(),typeName:F.ZodObject,...B(e)}),re.strictCreate=(n,e)=>new re({shape:()=>n,unknownKeys:"strict",catchall:it.create(),typeName:F.ZodObject,...B(e)}),re.lazycreate=(n,e)=>new re({shape:n,unknownKeys:"strip",catchall:it.create(),typeName:F.ZodObject,...B(e)});class Ni extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(r){for(const o of r)if(o.result.status==="valid")return o.result;for(const o of r)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=r.map(o=>new Re(o.ctx.common.issues));return I(t,{code:_.invalid_union,unionErrors:a}),j}if(t.common.async)return Promise.all(i.map(async r=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let r;const a=[];for(const c of i){const d={...t,common:{...t.common,issues:[]},parent:null},l=c._parseSync({data:t.data,path:t.path,parent:d});if(l.status==="valid")return l;l.status==="dirty"&&!r&&(r={result:l,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;const o=a.map(c=>new Re(c));return I(t,{code:_.invalid_union,unionErrors:o}),j}}get options(){return this._def.options}}Ni.create=(n,e)=>new Ni({options:n,typeName:F.ZodUnion,...B(e)});const nt=n=>n instanceof Fi?nt(n.schema):n instanceof Me?nt(n.innerType()):n instanceof ji?[n.value]:n instanceof Tt?n.options:n instanceof $i?H.objectValues(n.enum):n instanceof Bi?nt(n._def.innerType):n instanceof Di?[void 0]:n instanceof Mi?[null]:n instanceof He?[void 0,...nt(n.unwrap())]:n instanceof St?[null,...nt(n.unwrap())]:n instanceof ws||n instanceof zi?nt(n.unwrap()):n instanceof Vi?nt(n._def.innerType):[];class Sn extends V{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.object)return I(t,{code:_.invalid_type,expected:O.object,received:t.parsedType}),j;const i=this.discriminator,s=t.data[i],r=this.optionsMap.get(s);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(I(t,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),j)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const s=new Map;for(const r of t){const a=nt(r.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,r)}}return new Sn({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(i)})}}function Es(n,e){const t=tt(n),i=tt(e);if(n===e)return{valid:!0,data:n};if(t===O.object&&i===O.object){const s=H.objectKeys(e),r=H.objectKeys(n).filter(o=>s.indexOf(o)!==-1),a={...n,...e};for(const o of r){const c=Es(n[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===O.array&&i===O.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let r=0;r<n.length;r++){const a=n[r],o=e[r],c=Es(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===O.date&&i===O.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Li extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(r,a)=>{if(Ss(r)||Ss(a))return j;const o=Es(r.value,a.value);return o.valid?((Cs(r)||Cs(a))&&t.dirty(),{status:t.value,value:o.data}):(I(i,{code:_.invalid_intersection_types}),j)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,a])=>s(r,a)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Li.create=(n,e,t)=>new Li({left:n,right:e,typeName:F.ZodIntersection,...B(t)});class We extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.array)return I(i,{code:_.invalid_type,expected:O.array,received:i.parsedType}),j;if(i.data.length<this._def.items.length)return I(i,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),j;!this._def.rest&&i.data.length>this._def.items.length&&(I(i,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...i.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Ge(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(r).then(a=>ye.mergeArray(t,a)):ye.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new We({...this._def,rest:e})}}We.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new We({items:n,typeName:F.ZodTuple,rest:null,...B(e)})};class Ui extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.object)return I(i,{code:_.invalid_type,expected:O.object,received:i.parsedType}),j;const s=[],r=this._def.keyType,a=this._def.valueType;for(const o in i.data)s.push({key:r._parse(new Ge(i,o,i.path,o)),value:a._parse(new Ge(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?ye.mergeObjectAsync(t,s):ye.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof V?new Ui({keyType:e,valueType:t,typeName:F.ZodRecord,...B(i)}):new Ui({keyType:Oe.create(),valueType:e,typeName:F.ZodRecord,...B(t)})}}class Cn extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.map)return I(i,{code:_.invalid_type,expected:O.map,received:i.parsedType}),j;const s=this._def.keyType,r=this._def.valueType,a=[...i.data.entries()].map(([o,c],d)=>({key:s._parse(new Ge(i,o,i.path,[d,"key"])),value:r._parse(new Ge(i,c,i.path,[d,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const d=await c.key,l=await c.value;if(d.status==="aborted"||l.status==="aborted")return j;(d.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(d.value,l.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of a){const d=c.key,l=c.value;if(d.status==="aborted"||l.status==="aborted")return j;(d.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(d.value,l.value)}return{status:t.value,value:o}}}}Cn.create=(n,e,t)=>new Cn({valueType:e,keyType:n,typeName:F.ZodMap,...B(t)});class $t extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==O.set)return I(i,{code:_.invalid_type,expected:O.set,received:i.parsedType}),j;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(I(i,{code:_.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(I(i,{code:_.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const r=this._def.valueType;function a(c){const d=new Set;for(const l of c){if(l.status==="aborted")return j;l.status==="dirty"&&t.dirty(),d.add(l.value)}return{status:t.value,value:d}}const o=[...i.data.values()].map((c,d)=>r._parse(new Ge(i,c,i.path,d)));return i.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new $t({...this._def,minSize:{value:e,message:N.toString(t)}})}max(e,t){return new $t({...this._def,maxSize:{value:e,message:N.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}$t.create=(n,e)=>new $t({valueType:n,minSize:null,maxSize:null,typeName:F.ZodSet,...B(e)});class si extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.function)return I(t,{code:_.invalid_type,expected:O.function,received:t.parsedType}),j;function i(o,c){return yn({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,vn(),ei].filter(d=>!!d),issueData:{code:_.invalid_arguments,argumentsError:c}})}function s(o,c){return yn({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,vn(),ei].filter(d=>!!d),issueData:{code:_.invalid_return_type,returnTypeError:c}})}const r={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ri){const o=this;return be(async function(...c){const d=new Re([]),l=await o._def.args.parseAsync(c,r).catch(p=>{throw d.addIssue(i(c,p)),d}),u=await Reflect.apply(a,this,l);return await o._def.returns._def.type.parseAsync(u,r).catch(p=>{throw d.addIssue(s(u,p)),d})})}else{const o=this;return be(function(...c){const d=o._def.args.safeParse(c,r);if(!d.success)throw new Re([i(c,d.error)]);const l=Reflect.apply(a,this,d.data),u=o._def.returns.safeParse(l,r);if(!u.success)throw new Re([s(l,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new si({...this._def,args:We.create(e).rest(jt.create())})}returns(e){return new si({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new si({args:e||We.create([]).rest(jt.create()),returns:t||jt.create(),typeName:F.ZodFunction,...B(i)})}}class Fi extends V{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Fi.create=(n,e)=>new Fi({getter:n,typeName:F.ZodLazy,...B(e)});class ji extends V{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:_.invalid_literal,expected:this._def.value}),j}return{status:"valid",value:e.data}}get value(){return this._def.value}}ji.create=(n,e)=>new ji({value:n,typeName:F.ZodLiteral,...B(e)});function la(n,e){return new Tt({values:n,typeName:F.ZodEnum,...B(e)})}class Tt extends V{constructor(){super(...arguments),Ii.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return I(t,{expected:H.joinValues(i),received:t.parsedType,code:_.invalid_type}),j}if(bn(this,Ii,"f")||ra(this,Ii,new Set(this._def.values),"f"),!bn(this,Ii,"f").has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return I(t,{received:t.data,code:_.invalid_enum_value,options:i}),j}return be(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Tt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Tt.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}Ii=new WeakMap,Tt.create=la;class $i extends V{constructor(){super(...arguments),Ai.set(this,void 0)}_parse(e){const t=H.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==O.string&&i.parsedType!==O.number){const s=H.objectValues(t);return I(i,{expected:H.joinValues(s),received:i.parsedType,code:_.invalid_type}),j}if(bn(this,Ai,"f")||ra(this,Ai,new Set(H.getValidEnumValues(this._def.values)),"f"),!bn(this,Ai,"f").has(e.data)){const s=H.objectValues(t);return I(i,{received:i.data,code:_.invalid_enum_value,options:s}),j}return be(e.data)}get enum(){return this._def.values}}Ai=new WeakMap,$i.create=(n,e)=>new $i({values:n,typeName:F.ZodNativeEnum,...B(e)});class ri extends V{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.promise&&t.common.async===!1)return I(t,{code:_.invalid_type,expected:O.promise,received:t.parsedType}),j;const i=t.parsedType===O.promise?t.data:Promise.resolve(t.data);return be(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ri.create=(n,e)=>new ri({type:n,typeName:F.ZodPromise,...B(e)});class Me extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,r={addIssue:a=>{I(i,a),a.fatal?t.abort():t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),s.type==="preprocess"){const a=s.transform(i.data,r);if(i.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return j;const c=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return c.status==="aborted"?j:c.status==="dirty"||t.value==="dirty"?ti(c.value):c});{if(t.value==="aborted")return j;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?j:o.status==="dirty"||t.value==="dirty"?ti(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,r);if(i.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?j:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?j:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Ut(a))return a;const o=s.transform(a.value,r);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>Ut(a)?Promise.resolve(s.transform(a.value,r)).then(o=>({status:t.value,value:o})):a);H.assertNever(s)}}Me.create=(n,e,t)=>new Me({schema:n,typeName:F.ZodEffects,effect:e,...B(t)}),Me.createWithPreprocess=(n,e,t)=>new Me({schema:e,effect:{type:"preprocess",transform:n},typeName:F.ZodEffects,...B(t)});class He extends V{_parse(e){return this._getType(e)===O.undefined?be(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}He.create=(n,e)=>new He({innerType:n,typeName:F.ZodOptional,...B(e)});class St extends V{_parse(e){return this._getType(e)===O.null?be(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}St.create=(n,e)=>new St({innerType:n,typeName:F.ZodNullable,...B(e)});class Bi extends V{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===O.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Bi.create=(n,e)=>new Bi({innerType:n,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});class Vi extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return xi(s)?s.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Re(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Re(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Vi.create=(n,e)=>new Vi({innerType:n,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});class _n extends V{_parse(e){if(this._getType(e)!==O.nan){const i=this._getOrReturnCtx(e);return I(i,{code:_.invalid_type,expected:O.nan,received:i.parsedType}),j}return{status:"valid",value:e.data}}}_n.create=n=>new _n({typeName:F.ZodNaN,...B(n)});const bl=Symbol("zod_brand");class ws extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class qi extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?j:r.status==="dirty"?(t.dirty(),ti(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?j:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new qi({in:e,out:t,typeName:F.ZodPipeline})}}class zi extends V{_parse(e){const t=this._def.innerType._parse(e),i=s=>(Ut(s)&&(s.value=Object.freeze(s.value)),s);return xi(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}zi.create=(n,e)=>new zi({innerType:n,typeName:F.ZodReadonly,...B(e)});function ua(n,e){const t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function ha(n,e={},t){return n?ii.create().superRefine((i,s)=>{var r,a;const o=n(i);if(o instanceof Promise)return o.then(c=>{var d,l;if(!c){const u=ua(e,i),h=(l=(d=u.fatal)!==null&&d!==void 0?d:t)!==null&&l!==void 0?l:!0;s.addIssue({code:"custom",...u,fatal:h})}});if(!o){const c=ua(e,i),d=(a=(r=c.fatal)!==null&&r!==void 0?r:t)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...c,fatal:d})}}):ii.create()}const kl={object:re.lazycreate};var F;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(F||(F={}));const Tl=(n,e={message:`Input not instance of ${n.name}`})=>ha(t=>t instanceof n,e),fa=Oe.create,pa=bt.create,Sl=_n.create,Cl=kt.create,ma=Oi.create,_l=Ft.create,El=kn.create,wl=Di.create,Pl=Mi.create,Rl=ii.create,xl=jt.create,Il=it.create,Al=Tn.create,Ol=De.create,Dl=re.create,Ml=re.strictCreate,Nl=Ni.create,Ll=Sn.create,Ul=Li.create,Fl=We.create,jl=Ui.create,$l=Cn.create,Bl=$t.create,Vl=si.create,ql=Fi.create,zl=ji.create,Kl=Tt.create,Gl=$i.create,Wl=ri.create,ga=Me.create,Hl=He.create,Zl=St.create,Jl=Me.createWithPreprocess,Yl=qi.create;var st=Object.freeze({__proto__:null,defaultErrorMap:ei,setErrorMap:Jd,getErrorMap:vn,makeIssue:yn,EMPTY_PATH:Yd,addIssueToContext:I,ParseStatus:ye,INVALID:j,DIRTY:ti,OK:be,isAborted:Ss,isDirty:Cs,isValid:Ut,isAsync:xi,get util(){return H},get objectUtil(){return Ts},ZodParsedType:O,getParsedType:tt,ZodType:V,datetimeRegex:da,ZodString:Oe,ZodNumber:bt,ZodBigInt:kt,ZodBoolean:Oi,ZodDate:Ft,ZodSymbol:kn,ZodUndefined:Di,ZodNull:Mi,ZodAny:ii,ZodUnknown:jt,ZodNever:it,ZodVoid:Tn,ZodArray:De,ZodObject:re,ZodUnion:Ni,ZodDiscriminatedUnion:Sn,ZodIntersection:Li,ZodTuple:We,ZodRecord:Ui,ZodMap:Cn,ZodSet:$t,ZodFunction:si,ZodLazy:Fi,ZodLiteral:ji,ZodEnum:Tt,ZodNativeEnum:$i,ZodPromise:ri,ZodEffects:Me,ZodTransformer:Me,ZodOptional:He,ZodNullable:St,ZodDefault:Bi,ZodCatch:Vi,ZodNaN:_n,BRAND:bl,ZodBranded:ws,ZodPipeline:qi,ZodReadonly:zi,custom:ha,Schema:V,ZodSchema:V,late:kl,get ZodFirstPartyTypeKind(){return F},coerce:{string:n=>Oe.create({...n,coerce:!0}),number:n=>bt.create({...n,coerce:!0}),boolean:n=>Oi.create({...n,coerce:!0}),bigint:n=>kt.create({...n,coerce:!0}),date:n=>Ft.create({...n,coerce:!0})},any:Rl,array:Ol,bigint:Cl,boolean:ma,date:_l,discriminatedUnion:Ll,effect:ga,enum:Kl,function:Vl,instanceof:Tl,intersection:Ul,lazy:ql,literal:zl,map:$l,nan:Sl,nativeEnum:Gl,never:Il,null:Pl,nullable:Zl,number:pa,object:Dl,oboolean:()=>ma().optional(),onumber:()=>pa().optional(),optional:Hl,ostring:()=>fa().optional(),pipeline:Yl,preprocess:Jl,promise:Wl,record:jl,set:Bl,strictObject:Ml,string:fa,symbol:El,transformer:ga,tuple:Fl,undefined:wl,union:Nl,unknown:xl,void:Al,NEVER:j,ZodIssueCode:_,quotelessJson:Zd,ZodError:Re});const va="https://iamobi.ai/api",Ql=st.object({apiKey:st.string().optional(),enableVoice:st.boolean().default(!0),enableScreenCapture:st.boolean().default(!0),debug:st.boolean().default(!1),user:st.object({id:st.string(),email:st.string().optional(),metadata:st.any().optional()}).optional()});var rt=(n=>(n.READY="ready",n.ERROR="error",n.VOICE_START="voice:start",n.VOICE_STOP="voice:stop",n.SCREEN_CAPTURE_START="screen:start",n.SCREEN_CAPTURE_STOP="screen:stop",n.STATE_CHANGE="state:change",n))(rt||{}),$=(n=>(n.READY="ready",n.ERROR="error",n.PAUSED="paused",n.LOADING="loading",n.THINKING="thinking",n.RESEARCHING="researching",n.AGENT_SPEAKING="agent_speaking",n.USER_SPEAKING="user_speaking",n.AWAITING_USER_INPUT="awaiting_user_input",n))($||{}),Xl=Object.defineProperty,eu=Object.getOwnPropertyDescriptor,En=(n,e,t,i)=>{for(var s=i>1?void 0:i?eu(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Xl(e,t,s),s};class ai extends L.LitElement{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return L.html`
18
18
  <button
19
19
  id="obi-nav-${this.id}"
20
20
  class=${this.isSpecial?"special":""}
@@ -24,7 +24,7 @@
24
24
  >
25
25
  <slot></slot>
26
26
  </button>
27
- `}}ri.styles=L.css`
27
+ `}}ai.styles=L.css`
28
28
  :host {
29
29
  display: block;
30
30
  }
@@ -76,7 +76,7 @@
76
76
  width: 18px;
77
77
  height: 18px;
78
78
  }
79
- `,_n([Y({type:String})],ri.prototype,"id",2),_n([Y({type:Boolean})],ri.prototype,"isActive",2),_n([Y({type:Boolean})],ri.prototype,"isSpecial",2),_n([Y({type:Function})],ri.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",ri);const zi=n=>L.html`
79
+ `,En([Y({type:String})],ai.prototype,"id",2),En([Y({type:Boolean})],ai.prototype,"isActive",2),En([Y({type:Boolean})],ai.prototype,"isSpecial",2),En([Y({type:Function})],ai.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",ai);const Ki=n=>L.html`
80
80
  <svg
81
81
  xmlns="http://www.w3.org/2000/svg"
82
82
  width="24"
@@ -92,18 +92,18 @@
92
92
  >
93
93
  ${n}
94
94
  </svg>
95
- `,Ql=zi(L.svg`
95
+ `,tu=Ki(L.svg`
96
96
  <rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>
97
- `),Xl=zi(L.svg`<polygon points="6 3 20 12 6 21 6 3"/>`),eu=zi(L.svg`
97
+ `),iu=Ki(L.svg`<polygon points="6 3 20 12 6 21 6 3"/>`),nu=Ki(L.svg`
98
98
  <path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>
99
- `),tu=zi(L.svg`
99
+ `),su=Ki(L.svg`
100
100
  <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
101
- `),iu=zi(L.svg`
101
+ `),ru=Ki(L.svg`
102
102
  <path d="M12 7v14" />
103
103
  <path
104
104
  d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"
105
105
  />
106
- `),ga=L.html`
106
+ `),ya=L.html`
107
107
  <img
108
108
  class="widget-icon"
109
109
  src="data:image/svg+xml;base64,${btoa(`<?xml version="1.0" encoding="UTF-8"?>
@@ -124,14 +124,14 @@
124
124
  </svg>`)}"
125
125
  alt="Obi Icon"
126
126
  />
127
- `;var nu=Object.defineProperty,su=Object.getOwnPropertyDescriptor,ai=(n,e,t,i)=>{for(var s=i>1?void 0:i?su(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&nu(e,t,s),s};class St extends L.LitElement{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=$.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return L.html`
127
+ `;var au=Object.defineProperty,ou=Object.getOwnPropertyDescriptor,oi=(n,e,t,i)=>{for(var s=i>1?void 0:i?ou(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&au(e,t,s),s};class Ct extends L.LitElement{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=$.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return L.html`
128
128
  ${this.isActive?L.html`
129
129
  <obi-nav-icon
130
130
  id="pause"
131
131
  ?isActive=${this.currentState===$.PAUSED}
132
132
  @click=${()=>this.handleIconClick("pause",this.currentState!==$.PAUSED)}
133
133
  >
134
- ${this.currentState===$.PAUSED?Xl:Ql}
134
+ ${this.currentState===$.PAUSED?iu:tu}
135
135
  </obi-nav-icon>
136
136
  <obi-nav-icon
137
137
  id="activate"
@@ -139,17 +139,17 @@
139
139
  ?isSpecial=${!0}
140
140
  @click=${()=>this.handleIconClick("activate",!this.isActive)}
141
141
  >
142
- ${this.isActive?tu:eu}
142
+ ${this.isActive?su:nu}
143
143
  </obi-nav-icon>
144
144
  `:L.html`
145
145
  <obi-nav-icon
146
146
  id="experiences"
147
147
  @click=${()=>this.handleIconClick("experiences",!0)}
148
148
  >
149
- ${iu}
149
+ ${ru}
150
150
  </obi-nav-icon>
151
151
  `}
152
- `}}St.styles=L.css`
152
+ `}}Ct.styles=L.css`
153
153
  :host {
154
154
  display: flex;
155
155
  position: absolute;
@@ -173,13 +173,13 @@
173
173
  bottom: auto;
174
174
  flex-direction: column;
175
175
  }
176
- `,ai([Y({type:Boolean})],St.prototype,"isActive",2),ai([Y({type:Boolean})],St.prototype,"isScreenActive",2),ai([Y({type:Object})],St.prototype,"position",2),ai([Y({type:String})],St.prototype,"currentState",2),ai([Y({type:String})],St.prototype,"direction",2),ai([Y({type:Function})],St.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",St);var ru=Object.defineProperty,au=Object.getOwnPropertyDescriptor,rt=(n,e,t,i)=>{for(var s=i>1?void 0:i?au(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&ru(e,t,s),s};class $t extends L.LitElement{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return L.html`
176
+ `,oi([Y({type:Boolean})],Ct.prototype,"isActive",2),oi([Y({type:Boolean})],Ct.prototype,"isScreenActive",2),oi([Y({type:Object})],Ct.prototype,"position",2),oi([Y({type:String})],Ct.prototype,"currentState",2),oi([Y({type:String})],Ct.prototype,"direction",2),oi([Y({type:Function})],Ct.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",Ct);var cu=Object.defineProperty,du=Object.getOwnPropertyDescriptor,at=(n,e,t,i)=>{for(var s=i>1?void 0:i?du(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&cu(e,t,s),s};class Bt extends L.LitElement{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return L.html`
177
177
  <div class="course-container" @click=${this.handleClick}>
178
178
  <img src=${this.imageSrc} alt="Course Preview" class="course-image" />
179
179
  <h2 class="course-title">${this.name}</h2>
180
180
  ${this.description?L.html`<p class="course-description">${this.description}</p>`:""}
181
181
  </div>
182
- `}}$t.styles=L.css`
182
+ `}}Bt.styles=L.css`
183
183
  :host {
184
184
  display: block;
185
185
  }
@@ -224,7 +224,7 @@
224
224
  color: #71717a;
225
225
  margin: 0;
226
226
  }
227
- `,rt([Y({type:String})],$t.prototype,"id",2),rt([Y({type:String})],$t.prototype,"name",2),rt([Y({type:String})],$t.prototype,"description",2),rt([Y({type:String})],$t.prototype,"imageSrc",2),rt([Y({type:Function})],$t.prototype,"onSelect",2);class oi extends L.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return L.html`<div class="loading">Loading...</div>`;if(this.error)return L.html`<div class="error">${this.error}</div>`;if(!this.courses||this.courses.length===0)return L.html`<div class="empty">No courses available</div>`;const e=this.courses.length===1?"grid-cols-1":this.courses.length===2?"grid-cols-2":"grid-cols-3";return L.html`
227
+ `,at([Y({type:String})],Bt.prototype,"id",2),at([Y({type:String})],Bt.prototype,"name",2),at([Y({type:String})],Bt.prototype,"description",2),at([Y({type:String})],Bt.prototype,"imageSrc",2),at([Y({type:Function})],Bt.prototype,"onSelect",2);class ci extends L.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return L.html`<div class="loading">Loading...</div>`;if(this.error)return L.html`<div class="error">${this.error}</div>`;if(!this.courses||this.courses.length===0)return L.html`<div class="empty">No courses available</div>`;const e=this.courses.length===1?"grid-cols-1":this.courses.length===2?"grid-cols-2":"grid-cols-3";return L.html`
228
228
  <div class="course-grid ${e}">
229
229
  ${this.courses.map(t=>L.html`
230
230
  <obi-course
@@ -236,7 +236,7 @@
236
236
  ></obi-course>
237
237
  `)}
238
238
  </div>
239
- `}}oi.styles=L.css`
239
+ `}}ci.styles=L.css`
240
240
  :host {
241
241
  display: block;
242
242
  }
@@ -271,7 +271,7 @@
271
271
  .error {
272
272
  color: #ef4444;
273
273
  }
274
- `,rt([Y({type:Array})],oi.prototype,"courses",2),rt([Y({type:Boolean})],oi.prototype,"loading",2),rt([Y({type:String})],oi.prototype,"error",2),rt([Y({type:Function})],oi.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",$t),customElements.get("obi-course-list")||customElements.define("obi-course-list",oi);var ou=Object.defineProperty,cu=Object.getOwnPropertyDescriptor,Bt=(n,e,t,i)=>{for(var s=i>1?void 0:i?cu(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&ou(e,t,s),s};class at extends L.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiBaseUrl="",this.apiKey=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const s=(await(await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`)).json()).map(r=>({id:r.uuid,name:r.onboarding_plan.name,description:r.onboarding_plan.description,imageSrc:r.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"})).filter(r=>!!r.name);this.courses=[...s],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){var e;super.connectedCallback(),(e=window.obiWidgetConfig)!=null&&e.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),this.apiBaseUrl=ma,this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return L.html`
274
+ `,at([Y({type:Array})],ci.prototype,"courses",2),at([Y({type:Boolean})],ci.prototype,"loading",2),at([Y({type:String})],ci.prototype,"error",2),at([Y({type:Function})],ci.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",Bt),customElements.get("obi-course-list")||customElements.define("obi-course-list",ci);var lu=Object.defineProperty,uu=Object.getOwnPropertyDescriptor,Vt=(n,e,t,i)=>{for(var s=i>1?void 0:i?uu(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&lu(e,t,s),s};class ot extends L.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiBaseUrl="",this.apiKey=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const s=(await(await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`)).json()).map(r=>({id:r.uuid,name:r.onboarding_plan.name,description:r.onboarding_plan.description,imageSrc:r.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"})).filter(r=>!!r.name);this.courses=[...s],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){var e;super.connectedCallback(),(e=window.obiWidgetConfig)!=null&&e.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),this.apiBaseUrl=va,this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return L.html`
275
275
  <div class="backdrop" @click=${this.handleClose}></div>
276
276
  <div class="container">
277
277
  <button class="close-button" @click=${this.handleClose}>×</button>
@@ -287,7 +287,7 @@
287
287
  @course-select=${this.handleCourseSelect}
288
288
  ></obi-course-list>
289
289
  </div>
290
- `}}at.styles=L.css`
290
+ `}}ot.styles=L.css`
291
291
  :host {
292
292
  display: block;
293
293
  font-family: "Syne", sans-serif;
@@ -370,29 +370,29 @@
370
370
  font-size: 24px;
371
371
  color: #6b7280;
372
372
  }
373
- `,Bt([Y({type:Array})],at.prototype,"courses",2),Bt([Y({type:Boolean})],at.prototype,"loading",2),Bt([Y({type:String})],at.prototype,"error",2),Bt([Y({type:String})],at.prototype,"apiBaseUrl",2),Bt([Y({type:String})],at.prototype,"apiKey",2),Bt([Y({type:Function})],at.prototype,"onCourseSelect",2),Bt([Y({type:Function})],at.prototype,"onClose",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",at);/**
373
+ `,Vt([Y({type:Array})],ot.prototype,"courses",2),Vt([Y({type:Boolean})],ot.prototype,"loading",2),Vt([Y({type:String})],ot.prototype,"error",2),Vt([Y({type:String})],ot.prototype,"apiBaseUrl",2),Vt([Y({type:String})],ot.prototype,"apiKey",2),Vt([Y({type:Function})],ot.prototype,"onCourseSelect",2),Vt([Y({type:Function})],ot.prototype,"onClose",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",ot);/**
374
374
  * @license
375
375
  * Copyright 2017 Google LLC
376
376
  * SPDX-License-Identifier: BSD-3-Clause
377
- */const Ki=globalThis,En=Ki.trustedTypes,va=En?En.createPolicy("lit-html",{createHTML:n=>n}):void 0,ya="$lit$",Ct=`lit$${Math.random().toFixed(9).slice(2)}$`,ba="?"+Ct,du=`<${ba}>`,Vt=document,wn=()=>Vt.createComment(""),Gi=n=>n===null||typeof n!="object"&&typeof n!="function",Es=Array.isArray,lu=n=>Es(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",ws=`[
378
- \f\r]`,Wi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ka=/-->/g,Ta=/>/g,qt=RegExp(`>|${ws}(?:([^\\s"'>=/]+)(${ws}*=${ws}*(?:[^
379
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Sa=/'/g,Ca=/"/g,_a=/^(?:script|style|textarea|title)$/i,Hi=Symbol.for("lit-noChange"),ue=Symbol.for("lit-nothing"),Ea=new WeakMap,zt=Vt.createTreeWalker(Vt,129);function wa(n,e){if(!Es(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return va!==void 0?va.createHTML(e):e}const uu=(n,e)=>{const t=n.length-1,i=[];let s,r=e===2?"<svg>":e===3?"<math>":"",a=Wi;for(let o=0;o<t;o++){const c=n[o];let d,l,u=-1,h=0;for(;h<c.length&&(a.lastIndex=h,l=a.exec(c),l!==null);)h=a.lastIndex,a===Wi?l[1]==="!--"?a=ka:l[1]!==void 0?a=Ta:l[2]!==void 0?(_a.test(l[2])&&(s=RegExp("</"+l[2],"g")),a=qt):l[3]!==void 0&&(a=qt):a===qt?l[0]===">"?(a=s??Wi,u=-1):l[1]===void 0?u=-2:(u=a.lastIndex-l[2].length,d=l[1],a=l[3]===void 0?qt:l[3]==='"'?Ca:Sa):a===Ca||a===Sa?a=qt:a===ka||a===Ta?a=Wi:(a=qt,s=void 0);const p=a===qt&&n[o+1].startsWith("/>")?" ":"";r+=a===Wi?c+du:u>=0?(i.push(d),c.slice(0,u)+ya+c.slice(u)+Ct+p):c+Ct+(u===-2?o:p)}return[wa(n,r+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class Zi{constructor({strings:e,_$litType$:t},i){let s;this.parts=[];let r=0,a=0;const o=e.length-1,c=this.parts,[d,l]=uu(e,t);if(this.el=Zi.createElement(d,i),zt.currentNode=this.el.content,t===2||t===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=zt.nextNode())!==null&&c.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(ya)){const h=l[a++],p=s.getAttribute(u).split(Ct),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:p,ctor:g[1]==="."?fu:g[1]==="?"?pu:g[1]==="@"?mu:Rn}),s.removeAttribute(u)}else u.startsWith(Ct)&&(c.push({type:6,index:r}),s.removeAttribute(u));if(_a.test(s.tagName)){const u=s.textContent.split(Ct),h=u.length-1;if(h>0){s.textContent=En?En.emptyScript:"";for(let p=0;p<h;p++)s.append(u[p],wn()),zt.nextNode(),c.push({type:2,index:++r});s.append(u[h],wn())}}}else if(s.nodeType===8)if(s.data===ba)c.push({type:2,index:r});else{let u=-1;for(;(u=s.data.indexOf(Ct,u+1))!==-1;)c.push({type:7,index:r}),u+=Ct.length-1}r++}}static createElement(e,t){const i=Vt.createElement("template");return i.innerHTML=e,i}}function ci(n,e,t=n,i){var a,o;if(e===Hi)return e;let s=i!==void 0?(a=t._$Co)==null?void 0:a[i]:t._$Cl;const r=Gi(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==r&&((o=s==null?void 0:s._$AO)==null||o.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=ci(n,s._$AS(n,e.values),s,i)),e}class hu{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)??Vt).importNode(t,!0);zt.currentNode=s;let r=zt.nextNode(),a=0,o=0,c=i[0];for(;c!==void 0;){if(a===c.index){let d;c.type===2?d=new Pn(r,r.nextSibling,this,e):c.type===1?d=new c.ctor(r,c.name,c.strings,this,e):c.type===6&&(d=new gu(r,this,e)),this._$AV.push(d),c=i[++o]}a!==(c==null?void 0:c.index)&&(r=zt.nextNode(),a++)}return zt.currentNode=Vt,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 Pn{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=ue,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=ci(this,e,t),Gi(e)?e===ue||e==null||e===""?(this._$AH!==ue&&this._$AR(),this._$AH=ue):e!==this._$AH&&e!==Hi&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):lu(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!==ue&&Gi(this._$AH)?this._$AA.nextSibling.data=e:this.T(Vt.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=Zi.createElement(wa(i.h,i.h[0]),this.options)),i);if(((r=this._$AH)==null?void 0:r._$AD)===s)this._$AH.p(t);else{const a=new hu(s,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=Ea.get(e.strings);return t===void 0&&Ea.set(e.strings,t=new Zi(e)),t}k(e){Es(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 Pn(this.O(wn()),this.O(wn()),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&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class Rn{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,s,r){this.type=1,this._$AH=ue,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=ue}_$AI(e,t=this,i,s){const r=this.strings;let a=!1;if(r===void 0)e=ci(this,e,t,0),a=!Gi(e)||e!==this._$AH&&e!==Hi,a&&(this._$AH=e);else{const o=e;let c,d;for(e=r[0],c=0;c<r.length-1;c++)d=ci(this,o[i+c],t,c),d===Hi&&(d=this._$AH[c]),a||(a=!Gi(d)||d!==this._$AH[c]),d===ue?e=ue:e!==ue&&(e+=(d??"")+r[c+1]),this._$AH[c]=d}a&&!s&&this.j(e)}j(e){e===ue?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class fu extends Rn{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===ue?void 0:e}}class pu extends Rn{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==ue)}}class mu extends Rn{constructor(e,t,i,s,r){super(e,t,i,s,r),this.type=5}_$AI(e,t=this){if((e=ci(this,e,t,0)??ue)===Hi)return;const i=this._$AH,s=e===ue&&i!==ue||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,r=e!==ue&&(i===ue||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 gu{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){ci(this,e)}}const Ps=Ki.litHtmlPolyfillSupport;Ps==null||Ps(Zi,Pn),(Ki.litHtmlVersions??(Ki.litHtmlVersions=[])).push("3.3.0");/**
377
+ */const Gi=globalThis,wn=Gi.trustedTypes,ba=wn?wn.createPolicy("lit-html",{createHTML:n=>n}):void 0,ka="$lit$",_t=`lit$${Math.random().toFixed(9).slice(2)}$`,Ta="?"+_t,hu=`<${Ta}>`,qt=document,Pn=()=>qt.createComment(""),Wi=n=>n===null||typeof n!="object"&&typeof n!="function",Ps=Array.isArray,fu=n=>Ps(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",Rs=`[
378
+ \f\r]`,Hi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Sa=/-->/g,Ca=/>/g,zt=RegExp(`>|${Rs}(?:([^\\s"'>=/]+)(${Rs}*=${Rs}*(?:[^
379
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),_a=/'/g,Ea=/"/g,wa=/^(?:script|style|textarea|title)$/i,Zi=Symbol.for("lit-noChange"),ue=Symbol.for("lit-nothing"),Pa=new WeakMap,Kt=qt.createTreeWalker(qt,129);function Ra(n,e){if(!Ps(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return ba!==void 0?ba.createHTML(e):e}const pu=(n,e)=>{const t=n.length-1,i=[];let s,r=e===2?"<svg>":e===3?"<math>":"",a=Hi;for(let o=0;o<t;o++){const c=n[o];let d,l,u=-1,h=0;for(;h<c.length&&(a.lastIndex=h,l=a.exec(c),l!==null);)h=a.lastIndex,a===Hi?l[1]==="!--"?a=Sa:l[1]!==void 0?a=Ca:l[2]!==void 0?(wa.test(l[2])&&(s=RegExp("</"+l[2],"g")),a=zt):l[3]!==void 0&&(a=zt):a===zt?l[0]===">"?(a=s??Hi,u=-1):l[1]===void 0?u=-2:(u=a.lastIndex-l[2].length,d=l[1],a=l[3]===void 0?zt:l[3]==='"'?Ea:_a):a===Ea||a===_a?a=zt:a===Sa||a===Ca?a=Hi:(a=zt,s=void 0);const p=a===zt&&n[o+1].startsWith("/>")?" ":"";r+=a===Hi?c+hu:u>=0?(i.push(d),c.slice(0,u)+ka+c.slice(u)+_t+p):c+_t+(u===-2?o:p)}return[Ra(n,r+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class Ji{constructor({strings:e,_$litType$:t},i){let s;this.parts=[];let r=0,a=0;const o=e.length-1,c=this.parts,[d,l]=pu(e,t);if(this.el=Ji.createElement(d,i),Kt.currentNode=this.el.content,t===2||t===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=Kt.nextNode())!==null&&c.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(ka)){const h=l[a++],p=s.getAttribute(u).split(_t),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:p,ctor:g[1]==="."?gu:g[1]==="?"?vu:g[1]==="@"?yu:xn}),s.removeAttribute(u)}else u.startsWith(_t)&&(c.push({type:6,index:r}),s.removeAttribute(u));if(wa.test(s.tagName)){const u=s.textContent.split(_t),h=u.length-1;if(h>0){s.textContent=wn?wn.emptyScript:"";for(let p=0;p<h;p++)s.append(u[p],Pn()),Kt.nextNode(),c.push({type:2,index:++r});s.append(u[h],Pn())}}}else if(s.nodeType===8)if(s.data===Ta)c.push({type:2,index:r});else{let u=-1;for(;(u=s.data.indexOf(_t,u+1))!==-1;)c.push({type:7,index:r}),u+=_t.length-1}r++}}static createElement(e,t){const i=qt.createElement("template");return i.innerHTML=e,i}}function di(n,e,t=n,i){var a,o;if(e===Zi)return e;let s=i!==void 0?(a=t._$Co)==null?void 0:a[i]:t._$Cl;const r=Wi(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==r&&((o=s==null?void 0:s._$AO)==null||o.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=di(n,s._$AS(n,e.values),s,i)),e}class mu{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)??qt).importNode(t,!0);Kt.currentNode=s;let r=Kt.nextNode(),a=0,o=0,c=i[0];for(;c!==void 0;){if(a===c.index){let d;c.type===2?d=new Rn(r,r.nextSibling,this,e):c.type===1?d=new c.ctor(r,c.name,c.strings,this,e):c.type===6&&(d=new bu(r,this,e)),this._$AV.push(d),c=i[++o]}a!==(c==null?void 0:c.index)&&(r=Kt.nextNode(),a++)}return Kt.currentNode=qt,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 Rn{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=ue,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=di(this,e,t),Wi(e)?e===ue||e==null||e===""?(this._$AH!==ue&&this._$AR(),this._$AH=ue):e!==this._$AH&&e!==Zi&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):fu(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!==ue&&Wi(this._$AH)?this._$AA.nextSibling.data=e:this.T(qt.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=Ji.createElement(Ra(i.h,i.h[0]),this.options)),i);if(((r=this._$AH)==null?void 0:r._$AD)===s)this._$AH.p(t);else{const a=new mu(s,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=Pa.get(e.strings);return t===void 0&&Pa.set(e.strings,t=new Ji(e)),t}k(e){Ps(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 Rn(this.O(Pn()),this.O(Pn()),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&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class xn{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,s,r){this.type=1,this._$AH=ue,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=ue}_$AI(e,t=this,i,s){const r=this.strings;let a=!1;if(r===void 0)e=di(this,e,t,0),a=!Wi(e)||e!==this._$AH&&e!==Zi,a&&(this._$AH=e);else{const o=e;let c,d;for(e=r[0],c=0;c<r.length-1;c++)d=di(this,o[i+c],t,c),d===Zi&&(d=this._$AH[c]),a||(a=!Wi(d)||d!==this._$AH[c]),d===ue?e=ue:e!==ue&&(e+=(d??"")+r[c+1]),this._$AH[c]=d}a&&!s&&this.j(e)}j(e){e===ue?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class gu extends xn{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===ue?void 0:e}}class vu extends xn{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==ue)}}class yu extends xn{constructor(e,t,i,s,r){super(e,t,i,s,r),this.type=5}_$AI(e,t=this){if((e=di(this,e,t,0)??ue)===Zi)return;const i=this._$AH,s=e===ue&&i!==ue||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,r=e!==ue&&(i===ue||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 bu{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){di(this,e)}}const xs=Gi.litHtmlPolyfillSupport;xs==null||xs(Ji,Rn),(Gi.litHtmlVersions??(Gi.litHtmlVersions=[])).push("3.3.0");/**
380
380
  * @license
381
381
  * Copyright 2020 Google LLC
382
382
  * SPDX-License-Identifier: BSD-3-Clause
383
- */const vu=n=>n.strings===void 0;/**
383
+ */const ku=n=>n.strings===void 0;/**
384
384
  * @license
385
385
  * Copyright 2017 Google LLC
386
386
  * SPDX-License-Identifier: BSD-3-Clause
387
- */const yu={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},bu=n=>(...e)=>({_$litDirective$:n,values:e});class ku{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
387
+ */const Tu={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Su=n=>(...e)=>({_$litDirective$:n,values:e});class Cu{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
388
388
  * @license
389
389
  * Copyright 2017 Google LLC
390
390
  * SPDX-License-Identifier: BSD-3-Clause
391
- */const Ji=(n,e)=>{var i;const t=n._$AN;if(t===void 0)return!1;for(const s of t)(i=s._$AO)==null||i.call(s,e,!1),Ji(s,e);return!0},xn=n=>{let e,t;do{if((e=n._$AM)===void 0)break;t=e._$AN,t.delete(n),n=e}while((t==null?void 0:t.size)===0)},Pa=n=>{for(let e;e=n._$AM;n=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(n))break;t.add(n),Cu(e)}};function Tu(n){this._$AN!==void 0?(xn(this),this._$AM=n,Pa(this)):this._$AM=n}function Su(n,e=!1,t=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(i))for(let r=t;r<i.length;r++)Ji(i[r],!1),xn(i[r]);else i!=null&&(Ji(i,!1),xn(i));else Ji(this,n)}const Cu=n=>{n.type==yu.CHILD&&(n._$AP??(n._$AP=Su),n._$AQ??(n._$AQ=Tu))};class _u extends ku{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),Pa(this),this.isConnected=e._$AU}_$AO(e,t=!0){var i,s;e!==this.isConnected&&(this.isConnected=e,e?(i=this.reconnected)==null||i.call(this):(s=this.disconnected)==null||s.call(this)),t&&(Ji(this,e),xn(this))}setValue(e){if(vu(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}/**
391
+ */const Yi=(n,e)=>{var i;const t=n._$AN;if(t===void 0)return!1;for(const s of t)(i=s._$AO)==null||i.call(s,e,!1),Yi(s,e);return!0},In=n=>{let e,t;do{if((e=n._$AM)===void 0)break;t=e._$AN,t.delete(n),n=e}while((t==null?void 0:t.size)===0)},xa=n=>{for(let e;e=n._$AM;n=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(n))break;t.add(n),wu(e)}};function _u(n){this._$AN!==void 0?(In(this),this._$AM=n,xa(this)):this._$AM=n}function Eu(n,e=!1,t=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(i))for(let r=t;r<i.length;r++)Yi(i[r],!1),In(i[r]);else i!=null&&(Yi(i,!1),In(i));else Yi(this,n)}const wu=n=>{n.type==Tu.CHILD&&(n._$AP??(n._$AP=Eu),n._$AQ??(n._$AQ=_u))};class Pu extends Cu{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),xa(this),this.isConnected=e._$AU}_$AO(e,t=!0){var i,s;e!==this.isConnected&&(this.isConnected=e,e?(i=this.reconnected)==null||i.call(this):(s=this.disconnected)==null||s.call(this)),t&&(Yi(this,e),In(this))}setValue(e){if(ku(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}/**
392
392
  * @license
393
393
  * Copyright 2020 Google LLC
394
394
  * SPDX-License-Identifier: BSD-3-Clause
395
- */const Eu=()=>new wu;let wu=class{};const Rs=new WeakMap,Pu=bu(class extends _u{render(n){return ue}update(n,[e]){var i;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(i=n.options)==null?void 0:i.host,this.rt(this.ct=n.element)),ue}rt(n){if(this.isConnected||(n=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=Rs.get(e);t===void 0&&(t=new WeakMap,Rs.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,n),n!==void 0&&this.G.call(this.ht,n)}else this.G.value=n}get lt(){var n,e;return typeof this.G=="function"?(n=Rs.get(this.ht??globalThis))==null?void 0:n.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var Ru=Object.defineProperty,xu=Object.getOwnPropertyDescriptor,Ra=(n,e,t,i)=>{for(var s=i>1?void 0:i?xu(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Ru(e,t,s),s};class In extends L.LitElement{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=Eu(),this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const i=window.devicePixelRatio||1,s=e.clientWidth,r=e.clientHeight;e.width=s*i,e.height=r*i,t.scale(i,i),t.clearRect(0,0,s,r);const a=3,o=Math.max(1,(s-(this.barCount-1)*a)/this.barCount),c=r/2,d=this.volume.speaker==="USER"?this.volume.volume:this.volume.volume,l=this.volume.speaker==="USER"?this.volume.spectrum:this.volume.spectrum;if(d===0)return;let u=[];if(l&&l.length>0){const h=l.length,p=Math.ceil(h/10);let g=[];for(let v=0;v<10;v++){const y=v*p,E=Math.min((v+1)*p,h);let M=0;for(let U=y;U<E;U++)M+=l[U]||0;g.push({region:v,startIdx:y,endIdx:E,energy:M})}g.sort((v,y)=>y.energy-v.energy);const m=g.slice(0,3),T=Math.min(...m.map(v=>v.startIdx)),k=Math.max(...m.map(v=>v.endIdx));if(k>T)for(let v=0;v<this.barCount;v++){const y=T+v/(this.barCount-1)*(k-T),E=Math.min(h-1,Math.floor(y));u[v]=l[E]||0}else for(let v=0;v<this.barCount;v++){const y=v/(this.barCount-1)*(h/2),E=Math.min(h-1,Math.floor(y));u[v]=l[E]||0}const x=Math.max(...u,1),D=this.volume.speaker==="USER"?.7:.6;u=u.map((v,y)=>{const E=v/x,M=D+y/(this.barCount-1)*.3;return Math.min(1,E*M)})}else if(this.volume.speaker!=="USER")for(let h=0;h<this.barCount;h++){const p=Date.now()*.002,g=.3+.2*Math.sin(p+h*.7);u[h]=g}for(let h=0;h<this.barCount;h++){const p=u.length>0&&u[h]!==void 0?u[h]:d;this.volume.speaker==="USER"?t.fillStyle=`rgba(109, 40, 217, ${p*.5+.5})`:t.fillStyle=`rgba(255, 255, 255, ${p*.5+.5})`;const g=Math.max(2,p*.8*c),m=s-(this.barCount-h)*(o+a),T=o/2;t.beginPath(),t.moveTo(m+T,r/2-g),t.lineTo(m+o-T,r/2-g),t.quadraticCurveTo(m+o,r/2-g,m+o,r/2-g+T),t.lineTo(m+o,r/2),t.lineTo(m,r/2),t.lineTo(m,r/2-g+T),t.quadraticCurveTo(m,r/2-g,m+T,r/2-g),t.fill(),t.beginPath(),t.moveTo(m,r/2),t.lineTo(m+o,r/2),t.lineTo(m+o,r/2+g-T),t.quadraticCurveTo(m+o,r/2+g,m+o-T,r/2+g),t.lineTo(m+T,r/2+g),t.quadraticCurveTo(m,r/2+g,m,r/2+g-T),t.lineTo(m,r/2),t.fill()}}render(){return L.html` <canvas ${Pu(this.canvasRef)} width="52" height="52"></canvas> `}}In.styles=L.css`
395
+ */const Ru=()=>new xu;let xu=class{};const Is=new WeakMap,Iu=Su(class extends Pu{render(n){return ue}update(n,[e]){var i;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(i=n.options)==null?void 0:i.host,this.rt(this.ct=n.element)),ue}rt(n){if(this.isConnected||(n=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=Is.get(e);t===void 0&&(t=new WeakMap,Is.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,n),n!==void 0&&this.G.call(this.ht,n)}else this.G.value=n}get lt(){var n,e;return typeof this.G=="function"?(n=Is.get(this.ht??globalThis))==null?void 0:n.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var Au=Object.defineProperty,Ou=Object.getOwnPropertyDescriptor,Ia=(n,e,t,i)=>{for(var s=i>1?void 0:i?Ou(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Au(e,t,s),s};class An extends L.LitElement{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=Ru(),this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const i=window.devicePixelRatio||1,s=e.clientWidth,r=e.clientHeight;e.width=s*i,e.height=r*i,t.scale(i,i),t.clearRect(0,0,s,r);const a=3,o=Math.max(1,(s-(this.barCount-1)*a)/this.barCount),c=r/2,d=this.volume.speaker==="USER"?this.volume.volume:this.volume.volume,l=this.volume.speaker==="USER"?this.volume.spectrum:this.volume.spectrum;if(d===0)return;let u=[];if(l&&l.length>0){const h=l.length,p=Math.ceil(h/10);let g=[];for(let v=0;v<10;v++){const y=v*p,E=Math.min((v+1)*p,h);let M=0;for(let U=y;U<E;U++)M+=l[U]||0;g.push({region:v,startIdx:y,endIdx:E,energy:M})}g.sort((v,y)=>y.energy-v.energy);const m=g.slice(0,3),T=Math.min(...m.map(v=>v.startIdx)),k=Math.max(...m.map(v=>v.endIdx));if(k>T)for(let v=0;v<this.barCount;v++){const y=T+v/(this.barCount-1)*(k-T),E=Math.min(h-1,Math.floor(y));u[v]=l[E]||0}else for(let v=0;v<this.barCount;v++){const y=v/(this.barCount-1)*(h/2),E=Math.min(h-1,Math.floor(y));u[v]=l[E]||0}const x=Math.max(...u,1),D=this.volume.speaker==="USER"?.7:.6;u=u.map((v,y)=>{const E=v/x,M=D+y/(this.barCount-1)*.3;return Math.min(1,E*M)})}else if(this.volume.speaker!=="USER")for(let h=0;h<this.barCount;h++){const p=Date.now()*.002,g=.3+.2*Math.sin(p+h*.7);u[h]=g}for(let h=0;h<this.barCount;h++){const p=u.length>0&&u[h]!==void 0?u[h]:d;this.volume.speaker==="USER"?t.fillStyle=`rgba(109, 40, 217, ${p*.5+.5})`:t.fillStyle=`rgba(255, 255, 255, ${p*.5+.5})`;const g=Math.max(2,p*.8*c),m=s-(this.barCount-h)*(o+a),T=o/2;t.beginPath(),t.moveTo(m+T,r/2-g),t.lineTo(m+o-T,r/2-g),t.quadraticCurveTo(m+o,r/2-g,m+o,r/2-g+T),t.lineTo(m+o,r/2),t.lineTo(m,r/2),t.lineTo(m,r/2-g+T),t.quadraticCurveTo(m,r/2-g,m+T,r/2-g),t.fill(),t.beginPath(),t.moveTo(m,r/2),t.lineTo(m+o,r/2),t.lineTo(m+o,r/2+g-T),t.quadraticCurveTo(m+o,r/2+g,m+o-T,r/2+g),t.lineTo(m+T,r/2+g),t.quadraticCurveTo(m,r/2+g,m,r/2+g-T),t.lineTo(m,r/2),t.fill()}}render(){return L.html` <canvas ${Iu(this.canvasRef)} width="52" height="52"></canvas> `}}An.styles=L.css`
396
396
  :host {
397
397
  display: block;
398
398
  width: 40px;
@@ -404,7 +404,7 @@
404
404
  width: 100%;
405
405
  height: 100%;
406
406
  }
407
- `,Ra([Y({type:Object})],In.prototype,"volume",2),Ra([ft()],In.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",In);var Iu=Object.defineProperty,Au=Object.getOwnPropertyDescriptor,Ou=(n,e,t,i)=>{for(var s=i>1?void 0:i?Au(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Iu(e,t,s),s};class xs extends L.LitElement{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach(e=>window.clearTimeout(e)),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const i=t*(this.animationDuration*this.overlapFactor),s=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const r=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1},this.animationDuration);this.timeoutIds.push(r)},i);this.timeoutIds.push(s)}const e=window.setTimeout(()=>{this.animateSequence()},this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return L.html`
407
+ `,Ia([Y({type:Object})],An.prototype,"volume",2),Ia([pt()],An.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",An);var Du=Object.defineProperty,Mu=Object.getOwnPropertyDescriptor,Nu=(n,e,t,i)=>{for(var s=i>1?void 0:i?Mu(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Du(e,t,s),s};class As extends L.LitElement{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach(e=>window.clearTimeout(e)),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const i=t*(this.animationDuration*this.overlapFactor),s=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const r=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1},this.animationDuration);this.timeoutIds.push(r)},i);this.timeoutIds.push(s)}const e=window.setTimeout(()=>{this.animateSequence()},this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return L.html`
408
408
  <div class="dot-loader">
409
409
  ${this.activeDots.map(e=>L.html`
410
410
  <div
@@ -413,7 +413,7 @@
413
413
  ></div>
414
414
  `)}
415
415
  </div>
416
- `}}xs.styles=L.css`
416
+ `}}As.styles=L.css`
417
417
  :host {
418
418
  display: block;
419
419
  }
@@ -440,10 +440,10 @@
440
440
  transition: transform 0.2s ease-in-out;
441
441
  opacity: 1;
442
442
  }
443
- `,Ou([ft()],xs.prototype,"activeDots",2),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",xs);class xa extends L.LitElement{render(){return L.html`
443
+ `,Nu([pt()],As.prototype,"activeDots",2),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",As);class Aa extends L.LitElement{render(){return L.html`
444
444
  <obi-dot-loader loading style="margin-left: 2px"></obi-dot-loader>
445
445
  <span class="text">Searching the knowledge base</span>
446
- `}}xa.styles=L.css`
446
+ `}}Aa.styles=L.css`
447
447
  :host {
448
448
  display: flex;
449
449
  align-items: center;
@@ -458,7 +458,7 @@
458
458
  font-weight: 500;
459
459
  font-size: 14px;
460
460
  }
461
- `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",xa);var Du=Object.defineProperty,Mu=Object.getOwnPropertyDescriptor,He=(n,e,t,i)=>{for(var s=i>1?void 0:i?Mu(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Du(e,t,s),s};class Te extends L.LitElement{constructor(){super(),this.apiBaseUrl=ma,this.apiKey="",this.position="bottom-right",this.user=null,this.state=$.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.closeNavTimeoutRef=null,window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position),window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user))}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig||(window.obiWidgetConfig={apiKey:this.apiKey||""}),this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey),this.setAttribute("position",this.position)}disconnectedCallback(){super.disconnectedCallback(),this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}mn([e,t]).with(["pause",!0],()=>{var i;(i=this.activeSession)==null||i.pauseRecording()}).with(["pause",!1],()=>{var i;(i=this.activeSession)==null||i.resumeRecording()}).with(["activate",!1],()=>{var i;(i=this.activeSession)==null||i.disconnect()}).otherwise(()=>{})}async handleSessionStart(e){this.showCourseModal=!1,this.state=$.LOADING;try{const{ObiSession:t}=await Promise.resolve().then(()=>Cm),i=new t({token:e,apiBaseUrl:this.apiBaseUrl});i.on("stateChanged",s=>{this.state=s.newState}),i.on("volume",s=>{this.volume=s}),i.on("error",s=>{console.error("Session error:",s.error),this.state=$.ERROR,this.activeSession=null}),await i.connect(),this.activeSession=i}catch(t){console.error("Failed to connect to session:",t),this.state=$.ERROR}}render(){const e=mn(this.state).with($.LOADING,()=>L.html`<obi-dot-loader></obi-dot-loader>`).with($.RESEARCHING,()=>L.html`<obi-searching-loader></obi-searching-loader>`).with(Vd.union($.USER_SPEAKING,$.AGENT_SPEAKING),()=>L.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with($.PAUSED,()=>ga).otherwise(()=>ga);return L.html`
461
+ `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",Aa);var Lu=Object.defineProperty,Uu=Object.getOwnPropertyDescriptor,Ze=(n,e,t,i)=>{for(var s=i>1?void 0:i?Uu(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Lu(e,t,s),s};class Te extends L.LitElement{constructor(){super(),this.apiBaseUrl=va,this.apiKey="",this.position="bottom-right",this.user=null,this.state=$.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.closeNavTimeoutRef=null,window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position),window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user))}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig||(window.obiWidgetConfig={apiKey:this.apiKey||""}),this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey),this.setAttribute("position",this.position)}disconnectedCallback(){super.disconnectedCallback(),this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}gn([e,t]).with(["pause",!0],()=>{var i;(i=this.activeSession)==null||i.pauseRecording()}).with(["pause",!1],()=>{var i;(i=this.activeSession)==null||i.resumeRecording()}).with(["activate",!1],()=>{var i;(i=this.activeSession)==null||i.disconnect()}).otherwise(()=>{})}async handleSessionStart(e){this.showCourseModal=!1,this.state=$.LOADING;try{const{ObiSession:t}=await Promise.resolve().then(()=>Em),i=new t({token:e,apiBaseUrl:this.apiBaseUrl});i.on("stateChanged",s=>{this.state=s.newState}),i.on("volume",s=>{this.volume=s}),i.on("error",s=>{console.error("Session error:",s.error),this.state=$.ERROR,this.activeSession=null}),await i.connect(),this.activeSession=i}catch(t){console.error("Failed to connect to session:",t),this.state=$.ERROR}}render(){const e=gn(this.state).with($.LOADING,()=>L.html`<obi-dot-loader></obi-dot-loader>`).with($.RESEARCHING,()=>L.html`<obi-searching-loader></obi-searching-loader>`).with(Kd.union($.USER_SPEAKING,$.AGENT_SPEAKING),()=>L.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with($.PAUSED,()=>ya).otherwise(()=>ya);return L.html`
462
462
  <div
463
463
  class="widget-container ${this.state===$.USER_SPEAKING||this.state===$.AGENT_SPEAKING?"pulse":""} ${this.state!==$.READY||this.navVisible?"rounded":""} ${this.state===$.RESEARCHING?"researching":""} ${this.state===$.USER_SPEAKING?"user-speaking":""}"
464
464
  @mouseenter=${this.handleMouseEnter}
@@ -580,8 +580,8 @@
580
580
  .pulse {
581
581
  animation: pulse-shadow 2s ease-in-out infinite;
582
582
  }
583
- `,He([Y({type:String})],Te.prototype,"apiBaseUrl",2),He([Y({type:String})],Te.prototype,"apiKey",2),He([Y({type:String})],Te.prototype,"position",2),He([Y({type:Object})],Te.prototype,"user",2),He([ft()],Te.prototype,"state",2),He([ft()],Te.prototype,"showCourseModal",2),He([ft()],Te.prototype,"isHovering",2),He([ft()],Te.prototype,"navVisible",2),He([ft()],Te.prototype,"activeSession",2),He([ft()],Te.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",Te);function Ia(n){return{all:n=n||new Map,on:function(e,t){var i=n.get(e);i?i.push(t):n.set(e,[t])},off:function(e,t){var i=n.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var i=n.get(e);i&&i.slice().map(function(s){s(t)}),(i=n.get("*"))&&i.slice().map(function(s){s(e,t)})}}}class Nu{constructor(e={}){this.state=$.READY,this.emitter=Ia(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=Zl.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState($.READY),this.emitter.emit(st.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(st.STATE_CHANGE,e)}handleError(e){this.setState($.ERROR),this.emitter.emit(st.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(!this.voiceEnabled){this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"});return}try{this.setState($.AGENT_SPEAKING),this.emitter.emit(st.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}}async stopVoiceRecording(){if(this.state===$.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState($.READY),this.emitter.emit(st.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(!this.screenCaptureEnabled){this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"});return}try{this.setState($.AGENT_SPEAKING),this.emitter.emit(st.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}}async stopScreenCapture(){if(this.state===$.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState($.READY),this.emitter.emit(st.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}}const Lu=()=>{customElements.get("obi-widget")||customElements.define("obi-widget",Te)};class Uu{static init(e){Lu();const t=document.createElement("obi-widget");return e.apiKey&&(t.apiKey=e.apiKey),e.position&&(t.position=e.position),e.user&&(t.user=e.user),window.obiWidgetConfig=e,document.body.appendChild(t),console.log("Obi Widget initialized and mounted"),t}}const ju="https://registry.npmjs.org/obi-sdk/latest",Aa="https://unpkg.com/obi-sdk",Fu=()=>new Promise(n=>{try{const e=new XMLHttpRequest;e.open("GET",ju),e.onload=()=>{if(e.status===200)try{const t=JSON.parse(e.responseText);n(t.version)}catch{n(null)}else n(null)},e.onerror=()=>n(null),e.send()}catch{n(null)}}),$u=n=>new Promise((e,t)=>{var r;if(window.ObiAssistant){e({ObiAssistant:window.ObiAssistant,ObiSDK:window.ObiSDK,createSession:(r=window.ObiSDK)==null?void 0:r.createSession});return}const i=document.createElement("script"),s=n||"latest";i.src=`${Aa}@${s}/dist/obi-sdk.standalone.iife.js`,i.type="text/javascript",i.async=!0,i.onload=()=>{var a;e({ObiAssistant:window.ObiAssistant,ObiSDK:window.ObiSDK,createSession:(a=window.ObiSDK)==null?void 0:a.createSession})},i.onerror=()=>{s!=="latest"?(console.warn("Failed to load specific version, falling back to latest"),i.src=`${Aa}@latest/dist/obi-sdk.standalone.iife.js`,i.onload=()=>{var a;e({ObiAssistant:window.ObiAssistant,ObiSDK:window.ObiSDK,createSession:(a=window.ObiSDK)==null?void 0:a.createSession})}):t(new Error("Failed to load Obi SDK from CDN"))},document.head.appendChild(i)}),Bu=async()=>{const n=await Fu();return $u(n)},Vu=async n=>{const{ObiAssistant:e}=await Bu();if(!e)throw new Error("Obi SDK loaded but ObiAssistant not found");return e.init(n)};function qu(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 zu=Object.defineProperty,Ku=(n,e,t)=>e in n?zu(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Oa=(n,e,t)=>Ku(n,typeof e!="symbol"?e+"":e,t);class Se{constructor(){Oa(this,"_locking"),Oa(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 ae(n,e){if(!n)throw new Error(e)}const Gu=34028234663852886e22,Wu=-34028234663852886e22,Hu=4294967295,Zu=2147483647,Ju=-2147483648;function An(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>Zu||n<Ju)throw new Error("invalid int 32: "+n)}function Is(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Hu||n<0)throw new Error("invalid uint 32: "+n)}function Da(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Gu||n<Wu))throw new Error("invalid float 32: "+n)}const Ma=Symbol("@bufbuild/protobuf/enum-type");function Yu(n){const e=n[Ma];return ae(e,"missing enum type on enum object"),e}function Na(n,e,t,i){n[Ma]=La(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function La(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=Ua(a);r.push(o),i[a.name]=o,s[a.no]=o}return{typeName:n,values:r,findName(a){return i[a]},findNumber(a){return s[a]}}}function Qu(n,e,t){const i={};for(const s of e){const r=Ua(s);i[r.localName]=r.no,i[r.no]=r.localName}return Na(i,n,e),i}function Ua(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class As{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 Xu(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),a={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new As),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}function eh(){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))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))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))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Os(n,e,t){for(let r=0;r<28;r=r+7){const a=n>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,s=!!(e>>3);if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const On=4294967296;function ja(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(a,o){const c=Number(n.slice(a,o));s*=t,i=i*t+c,i>=On&&(s=s+(i/On|0),i=i%On)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?$a(i,s):Ds(i,s)}function th(n,e){let t=Ds(n,e);const i=t.hi&2147483648;i&&(t=$a(t.lo,t.hi));const s=Fa(t.lo,t.hi);return i?"-"+s:s}function Fa(n,e){if({lo:n,hi:e}=ih(n,e),e<=2097151)return String(On*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,a=i+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Ba(a)+Ba(r)}function ih(n,e){return{lo:n>>>0,hi:e>>>0}}function Ds(n,e){return{lo:n|0,hi:e|0}}function $a(n,e){return e=~e,n?n=~n+1:e+=1,Ds(n,e)}const Ba=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Va(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 nh(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function sh(){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"),a=BigInt("0"),o=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>o||d<a)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=>ae(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>ae(/^[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),ja(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),ja(s)},dec(s,r){return th(s,r)},uDec(s,r){return Fa(s,r)}}}const se=sh();var S;(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"})(S||(S={}));var _t;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(_t||(_t={}));function Et(n,e,t){if(e===t)return!0;if(n==S.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 S.UINT64:case S.FIXED64:case S.INT64:case S.SFIXED64:case S.SINT64:return e==t}return!1}function di(n,e){switch(n){case S.BOOL:return!1;case S.UINT64:case S.FIXED64:case S.INT64:case S.SFIXED64:case S.SINT64:return e==0?se.zero:"0";case S.DOUBLE:case S.FLOAT:return 0;case S.BYTES:return new Uint8Array(0);case S.STRING:return"";default:return 0}}function qa(n,e){switch(n){case S.BOOL:return e===!1;case S.STRING:return e==="";case S.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var le;(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"})(le||(le={}));class rh{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(Is(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return An(e),Va(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){Da(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){Is(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){An(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return An(e),e=(e<<1^e>>31)>>>0,Va(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=se.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=se.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=se.enc(e);return Os(t.lo,t.hi,this.buf),this}sint64(e){let t=se.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return Os(s,r,this.buf),this}uint64(e){let t=se.uEnc(e);return Os(t.lo,t.hi,this.buf),this}}class ah{constructor(e,t){this.varint64=eh,this.uint32=nh,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 le.Varint:for(;this.buf[this.pos++]&128;);break;case le.Bit64:this.pos+=4;case le.Bit32:this.pos+=4;break;case le.LengthDelimited:let s=this.uint32();this.pos+=s;break;case le.StartGroup:for(;;){const[r,a]=this.tag();if(a===le.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(a,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 se.dec(...this.varint64())}uint64(){return se.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,se.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 se.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return se.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 oh(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 za(n){const e=n.field.localName,t=Object.create(null);return t[e]=ch(n),[t,()=>t[e]]}function ch(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 di(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 dh(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 ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Dn=[];for(let n=0;n<ot.length;n++)Dn[ot[n].charCodeAt(0)]=n;Dn["-".charCodeAt(0)]=ot.indexOf("+"),Dn["_".charCodeAt(0)]=ot.indexOf("/");const Ka={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,a=0;for(let o=0;o<n.length;o++){if(r=Dn[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":s=0;case`
584
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[i++]=(a&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+=ot[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=ot[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=ot[s|i>>6],e+=ot[i&63],t=0;break}return t&&(e+=ot[s],e+="=",t==1&&(e+="=")),e}};function lh(n,e,t){Wa(e,n);const i=e.runtime.bin.makeReadOptions(t),s=dh(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,a]=za(e);for(const o of s)e.runtime.bin.readField(r,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function uh(n,e,t,i){Wa(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(Ga(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 a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const c=s.readerFactory(a.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 Ga(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 Wa(n,e){ae(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Ha(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:!qa(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Za(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?di(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function Kt(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(As.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 Ja(n,e){return Kt(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}S.DOUBLE,S.FLOAT,S.INT64,S.UINT64,S.INT32,S.UINT32,S.BOOL,S.STRING,S.BYTES;const Ya={ignoreUnknownFields:!1},Qa={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function hh(n){return n?Object.assign(Object.assign({},Ya),n):Ya}function fh(n){return n?Object.assign(Object.assign({},Qa),n):Qa}const Mn=Symbol(),Nn=Symbol();function ph(){return{makeReadOptions:hh,makeWriteOptions:fh,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(Ze(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=n.fields.findJsonName(a);if(c){if(c.oneof){if(o===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(a,'"'));s.set(c.oneof,a)}Xa(i,o,c,t,n)}else{let d=!1;if(r!=null&&r.findExtension&&a.startsWith("[")&&a.endsWith("]")){const l=r.findExtension(a.substring(1,a.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=za(l);Xa(u,o,l.field,t,l),uh(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!Ha(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!gh(s))continue}const a=s.oneof?n[s.oneof.localName].value:n[s.localName],o=eo(s,a,e);o!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&Ga(n,o)){const c=lh(n,o,e),d=eo(o.field,c,e);d!==void 0&&(i[o.field.jsonName]=d)}}}catch(r){const a=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=r instanceof Error?r.message:String(r);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return Yi(n,e,t??_t.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||qa(n,e)))return Ln(n,e)},debug:Ze}}function Ze(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 Xa(n,e,t,i,s){let r=t.localName;if(t.repeated){if(ae(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(Ze(e)));const a=n[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ze(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,i));break;case"enum":const c=Ms(t.T,o,i.ignoreUnknownFields,!0);c!==Nn&&a.push(c);break;case"scalar":try{a.push(Yi(t.T,o,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ze(o));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(Ze(e)));const a=n[r];for(const[o,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=mh(t.K,o)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ze(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":a[d]=t.V.T.fromJson(c,i);break;case"enum":const l=Ms(t.V.T,c,i.ignoreUnknownFields,!0);l!==Nn&&(a[d]=l);break;case"scalar":try{a[d]=Yi(t.V.T,c,_t.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ze(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 a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=n[r];Kt(o)?o.fromJson(e,i):(n[r]=o=a.fromJson(e,i),a.fieldWrapper&&!t.oneof&&(n[r]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Ms(t.T,e,i.ignoreUnknownFields,!1);switch(c){case Mn:Za(t,n);break;case Nn:break;default:n[r]=c;break}break;case"scalar":try{const d=Yi(t.T,e,t.L,!1);switch(d){case Mn:Za(t,n);break;default:n[r]=d;break}}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ze(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function mh(n,e){if(n===S.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Yi(n,e,_t.BIGINT,!0).toString()}function Yi(n,e,t,i){if(e===null)return i?di(n,t):Mn;switch(n){case S.DOUBLE:case S.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==S.FLOAT&&Da(s),s;case S.INT32:case S.FIXED32:case S.SFIXED32:case S.SINT32:case S.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==S.UINT32||n==S.FIXED32?Is(r):An(r),r;case S.INT64:case S.SFIXED64:case S.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=se.parse(e);return t?a.toString():a;case S.FIXED64:case S.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=se.uParse(e);return t?o.toString():o;case S.BOOL:if(typeof e!="boolean")break;return e;case S.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case S.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Ka.dec(e)}throw new Error}function Ms(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Mn;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 Nn;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Ze(e)))}function gh(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function eo(n,e,t){if(n.kind=="map"){ae(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[a,o]of s)i[a.toString()]=Ln(n.V.T,o);break;case"message":for(const[a,o]of s)i[a.toString()]=o.toJson(t);break;case"enum":const r=n.V.T;for(const[a,o]of s)i[a.toString()]=Ns(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){ae(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(Ln(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(Ns(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 Ln(n.T,e);case"enum":return Ns(n.T,e,t.enumAsInteger);case"message":return Ja(n.T,e).toJson(t)}}function Ns(n,e,t){var i;if(ae(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 Ln(n,e){switch(n){case S.INT32:case S.SFIXED32:case S.SINT32:case S.FIXED32:case S.UINT32:return ae(typeof e=="number"),e;case S.FLOAT:case S.DOUBLE:return ae(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case S.STRING:return ae(typeof e=="string"),e;case S.BOOL:return ae(typeof e=="boolean"),e;case S.UINT64:case S.FIXED64:case S.INT64:case S.SFIXED64:case S.SINT64:return ae(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case S.BYTES:return ae(e instanceof Uint8Array),Ka.enc(e)}}const li=Symbol("@bufbuild/protobuf/unknown-fields"),to={readUnknownFields:!0,readerFactory:n=>new ah(n)},io={writeUnknownFields:!0,writerFactory:()=>new rh};function vh(n){return n?Object.assign(Object.assign({},to),n):to}function yh(n){return n?Object.assign(Object.assign({},io),n):io}function bh(){return{makeReadOptions:vh,makeWriteOptions:yh,listUnknownFields(n){var e;return(e=n[li])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[li]},writeUnknownFields(n,e){const i=n[li];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[li])||(s[li]=[]),s[li].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),a=s?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(s===!0&&c==le.EndGroup));){const d=r.fields.find(o);if(!d){const l=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(n,o,c,l);continue}no(n,e,d,c,i)}if(s&&(c!=le.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:no,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!Ha(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];so(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&so(n,e,t,i)}}}function no(n,e,t,i,s){let{repeated:r,localName:a}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?S.INT32:t.T;let c=jn;if(t.kind=="scalar"&&t.L>0&&(c=Th),r){let h=n[a];if(i==le.LengthDelimited&&o!=S.STRING&&o!=S.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,o))}else h.push(c(e,o))}else n[a]=c(e,o);break;case"message":const d=t.T;r?n[a].push(Un(e,new d,s,t)):Kt(n[a])?Un(e,n[a],s,t):(n[a]=Un(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=d.fieldWrapper.unwrapField(n[a])));break;case"map":let[l,u]=kh(t,e,s);n[a][l]=u;break}}function Un(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 kh(n,e,t){const i=e.uint32(),s=e.pos+i;let r,a;for(;e.pos<s;){const[o]=e.tag();switch(o){case 1:r=jn(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=jn(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=Un(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=di(n.K,_t.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(n.V.kind){case"scalar":a=di(n.V.T,_t.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[r,a]}function Th(n,e){const t=jn(n,e);return typeof t=="bigint"?t.toString():t}function jn(n,e){switch(e){case S.STRING:return n.string();case S.BOOL:return n.bool();case S.DOUBLE:return n.double();case S.FLOAT:return n.float();case S.INT32:return n.int32();case S.INT64:return n.int64();case S.UINT64:return n.uint64();case S.FIXED64:return n.fixed64();case S.BYTES:return n.bytes();case S.FIXED32:return n.fixed32();case S.SFIXED32:return n.sfixed32();case S.SFIXED64:return n.sfixed64();case S.SINT64:return n.sint64();case S.UINT32:return n.uint32();case S.SINT32:return n.sint32()}}function so(n,e,t,i){ae(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?S.INT32:n.T;if(s)if(ae(Array.isArray(e)),n.packed)Ch(t,r,n.no,e);else for(const a of e)Qi(t,r,n.no,a);else Qi(t,r,n.no,e);break;case"message":if(s){ae(Array.isArray(e));for(const a of e)ro(t,i,n,a)}else ro(t,i,n,e);break;case"map":ae(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))Sh(t,i,n,a,o);break}}function Sh(n,e,t,i,s){n.tag(t.no,le.LengthDelimited),n.fork();let r=i;switch(t.K){case S.INT32:case S.FIXED32:case S.UINT32:case S.SFIXED32:case S.SINT32:r=Number.parseInt(i);break;case S.BOOL:ae(i=="true"||i=="false"),r=i=="true";break}switch(Qi(n,t.K,1,r),t.V.kind){case"scalar":Qi(n,t.V.T,2,s);break;case"enum":Qi(n,S.INT32,2,s);break;case"message":ae(s!==void 0),n.tag(2,le.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function ro(n,e,t,i){const s=Ja(t.T,i);t.delimited?n.tag(t.no,le.StartGroup).raw(s.toBinary(e)).tag(t.no,le.EndGroup):n.tag(t.no,le.LengthDelimited).bytes(s.toBinary(e))}function Qi(n,e,t,i){ae(i!==void 0);let[s,r]=ao(e);n.tag(t,s)[r](i)}function Ch(n,e,t,i){if(!i.length)return;n.tag(t,le.LengthDelimited).fork();let[,s]=ao(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function ao(n){let e=le.Varint;switch(n){case S.BYTES:case S.STRING:e=le.LengthDelimited;break;case S.DOUBLE:case S.FIXED64:case S.SFIXED64:e=le.Bit64;break;case S.FIXED32:case S.SFIXED32:case S.FLOAT:e=le.Bit32;break}const t=S[n].toLowerCase();return[e,t]}function _h(){return{setEnumType:Na,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,a=n;if(a[s]!=null)switch(i.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=i.findField(o);let d=a[s].value;c&&c.kind=="message"&&!Kt(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===S.BYTES&&(d=Xi(d)),r[s]={case:o,value:d};break;case"scalar":case"enum":let l=a[s];i.T===S.BYTES&&(l=i.repeated?l.map(Xi):Xi(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===S.BYTES)for(const[p,g]of Object.entries(a[s]))r[s][p]=Xi(g);else Object.assign(r[s],a[s]);break;case"message":const h=i.V.T;for(const p of Object.keys(a[s])){let g=a[s][p];h.fieldWrapper||(g=new h(g)),r[s][p]=g}break}break;case"message":const u=i.T;if(i.repeated)r[s]=a[s].map(h=>Kt(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Xi(h):r[s]=h:r[s]=Kt(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((a,o)=>i.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>Et(i.T,a,r[o]));case"enum":return s.every((a,o)=>Et(S.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":return i.T.equals(s,r);case"enum":return Et(S.INT32,s,r);case"scalar":return Et(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const a=i.findField(s.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(s.value,r.value);case"enum":return Et(S.INT32,s.value,r.value);case"scalar":return Et(a.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const c=i.V.T;return o.every(l=>c.equals(s[l],r[l]));case"enum":return o.every(l=>Et(S.INT32,s[l],r[l]));case"scalar":const d=i.V.T;return o.every(l=>Et(d,s[l],r[l]))}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 a;if(s.repeated)a=r.map(Fn);else if(s.kind=="map"){a=i[s.localName];for(const[o,c]of Object.entries(r))a[o]=Fn(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:Fn(r.value)}:{case:void 0}:a=Fn(r);i[s.localName]=a}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function Fn(n){if(n===void 0)return n;if(Kt(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Xi(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Eh(n,e,t){return{syntax:n,json:ph(),bin:bh(),util:Object.assign(Object.assign({},_h()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return Xu(this,i,s,r)},makeEnum:Qu,makeEnumType:La,getEnumType:Yu,makeExtension(i,s,r){return oh(this,i,s,r)}}}class wh{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 oo(n,e){const t=co(n);return e?t:Oh(Ah(t))}function Ph(n){return oo(n,!1)}const Rh=co;function co(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 xh=new Set(["constructor","toString","toJSON","valueOf"]),Ih=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),lo=n=>"".concat(n,"$"),Ah=n=>Ih.has(n)?lo(n):n,Oh=n=>xh.has(n)?lo(n):n;class Dh{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=Ph(e)}addField(e){ae(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 Mh(n,e){var t,i,s,r,a,o;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=oo(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Rh(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:_t.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=S.BYTES&&l.T!=S.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new Dh(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const b=Eh("proto3",n=>new wh(n,e=>Mh(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]=di(e.T,e.L);break}}});class Ce extends As{constructor(e){super(),this.seconds=se.zero,this.nanos=0,b.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(b.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=se.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 Ce.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ce({seconds:se.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Ce().fromBinary(e,t)}static fromJson(e,t){return new Ce().fromJson(e,t)}static fromJsonString(e,t){return new Ce().fromJsonString(e,t)}static equals(e,t){return b.util.equals(Ce,e,t)}}Ce.runtime=b,Ce.typeName="google.protobuf.Timestamp",Ce.fields=b.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Nh=b.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ce},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Lh,repeated:!0},{no:5,name:"events",kind:"message",T:jh,repeated:!0}]),Lh=b.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:Uh,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Uh=b.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ce},{no:3,name:"value",kind:"scalar",T:2}]),jh=b.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:Ce},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ce,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),uo=b.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ne=b.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),he=b.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"}]),ui=b.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),en=b.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),tn=b.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Le=b.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"}]),hi=b.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"}]),Fh=b.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Je=b.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"}]),Ls=b.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:$n,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:_o}]),$n=b.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),$h=b.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:b.getEnumType(he),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}]),nn=b.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:b.getEnumType(Us)},{no:4,name:"tracks",kind:"message",T:fi,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:$h},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:b.getEnumType(Bn)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:b.getEnumType(Le)},{no:18,name:"kind_details",kind:"enum",T:b.getEnumType(Bh),repeated:!0}]),Us=b.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Bn=b.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Bh=b.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),xe=b.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Vh=b.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:Gt,repeated:!0}]),fi=b.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:b.getEnumType(Ne)},{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:b.getEnumType(he)},{no:10,name:"layers",kind:"message",T:Gt,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:Vh,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:b.getEnumType(xe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:_o},{no:19,name:"audio_features",kind:"enum",T:b.getEnumType(Je),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(uo)}]),Gt=b.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(ui)},{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}]),_e=b.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:b.getEnumType(J)},{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:fo,oneof:"value"},{no:3,name:"speaker",kind:"message",T:qh,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:po,oneof:"value"},{no:7,name:"transcription",kind:"message",T:zh,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Nh,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:js,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:mo,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:go,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:vo,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:$s,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Bs,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Vs,oneof:"value"}]),J=b.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),qh=b.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:ho,repeated:!0}]),ho=b.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}]),fo=b.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}]),po=b.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),zh=b.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:Kh,repeated:!0}]),Kh=b.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),js=b.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}]),mo=b.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}]),go=b.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),vo=b.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:yo,oneof:"value"}]),yo=b.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}]),bo=b.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Gh=b.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:b.getEnumType(ko)},{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}]),ko=b.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Wh=b.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:b.getEnumType(To)},{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}]),To=b.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"}]),So=b.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Co},{no:2,name:"screen",kind:"message",T:Co},{no:3,name:"resume_connection",kind:"enum",T:b.getEnumType(tn)},{no:4,name:"disabled_codecs",kind:"message",T:Hh},{no:5,name:"force_relay",kind:"enum",T:b.getEnumType(tn)}]),Co=b.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:b.getEnumType(tn)}]),Hh=b.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:$n,repeated:!0},{no:2,name:"publish",kind:"message",T:$n,repeated:!0}]),_o=b.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Fs=b.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Eo=b.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:b.getEnumType(Fs)},{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"}),wo=b.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),$s=b.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:b.getEnumType(xe)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Eo,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:wo,oneof:"content_header"}],{localName:"DataStream_Header"}),Bs=b.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"}),Vs=b.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"}),Ue=b.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),qs=b.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Zh=b.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Jh=b.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Wt,oneof:"message"},{no:2,name:"answer",kind:"message",T:Wt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Gs,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ks,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ws,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Vn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ro,oneof:"message"},{no:8,name:"leave",kind:"message",T:qn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Io,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Mo,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:No,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ye,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ao,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Uo,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:xo,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:tf,oneof:"message"}]),Po=b.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Yh,oneof:"message"},{no:2,name:"answer",kind:"message",T:Wt,oneof:"message"},{no:3,name:"offer",kind:"message",T:Wt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Gs,oneof:"message"},{no:5,name:"update",kind:"message",T:ef,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Hs,oneof:"message"},{no:8,name:"leave",kind:"message",T:qn,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ws,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:nf,oneof:"message"},{no:11,name:"room_update",kind:"message",T:sf,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:af,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:cf,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:lf,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:uf,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Xh,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Qh,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:hf,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:mf,oneof:"message"},{no:22,name:"request_response",kind:"message",T:gf,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:vf,oneof:"message"}]),zs=b.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),Ks=b.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:b.getEnumType(Ne)},{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:b.getEnumType(he)},{no:9,name:"layers",kind:"message",T:Gt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:zs,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:b.getEnumType(xe)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(uo)}]),Gs=b.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:b.getEnumType(Ue)},{no:3,name:"final",kind:"scalar",T:8}]),Ws=b.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Yh=b.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Ls},{no:2,name:"participant",kind:"message",T:nn},{no:3,name:"other_participants",kind:"message",T:nn,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Oo,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:So},{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:Gh},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:$n,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Qh=b.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Oo,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:So}]),Hs=b.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:fi}]),Xh=b.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Wt=b.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]),ef=b.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:nn,repeated:!0}]),Vn=b.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:bo,repeated:!0}]),Ro=b.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:b.getEnumType(ui)},{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}]),xo=b.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:b.getEnumType(Je),repeated:!0}]),tf=b.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}]),qn=b.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:b.getEnumType(Le)},{no:3,name:"action",kind:"enum",T:b.getEnumType(pi)},{no:4,name:"regions",kind:"message",T:ff}]),pi=b.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Io=b.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Gt,repeated:!0}]),Ao=b.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}]),Oo=b.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}]),nf=b.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:ho,repeated:!0}]),sf=b.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Ls}]),rf=b.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:b.getEnumType(en)},{no:3,name:"score",kind:"scalar",T:2}]),af=b.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:rf,repeated:!0}]),of=b.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:b.getEnumType(qs)}]),cf=b.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:of,repeated:!0}]),Zs=b.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(ui)},{no:2,name:"enabled",kind:"scalar",T:8}]),df=b.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Zs,repeated:!0}]),lf=b.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Zs,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:df,repeated:!0}]),Do=b.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}]),Mo=b.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Do,repeated:!0}]),uf=b.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}]),No=b.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Wt},{no:2,name:"subscription",kind:"message",T:Vn},{no:3,name:"publish_tracks",kind:"message",T:Hs,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Lo,repeated:!0},{no:5,name:"offer",kind:"message",T:Wt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]),Lo=b.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:b.getEnumType(Ue)}]),Ye=b.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:b.getEnumType(Zh),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"}]),Uo=b.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),hf=b.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),ff=b.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:pf,repeated:!0}]),pf=b.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}]),mf=b.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:b.getEnumType(Fh)}]),gf=b.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:b.getEnumType(Js)},{no:3,name:"message",kind:"scalar",T:9}]),Js=b.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),vf=b.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function yf(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var zn={exports:{}},bf=zn.exports,jo;function kf(){return jo||(jo=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(bf,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={},a=null;function o(m,T){var k=m[T];if(typeof k.bind=="function")return k.bind(m);try{return Function.prototype.bind.call(k,m)}catch{return function(){return Function.prototype.apply.apply(k,[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?o(console,m):console.log!==void 0?o(console,"log"):e}function l(){for(var m=this.getLevel(),T=0;T<s.length;T++){var k=s[T];this[k]=T<m?e:this.methodFactory(k,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,T,k){return d(m)||u.apply(this,arguments)}function p(m,T){var k=this,x,D,v,y="loglevel";typeof m=="string"?y+=":"+m:typeof m=="symbol"&&(y=void 0);function E(z){var de=(s[z]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=de;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+de+";"}catch{}}}function M(){var z;if(!(typeof window===t||!y)){try{z=window.localStorage[y]}catch{}if(typeof z===t)try{var de=window.document.cookie,Qt=encodeURIComponent(y),us=de.indexOf(Qt+"=");us!==-1&&(z=/^([^;]+)/.exec(de.slice(us+Qt.length+1))[1])}catch{}return k.levels[z]===void 0&&(z=void 0),z}}function U(){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 G(z){var de=z;if(typeof de=="string"&&k.levels[de.toUpperCase()]!==void 0&&(de=k.levels[de.toUpperCase()]),typeof de=="number"&&de>=0&&de<=k.levels.SILENT)return de;throw new TypeError("log.setLevel() called with invalid level: "+z)}k.name=m,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=T||h,k.getLevel=function(){return v??D??x},k.setLevel=function(z,de){return v=G(z),de!==!1&&E(v),l.call(k)},k.setDefaultLevel=function(z){D=G(z),M()||k.setLevel(z,!1)},k.resetLevel=function(){v=null,U(),l.call(k)},k.enableAll=function(z){k.setLevel(k.levels.TRACE,z)},k.disableAll=function(z){k.setLevel(k.levels.SILENT,z)},k.rebuild=function(){if(a!==k&&(x=G(a.getLevel())),l.call(k),a===k)for(var z in r)r[z].rebuild()},x=G(a?a.getLevel():"WARN");var q=M();q!=null&&(v=G(q)),l.call(k)}a=new p,a.getLogger=function(T){if(typeof T!="symbol"&&typeof T!="string"||T==="")throw new TypeError("You must supply a name when creating a logger.");var k=r[T];return k||(k=r[T]=new p(T,a.methodFactory)),k};var g=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=g),a},a.getLoggers=function(){return r},a.default=a,a})}(zn)),zn.exports}var Kn=kf(),Ys;(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"})(Ys||(Ys={}));var je;(function(n){n.Default="livekit",n.Room="livekit-room",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"})(je||(je={}));let K=Kn.getLogger("livekit");Object.values(je).map(n=>Kn.getLogger(n)),K.setDefaultLevel(Ys.info);function ct(n){const e=Kn.getLogger(n);return e.setDefaultLevel(K.getLevel()),e}const Tf=Kn.getLogger("lk-e2ee"),sn=7e3,Sf=[0,300,2*2*300,3*3*300,4*4*300,sn,sn,sn,sn,sn];class Cf{constructor(e){this._retryDelays=e!==void 0?[...e]:Sf}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 _f(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 f(n,e,t,i){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(l){try{d(i.next(l))}catch(u){a(u)}}function c(l){try{d(i.throw(l))}catch(u){a(u)}}function d(l){l.done?r(l.value):s(l.value).then(o,c)}d((i=i.apply(n,e||[])).next())})}function Fo(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 wt(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 Fo=="function"?Fo(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(a){return new Promise(function(o,c){a=n[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(d){r({value:d,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var Gn={exports:{}},$o;function Ef(){if($o)return Gn.exports;$o=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(y,E,M){return Function.prototype.apply.call(y,E,M)},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(v){console&&console.warn&&console.warn(v)}var s=Number.isNaN||function(y){return y!==y};function r(){r.init.call(this)}Gn.exports=r,Gn.exports.once=k,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(v){if(typeof v!="number"||v<0||s(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");a=v}}),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(v){return v._maxListeners===void 0?r.defaultMaxListeners:v._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(y){for(var E=[],M=1;M<arguments.length;M++)E.push(arguments[M]);var U=y==="error",G=this._events;if(G!==void 0)U=U&&G.error===void 0;else if(!U)return!1;if(U){var q;if(E.length>0&&(q=E[0]),q instanceof Error)throw q;var z=new Error("Unhandled error."+(q?" ("+q.message+")":""));throw z.context=q,z}var de=G[y];if(de===void 0)return!1;if(typeof de=="function")e(de,this,E);else for(var Qt=de.length,us=g(de,Qt),M=0;M<Qt;++M)e(us[M],this,E);return!0};function d(v,y,E,M){var U,G,q;if(o(E),G=v._events,G===void 0?(G=v._events=Object.create(null),v._eventsCount=0):(G.newListener!==void 0&&(v.emit("newListener",y,E.listener?E.listener:E),G=v._events),q=G[y]),q===void 0)q=G[y]=E,++v._eventsCount;else if(typeof q=="function"?q=G[y]=M?[E,q]:[q,E]:M?q.unshift(E):q.push(E),U=c(v),U>0&&q.length>U&&!q.warned){q.warned=!0;var z=new Error("Possible EventEmitter memory leak detected. "+q.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");z.name="MaxListenersExceededWarning",z.emitter=v,z.type=y,z.count=q.length,i(z)}return v}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(v,y,E){var M={fired:!1,wrapFn:void 0,target:v,type:y,listener:E},U=l.bind(M);return U.listener=E,M.wrapFn=U,U}r.prototype.once=function(y,E){return o(E),this.on(y,u(this,y,E)),this},r.prototype.prependOnceListener=function(y,E){return o(E),this.prependListener(y,u(this,y,E)),this},r.prototype.removeListener=function(y,E){var M,U,G,q,z;if(o(E),U=this._events,U===void 0)return this;if(M=U[y],M===void 0)return this;if(M===E||M.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete U[y],U.removeListener&&this.emit("removeListener",y,M.listener||E));else if(typeof M!="function"){for(G=-1,q=M.length-1;q>=0;q--)if(M[q]===E||M[q].listener===E){z=M[q].listener,G=q;break}if(G<0)return this;G===0?M.shift():m(M,G),M.length===1&&(U[y]=M[0]),U.removeListener!==void 0&&this.emit("removeListener",y,z||E)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(y){var E,M,U;if(M=this._events,M===void 0)return this;if(M.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):M[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete M[y]),this;if(arguments.length===0){var G=Object.keys(M),q;for(U=0;U<G.length;++U)q=G[U],q!=="removeListener"&&this.removeAllListeners(q);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=M[y],typeof E=="function")this.removeListener(y,E);else if(E!==void 0)for(U=E.length-1;U>=0;U--)this.removeListener(y,E[U]);return this};function h(v,y,E){var M=v._events;if(M===void 0)return[];var U=M[y];return U===void 0?[]:typeof U=="function"?E?[U.listener||U]:[U]:E?T(U):g(U,U.length)}r.prototype.listeners=function(y){return h(this,y,!0)},r.prototype.rawListeners=function(y){return h(this,y,!1)},r.listenerCount=function(v,y){return typeof v.listenerCount=="function"?v.listenerCount(y):p.call(v,y)},r.prototype.listenerCount=p;function p(v){var y=this._events;if(y!==void 0){var E=y[v];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(v,y){for(var E=new Array(y),M=0;M<y;++M)E[M]=v[M];return E}function m(v,y){for(;y+1<v.length;y++)v[y]=v[y+1];v.pop()}function T(v){for(var y=new Array(v.length),E=0;E<y.length;++E)y[E]=v[E].listener||v[E];return y}function k(v,y){return new Promise(function(E,M){function U(q){v.removeListener(y,G),M(q)}function G(){typeof v.removeListener=="function"&&v.removeListener("error",U),E([].slice.call(arguments))}D(v,y,G,{once:!0}),y!=="error"&&x(v,U,{once:!0})})}function x(v,y,E){typeof v.on=="function"&&D(v,"error",y,E)}function D(v,y,E,M){if(typeof v.on=="function")M.once?v.once(y,E):v.on(y,E);else if(typeof v.addEventListener=="function")v.addEventListener(y,function U(G){M.once&&v.removeEventListener(y,U),E(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return Gn.exports}var Qe=Ef();let Bo=!0,Vo=!0;function Wn(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function Ht(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function wf(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Bo=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Pf(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Vo=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function qo(){if(typeof window=="object"){if(Bo)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Qs(n,e){Vo&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Rf(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=Wn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=Wn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Wn(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function zo(n){return Object.prototype.toString.call(n)==="[object Object]"}function Ko(n){return zo(n)?Object.keys(n).reduce(function(e,t){const i=zo(n[t]),s=i?Ko(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function Xs(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Xs(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{Xs(n,n.get(s),t)})}))}function Go(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&Xs(n,o,s)})}),s}const Wo=qo;function Ho(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};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])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.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 o.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 p=h.find(g=>u.some(m=>g.label.toLowerCase().includes(m)));return!p&&h.length&&u.includes("back")&&(p=h[h.length-1]),p&&(o.video.deviceId=d.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=i(o.video),Wo("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return Wo("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){s(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>o(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 Zo(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Jo(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(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Ht(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Yo(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(o,c){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);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(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),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 Qo(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(a=>a._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(a=>Go(a,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}),Ht(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Go(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,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(r?a=!0:r=o),o.track===i)),a||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 Xo(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function ec(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Xo(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(p=>p.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 p=d._reverseStreams[h],g=d._streams[p.id];u=u.replace(new RegExp(g.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const p=d._reverseStreams[h],g=d._streams[p.id];u=u.replace(new RegExp(p.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 o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.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(p=>{this._streams[p].getTracks().find(m=>l.track===m)&&(h=this._streams[p])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function er(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 tc(n,e){Ht(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var ic=Object.freeze({__proto__:null,fixNegotiationNeeded:tc,shimAddTrackRemoveTrack:ec,shimAddTrackRemoveTrackWithNative:Xo,shimGetSendersWithDtmf:Yo,shimGetUserMedia:Ho,shimMediaStream:Zo,shimOnTrack:Jo,shimPeerConnection:er,shimSenderReceiverGetStats:Qo});function nc(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){Qs("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function xf(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 sc(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 tr(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],a={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=a[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,a,o]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)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(a,o)}}function rc(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 ac(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}),Ht(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function oc(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){Qs("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function cc(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function dc(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(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function lc(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 uc(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 hc(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 fc=Object.freeze({__proto__:null,shimAddTransceiver:dc,shimCreateAnswer:hc,shimCreateOffer:uc,shimGetDisplayMedia:xf,shimGetParameters:lc,shimGetUserMedia:nc,shimOnTrack:sc,shimPeerConnection:tr,shimRTCDataChannel:cc,shimReceiverGetStats:ac,shimRemoveStream:oc,shimSenderGetStats:rc});function pc(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),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),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 mc(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 a=new Event("addstream");a.stream=r,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function gc(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,a=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 o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function vc(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(yc(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}).bind(e))}function yc(n){return n&&n.video!==void 0?Object.assign({},n,{video:Ko(n.video)}):n}function bc(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(Qs("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(i.iceServers[a])}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 kc(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 Tc(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(a=>a.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(a=>a.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 Sc(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Cc=Object.freeze({__proto__:null,shimAudioContext:Sc,shimCallbacksAPI:gc,shimConstraints:yc,shimCreateOfferLegacy:Tc,shimGetUserMedia:vc,shimLocalStreamsAPI:pc,shimRTCIceServerUrls:bc,shimRemoteStreamsAPI:mc,shimTrackEventTransceiver:kc}),ir={exports:{}},_c;function If(){return _c||(_c=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(`
583
+ `,Ze([Y({type:String})],Te.prototype,"apiBaseUrl",2),Ze([Y({type:String})],Te.prototype,"apiKey",2),Ze([Y({type:String})],Te.prototype,"position",2),Ze([Y({type:Object})],Te.prototype,"user",2),Ze([pt()],Te.prototype,"state",2),Ze([pt()],Te.prototype,"showCourseModal",2),Ze([pt()],Te.prototype,"isHovering",2),Ze([pt()],Te.prototype,"navVisible",2),Ze([pt()],Te.prototype,"activeSession",2),Ze([pt()],Te.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",Te);function Oa(n){return{all:n=n||new Map,on:function(e,t){var i=n.get(e);i?i.push(t):n.set(e,[t])},off:function(e,t){var i=n.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var i=n.get(e);i&&i.slice().map(function(s){s(t)}),(i=n.get("*"))&&i.slice().map(function(s){s(e,t)})}}}class Fu{constructor(e={}){this.state=$.READY,this.emitter=Oa(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=Ql.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState($.READY),this.emitter.emit(rt.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(rt.STATE_CHANGE,e)}handleError(e){this.setState($.ERROR),this.emitter.emit(rt.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(!this.voiceEnabled){this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"});return}try{this.setState($.AGENT_SPEAKING),this.emitter.emit(rt.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}}async stopVoiceRecording(){if(this.state===$.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState($.READY),this.emitter.emit(rt.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(!this.screenCaptureEnabled){this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"});return}try{this.setState($.AGENT_SPEAKING),this.emitter.emit(rt.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}}async stopScreenCapture(){if(this.state===$.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState($.READY),this.emitter.emit(rt.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}}const ju=()=>{customElements.get("obi-widget")||customElements.define("obi-widget",Te)};class $u{static init(e){ju();const t=document.createElement("obi-widget");return e.apiKey&&(t.apiKey=e.apiKey),e.position&&(t.position=e.position),e.user&&(t.user=e.user),window.obiWidgetConfig=e,document.body.appendChild(t),console.log("Obi Widget initialized and mounted"),t}}const Bu="https://registry.npmjs.org/obi-sdk/latest",Da="https://unpkg.com/obi-sdk",Ne=window;Ne.__obiSDKLoading=Ne.__obiSDKLoading||!1;const Vu=async n=>(Ne.obiWidgetConfig=n,new Promise((e,t)=>{if(Ne.ObiAssistant)try{const i=On(n);e(i);return}catch(i){t(new Error(`Error creating widget: ${i}`));return}if(Ne.__obiSDKLoading){qu(()=>{try{const i=On(n);e(i)}catch(i){t(new Error(`Error creating widget after waiting: ${i}`))}});return}zu().then(i=>{Ma(i,()=>{Ne.__obiSDKLoading=!1;try{const s=On(n);e(s)}catch(s){t(new Error(`Error creating widget after loading SDK: ${s}`))}},t)}).catch(()=>{Ma(null,()=>{Ne.__obiSDKLoading=!1;try{const i=On(n);e(i)}catch(i){t(new Error(`Error creating widget with latest version: ${i}`))}},t)})}));function qu(n){const e=setInterval(()=>{(typeof Ne.ObiAssistant=="function"||typeof Ne.ObiAssistant=="object")&&(clearInterval(e),n())},100)}async function zu(){return new Promise(n=>{try{const e=new XMLHttpRequest;e.open("GET",Bu),e.onload=()=>{if(e.status===200)try{const t=JSON.parse(e.responseText);n(t.version)}catch{n(null)}else n(null)},e.onerror=()=>n(null),e.send()}catch{n(null)}})}function Ma(n,e,t){Ne.__obiSDKLoading=!0;const i=document.createElement("script");i.type="text/javascript",i.async=!0;const s=n||"latest";i.src=`${Da}@${s}/dist/obi-sdk.standalone.iife.js`,i.onload=e,i.onerror=()=>{s!=="latest"?(console.warn("Failed to load specific version, falling back to latest"),i.src=`${Da}@latest/dist/obi-sdk.standalone.iife.js`,i.onload=e):(Ne.__obiSDKLoading=!1,t(new Error("Failed to load Obi SDK from CDN")))},document.head.appendChild(i)}function On(n){const e=document,t=e.querySelector("obi-widget");if(t)return console.log("Obi Widget already exists on the page"),t;if(!customElements.get("obi-widget"))throw new Error("Obi Widget component not registered - SDK may not have loaded properly");const i=e.createElement("obi-widget");return n.apiKey&&i.setAttribute("api-key",n.apiKey),n.position&&i.setAttribute("position",n.position),n.user&&i.setAttribute("user",JSON.stringify(n.user)),e.body.appendChild(i),console.log("Obi Widget added to page"),i}function Ku(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 Gu=Object.defineProperty,Wu=(n,e,t)=>e in n?Gu(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Na=(n,e,t)=>Wu(n,typeof e!="symbol"?e+"":e,t);class Se{constructor(){Na(this,"_locking"),Na(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 ae(n,e){if(!n)throw new Error(e)}const Hu=34028234663852886e22,Zu=-34028234663852886e22,Ju=4294967295,Yu=2147483647,Qu=-2147483648;function Dn(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>Yu||n<Qu)throw new Error("invalid int 32: "+n)}function Os(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Ju||n<0)throw new Error("invalid uint 32: "+n)}function La(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Hu||n<Zu))throw new Error("invalid float 32: "+n)}const Ua=Symbol("@bufbuild/protobuf/enum-type");function Xu(n){const e=n[Ua];return ae(e,"missing enum type on enum object"),e}function Fa(n,e,t,i){n[Ua]=ja(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function ja(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=$a(a);r.push(o),i[a.name]=o,s[a.no]=o}return{typeName:n,values:r,findName(a){return i[a]},findNumber(a){return s[a]}}}function eh(n,e,t){const i={};for(const s of e){const r=$a(s);i[r.localName]=r.no,i[r.no]=r.localName}return Fa(i,n,e),i}function $a(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Ds{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 th(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),a={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new Ds),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}function ih(){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))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))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))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Ms(n,e,t){for(let r=0;r<28;r=r+7){const a=n>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,s=!!(e>>3);if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const Mn=4294967296;function Ba(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(a,o){const c=Number(n.slice(a,o));s*=t,i=i*t+c,i>=Mn&&(s=s+(i/Mn|0),i=i%Mn)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?qa(i,s):Ns(i,s)}function nh(n,e){let t=Ns(n,e);const i=t.hi&2147483648;i&&(t=qa(t.lo,t.hi));const s=Va(t.lo,t.hi);return i?"-"+s:s}function Va(n,e){if({lo:n,hi:e}=sh(n,e),e<=2097151)return String(Mn*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,a=i+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+za(a)+za(r)}function sh(n,e){return{lo:n>>>0,hi:e>>>0}}function Ns(n,e){return{lo:n|0,hi:e|0}}function qa(n,e){return e=~e,n?n=~n+1:e+=1,Ns(n,e)}const za=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Ka(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 rh(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function ah(){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"),a=BigInt("0"),o=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>o||d<a)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=>ae(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>ae(/^[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),Ba(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),Ba(s)},dec(s,r){return nh(s,r)},uDec(s,r){return Va(s,r)}}}const se=ah();var S;(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"})(S||(S={}));var Et;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Et||(Et={}));function wt(n,e,t){if(e===t)return!0;if(n==S.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 S.UINT64:case S.FIXED64:case S.INT64:case S.SFIXED64:case S.SINT64:return e==t}return!1}function li(n,e){switch(n){case S.BOOL:return!1;case S.UINT64:case S.FIXED64:case S.INT64:case S.SFIXED64:case S.SINT64:return e==0?se.zero:"0";case S.DOUBLE:case S.FLOAT:return 0;case S.BYTES:return new Uint8Array(0);case S.STRING:return"";default:return 0}}function Ga(n,e){switch(n){case S.BOOL:return e===!1;case S.STRING:return e==="";case S.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var le;(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"})(le||(le={}));class oh{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(Os(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Dn(e),Ka(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){La(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){Os(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Dn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Dn(e),e=(e<<1^e>>31)>>>0,Ka(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=se.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=se.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=se.enc(e);return Ms(t.lo,t.hi,this.buf),this}sint64(e){let t=se.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return Ms(s,r,this.buf),this}uint64(e){let t=se.uEnc(e);return Ms(t.lo,t.hi,this.buf),this}}class ch{constructor(e,t){this.varint64=ih,this.uint32=rh,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 le.Varint:for(;this.buf[this.pos++]&128;);break;case le.Bit64:this.pos+=4;case le.Bit32:this.pos+=4;break;case le.LengthDelimited:let s=this.uint32();this.pos+=s;break;case le.StartGroup:for(;;){const[r,a]=this.tag();if(a===le.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(a,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 se.dec(...this.varint64())}uint64(){return se.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,se.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 se.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return se.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 dh(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 Wa(n){const e=n.field.localName,t=Object.create(null);return t[e]=lh(n),[t,()=>t[e]]}function lh(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 li(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 uh(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 ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Nn=[];for(let n=0;n<ct.length;n++)Nn[ct[n].charCodeAt(0)]=n;Nn["-".charCodeAt(0)]=ct.indexOf("+"),Nn["_".charCodeAt(0)]=ct.indexOf("/");const Ha={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,a=0;for(let o=0;o<n.length;o++){if(r=Nn[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":s=0;case`
584
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[i++]=(a&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+=ct[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=ct[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=ct[s|i>>6],e+=ct[i&63],t=0;break}return t&&(e+=ct[s],e+="=",t==1&&(e+="=")),e}};function hh(n,e,t){Ja(e,n);const i=e.runtime.bin.makeReadOptions(t),s=uh(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,a]=Wa(e);for(const o of s)e.runtime.bin.readField(r,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function fh(n,e,t,i){Ja(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(Za(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 a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const c=s.readerFactory(a.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 Za(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 Ja(n,e){ae(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Ya(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:!Ga(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Qa(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?li(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function Gt(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(Ds.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 Xa(n,e){return Gt(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}S.DOUBLE,S.FLOAT,S.INT64,S.UINT64,S.INT32,S.UINT32,S.BOOL,S.STRING,S.BYTES;const eo={ignoreUnknownFields:!1},to={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ph(n){return n?Object.assign(Object.assign({},eo),n):eo}function mh(n){return n?Object.assign(Object.assign({},to),n):to}const Ln=Symbol(),Un=Symbol();function gh(){return{makeReadOptions:ph,makeWriteOptions:mh,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(Je(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=n.fields.findJsonName(a);if(c){if(c.oneof){if(o===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(a,'"'));s.set(c.oneof,a)}io(i,o,c,t,n)}else{let d=!1;if(r!=null&&r.findExtension&&a.startsWith("[")&&a.endsWith("]")){const l=r.findExtension(a.substring(1,a.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=Wa(l);io(u,o,l.field,t,l),fh(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!Ya(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!yh(s))continue}const a=s.oneof?n[s.oneof.localName].value:n[s.localName],o=no(s,a,e);o!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&Za(n,o)){const c=hh(n,o,e),d=no(o.field,c,e);d!==void 0&&(i[o.field.jsonName]=d)}}}catch(r){const a=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=r instanceof Error?r.message:String(r);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return Qi(n,e,t??Et.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Ga(n,e)))return Fn(n,e)},debug:Je}}function Je(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 io(n,e,t,i,s){let r=t.localName;if(t.repeated){if(ae(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(Je(e)));const a=n[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,i));break;case"enum":const c=Ls(t.T,o,i.ignoreUnknownFields,!0);c!==Un&&a.push(c);break;case"scalar":try{a.push(Qi(t.T,o,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(o));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(Je(e)));const a=n[r];for(const[o,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=vh(t.K,o)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":a[d]=t.V.T.fromJson(c,i);break;case"enum":const l=Ls(t.V.T,c,i.ignoreUnknownFields,!0);l!==Un&&(a[d]=l);break;case"scalar":try{a[d]=Qi(t.V.T,c,Et.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(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 a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=n[r];Gt(o)?o.fromJson(e,i):(n[r]=o=a.fromJson(e,i),a.fieldWrapper&&!t.oneof&&(n[r]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Ls(t.T,e,i.ignoreUnknownFields,!1);switch(c){case Ln:Qa(t,n);break;case Un:break;default:n[r]=c;break}break;case"scalar":try{const d=Qi(t.T,e,t.L,!1);switch(d){case Ln:Qa(t,n);break;default:n[r]=d;break}}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function vh(n,e){if(n===S.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Qi(n,e,Et.BIGINT,!0).toString()}function Qi(n,e,t,i){if(e===null)return i?li(n,t):Ln;switch(n){case S.DOUBLE:case S.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==S.FLOAT&&La(s),s;case S.INT32:case S.FIXED32:case S.SFIXED32:case S.SINT32:case S.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==S.UINT32||n==S.FIXED32?Os(r):Dn(r),r;case S.INT64:case S.SFIXED64:case S.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=se.parse(e);return t?a.toString():a;case S.FIXED64:case S.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=se.uParse(e);return t?o.toString():o;case S.BOOL:if(typeof e!="boolean")break;return e;case S.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case S.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Ha.dec(e)}throw new Error}function Ls(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Ln;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 Un;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Je(e)))}function yh(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function no(n,e,t){if(n.kind=="map"){ae(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[a,o]of s)i[a.toString()]=Fn(n.V.T,o);break;case"message":for(const[a,o]of s)i[a.toString()]=o.toJson(t);break;case"enum":const r=n.V.T;for(const[a,o]of s)i[a.toString()]=Us(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){ae(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(Fn(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(Us(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 Fn(n.T,e);case"enum":return Us(n.T,e,t.enumAsInteger);case"message":return Xa(n.T,e).toJson(t)}}function Us(n,e,t){var i;if(ae(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 Fn(n,e){switch(n){case S.INT32:case S.SFIXED32:case S.SINT32:case S.FIXED32:case S.UINT32:return ae(typeof e=="number"),e;case S.FLOAT:case S.DOUBLE:return ae(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case S.STRING:return ae(typeof e=="string"),e;case S.BOOL:return ae(typeof e=="boolean"),e;case S.UINT64:case S.FIXED64:case S.INT64:case S.SFIXED64:case S.SINT64:return ae(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case S.BYTES:return ae(e instanceof Uint8Array),Ha.enc(e)}}const ui=Symbol("@bufbuild/protobuf/unknown-fields"),so={readUnknownFields:!0,readerFactory:n=>new ch(n)},ro={writeUnknownFields:!0,writerFactory:()=>new oh};function bh(n){return n?Object.assign(Object.assign({},so),n):so}function kh(n){return n?Object.assign(Object.assign({},ro),n):ro}function Th(){return{makeReadOptions:bh,makeWriteOptions:kh,listUnknownFields(n){var e;return(e=n[ui])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[ui]},writeUnknownFields(n,e){const i=n[ui];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[ui])||(s[ui]=[]),s[ui].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),a=s?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(s===!0&&c==le.EndGroup));){const d=r.fields.find(o);if(!d){const l=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(n,o,c,l);continue}ao(n,e,d,c,i)}if(s&&(c!=le.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:ao,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!Ya(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];oo(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&oo(n,e,t,i)}}}function ao(n,e,t,i,s){let{repeated:r,localName:a}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?S.INT32:t.T;let c=$n;if(t.kind=="scalar"&&t.L>0&&(c=Ch),r){let h=n[a];if(i==le.LengthDelimited&&o!=S.STRING&&o!=S.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,o))}else h.push(c(e,o))}else n[a]=c(e,o);break;case"message":const d=t.T;r?n[a].push(jn(e,new d,s,t)):Gt(n[a])?jn(e,n[a],s,t):(n[a]=jn(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=d.fieldWrapper.unwrapField(n[a])));break;case"map":let[l,u]=Sh(t,e,s);n[a][l]=u;break}}function jn(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 Sh(n,e,t){const i=e.uint32(),s=e.pos+i;let r,a;for(;e.pos<s;){const[o]=e.tag();switch(o){case 1:r=$n(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=$n(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=jn(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=li(n.K,Et.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(n.V.kind){case"scalar":a=li(n.V.T,Et.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[r,a]}function Ch(n,e){const t=$n(n,e);return typeof t=="bigint"?t.toString():t}function $n(n,e){switch(e){case S.STRING:return n.string();case S.BOOL:return n.bool();case S.DOUBLE:return n.double();case S.FLOAT:return n.float();case S.INT32:return n.int32();case S.INT64:return n.int64();case S.UINT64:return n.uint64();case S.FIXED64:return n.fixed64();case S.BYTES:return n.bytes();case S.FIXED32:return n.fixed32();case S.SFIXED32:return n.sfixed32();case S.SFIXED64:return n.sfixed64();case S.SINT64:return n.sint64();case S.UINT32:return n.uint32();case S.SINT32:return n.sint32()}}function oo(n,e,t,i){ae(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?S.INT32:n.T;if(s)if(ae(Array.isArray(e)),n.packed)Eh(t,r,n.no,e);else for(const a of e)Xi(t,r,n.no,a);else Xi(t,r,n.no,e);break;case"message":if(s){ae(Array.isArray(e));for(const a of e)co(t,i,n,a)}else co(t,i,n,e);break;case"map":ae(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))_h(t,i,n,a,o);break}}function _h(n,e,t,i,s){n.tag(t.no,le.LengthDelimited),n.fork();let r=i;switch(t.K){case S.INT32:case S.FIXED32:case S.UINT32:case S.SFIXED32:case S.SINT32:r=Number.parseInt(i);break;case S.BOOL:ae(i=="true"||i=="false"),r=i=="true";break}switch(Xi(n,t.K,1,r),t.V.kind){case"scalar":Xi(n,t.V.T,2,s);break;case"enum":Xi(n,S.INT32,2,s);break;case"message":ae(s!==void 0),n.tag(2,le.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function co(n,e,t,i){const s=Xa(t.T,i);t.delimited?n.tag(t.no,le.StartGroup).raw(s.toBinary(e)).tag(t.no,le.EndGroup):n.tag(t.no,le.LengthDelimited).bytes(s.toBinary(e))}function Xi(n,e,t,i){ae(i!==void 0);let[s,r]=lo(e);n.tag(t,s)[r](i)}function Eh(n,e,t,i){if(!i.length)return;n.tag(t,le.LengthDelimited).fork();let[,s]=lo(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function lo(n){let e=le.Varint;switch(n){case S.BYTES:case S.STRING:e=le.LengthDelimited;break;case S.DOUBLE:case S.FIXED64:case S.SFIXED64:e=le.Bit64;break;case S.FIXED32:case S.SFIXED32:case S.FLOAT:e=le.Bit32;break}const t=S[n].toLowerCase();return[e,t]}function wh(){return{setEnumType:Fa,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,a=n;if(a[s]!=null)switch(i.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=i.findField(o);let d=a[s].value;c&&c.kind=="message"&&!Gt(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===S.BYTES&&(d=en(d)),r[s]={case:o,value:d};break;case"scalar":case"enum":let l=a[s];i.T===S.BYTES&&(l=i.repeated?l.map(en):en(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===S.BYTES)for(const[p,g]of Object.entries(a[s]))r[s][p]=en(g);else Object.assign(r[s],a[s]);break;case"message":const h=i.V.T;for(const p of Object.keys(a[s])){let g=a[s][p];h.fieldWrapper||(g=new h(g)),r[s][p]=g}break}break;case"message":const u=i.T;if(i.repeated)r[s]=a[s].map(h=>Gt(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=en(h):r[s]=h:r[s]=Gt(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((a,o)=>i.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>wt(i.T,a,r[o]));case"enum":return s.every((a,o)=>wt(S.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":return i.T.equals(s,r);case"enum":return wt(S.INT32,s,r);case"scalar":return wt(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const a=i.findField(s.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(s.value,r.value);case"enum":return wt(S.INT32,s.value,r.value);case"scalar":return wt(a.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const c=i.V.T;return o.every(l=>c.equals(s[l],r[l]));case"enum":return o.every(l=>wt(S.INT32,s[l],r[l]));case"scalar":const d=i.V.T;return o.every(l=>wt(d,s[l],r[l]))}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 a;if(s.repeated)a=r.map(Bn);else if(s.kind=="map"){a=i[s.localName];for(const[o,c]of Object.entries(r))a[o]=Bn(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:Bn(r.value)}:{case:void 0}:a=Bn(r);i[s.localName]=a}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function Bn(n){if(n===void 0)return n;if(Gt(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function en(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Ph(n,e,t){return{syntax:n,json:gh(),bin:Th(),util:Object.assign(Object.assign({},wh()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return th(this,i,s,r)},makeEnum:eh,makeEnumType:ja,getEnumType:Xu,makeExtension(i,s,r){return dh(this,i,s,r)}}}class Rh{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 uo(n,e){const t=ho(n);return e?t:Mh(Dh(t))}function xh(n){return uo(n,!1)}const Ih=ho;function ho(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 Ah=new Set(["constructor","toString","toJSON","valueOf"]),Oh=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),fo=n=>"".concat(n,"$"),Dh=n=>Oh.has(n)?fo(n):n,Mh=n=>Ah.has(n)?fo(n):n;class Nh{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=xh(e)}addField(e){ae(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 Lh(n,e){var t,i,s,r,a,o;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=uo(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Ih(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:Et.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=S.BYTES&&l.T!=S.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new Nh(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const b=Ph("proto3",n=>new Rh(n,e=>Lh(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]=li(e.T,e.L);break}}});class Ce extends Ds{constructor(e){super(),this.seconds=se.zero,this.nanos=0,b.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(b.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=se.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 Ce.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ce({seconds:se.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Ce().fromBinary(e,t)}static fromJson(e,t){return new Ce().fromJson(e,t)}static fromJsonString(e,t){return new Ce().fromJsonString(e,t)}static equals(e,t){return b.util.equals(Ce,e,t)}}Ce.runtime=b,Ce.typeName="google.protobuf.Timestamp",Ce.fields=b.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Uh=b.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ce},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Fh,repeated:!0},{no:5,name:"events",kind:"message",T:$h,repeated:!0}]),Fh=b.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:jh,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),jh=b.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ce},{no:3,name:"value",kind:"scalar",T:2}]),$h=b.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:Ce},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ce,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),po=b.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Le=b.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),he=b.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"}]),hi=b.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),tn=b.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),nn=b.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Ue=b.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"}]),fi=b.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"}]),Bh=b.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ye=b.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"}]),Fs=b.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:Vn,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:Po}]),Vn=b.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Vh=b.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:b.getEnumType(he),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}]),sn=b.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:b.getEnumType(js)},{no:4,name:"tracks",kind:"message",T:pi,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:Vh},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:b.getEnumType(qn)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:b.getEnumType(Ue)},{no:18,name:"kind_details",kind:"enum",T:b.getEnumType(qh),repeated:!0}]),js=b.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),qn=b.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),qh=b.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),xe=b.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),zh=b.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:Wt,repeated:!0}]),pi=b.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:b.getEnumType(Le)},{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:b.getEnumType(he)},{no:10,name:"layers",kind:"message",T:Wt,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:zh,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:b.getEnumType(xe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Po},{no:19,name:"audio_features",kind:"enum",T:b.getEnumType(Ye),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(po)}]),Wt=b.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(hi)},{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}]),_e=b.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:b.getEnumType(J)},{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:go,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Kh,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:vo,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Gh,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Uh,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:$s,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:yo,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:bo,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ko,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Vs,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:qs,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:zs,oneof:"value"}]),J=b.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Kh=b.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:mo,repeated:!0}]),mo=b.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}]),go=b.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}]),vo=b.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Gh=b.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:Wh,repeated:!0}]),Wh=b.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}]),$s=b.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}]),yo=b.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}]),bo=b.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ko=b.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:To,oneof:"value"}]),To=b.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}]),So=b.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Hh=b.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:b.getEnumType(Co)},{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}]),Co=b.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Zh=b.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:b.getEnumType(_o)},{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}]),_o=b.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"}]),Eo=b.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:wo},{no:2,name:"screen",kind:"message",T:wo},{no:3,name:"resume_connection",kind:"enum",T:b.getEnumType(nn)},{no:4,name:"disabled_codecs",kind:"message",T:Jh},{no:5,name:"force_relay",kind:"enum",T:b.getEnumType(nn)}]),wo=b.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:b.getEnumType(nn)}]),Jh=b.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Vn,repeated:!0},{no:2,name:"publish",kind:"message",T:Vn,repeated:!0}]),Po=b.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Bs=b.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Ro=b.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:b.getEnumType(Bs)},{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"}),xo=b.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Vs=b.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:b.getEnumType(xe)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ro,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:xo,oneof:"content_header"}],{localName:"DataStream_Header"}),qs=b.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),zs=b.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"}),Fe=b.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ks=b.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Yh=b.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Qh=b.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Ht,oneof:"message"},{no:2,name:"answer",kind:"message",T:Ht,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Hs,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ws,oneof:"message"},{no:5,name:"mute",kind:"message",T:Zs,oneof:"message"},{no:6,name:"subscription",kind:"message",T:zn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ao,oneof:"message"},{no:8,name:"leave",kind:"message",T:Kn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Do,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Uo,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Fo,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Qe,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Mo,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:$o,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Oo,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:sf,oneof:"message"}]),Io=b.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Xh,oneof:"message"},{no:2,name:"answer",kind:"message",T:Ht,oneof:"message"},{no:3,name:"offer",kind:"message",T:Ht,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Hs,oneof:"message"},{no:5,name:"update",kind:"message",T:nf,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Js,oneof:"message"},{no:8,name:"leave",kind:"message",T:Kn,oneof:"message"},{no:9,name:"mute",kind:"message",T:Zs,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:rf,oneof:"message"},{no:11,name:"room_update",kind:"message",T:af,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:cf,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:lf,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:hf,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ff,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:tf,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:ef,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:pf,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:vf,oneof:"message"},{no:22,name:"request_response",kind:"message",T:yf,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:bf,oneof:"message"}]),Gs=b.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),Ws=b.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:b.getEnumType(Le)},{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:b.getEnumType(he)},{no:9,name:"layers",kind:"message",T:Wt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Gs,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:b.getEnumType(xe)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(po)}]),Hs=b.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:b.getEnumType(Fe)},{no:3,name:"final",kind:"scalar",T:8}]),Zs=b.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Xh=b.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Fs},{no:2,name:"participant",kind:"message",T:sn},{no:3,name:"other_participants",kind:"message",T:sn,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:No,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:Eo},{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:Hh},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Vn,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),ef=b.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:No,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Eo}]),Js=b.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:pi}]),tf=b.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Ht=b.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]),nf=b.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:sn,repeated:!0}]),zn=b.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:So,repeated:!0}]),Ao=b.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:b.getEnumType(hi)},{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}]),Oo=b.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:b.getEnumType(Ye),repeated:!0}]),sf=b.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}]),Kn=b.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:b.getEnumType(Ue)},{no:3,name:"action",kind:"enum",T:b.getEnumType(mi)},{no:4,name:"regions",kind:"message",T:mf}]),mi=b.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Do=b.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Wt,repeated:!0}]),Mo=b.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}]),No=b.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}]),rf=b.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:mo,repeated:!0}]),af=b.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Fs}]),of=b.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:b.getEnumType(tn)},{no:3,name:"score",kind:"scalar",T:2}]),cf=b.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:of,repeated:!0}]),df=b.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:b.getEnumType(Ks)}]),lf=b.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:df,repeated:!0}]),Ys=b.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(hi)},{no:2,name:"enabled",kind:"scalar",T:8}]),uf=b.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Ys,repeated:!0}]),hf=b.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Ys,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:uf,repeated:!0}]),Lo=b.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}]),Uo=b.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Lo,repeated:!0}]),ff=b.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}]),Fo=b.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Ht},{no:2,name:"subscription",kind:"message",T:zn},{no:3,name:"publish_tracks",kind:"message",T:Js,repeated:!0},{no:4,name:"data_channels",kind:"message",T:jo,repeated:!0},{no:5,name:"offer",kind:"message",T:Ht},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]),jo=b.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:b.getEnumType(Fe)}]),Qe=b.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:b.getEnumType(Yh),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"}]),$o=b.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),pf=b.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),mf=b.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:gf,repeated:!0}]),gf=b.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}]),vf=b.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:b.getEnumType(Bh)}]),yf=b.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:b.getEnumType(Qs)},{no:3,name:"message",kind:"scalar",T:9}]),Qs=b.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),bf=b.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function kf(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Gn={exports:{}},Tf=Gn.exports,Bo;function Sf(){return Bo||(Bo=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(Tf,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={},a=null;function o(m,T){var k=m[T];if(typeof k.bind=="function")return k.bind(m);try{return Function.prototype.bind.call(k,m)}catch{return function(){return Function.prototype.apply.apply(k,[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?o(console,m):console.log!==void 0?o(console,"log"):e}function l(){for(var m=this.getLevel(),T=0;T<s.length;T++){var k=s[T];this[k]=T<m?e:this.methodFactory(k,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,T,k){return d(m)||u.apply(this,arguments)}function p(m,T){var k=this,x,D,v,y="loglevel";typeof m=="string"?y+=":"+m:typeof m=="symbol"&&(y=void 0);function E(z){var de=(s[z]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=de;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+de+";"}catch{}}}function M(){var z;if(!(typeof window===t||!y)){try{z=window.localStorage[y]}catch{}if(typeof z===t)try{var de=window.document.cookie,Xt=encodeURIComponent(y),fs=de.indexOf(Xt+"=");fs!==-1&&(z=/^([^;]+)/.exec(de.slice(fs+Xt.length+1))[1])}catch{}return k.levels[z]===void 0&&(z=void 0),z}}function U(){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 G(z){var de=z;if(typeof de=="string"&&k.levels[de.toUpperCase()]!==void 0&&(de=k.levels[de.toUpperCase()]),typeof de=="number"&&de>=0&&de<=k.levels.SILENT)return de;throw new TypeError("log.setLevel() called with invalid level: "+z)}k.name=m,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=T||h,k.getLevel=function(){return v??D??x},k.setLevel=function(z,de){return v=G(z),de!==!1&&E(v),l.call(k)},k.setDefaultLevel=function(z){D=G(z),M()||k.setLevel(z,!1)},k.resetLevel=function(){v=null,U(),l.call(k)},k.enableAll=function(z){k.setLevel(k.levels.TRACE,z)},k.disableAll=function(z){k.setLevel(k.levels.SILENT,z)},k.rebuild=function(){if(a!==k&&(x=G(a.getLevel())),l.call(k),a===k)for(var z in r)r[z].rebuild()},x=G(a?a.getLevel():"WARN");var q=M();q!=null&&(v=G(q)),l.call(k)}a=new p,a.getLogger=function(T){if(typeof T!="symbol"&&typeof T!="string"||T==="")throw new TypeError("You must supply a name when creating a logger.");var k=r[T];return k||(k=r[T]=new p(T,a.methodFactory)),k};var g=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=g),a},a.getLoggers=function(){return r},a.default=a,a})}(Gn)),Gn.exports}var Wn=Sf(),Xs;(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"})(Xs||(Xs={}));var je;(function(n){n.Default="livekit",n.Room="livekit-room",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"})(je||(je={}));let K=Wn.getLogger("livekit");Object.values(je).map(n=>Wn.getLogger(n)),K.setDefaultLevel(Xs.info);function dt(n){const e=Wn.getLogger(n);return e.setDefaultLevel(K.getLevel()),e}const Cf=Wn.getLogger("lk-e2ee"),rn=7e3,_f=[0,300,2*2*300,3*3*300,4*4*300,rn,rn,rn,rn,rn];class Ef{constructor(e){this._retryDelays=e!==void 0?[...e]:_f}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 wf(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 f(n,e,t,i){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(l){try{d(i.next(l))}catch(u){a(u)}}function c(l){try{d(i.throw(l))}catch(u){a(u)}}function d(l){l.done?r(l.value):s(l.value).then(o,c)}d((i=i.apply(n,e||[])).next())})}function Vo(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 Pt(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 Vo=="function"?Vo(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(a){return new Promise(function(o,c){a=n[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(d){r({value:d,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var Hn={exports:{}},qo;function Pf(){if(qo)return Hn.exports;qo=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(y,E,M){return Function.prototype.apply.call(y,E,M)},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(v){console&&console.warn&&console.warn(v)}var s=Number.isNaN||function(y){return y!==y};function r(){r.init.call(this)}Hn.exports=r,Hn.exports.once=k,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(v){if(typeof v!="number"||v<0||s(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");a=v}}),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(v){return v._maxListeners===void 0?r.defaultMaxListeners:v._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(y){for(var E=[],M=1;M<arguments.length;M++)E.push(arguments[M]);var U=y==="error",G=this._events;if(G!==void 0)U=U&&G.error===void 0;else if(!U)return!1;if(U){var q;if(E.length>0&&(q=E[0]),q instanceof Error)throw q;var z=new Error("Unhandled error."+(q?" ("+q.message+")":""));throw z.context=q,z}var de=G[y];if(de===void 0)return!1;if(typeof de=="function")e(de,this,E);else for(var Xt=de.length,fs=g(de,Xt),M=0;M<Xt;++M)e(fs[M],this,E);return!0};function d(v,y,E,M){var U,G,q;if(o(E),G=v._events,G===void 0?(G=v._events=Object.create(null),v._eventsCount=0):(G.newListener!==void 0&&(v.emit("newListener",y,E.listener?E.listener:E),G=v._events),q=G[y]),q===void 0)q=G[y]=E,++v._eventsCount;else if(typeof q=="function"?q=G[y]=M?[E,q]:[q,E]:M?q.unshift(E):q.push(E),U=c(v),U>0&&q.length>U&&!q.warned){q.warned=!0;var z=new Error("Possible EventEmitter memory leak detected. "+q.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");z.name="MaxListenersExceededWarning",z.emitter=v,z.type=y,z.count=q.length,i(z)}return v}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(v,y,E){var M={fired:!1,wrapFn:void 0,target:v,type:y,listener:E},U=l.bind(M);return U.listener=E,M.wrapFn=U,U}r.prototype.once=function(y,E){return o(E),this.on(y,u(this,y,E)),this},r.prototype.prependOnceListener=function(y,E){return o(E),this.prependListener(y,u(this,y,E)),this},r.prototype.removeListener=function(y,E){var M,U,G,q,z;if(o(E),U=this._events,U===void 0)return this;if(M=U[y],M===void 0)return this;if(M===E||M.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete U[y],U.removeListener&&this.emit("removeListener",y,M.listener||E));else if(typeof M!="function"){for(G=-1,q=M.length-1;q>=0;q--)if(M[q]===E||M[q].listener===E){z=M[q].listener,G=q;break}if(G<0)return this;G===0?M.shift():m(M,G),M.length===1&&(U[y]=M[0]),U.removeListener!==void 0&&this.emit("removeListener",y,z||E)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(y){var E,M,U;if(M=this._events,M===void 0)return this;if(M.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):M[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete M[y]),this;if(arguments.length===0){var G=Object.keys(M),q;for(U=0;U<G.length;++U)q=G[U],q!=="removeListener"&&this.removeAllListeners(q);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=M[y],typeof E=="function")this.removeListener(y,E);else if(E!==void 0)for(U=E.length-1;U>=0;U--)this.removeListener(y,E[U]);return this};function h(v,y,E){var M=v._events;if(M===void 0)return[];var U=M[y];return U===void 0?[]:typeof U=="function"?E?[U.listener||U]:[U]:E?T(U):g(U,U.length)}r.prototype.listeners=function(y){return h(this,y,!0)},r.prototype.rawListeners=function(y){return h(this,y,!1)},r.listenerCount=function(v,y){return typeof v.listenerCount=="function"?v.listenerCount(y):p.call(v,y)},r.prototype.listenerCount=p;function p(v){var y=this._events;if(y!==void 0){var E=y[v];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(v,y){for(var E=new Array(y),M=0;M<y;++M)E[M]=v[M];return E}function m(v,y){for(;y+1<v.length;y++)v[y]=v[y+1];v.pop()}function T(v){for(var y=new Array(v.length),E=0;E<y.length;++E)y[E]=v[E].listener||v[E];return y}function k(v,y){return new Promise(function(E,M){function U(q){v.removeListener(y,G),M(q)}function G(){typeof v.removeListener=="function"&&v.removeListener("error",U),E([].slice.call(arguments))}D(v,y,G,{once:!0}),y!=="error"&&x(v,U,{once:!0})})}function x(v,y,E){typeof v.on=="function"&&D(v,"error",y,E)}function D(v,y,E,M){if(typeof v.on=="function")M.once?v.once(y,E):v.on(y,E);else if(typeof v.addEventListener=="function")v.addEventListener(y,function U(G){M.once&&v.removeEventListener(y,U),E(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return Hn.exports}var Xe=Pf();let zo=!0,Ko=!0;function Zn(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function Zt(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function Rf(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(zo=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function xf(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Ko=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function Go(){if(typeof window=="object"){if(zo)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function er(n,e){Ko&&console.warn(n+" is deprecated, please use "+e+" instead.")}function If(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=Zn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=Zn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Zn(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Wo(n){return Object.prototype.toString.call(n)==="[object Object]"}function Ho(n){return Wo(n)?Object.keys(n).reduce(function(e,t){const i=Wo(n[t]),s=i?Ho(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function tr(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?tr(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{tr(n,n.get(s),t)})}))}function Zo(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&tr(n,o,s)})}),s}const Jo=Go;function Yo(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};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])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.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 o.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 p=h.find(g=>u.some(m=>g.label.toLowerCase().includes(m)));return!p&&h.length&&u.includes("back")&&(p=h[h.length-1]),p&&(o.video.deviceId=d.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=i(o.video),Jo("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return Jo("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){s(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>o(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 Qo(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Xo(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(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Zt(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function ec(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(o,c){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);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(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),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 tc(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(a=>a._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(a=>Zo(a,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}),Zt(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Zo(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,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(r?a=!0:r=o),o.track===i)),a||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 ic(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function nc(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ic(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(p=>p.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 p=d._reverseStreams[h],g=d._streams[p.id];u=u.replace(new RegExp(g.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const p=d._reverseStreams[h],g=d._streams[p.id];u=u.replace(new RegExp(p.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 o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.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(p=>{this._streams[p].getTracks().find(m=>l.track===m)&&(h=this._streams[p])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ir(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 sc(n,e){Zt(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var rc=Object.freeze({__proto__:null,fixNegotiationNeeded:sc,shimAddTrackRemoveTrack:nc,shimAddTrackRemoveTrackWithNative:ic,shimGetSendersWithDtmf:ec,shimGetUserMedia:Yo,shimMediaStream:Qo,shimOnTrack:Xo,shimPeerConnection:ir,shimSenderReceiverGetStats:tc});function ac(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){er("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Af(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 oc(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 nr(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],a={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=a[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,a,o]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)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(a,o)}}function cc(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 dc(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}),Zt(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function lc(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){er("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function uc(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function hc(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(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function fc(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 pc(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 mc(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 gc=Object.freeze({__proto__:null,shimAddTransceiver:hc,shimCreateAnswer:mc,shimCreateOffer:pc,shimGetDisplayMedia:Af,shimGetParameters:fc,shimGetUserMedia:ac,shimOnTrack:oc,shimPeerConnection:nr,shimRTCDataChannel:uc,shimReceiverGetStats:dc,shimRemoveStream:lc,shimSenderGetStats:cc});function vc(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),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),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 yc(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 a=new Event("addstream");a.stream=r,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function bc(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,a=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 o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function kc(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(Tc(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}).bind(e))}function Tc(n){return n&&n.video!==void 0?Object.assign({},n,{video:Ho(n.video)}):n}function Sc(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(er("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(i.iceServers[a])}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 Cc(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 _c(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(a=>a.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(a=>a.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 Ec(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var wc=Object.freeze({__proto__:null,shimAudioContext:Ec,shimCallbacksAPI:bc,shimConstraints:Tc,shimCreateOfferLegacy:_c,shimGetUserMedia:kc,shimLocalStreamsAPI:vc,shimRTCIceServerUrls:Sc,shimRemoteStreamsAPI:yc,shimTrackEventTransceiver:Cc}),sr={exports:{}},Pc;function Of(){return Pc||(Pc=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(`
585
585
  `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
586
586
  m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
587
587
  `)},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
@@ -612,9 +612,9 @@ a=ice-pwd:`+t.password+`\r
612
612
  o=`+(s||"thisisadapterortc")+" "+r+" "+a+` IN IP4 127.0.0.1\r
613
613
  s=-\r
614
614
  t=0 0\r
615
- `},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}(ir)),ir.exports}var Ec=If(),mi=yf(Ec),Af=qu({__proto__:null,default:mi},[Ec]);function Hn(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=mi.parseCandidate(i.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});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,Ht(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function nr(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||Ht(n,"icecandidate",e=>{if(e.candidate){const t=mi.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Zn(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(o){if(!o||!o.sdp)return!1;const c=mi.splitSections(o.sdp);return c.shift(),c.some(d=>{const l=mi.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.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(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=mi.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=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 a.apply(this,arguments)}}function Jn(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const o=arguments[0],c=o.length||o.size||o.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},Ht(n,"datachannel",i=>(e(i.channel,i.target),i))}function sr(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 a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function rr(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
615
+ `},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}(sr)),sr.exports}var Rc=Of(),gi=kf(Rc),Df=Ku({__proto__:null,default:gi},[Rc]);function Jn(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=gi.parseCandidate(i.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});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,Zt(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function rr(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||Zt(n,"icecandidate",e=>{if(e.candidate){const t=gi.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Yn(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(o){if(!o||!o.sdp)return!1;const c=gi.splitSections(o.sdp);return c.shift(),c.some(d=>{const l=gi.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.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(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=gi.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=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 a.apply(this,arguments)}}function Qn(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const o=arguments[0],c=o.length||o.size||o.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},Zt(n,"datachannel",i=>(e(i.channel,i.target),i))}function ar(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 a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function or(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
616
616
  a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
617
617
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
618
- `);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 Yn(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 Qn(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(a=>t.apply(this,[a]))})}var Of=Object.freeze({__proto__:null,removeExtmapAllowMixed:rr,shimAddIceCandidateNullOrEmpty:Yn,shimConnectionState:sr,shimMaxMessageSize:Zn,shimParameterlessSetLocalDescription:Qn,shimRTCIceCandidate:Hn,shimRTCIceCandidateRelayProtocol:nr,shimSendThrowTypeError:Jn});function Df(){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=qo,i=Rf(n),s={browserDetails:i,commonShim:Of,extractVersion:Wn,disableLog:wf,disableWarnings:Pf,sdp:Af};switch(i.browser){case"chrome":if(!ic||!er||!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=ic,Yn(n,i),Qn(n),Ho(n,i),Zo(n),er(n,i),Jo(n),ec(n,i),Yo(n),Qo(n),tc(n,i),Hn(n),nr(n),sr(n),Zn(n,i),Jn(n),rr(n,i);break;case"firefox":if(!fc||!tr||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=fc,Yn(n,i),Qn(n),nc(n,i),tr(n,i),sc(n),oc(n),rc(n),ac(n),cc(n),dc(n),lc(n),uc(n),hc(n),Hn(n),sr(n),Zn(n,i),Jn(n);break;case"safari":if(!Cc||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Cc,Yn(n,i),Qn(n),bc(n),Tc(n),gc(n),pc(n),mc(n),kc(n),vc(n),Sc(n),Hn(n),nr(n),Zn(n,i),Jn(n),rr(n,i);break;default:t("Unsupported browser!");break}return s}Df({window:typeof window>"u"?void 0:window});const Mf=10,Xn="lk_e2ee",Nf={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Mf,keyringSize:16};var Pt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Pt||(Pt={}));var wc;(function(n){n.KeyRatcheted="keyRatcheted"})(wc||(wc={}));var Rt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(Rt||(Rt={}));var Pc;(function(n){n.Error="cryptorError"})(Pc||(Pc={}));function Lf(){return Uf()||ar()}function ar(){return typeof window.RTCRtpScriptTransform<"u"}function Uf(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Am extends Qe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i)=>{K.debug("key ratcheted event received",{material:t,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Nf),e),this.on(Pt.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(Pt.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Pt.RatchetRequest,e,t)}}class xt extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var Z;(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"})(Z||(Z={}));class te extends xt{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=Z[t]}}class or extends xt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class dt extends xt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class jf extends xt{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class fe extends xt{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class cr extends xt{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class dr extends xt{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Rc extends xt{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Js[t]}}var es;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(es||(es={})),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}(es||(es={}));var xc;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(xc||(xc={}));var w;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",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.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 A;(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.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.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage"})(A||(A={}));var R;(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"})(R||(R={}));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.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"})(P||(P={}));function Ff(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const $f=/version\/(\d+(\.?_?\d+)+)/i;let lr;function Fe(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const t=(n??navigator.userAgent).toLowerCase();if(lr===void 0||e){const i=Bf.find(s=>{let{test:r}=s;return r.test(t)});lr=i==null?void 0:i.describe(t)}return lr}const Bf=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:ts(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ur(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:ts(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ur(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:ts($f,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:ur(n)}}}];function ts(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 ur(n){return n.includes("mac os")?ts(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Vf="2.11.4";const qf=Vf,zf=15;class ve{}ve.setTimeout=function(){return setTimeout(...arguments)},ve.setInterval=function(){return setInterval(...arguments)},ve.clearTimeout=function(){return clearTimeout(...arguments)},ve.clearInterval=function(){return clearInterval(...arguments)};const Kf=5e3,rn=[];var Ae;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ae||(Ae={}));class C extends Qe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=K,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Kf):this.handleAppVisibilityChanged()},this.log=ct((s=i.loggerName)!==null&&s!==void 0?s:je.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),X(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===C.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(rn.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&rn.splice(rn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),gi(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"?K.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):K.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){vi(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=>{vi(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=ct(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),rn.forEach(i=>{i.parentElement||(t=!1)}),t&&rn.push(e)}}handleAppVisibilityChanged(){return f(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===C.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){we()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){we()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function gi(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)),(!It()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(It()||yi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function vi(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 Ne.AUDIO;case e.Video:return Ne.VIDEO;default:return Ne.DATA}}n.kindToProto=s;function r(d){switch(d){case Ne.AUDIO:return e.Audio;case Ne.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return he.CAMERA;case t.Microphone:return he.MICROPHONE;case t.ScreenShare:return he.SCREEN_SHARE;case t.ScreenShareAudio:return he.SCREEN_SHARE_AUDIO;default:return he.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case he.CAMERA:return t.Camera;case he.MICROPHONE:return t.Microphone;case he.SCREEN_SHARE:return t.ScreenShare;case he.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case qs.ACTIVE:return i.Active;case qs.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(C||(C={}));class ee{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 Gf=["vp8","h264"],Wf=["vp8","h264","vp9","av1"];function Hf(n){return!!Gf.find(e=>e===n)}var Ic;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Ic||(Ic={}));var hr;(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}})(hr||(hr={}));const an={h90:new ee(160,90,9e4,20),h180:new ee(320,180,16e4,20),h216:new ee(384,216,18e4,20),h360:new ee(640,360,45e4,20),h540:new ee(960,540,8e5,25),h720:new ee(1280,720,17e5,30),h1080:new ee(1920,1080,3e6,30),h1440:new ee(2560,1440,5e6,30),h2160:new ee(3840,2160,8e6,30)},fr={h120:new ee(160,120,7e4,20),h180:new ee(240,180,125e3,20),h240:new ee(320,240,14e4,20),h360:new ee(480,360,33e4,20),h480:new ee(640,480,5e5,20),h540:new ee(720,540,6e5,25),h720:new ee(960,720,13e5,30),h1080:new ee(1440,1080,23e5,30),h1440:new ee(1920,1440,38e5,30)},pr={h360fps3:new ee(640,360,2e5,3,"medium"),h360fps15:new ee(640,360,4e5,15,"medium"),h720fps5:new ee(1280,720,8e5,5,"medium"),h720fps15:new ee(1280,720,15e5,15,"medium"),h720fps30:new ee(1280,720,2e6,30,"medium"),h1080fps15:new ee(1920,1080,25e5,15,"medium"),h1080fps30:new ee(1920,1080,5e6,30,"medium"),original:new ee(0,0,7e6,30,"medium")},Zf="|",Ac="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Jf(n){const e=n.split(Zf);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Ee(n){return f(this,void 0,void 0,function*(){return new Promise(e=>ve.setTimeout(e,n))})}function mr(){return"addTransceiver"in RTCPeerConnection.prototype}function gr(){return"addTrack"in RTCPeerConnection.prototype}function Yf(){if(!("getCapabilities"in RTCRtpSender)||It())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function Qf(){if(!("getCapabilities"in RTCRtpSender)||yi())return!1;if(It()){const t=Fe();if(t!=null&&t.version&&Zt(t.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function on(n){return n==="av1"||n==="vp9"}function vr(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function Xf(){return typeof RTCPeerConnection>"u"?!1:mr()||gr()}function yi(){var n;return((n=Fe())===null||n===void 0?void 0:n.name)==="Firefox"}function It(){var n;return((n=Fe())===null||n===void 0?void 0:n.name)==="Safari"}function ep(){const n=Fe();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function Oc(){var n,e;return we()?(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 tp(){const n=Fe(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Zt(e,n.osVersion)>=0?!0:n.name==="Safari"&&Zt(e,n.version)>=0}function we(){return typeof document<"u"}function Xe(){return navigator.product=="ReactNative"}function yr(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Dc(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Mc(){if(!Xe())return;let n=Dc();if(n)return n.platform}function Nc(){if(we())return window.devicePixelRatio;if(Xe()){let n=Dc();if(n)return n.devicePixelRatio}return 1}function Zt(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function ip(n){for(const e of n)e.target.handleResize(e)}function np(n){for(const e of n)e.target.handleVisibilityChanged(e)}let br=null;const Lc=()=>(br||(br=new ResizeObserver(ip)),br);let kr=null;const Uc=()=>(kr||(kr=new IntersectionObserver(np,{root:null,rootMargin:"0px"})),kr);function sp(){var n;const e=new Wh({sdk:To.JS,protocol:zf,version:qf});return Xe()&&(e.os=(n=Mc())!==null&&n!==void 0?n:""),e}function jc(){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 a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let cn;function Tr(){if(!cn){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(),[cn]=i.stream.getAudioTracks(),!cn)throw Error("Could not get empty media stream audio track");cn.enabled=!1}return cn.clone()}class Fc{constructor(e,t){this.onFinally=t,this.promise=new Promise((i,s)=>f(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function rp(n){return Wf.includes(n)}function At(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function ap(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Sr(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function op(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:a,endTime:o,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(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function cp(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 $c(n){switch(n.reason){case Z.LeaveRequest:return n.context;case Z.Cancelled:return Le.CLIENT_INITIATED;case Z.NotAllowed:return Le.USER_REJECTED;case Z.ServerUnreachable:return Le.JOIN_FAILURE;default:return Le.UNKNOWN_REASON}}function is(n){return n!==void 0?Number(n):void 0}function Jt(n){return n!==void 0?BigInt(n):void 0}function bi(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function lt(n){return!!n&&n.kind==C.Kind.Audio}function ki(n){return!!n&&n.kind==C.Kind.Video}function Ot(n){return bi(n)&&ki(n)}function Yt(n){return bi(n)&&lt(n)}function Cr(n){return!!n&&!n.isLocal}function dp(n){return!!n&&!n.isLocal}function _r(n){return Cr(n)&&ki(n)}function lp(n){return n.isLocal}function up(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 Bc(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Kc(n??{}),l=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Er(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&&(Er(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function Er(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function wr(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(d=>{switch(d){case"resolution":Er(o,c.resolution);break;default:o[d]=c[d]}}),r.video=a,(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 Vc(n){return f(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=qc();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Ee(t),s.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return i.close(),!c}return!1}()})}function qc(){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=()=>f(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)}(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return t}}function hp(n){return n==="audioinput"?C.Source.Microphone:n==="videoinput"?C.Source.Camera:C.Source.Unknown}function zc(n){return n===C.Source.Microphone?"audioinput":n===C.Source.Camera?"videoinput":void 0}function fp(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,It()?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 ns(n){return n.split("/")[1].toLowerCase()}function pp(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Hs({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function X(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?X(n.track):{})}}function mp(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function gp(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 Kc(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:Ff(e)}}function vp(n){switch(n){case he.CAMERA:return C.Source.Camera;case he.MICROPHONE:return C.Source.Microphone;case he.SCREEN_SHARE:return C.Source.ScreenShare;case he.SCREEN_SHARE_AUDIO:return C.Source.ScreenShareAudio;default:return C.Source.Unknown}}class yp extends Qe.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,s;const{kind:r,data:a}=t.data;switch(r){case"error":K.error(a.error.message),this.emit(Rt.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(Rt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(Rt.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Pt.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{K.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Rt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Lf())throw new or("tried to setup end-to-end encryption on an unsupported browser");if(K.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:Tf.getLevel()}};this.worker&&(K.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){K.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?K.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(R.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(w.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==xe.NONE,s.identity)),e.on(w.ConnectionStateChanged,i=>{i===Q.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==xe.NONE,s.identity)})})}).on(w.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).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(A.LocalTrackPublished,i=>f(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(Pt.SetKey,i=>this.postKey(i)).on(Pt.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}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 a={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(a)}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"?ns(i.mimeType):void 0)}}setupE2EESender(e,t){if(!bi(e)||!t){t||K.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return f(this,void 0,void 0,function*(){if(this.worker){if(ar()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Xn in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(o,[a,r])}e[Xn]=!0}})}handleSender(e,t,i){var s;if(!(Xn 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(ar()){K.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{K.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[r.readable,r.writable])}e[Xn]=!0}}}const Pr="default";class pe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new pe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return f(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=pe.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){K.debug("awaiting getUserMedia promise");try{t?yield pe.userMediaPromiseMap.get(t):yield Promise.all(pe.userMediaPromiseMap.values())}catch{K.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(It()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.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);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,i){return f(this,void 0,void 0,function*(){if(t!==Pr)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Pr);if(!r){K.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Pr&&o.groupId===(i??r.groupId));if(!a){K.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?pe.userMediaPromiseMap.has(e):pe.userMediaPromiseMap.size>0}}pe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],pe.userMediaPromiseMap=new Map;var dn;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(dn||(dn={}));class bp{constructor(){this.pendingTasks=new Map,this.taskMutex=new Se,this.nextTaskIndex=0}run(e){return f(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:dn.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=dn.RUNNING,yield e()}finally{t.status=dn.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return f(this,void 0,void 0,function*(){return this.run(()=>f(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function kp(n,e){const t=new URL(ap(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),Gc(t,"rtc")}function Tp(n){const e=new URL(Sr(n));return Gc(e,"validate")}function Sp(n){return n.endsWith("/")?n:"".concat(n,"/")}function Gc(n,e){return n.pathname="".concat(Sp(n.pathname)).concat(e),n.toString()}const Cp=["syncState","trickle","offer","answer","simulate","leave"];function _p(n){const e=Cp.indexOf(n.case)>=0;return K.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var ne;(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"})(ne||(ne={}));class Rr{get currentState(){return this.state}get isDisconnected(){return this.state===ne.DISCONNECTING||this.state===ne.DISCONNECTED}get isEstablishingConnection(){return this.state===ne.CONNECTING||this.state===ne.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=ne.DISCONNECTED,this.log=K,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=ct((i=t.loggerName)!==null&&i!==void 0?i:je.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new bp,this.queuedRequests=[],this.closingLock=new Se,this.connectionLock=new Se,this.state=ne.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 f(this,void 0,void 0,function*(){return this.state=ne.CONNECTING,this.options=i,yield this.connect(e,t,i,s)})}reconnect(e,t,i,s){return f(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=ne.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}))})}connect(e,t,i,s){this.connectOptions=i;const r=sp(),a=Ep(t,r,i),o=kp(e,a),c=Tp(o);return new Promise((d,l)=>f(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const h=()=>f(this,void 0,void 0,function*(){this.close(),clearTimeout(p),l(new te("room connection has been cancelled (signal)",Z.Cancelled))}),p=setTimeout(()=>{this.close(),l(new te("room connection has timed out (signal)",Z.ServerUnreachable))},i.websocketTimeout);s!=null&&s.aborted&&h(),s==null||s.addEventListener("abort",h);const g=new URL(o);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(p)},this.ws.onerror=m=>f(this,void 0,void 0,function*(){if(this.state!==ne.CONNECTED){this.state=ne.DISCONNECTED,clearTimeout(p);try{const T=yield fetch(c);if(T.status.toFixed(0).startsWith("4")){const k=yield T.text();l(new te(k,Z.NotAllowed,T.status))}else l(new te("Encountered unknown websocket error during connection: ".concat(m.toString()),Z.InternalError,T.status))}catch(T){l(new te(T instanceof Error?T.message:"server was not reachable",Z.ServerUnreachable))}return}this.handleWSError(m)}),this.ws.onmessage=m=>f(this,void 0,void 0,function*(){var T,k,x;let D;if(typeof m.data=="string"){const v=JSON.parse(m.data);D=Po.fromJson(v,{ignoreUnknownFields:!0})}else if(m.data instanceof ArrayBuffer)D=Po.fromBinary(new Uint8Array(m.data));else{this.log.error("could not decode websocket message: ".concat(typeof m.data),this.logContext);return}if(this.state!==ne.CONNECTED){let v=!1;if(((T=D.message)===null||T===void 0?void 0:T.case)==="join"?(this.state=ne.CONNECTED,s==null||s.removeEventListener("abort",h),this.pingTimeoutDuration=D.message.value.pingTimeout,this.pingIntervalDuration=D.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),d(D.message.value)):this.state===ne.RECONNECTING&&D.message.case!=="leave"?(this.state=ne.CONNECTED,s==null||s.removeEventListener("abort",h),this.startPingInterval(),((k=D.message)===null||k===void 0?void 0:k.case)==="reconnect"?d(D.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),d(void 0),v=!0)):this.isEstablishingConnection&&D.message.case==="leave"?l(new te("Received leave request while trying to (re)connect",Z.LeaveRequest,void 0,D.message.value.reason)):i.reconnect||l(new te("did not receive join response, got ".concat((x=D.message)===null||x===void 0?void 0:x.case," instead"),Z.InternalError)),!v)return}this.signalLatency&&(yield Ee(this.signalLatency)),this.handleSignalResponse(D)}),this.ws.onclose=m=>{this.isEstablishingConnection&&l(new te("Websocket got closed during a (re)connection attempt",Z.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:m.reason,code:m.code,wasClean:m.wasClean,state:this.state})),this.handleOnClose(m.reason)}}finally{u()}}))}close(){return f(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.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ne.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const s=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([s,Ee(250)])),e.ws=void 0}}finally{t&&(e.state=ne.DISCONNECTED),i()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ss(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ss(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Gs({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ws({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Ao({requestId:o,metadata:i,name:s,attributes:a})}),o}()})}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 Io({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Mo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:se.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Uo({timestamp:se.parse(Date.now()),rtt:se.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new xo({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new qn({reason:Le.CLIENT_INITIATED,action:pi.DISCONNECT})})}sendRequest(e){return f(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&&!_p(t)&&i.state===ne.RECONNECTING){i.queuedRequests.push(()=>f(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield Ee(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const a=new Jh({message:t});try{i.useJSON?i.ws.send(a.toJsonString()):i.ws.send(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}}()})}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 a=Wc(s.value);this.onAnswer&&this.onAnswer(a)}else if(s.case==="offer"){const a=Wc(s.value);this.onOffer&&this.onOffer(a)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,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):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 f(this,void 0,void 0,function*(){if(this.state===ne.DISCONNECTED)return;const t=this.onClose;yield this.close(),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=ve.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&&ve.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=ve.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ve.clearInterval(this.pingInterval)}}function Wc(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 ss(n){return new Wt({sdp:n.sdp,type:n.type})}function Ep(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",Xe()?"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}var $e={},xr={},Ir={exports:{}},Hc;function Ar(){if(Hc)return Ir.exports;Hc=1;var n=Ir.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")})}),Ir.exports}var Zc;function wp(){return Zc||(Zc=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Ar(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],p=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(p))return i(m,l,p)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.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(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.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}})})}}(xr)),xr}var Or,Jc;function Pp(){if(Jc)return Or;Jc=1;var n=Ar(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.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 Or=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=o.outerOrder||s,d=o.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){l.push(i(u,h,p))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(p){p.name in u&&u[p.name]!=null?l.push(i(h,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(g){l.push(i(h,p,g))})})})}),l.join(`\r
618
+ `);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 Xn(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 es(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(a=>t.apply(this,[a]))})}var Mf=Object.freeze({__proto__:null,removeExtmapAllowMixed:or,shimAddIceCandidateNullOrEmpty:Xn,shimConnectionState:ar,shimMaxMessageSize:Yn,shimParameterlessSetLocalDescription:es,shimRTCIceCandidate:Jn,shimRTCIceCandidateRelayProtocol:rr,shimSendThrowTypeError:Qn});function Nf(){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=Go,i=If(n),s={browserDetails:i,commonShim:Mf,extractVersion:Zn,disableLog:Rf,disableWarnings:xf,sdp:Df};switch(i.browser){case"chrome":if(!rc||!ir||!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=rc,Xn(n,i),es(n),Yo(n,i),Qo(n),ir(n,i),Xo(n),nc(n,i),ec(n),tc(n),sc(n,i),Jn(n),rr(n),ar(n),Yn(n,i),Qn(n),or(n,i);break;case"firefox":if(!gc||!nr||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=gc,Xn(n,i),es(n),ac(n,i),nr(n,i),oc(n),lc(n),cc(n),dc(n),uc(n),hc(n),fc(n),pc(n),mc(n),Jn(n),ar(n),Yn(n,i),Qn(n);break;case"safari":if(!wc||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=wc,Xn(n,i),es(n),Sc(n),_c(n),bc(n),vc(n),yc(n),Cc(n),kc(n),Ec(n),Jn(n),rr(n),Yn(n,i),Qn(n),or(n,i);break;default:t("Unsupported browser!");break}return s}Nf({window:typeof window>"u"?void 0:window});const Lf=10,ts="lk_e2ee",Uf={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Lf,keyringSize:16};var Rt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Rt||(Rt={}));var xc;(function(n){n.KeyRatcheted="keyRatcheted"})(xc||(xc={}));var xt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(xt||(xt={}));var Ic;(function(n){n.Error="cryptorError"})(Ic||(Ic={}));function Ff(){return jf()||cr()}function cr(){return typeof window.RTCRtpScriptTransform<"u"}function jf(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Dm extends Xe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i)=>{K.debug("key ratcheted event received",{material:t,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Uf),e),this.on(Rt.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(Rt.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Rt.RatchetRequest,e,t)}}class It extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var Z;(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"})(Z||(Z={}));class te extends It{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=Z[t]}}class dr extends It{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class lt extends It{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class $f extends It{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class fe extends It{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class lr extends It{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class ur extends It{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Ac extends It{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Qs[t]}}var is;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(is||(is={})),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}(is||(is={}));var Oc;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Oc||(Oc={}));var w;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",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.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 A;(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.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.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage"})(A||(A={}));var R;(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"})(R||(R={}));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.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"})(P||(P={}));function Bf(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const Vf=/version\/(\d+(\.?_?\d+)+)/i;let hr;function $e(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const t=(n??navigator.userAgent).toLowerCase();if(hr===void 0||e){const i=qf.find(s=>{let{test:r}=s;return r.test(t)});hr=i==null?void 0:i.describe(t)}return hr}const qf=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:ns(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:fr(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:ns(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:fr(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:ns(Vf,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:fr(n)}}}];function ns(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 fr(n){return n.includes("mac os")?ns(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var zf="2.11.4";const Kf=zf,Gf=15;class ve{}ve.setTimeout=function(){return setTimeout(...arguments)},ve.setInterval=function(){return setInterval(...arguments)},ve.clearTimeout=function(){return clearTimeout(...arguments)},ve.clearInterval=function(){return clearInterval(...arguments)};const Wf=5e3,an=[];var Ae;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ae||(Ae={}));class C extends Xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=K,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Wf):this.handleAppVisibilityChanged()},this.log=dt((s=i.loggerName)!==null&&s!==void 0?s:je.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),X(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===C.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(an.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&an.splice(an.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),vi(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"?K.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):K.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){yi(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=>{yi(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=dt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),an.forEach(i=>{i.parentElement||(t=!1)}),t&&an.push(e)}}handleAppVisibilityChanged(){return f(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===C.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){we()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){we()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function vi(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)),(!At()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(At()||bi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function yi(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 Le.AUDIO;case e.Video:return Le.VIDEO;default:return Le.DATA}}n.kindToProto=s;function r(d){switch(d){case Le.AUDIO:return e.Audio;case Le.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return he.CAMERA;case t.Microphone:return he.MICROPHONE;case t.ScreenShare:return he.SCREEN_SHARE;case t.ScreenShareAudio:return he.SCREEN_SHARE_AUDIO;default:return he.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case he.CAMERA:return t.Camera;case he.MICROPHONE:return t.Microphone;case he.SCREEN_SHARE:return t.ScreenShare;case he.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case Ks.ACTIVE:return i.Active;case Ks.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(C||(C={}));class ee{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 Hf=["vp8","h264"],Zf=["vp8","h264","vp9","av1"];function Jf(n){return!!Hf.find(e=>e===n)}var Dc;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Dc||(Dc={}));var pr;(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}})(pr||(pr={}));const on={h90:new ee(160,90,9e4,20),h180:new ee(320,180,16e4,20),h216:new ee(384,216,18e4,20),h360:new ee(640,360,45e4,20),h540:new ee(960,540,8e5,25),h720:new ee(1280,720,17e5,30),h1080:new ee(1920,1080,3e6,30),h1440:new ee(2560,1440,5e6,30),h2160:new ee(3840,2160,8e6,30)},mr={h120:new ee(160,120,7e4,20),h180:new ee(240,180,125e3,20),h240:new ee(320,240,14e4,20),h360:new ee(480,360,33e4,20),h480:new ee(640,480,5e5,20),h540:new ee(720,540,6e5,25),h720:new ee(960,720,13e5,30),h1080:new ee(1440,1080,23e5,30),h1440:new ee(1920,1440,38e5,30)},gr={h360fps3:new ee(640,360,2e5,3,"medium"),h360fps15:new ee(640,360,4e5,15,"medium"),h720fps5:new ee(1280,720,8e5,5,"medium"),h720fps15:new ee(1280,720,15e5,15,"medium"),h720fps30:new ee(1280,720,2e6,30,"medium"),h1080fps15:new ee(1920,1080,25e5,15,"medium"),h1080fps30:new ee(1920,1080,5e6,30,"medium"),original:new ee(0,0,7e6,30,"medium")},Yf="|",Mc="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Qf(n){const e=n.split(Yf);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Ee(n){return f(this,void 0,void 0,function*(){return new Promise(e=>ve.setTimeout(e,n))})}function vr(){return"addTransceiver"in RTCPeerConnection.prototype}function yr(){return"addTrack"in RTCPeerConnection.prototype}function Xf(){if(!("getCapabilities"in RTCRtpSender)||At())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function ep(){if(!("getCapabilities"in RTCRtpSender)||bi())return!1;if(At()){const t=$e();if(t!=null&&t.version&&Jt(t.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function cn(n){return n==="av1"||n==="vp9"}function br(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function tp(){return typeof RTCPeerConnection>"u"?!1:vr()||yr()}function bi(){var n;return((n=$e())===null||n===void 0?void 0:n.name)==="Firefox"}function At(){var n;return((n=$e())===null||n===void 0?void 0:n.name)==="Safari"}function ip(){const n=$e();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function Nc(){var n,e;return we()?(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 np(){const n=$e(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Jt(e,n.osVersion)>=0?!0:n.name==="Safari"&&Jt(e,n.version)>=0}function we(){return typeof document<"u"}function et(){return navigator.product=="ReactNative"}function kr(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Lc(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Uc(){if(!et())return;let n=Lc();if(n)return n.platform}function Fc(){if(we())return window.devicePixelRatio;if(et()){let n=Lc();if(n)return n.devicePixelRatio}return 1}function Jt(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function sp(n){for(const e of n)e.target.handleResize(e)}function rp(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Tr=null;const jc=()=>(Tr||(Tr=new ResizeObserver(sp)),Tr);let Sr=null;const $c=()=>(Sr||(Sr=new IntersectionObserver(rp,{root:null,rootMargin:"0px"})),Sr);function ap(){var n;const e=new Zh({sdk:_o.JS,protocol:Gf,version:Kf});return et()&&(e.os=(n=Uc())!==null&&n!==void 0?n:""),e}function Bc(){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 a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let dn;function Cr(){if(!dn){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(),[dn]=i.stream.getAudioTracks(),!dn)throw Error("Could not get empty media stream audio track");dn.enabled=!1}return dn.clone()}class Vc{constructor(e,t){this.onFinally=t,this.promise=new Promise((i,s)=>f(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function op(n){return Zf.includes(n)}function Ot(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function cp(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function _r(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function dp(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:a,endTime:o,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(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function lp(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 qc(n){switch(n.reason){case Z.LeaveRequest:return n.context;case Z.Cancelled:return Ue.CLIENT_INITIATED;case Z.NotAllowed:return Ue.USER_REJECTED;case Z.ServerUnreachable:return Ue.JOIN_FAILURE;default:return Ue.UNKNOWN_REASON}}function ss(n){return n!==void 0?Number(n):void 0}function Yt(n){return n!==void 0?BigInt(n):void 0}function ki(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function ut(n){return!!n&&n.kind==C.Kind.Audio}function Ti(n){return!!n&&n.kind==C.Kind.Video}function Dt(n){return ki(n)&&Ti(n)}function Qt(n){return ki(n)&&ut(n)}function Er(n){return!!n&&!n.isLocal}function up(n){return!!n&&!n.isLocal}function wr(n){return Er(n)&&Ti(n)}function hp(n){return n.isLocal}function fp(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 zc(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Hc(n??{}),l=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Pr(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&&(Pr(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function Pr(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Rr(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(d=>{switch(d){case"resolution":Pr(o,c.resolution);break;default:o[d]=c[d]}}),r.video=a,(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 Kc(n){return f(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=Gc();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Ee(t),s.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return i.close(),!c}return!1}()})}function Gc(){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=()=>f(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)}(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return t}}function pp(n){return n==="audioinput"?C.Source.Microphone:n==="videoinput"?C.Source.Camera:C.Source.Unknown}function Wc(n){return n===C.Source.Microphone?"audioinput":n===C.Source.Camera?"videoinput":void 0}function mp(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,At()?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 rs(n){return n.split("/")[1].toLowerCase()}function gp(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Js({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function X(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?X(n.track):{})}}function vp(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function yp(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 Hc(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:Bf(e)}}function bp(n){switch(n){case he.CAMERA:return C.Source.Camera;case he.MICROPHONE:return C.Source.Microphone;case he.SCREEN_SHARE:return C.Source.ScreenShare;case he.SCREEN_SHARE_AUDIO:return C.Source.ScreenShareAudio;default:return C.Source.Unknown}}class kp extends Xe.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,s;const{kind:r,data:a}=t.data;switch(r){case"error":K.error(a.error.message),this.emit(xt.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(xt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(xt.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Rt.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{K.error("e2ee worker encountered an error:",{error:t.error}),this.emit(xt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Ff())throw new dr("tried to setup end-to-end encryption on an unsupported browser");if(K.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:Cf.getLevel()}};this.worker&&(K.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){K.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?K.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(R.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(w.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==xe.NONE,s.identity)),e.on(w.ConnectionStateChanged,i=>{i===Q.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==xe.NONE,s.identity)})})}).on(w.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).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(A.LocalTrackPublished,i=>f(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(Rt.SetKey,i=>this.postKey(i)).on(Rt.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}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 a={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(a)}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"?rs(i.mimeType):void 0)}}setupE2EESender(e,t){if(!ki(e)||!t){t||K.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return f(this,void 0,void 0,function*(){if(this.worker){if(cr()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(ts in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(o,[a,r])}e[ts]=!0}})}handleSender(e,t,i){var s;if(!(ts 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(cr()){K.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{K.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[r.readable,r.writable])}e[ts]=!0}}}const xr="default";class pe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new pe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return f(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=pe.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){K.debug("awaiting getUserMedia promise");try{t?yield pe.userMediaPromiseMap.get(t):yield Promise.all(pe.userMediaPromiseMap.values())}catch{K.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(At()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.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);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,i){return f(this,void 0,void 0,function*(){if(t!==xr)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===xr);if(!r){K.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==xr&&o.groupId===(i??r.groupId));if(!a){K.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?pe.userMediaPromiseMap.has(e):pe.userMediaPromiseMap.size>0}}pe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],pe.userMediaPromiseMap=new Map;var ln;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(ln||(ln={}));class Tp{constructor(){this.pendingTasks=new Map,this.taskMutex=new Se,this.nextTaskIndex=0}run(e){return f(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ln.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ln.RUNNING,yield e()}finally{t.status=ln.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return f(this,void 0,void 0,function*(){return this.run(()=>f(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function Sp(n,e){const t=new URL(cp(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),Zc(t,"rtc")}function Cp(n){const e=new URL(_r(n));return Zc(e,"validate")}function _p(n){return n.endsWith("/")?n:"".concat(n,"/")}function Zc(n,e){return n.pathname="".concat(_p(n.pathname)).concat(e),n.toString()}const Ep=["syncState","trickle","offer","answer","simulate","leave"];function wp(n){const e=Ep.indexOf(n.case)>=0;return K.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var ne;(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"})(ne||(ne={}));class Ir{get currentState(){return this.state}get isDisconnected(){return this.state===ne.DISCONNECTING||this.state===ne.DISCONNECTED}get isEstablishingConnection(){return this.state===ne.CONNECTING||this.state===ne.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=ne.DISCONNECTED,this.log=K,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=dt((i=t.loggerName)!==null&&i!==void 0?i:je.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Tp,this.queuedRequests=[],this.closingLock=new Se,this.connectionLock=new Se,this.state=ne.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 f(this,void 0,void 0,function*(){return this.state=ne.CONNECTING,this.options=i,yield this.connect(e,t,i,s)})}reconnect(e,t,i,s){return f(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=ne.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}))})}connect(e,t,i,s){this.connectOptions=i;const r=ap(),a=Pp(t,r,i),o=Sp(e,a),c=Cp(o);return new Promise((d,l)=>f(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const h=()=>f(this,void 0,void 0,function*(){this.close(),clearTimeout(p),l(new te("room connection has been cancelled (signal)",Z.Cancelled))}),p=setTimeout(()=>{this.close(),l(new te("room connection has timed out (signal)",Z.ServerUnreachable))},i.websocketTimeout);s!=null&&s.aborted&&h(),s==null||s.addEventListener("abort",h);const g=new URL(o);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(p)},this.ws.onerror=m=>f(this,void 0,void 0,function*(){if(this.state!==ne.CONNECTED){this.state=ne.DISCONNECTED,clearTimeout(p);try{const T=yield fetch(c);if(T.status.toFixed(0).startsWith("4")){const k=yield T.text();l(new te(k,Z.NotAllowed,T.status))}else l(new te("Encountered unknown websocket error during connection: ".concat(m.toString()),Z.InternalError,T.status))}catch(T){l(new te(T instanceof Error?T.message:"server was not reachable",Z.ServerUnreachable))}return}this.handleWSError(m)}),this.ws.onmessage=m=>f(this,void 0,void 0,function*(){var T,k,x;let D;if(typeof m.data=="string"){const v=JSON.parse(m.data);D=Io.fromJson(v,{ignoreUnknownFields:!0})}else if(m.data instanceof ArrayBuffer)D=Io.fromBinary(new Uint8Array(m.data));else{this.log.error("could not decode websocket message: ".concat(typeof m.data),this.logContext);return}if(this.state!==ne.CONNECTED){let v=!1;if(((T=D.message)===null||T===void 0?void 0:T.case)==="join"?(this.state=ne.CONNECTED,s==null||s.removeEventListener("abort",h),this.pingTimeoutDuration=D.message.value.pingTimeout,this.pingIntervalDuration=D.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),d(D.message.value)):this.state===ne.RECONNECTING&&D.message.case!=="leave"?(this.state=ne.CONNECTED,s==null||s.removeEventListener("abort",h),this.startPingInterval(),((k=D.message)===null||k===void 0?void 0:k.case)==="reconnect"?d(D.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),d(void 0),v=!0)):this.isEstablishingConnection&&D.message.case==="leave"?l(new te("Received leave request while trying to (re)connect",Z.LeaveRequest,void 0,D.message.value.reason)):i.reconnect||l(new te("did not receive join response, got ".concat((x=D.message)===null||x===void 0?void 0:x.case," instead"),Z.InternalError)),!v)return}this.signalLatency&&(yield Ee(this.signalLatency)),this.handleSignalResponse(D)}),this.ws.onclose=m=>{this.isEstablishingConnection&&l(new te("Websocket got closed during a (re)connection attempt",Z.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:m.reason,code:m.code,wasClean:m.wasClean,state:this.state})),this.handleOnClose(m.reason)}}finally{u()}}))}close(){return f(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.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ne.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const s=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([s,Ee(250)])),e.ws=void 0}}finally{t&&(e.state=ne.DISCONNECTED),i()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:as(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:as(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Hs({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Zs({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Mo({requestId:o,metadata:i,name:s,attributes:a})}),o}()})}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 Do({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Uo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:se.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new $o({timestamp:se.parse(Date.now()),rtt:se.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Oo({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Kn({reason:Ue.CLIENT_INITIATED,action:mi.DISCONNECT})})}sendRequest(e){return f(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&&!wp(t)&&i.state===ne.RECONNECTING){i.queuedRequests.push(()=>f(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield Ee(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const a=new Qh({message:t});try{i.useJSON?i.ws.send(a.toJsonString()):i.ws.send(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}}()})}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 a=Jc(s.value);this.onAnswer&&this.onAnswer(a)}else if(s.case==="offer"){const a=Jc(s.value);this.onOffer&&this.onOffer(a)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,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):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 f(this,void 0,void 0,function*(){if(this.state===ne.DISCONNECTED)return;const t=this.onClose;yield this.close(),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=ve.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&&ve.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=ve.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ve.clearInterval(this.pingInterval)}}function Jc(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 as(n){return new Ht({sdp:n.sdp,type:n.type})}function Pp(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",et()?"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}var Be={},Ar={},Or={exports:{}},Yc;function Dr(){if(Yc)return Or.exports;Yc=1;var n=Or.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")})}),Or.exports}var Qc;function Rp(){return Qc||(Qc=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Dr(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],p=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(p))return i(m,l,p)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.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(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.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}})})}}(Ar)),Ar}var Mr,Xc;function xp(){if(Xc)return Mr;Xc=1;var n=Dr(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.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 Mr=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=o.outerOrder||s,d=o.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){l.push(i(u,h,p))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(p){p.name in u&&u[p.name]!=null?l.push(i(h,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(g){l.push(i(h,p,g))})})})}),l.join(`\r
619
619
  `)+`\r
620
- `},Or}var Yc;function Rp(){if(Yc)return $e;Yc=1;var n=wp(),e=Pp(),t=Ar();return $e.grammar=t,$e.write=e,$e.parse=n.parse,$e.parseParams=n.parseParams,$e.parseFmtpConfig=n.parseFmtpConfig,$e.parsePayloads=n.parsePayloads,$e.parseRemoteCandidates=n.parseRemoteCandidates,$e.parseImageAttributes=n.parseImageAttributes,$e.parseSimulcastStreamList=n.parseSimulcastStreamList,$e}var Dt=Rp();function Dr(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var p=Date.now()-d;if(p+e>=c)return c-p}return e}var h=function(){var p=[].slice.call(arguments),g=this;return new Promise(function(m,T){var k=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var D=n.apply(g,p);o&&o(D),l.forEach(function(v){return(0,v.resolve)(D)}),l=[]}},u()),k){var x=n.apply(g,p);return o&&o(x),m(x)}l.push({resolve:m,reject:T})})};return h.cancel=function(p){r!==void 0&&clearTimeout(r),l.forEach(function(g){return(0,g.reject)(p)}),l=[]},h}const xp=.7,Ip=20,Ti={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Qc extends Qe.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=K,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Dr(s=>f(this,void 0,void 0,function*(){this.emit(Ti.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Ip),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=ct((i=t.loggerName)!==null&&i!==void 0?i:je.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}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 f(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return f(this,void 0,void 0,function*(){var t;let i;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=Ap(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=Dt.parse((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||r.mid!=a.transceiver.mid)return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;let c=!1;for(const d of r.fmtp)if(d.payload===o){d.config=d.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Dt.write(s)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Ti.NegotiationComplete),e.sdp&&Dt.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Ti.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return f(this,void 0,void 0,function*(){var t;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 r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const s=Dt.parse((t=i.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{ed(r),r.type==="audio"?Xc(r,[],[]):r.type==="video"&&this.trackBitrates.some(a=>{if(!r.msid||!a.cid||!r.msid.includes(a.cid))return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0||(on(a.codec)&&this.ensureVideoDDExtensionForSVC(r,s),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*xp);for(const d of r.fmtp)if(d.payload===o){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(i,Dt.write(s)),this.onOffer(i)})}createAndSetAnswer(){return f(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Dt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{ed(s),s.type==="audio"&&Xc(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Dt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new fe("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 fe("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 f(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(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return f(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 a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new cr(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Ac))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Ac})}}}function Xc(n,e,t){let i=0;n.rtp.some(s=>s.codec==="opus"?(i=s.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(s=>s.payload===i&&s.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(s=>s.payload===i?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Ap(n){var e;const t=[],i=[],s=Dt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===r&&c.type==="nack")&&i.push(a.mid),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function ed(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)}}const Mr="vp8",Op={audioPreset:hr.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:pr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Mr,backupCodec:!0},td={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},id={deviceId:{ideal:"default"},resolution:an.h720.resolution},Dp={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Cf,disconnectOnPageLeave:!0,webAudioMix:!1},Nr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var oe;(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"})(oe||(oe={}));class Mp{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var s;this.peerConnectionTimeout=Nr.peerConnectionTimeout,this.log=K,this.updateState=()=>{var r;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=oe.CONNECTED:o.some(c=>c==="failed")?this.state=oe.FAILED:o.some(c=>c==="connecting")?this.state=oe.CONNECTING:o.every(c=>c==="closed")?this.state=oe.CLOSED:o.some(c=>c==="closed")?this.state=oe.CLOSING:o.every(c=>c==="new")&&(this.state=oe.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(oe[a]," to ").concat(oe[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=ct((s=i.loggerName)!==null&&s!==void 0?s:je.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Qc(e,i),this.subscriber=new Qc(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ue.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ue.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=r=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r)},this.state=oe.NEW,this.connectionLock=new Se,this.remoteOfferLock=new Se}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return f(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return f(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return f(this,void 0,void 0,function*(){t===Ue.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return f(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return f(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 f(this,void 0,void 0,function*(){return new Promise((t,i)=>f(this,void 0,void 0,function*(){const s=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Ti.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Ti.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),i(a)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Ue.PUBLISHER?this.publisher.getConnectedAddress():e===Ue.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>f(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),ve.clearTimeout(u),d(new te("room connection has been cancelled",Z.Cancelled))};s!=null&&s.signal.aborted&&l(),s==null||s.signal.addEventListener("abort",l);const u=ve.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",l),d(new te("could not establish pc connection",Z.InternalError))},a);for(;this.state!==oe.CONNECTED;)if(yield Ee(50),s!=null&&s.signal.aborted){d(new te("room connection has been cancelled",Z.Cancelled));return}ve.clearTimeout(u),s==null||s.signal.removeEventListener("abort",l),c()}))}()})}}class ce extends Error{constructor(e,t,i){super(t),this.code=e,this.message=sd(t,ce.MAX_MESSAGE_BYTES),this.data=i?sd(i,ce.MAX_DATA_BYTES):void 0}static fromProto(e){return new ce(e.code,e.message,e.data)}toProto(){return new yo({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ce(ce.ErrorCode[e],ce.ErrorMessage[e],t)}}ce.MAX_MESSAGE_BYTES=256,ce.MAX_DATA_BYTES=15360,ce.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},ce.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const nd=15360;function Lr(n){return new TextEncoder().encode(n).length}function sd(n,e){if(Lr(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 Ur=2e3;function rs(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 Np=1e3;class rd extends C{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}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=Dr(()=>f(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>f(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 Se,this.pauseUpstreamLock=new Se,this.processorLock=new Se,this.restartLock=new Se,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.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 f(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{vi(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){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(gi(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}finally{r()}}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=>{gi(s??e,r)}))})}waitForDimensions(){return f(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Np;return function*(){var i;if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Fe())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Ee(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Ee(50)}throw new dt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return f(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 f(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===C.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?pe.getInstance().normalizeDeviceId(r,i,s):i}()})}mute(){return f(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return f(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return f(this,void 0,void 0,function*(){if(!this.sender)throw new dt("unable to replace an unpublished track");let i,s;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return f(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=_f(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===C.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(d=>{vi(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return 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 f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Oc()&&(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 f(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=Fe();if((i==null?void 0:i.name)==="Safari"&&Zt(i.version,"12.0")<0)throw new or("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 f(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 f(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 f(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 a=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(gi(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(vi(i._mediaStreamTrack,d),gi(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{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return f(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))}()})}}class as extends rd{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,C.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>f(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=rs(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,Je.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,Je.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return f(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===C.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 f(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===C.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 f(this,void 0,void 0,function*(){let t;if(e){const i=wr({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 f(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){we()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Ur)))}setProcessor(e){return f(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Xe()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());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 f(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 f(this,void 0,void 0,function*(){const e=yield Vc(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}}function Lp(n,e,t){switch(n.kind){case"audio":return new as(n,e,!1,void 0,t);case"video":return new cs(n,e,!1,t);default:throw new dt("unsupported track type: ".concat(n.kind))}}const Up=Object.values(an),jp=Object.values(fr),Fp=Object.values(pr),$p=[an.h180,an.h360],Bp=[fr.h180,fr.h360],Vp=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new ee(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)}),jr=["q","h","f"];function Fr(n,e,t,i){var s,r;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,d=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=zp(n,e,t,d),K.debug("using video encoding",a));const l=a.maxFramerate,u=new ee(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&on(d)){const g=new os(c),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const T=Fe();if(It()||Xe()||(T==null?void 0:T.name)==="Chrome"&&Zt(T==null?void 0:T.version,"113")<0){const k=g.suffix=="h"?2:3;for(let x=0;x<g.spatial;x+=1)m.push({rid:jr[2-x],maxBitrate:a.maxBitrate/Math.pow(k,x),maxFramerate:u.encoding.maxFramerate});m[0].scalabilityMode=c}else m.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(m[0].priority=u.encoding.priority,m[0].networkPriority=u.encoding.priority),K.debug("using svc encoding",{encodings:m}),m}if(!o)return[a];let h=[];n?h=(s=od(i==null?void 0:i.screenShareSimulcastLayers))!==null&&s!==void 0?s:ad(n,u):h=(r=od(i==null?void 0:i.videoSimulcastLayers))!==null&&r!==void 0?r:ad(n,u);let p;if(h.length>0){const g=h[0];h.length>1&&([,p]=h);const m=Math.max(e,t);if(m>=960&&p)return $r(e,t,[g,p,u],l);if(m>=480)return $r(e,t,[g,u],l)}return $r(e,t,[u])}function qp(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&K.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Fr(n.source===C.Source.ScreenShare,c,d,t)}function zp(n,e,t,i){const s=Kp(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":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 Kp(n,e,t){if(n)return Fp;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Up:jp}function ad(n,e){if(n)return Vp(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)?$p:Bp}function $r(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=jr.length)return;const o=Math.min(n,e),d={rid:jr[a],scaleResolutionDownBy:Math.max(1,o/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=yi()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Xe()&&Mc()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,K.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),K.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function od(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 os{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 Gp(n){return n.source===C.Source.ScreenShare||n.constraints.height&&At(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Wp=5e3;class cs extends rd{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,C.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>f(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const a=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((c,d)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(d);o+=rs(c,u)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new Se}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!we())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()},Ur))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return f(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=wt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!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 f(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=wt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!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 f(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===C.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 f(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.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 f(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 a={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},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ae.LOW;i<=Ae.HIGH;i+=1)t.push(new Zs({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return f(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=wr({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o);try{for(var c=!0,d=wt(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.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 f(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,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,p=wt(s.simulcastCodecs.values()),g;g=yield p.next(),a=g.done,!a;h=!0)d=g.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(m){o={error:m}}finally{try{!h&&!a&&(c=p.return)&&(yield c.call(p))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return f(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)},Wp))}setPublishingCodecs(e){return f(this,void 0,void 0,function*(){var t,i,s,r,a,o,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(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=wt(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(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 cd(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e){return f(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield cd(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Oc()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function cd(n,e,t,i,s,r){return f(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:c}=o;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:c,senderEncodings:e}));return}let d=!1;const l=Fe();if((l==null?void 0:l.name)==="Chrome"&&Zt(l==null?void 0:l.version,"133")>0&&c[0].scalabilityMode){const h=c[0],p=new os(h.scalabilityMode);let g=ui.OFF;if(t.forEach(m=>{m.enabled&&(g===ui.OFF||m.quality>g)&&(g=m.quality)}),g===ui.OFF)h.active&&(h.active=!1,d=!0);else if(!h.active||p.spatial!==g+1){d=!0,h.active=!0;const m=new os(e[0].scalabilityMode);p.spatial=g+1,p.suffix=m.suffix,p.spatial===1&&(p.suffix=void 0),h.scalabilityMode=p.toString(),h.scaleResolutionDownBy=Math.pow(2,2-g),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else c.forEach((h,p)=>{var g;let m=(g=h.rid)!==null&&g!==void 0?g:"";m===""&&(m="q");const T=dd(m),k=t.find(x=>x.quality===T);k&&h.active!==k.enabled&&(d=!0,h.active=k.enabled,s.debug("setting layer ".concat(k.quality," to ").concat(h.active?"enabled":"disabled"),r),yi()&&(k.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))});d&&(o.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function dd(n){switch(n){case"f":return Ae.HIGH;case"h":return Ae.MEDIUM;case"q":return Ae.LOW;default:return Ae.HIGH}}function ld(n,e,t,i){if(!t)return[new Gt({quality:Ae.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new os(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new Gt({quality:Math.min(Ae.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=dd((a=s.rid)!==null&&a!==void 0?a:"");return new Gt({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const ud="_lossy",hd="_reliable",Hp=2*1e3,Br="leave-reconnect";var Be;(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"})(Be||(Be={}));class Zp extends Qe.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Nr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Be.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=K,this.handleDataChannel=i=>f(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return function*(){if(a){if(a.label===hd)r.reliableDCSub=a;else if(a.label===ud)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=i=>f(this,void 0,void 0,function*(){var s,r;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=_e.fromBinary(new Uint8Array(o));((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(R.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&Yp(c,c.value.value),this.emit(R.DataPacketReceived,c))}finally{a()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}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?J.LOSSY:J.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(R.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===Br&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ve.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Be.Connected&&i();const r=()=>{this.off(R.Disconnected,a),i()},a=()=>{this.off(R.Restarted,r),s()};this.once(R.Restarted,r),this.once(R.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(R.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ne.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(hi.RR_SIGNAL_DISCONNECTED))},this.log=ct((t=e.loggerName)!==null&&t!==void 0?t:je.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Rr(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Se,this.dataProcessLock=new Se,this.dcBufferStatus=new Map([[J.LOSSY,!0],[J.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(R.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(R.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(R.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(R.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(R.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(R.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(R.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(R.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a,o,c;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:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.sid}}join(e,t,i,s){return f(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,i,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(R.SignalConnected)},10),r}catch(r){if(r instanceof te&&r.reason===Z.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,s);throw r}})}close(){return f(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(R.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return f(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})}cleanupClient(){return f(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new dt("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new te("publication of local track timed out, no response from server",Z.InternalError))},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 f(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return f(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==oe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new Mp(s,e.subscriberPrimary,this.loggerOptions),this.emit(R.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,a)=>{this.client.sendIceCandidate(r,a)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,a,o)=>f(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),r===oe.CONNECTED){const l=this.pcState===Be.New;this.pcState=Be.Connected,l&&this.emit(R.Connected,e)}else r===oe.FAILED&&this.pcState===Be.Connected&&(this.pcState=Be.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?hi.RR_SUBSCRIBER_FAILED:hi.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===ne.RECONNECTING,d=[oe.FAILED,oe.CLOSING,oe.CLOSED].includes(r);c&&d&&!this._isClosed&&this.emit(R.Offline)}),this.pcManager.onTrack=r=>{this.emit(R.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Jp((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>f(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),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=>f(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(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(R.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(R.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(R.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(R.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",hi.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case pi.DISCONNECT:this.emit(R.Disconnected,e==null?void 0:e.reason),this.close();break;case pi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Br);break;case pi.RESUME:this.handleDisconnect(Br)}}}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 a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===tn.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(ud,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(hd,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,i){return f(this,void 0,void 0,function*(){if(mr())return yield this.createTransceiverRTCRtpSender(e,t,i);if(gr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new fe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return f(this,void 0,void 0,function*(){if(mr())return this.createSimulcastTransceiverSender(e,t,i,s);if(gr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new fe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),ki(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 f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return f(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){K.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===tn.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:oe.NEW)===oe.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 a=!0;r instanceof fe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Si||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",hi.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(R.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 f(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new fe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(R.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 Si;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof te&&a.reason===Z.NotAllowed?new fe("could not reconnect, token might be expired"):new Si}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(R.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ne.CONNECTED)throw new Si("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(R.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return f(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new fe("could not reconnect, url or token not saved");if(!this.pcManager)throw new fe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(R.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 te&&s.reason===Z.NotAllowed?new fe("could not reconnect, token might be expired"):s instanceof te&&s.reason===Z.LeaveRequest?s:new Si(r)}if(this.emit(R.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s)}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!==ne.CONNECTED)throw new Si("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(),this.emit(R.Resumed)})}waitForPCInitialConnection(e,t){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return f(this,void 0,void 0,function*(){this.pcState=Be.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ee(Hp),!this.pcManager)throw new fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Be.Connected}catch(e){throw this.pcState=Be.Disconnected,new te("could not establish PC connection, ".concat(e.message),Z.InternalError)}})}publishRpcResponse(e,t,i,s){return f(this,void 0,void 0,function*(){const r=new _e({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcResponse",value:new vo({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,J.RELIABLE)})}publishRpcAck(e,t){return f(this,void 0,void 0,function*(){const i=new _e({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcAck",value:new go({requestId:t})}});yield this.sendDataPacket(i,J.RELIABLE)})}sendDataPacket(e,t){return f(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(i),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,i)=>f(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i("Engine closed");for(this.once(R.Closing,s);!this.dcBufferStatus.get(e);)yield Ee(10);this.off(R.Closing,s),t()}}))}ensureDataTransportConnected(e){return f(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 fe("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw new te("".concat(o," connection not set"),Z.InternalError);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();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(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Ee(50)}throw new te("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),Z.InternalError)}()})}ensurePublisherConnected(e){return f(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==oe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return f(this,void 0,void 0,function*(){return new Promise((e,t)=>f(this,void 0,void 0,function*(){if(!this.pcManager){t(new cr("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("cannot negotiate on closed engine"),this.on(R.Closing,s),this.pcManager.publisher.once(Ti.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();rp(c)&&a.set(o.payload,c)}),this.emit(R.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof cr&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",hi.RR_UNKNOWN),t(r)}finally{this.off(R.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===J.LOSSY)return this.lossyDCSub;if(e===J.RELIABLE)return this.reliableDCSub}else{if(e===J.LOSSY)return this.lossyDC;if(e===J.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(s=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,d=new Array;e.forEach(l=>{l.isDesired!==o&&c.push(l.trackSid),l.isEnabled||d.push(l.trackSid)}),this.client.sendSyncState(new No({answer:r?ss({sdp:r.sdp,type:r.type}):void 0,offer:a?ss({sdp:a.sdp,type:a.type}):void 0,subscription:new Vn({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:pp(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:d}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Lo({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(J.LOSSY),Ue.PUBLISHER),t(this.dataChannelForKind(J.RELIABLE),Ue.PUBLISHER),t(this.dataChannelForKind(J.LOSSY,!0),Ue.SUBSCRIBER),t(this.dataChannelForKind(J.RELIABLE,!0),Ue.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ve.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){we()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){we()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Si extends Error{}function Jp(n){return n!==void 0&&n>13}function Yp(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 Vr{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return yr(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return f(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(s=>s.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),K.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return f(this,void 0,void 0,function*(){const t=yield fetch("".concat(Qp(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new te("Could not fetch region settings: ".concat(t.statusText),t.status===401?Z.NotAllowed:Z.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Qp(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class fd{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Xp extends fd{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;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();return{next:()=>f(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return f(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return f(this,void 0,void 0,function*(){var e,t,i,s;let r=new Set;try{for(var a=!0,o=wt(this),c;c=yield o.next(),e=c.done,!e;a=!0){s=c.value,a=!1;const d=s;r.add(d)}}catch(d){t={error:d}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(r)})}}class em extends fd{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=is(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;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;return{next:()=>f(this,void 0,void 0,function*(){try{const{done:i,value:s}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(s),{done:!1,value:t.decode(s.content)})}catch{return{done:!0,value:void 0}}}),return(){return f(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return f(this,void 0,void 0,function*(){var e,t,i,s;let r="";try{for(var a=!0,o=wt(this),c;c=yield o.next(),e=c.done,!e;a=!0)s=c.value,a=!1,r+=s}catch(d){t={error:d}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return r})}}class pd{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 f(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 tm extends pd{}class im extends pd{}class md extends C{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 f(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(),Ur)),mp()&&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 nm extends md{constructor(e,t,i,s,r,a){super(e,t,C.Kind.Audio,i,a),this.monitorReceiver=()=>f(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=rs(o,this.prevStats)),this.prevStats=o}),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;Xe()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Xe())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return f(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(vr(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&vr(e)&&e.setSinkId(this.sinkId),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 f(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 qr=100;class sm extends md{constructor(e,t,i,s,r){super(e,t,C.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>f(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=rs(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Dr(()=>{this.updateDimensions()},qr),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?vi(this._mediaStreamTrack,t):gi(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 rm(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 f(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 f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),s=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!s||r;if(this.lastVisible!==a){if(!a&&Date.now()-i<qr){ve.setTimeout(()=>{this.updateVisibility()},qr);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 a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,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"?Nc():t||(Nc()>2?2:1)}}class rm{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=ln(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=ln(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=ln(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??zr(e),this.isPiP=we()&&ln(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=zr(this.element),this.isPiP=ln(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Uc().observe(this.element),Lc().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=Uc())===null||e===void 0||e.unobserve(this.element),(t=Lc())===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 ln(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?zr(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function zr(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=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+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class ut extends Qe.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=xe.NONE,this.log=K,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=ct((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:je.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.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)),X(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==xe.NONE}get audioTrack(){if(lt(this.track))return this.track}get videoTrack(){if(ki(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.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={}))})(ut||(ut={}));class Kr extends ut{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.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(P.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(P.Ended,this.handleTrackEnded)}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 f(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return f(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return f(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return f(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(lt(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Je.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Je.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Je.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Je.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Je.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Je.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ds(n,e){return f(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Kc(n);let a=r.audio,o=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,a=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,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(r.video===!0||typeof r.video=="object"&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=Bc(r,td,id),d=wr(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(pe.userMediaPromiseMap.set("audioinput",l),l.catch(()=>pe.userMediaPromiseMap.delete("audioinput"))),r.video&&(pe.userMediaPromiseMap.set("videoinput",l),l.catch(()=>pe.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>f(this,void 0,void 0,function*(){const p=h.kind==="audio";let g=p?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let m;const T=p?d.audio:d.video;typeof T!="boolean"&&(m=T);const k=h.getSettings().deviceId;m!=null&&m.deviceId&&At(m.deviceId)!==k?m.deviceId=k:m||(m={deviceId:k});const x=Lp(h,m,e);return x.kind===C.Kind.Video?x.source=C.Source.Camera:x.kind===C.Kind.Audio&&(x.source=C.Source.Microphone),x.mediaStream=u,lt(x)&&i?yield x.setProcessor(i):ki(x)&&s&&(yield x.setProcessor(s)),x})))}catch(u){if(!t)throw u;return ds(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function am(n){return f(this,void 0,void 0,function*(){return(yield ds({audio:!1,video:n??!0}))[0]})}function om(n){return f(this,void 0,void 0,function*(){return(yield ds({audio:n??!0,video:!1}))[0]})}var Mt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Mt||(Mt={}));function cm(n){switch(n){case en.EXCELLENT:return Mt.Excellent;case en.GOOD:return Mt.Good;case en.POOR:return Mt.Poor;case en.LOST:return Mt.Lost;default:return Mt.Unknown}}class gd extends Qe.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===Bn.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Bn.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Mt.Unknown,this.log=K,this.log=ct((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:je.Participant),this.loggerOptions=a,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=o,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}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(C.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){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.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(A.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(A.ParticipantNameChanged,e)}_setAttributes(e){const t=gp(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(A.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;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!==((a=this.permissions)===null||a===void 0?void 0:a.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!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(A.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(A.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=cm(e),t!==this._connectionQuality&&this.emit(A.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>lt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(P.Muted,()=>{this.emit(A.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(A.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function dm(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 Do({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||[]})}const vd=15e3;class lm extends gd{constructor(e,t,i,s,r){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=xe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Fc)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(c=>this.log.warn(c.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:c,message:d}=a,l=this.pendingSignalRequests.get(o);l&&(c!==Js.OK&&l.reject(new Rc(d,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,d=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(d=ce.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,d);break;case"rpcAck":let l=a.value.value;this.handleIncomingRpcAck(l.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=>dm(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),X(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>f(this,void 0,void 0,function*(){var o,c,d,l,u,h;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const p=this.videoTrackPublications.get(a.trackSid);if(!p){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!p.videoTrack)return;const k=yield p.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var g=!0,m=wt(k),T;T=yield m.next(),o=T.done,!o;g=!0){l=T.value,g=!1;const x=l;Hf(x)&&(this.log.debug("publish ".concat(x," for ").concat(p.videoTrack.sid),Object.assign(Object.assign({},this.logContext),X(p))),yield this.publishAdditionalCodecForTrack(p.videoTrack,x,p.options))}}catch(x){c={error:x}}finally{try{!g&&!o&&(d=m.return)&&(yield d.call(m))}finally{if(c)throw c.error}}}else a.subscribedQualities.length>0&&(yield(h=p.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>f(this,void 0,void 0,function*(){if(a.source===C.Source.ScreenShare||a.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),X(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Yt(a)||Ot(a))try{if(we())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===C.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),X(a))),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.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),X(a))),Yt(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),X(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}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==xe.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){this.engine=e,this.engine.on(R.RemoteMute,(t,i)=>{const s=this.trackPublications.get(t);!s||!s.track||(i?s.mute():s.unmute())}),this.engine.on(R.Connected,this.handleReconnected).on(R.SignalRestarted,this.handleReconnected).on(R.SignalResumed,this.handleReconnected).on(R.Restarting,this.handleReconnecting).on(R.Resuming,this.handleReconnecting).on(R.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(R.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(R.Disconnected,this.handleDisconnected).on(R.SignalRequestResponse,this.handleSignalRequestResponse).on(R.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return f(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return f(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return f(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return f(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return function*(){return new Promise((o,c)=>f(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:"",a),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-p<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(g=>{let[m,T]=g;return this.attributes[m]===T||T===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),o();return}yield Ee(50)}c(new Rc("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(C.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(C.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(A.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return f(this,void 0,void 0,function*(){this.encryptionType=e?xe.GCM:xe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return f(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.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 C.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new dt(e)}}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(A.MediaDevicesError,d),this.pendingPublishing.delete(e),d}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),X(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return f(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.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(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return f(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Bc(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 ds(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(lt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(A.AudioStreamAcquired)),ki(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return f(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new or("getDisplayMedia not supported");e.resolution===void 0&&!ep()&&(e.resolution=pr.h1080fps30.resolution);const t=fp(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new dt("no video track found");const r=new cs(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(A.AudioStreamAcquired);const o=new as(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return f(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,d,l;Yt(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),bi(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let k;switch(i.source){case C.Source.Microphone:k="audioinput";break;case C.Source.Camera:k="videoinput"}k&&r.activeDeviceMap.has(k)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(k)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new as(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new cs(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new dt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(k=>{k.track&&k.track===i&&(h=k)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),X(h))),h;const p="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=s==null?void 0:s.forceStereo)!==null&&c!==void 0?c:p;g&&(s||(s={}),s.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),X(i))),s.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=s.dtx)!==null&&d!==void 0||(s.dtx=!1),(l=s.red)!==null&&l!==void 0||(s.red=!1));const m=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s);!tp()&&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)),m.simulcast=!1),m.source&&(i.source=m.source);const T=new Promise((k,x)=>f(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ne.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:X(i)}));const D=()=>f(this,void 0,void 0,function*(){try{const v=yield this.publish(i,m,g);k(v)}catch(v){x(v)}});setTimeout(()=>{this.engine.off(R.SignalConnected,D),x(new dr("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(R.SignalConnected,D),this.engine.on(R.Closing,()=>{this.engine.off(R.SignalConnected,D),x(new dr("publishing rejected as engine closed",499))})}else try{const D=yield this.publish(i,m,g);k(D)}catch(D){x(D)}}catch(D){x(D)}}));r.pendingPublishPromises.set(i,T);try{return yield T}catch(k){throw k}finally{r.pendingPublishPromises.delete(i)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),X(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>vp(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),X(e))),!1)}publish(e,t,i){return f(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(e))throw new dr("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(y=>bi(e)&&y.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),X(e))),t.stopMicTrackOnMute&&lt(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&yi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Yf()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Qf()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Mr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(y=>t.videoCodec===ns(y.mime))||(t.videoCodec=ns(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 T=new Ks({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:!(!((s=t.dtx)!==null&&s!==void 0)||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});let k;if(e.kind===C.Kind.Video){let y={width:0,height:0};try{y=yield e.waitForDimensions()}catch{const M=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:an.h720.resolution;y={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{dims:y}))}T.width=y.width,T.height=y.height,Ot(e)&&(on(m)&&(e.source===C.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),X(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),T.simulcastCodecs=[new zs({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Mr}),t.backupCodec&&m!==t.backupCodec.codec&&T.encryption===xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),T.simulcastCodecs.push(new zs({codec:t.backupCodec.codec,cid:""})))),k=Fr(e.source===C.Source.ScreenShare,T.width,T.height,t),T.layers=ld(T.width,T.height,k,on(t.videoCodec))}else e.kind===C.Kind.Audio&&(k=[{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:(p=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new fe("cannot publish track when not connected");const x=()=>f(this,void 0,void 0,function*(){var y,E,M;if(!this.engine.pcManager)throw new fe("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,k),Ot(e)&&((y=t.degradationPreference)!==null&&y!==void 0||(t.degradationPreference=Gp(e)),e.setDegradationPreference(t.degradationPreference)),k)if(yi()&&e.kind===C.Kind.Audio){let U;for(const G of this.engine.pcManager.publisher.getTransceivers())if(G.sender===e.sender){U=G;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((E=k[0])===null||E===void 0)&&E.maxBitrate?k[0].maxBitrate/1e3:0})}else e.codec&&on(e.codec)&&(!((M=k[0])===null||M===void 0)&&M.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:T.cid,codec:e.codec,maxbr:k[0].maxBitrate/1e3});yield this.engine.negotiate()});let D;if(this.enabledPublishVideoCodecs.length>0)D=(yield Promise.all([this.engine.addTrack(T),x()]))[0];else{D=yield this.engine.addTrack(T);let y;if(D.codecs.forEach(E=>{y===void 0&&(y=E.mimeType)}),y&&e.kind===C.Kind.Video){const E=ns(y);E!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{codec:E})),t.videoCodec=E,k=Fr(e.source===C.Source.ScreenShare,T.width,T.height,t))}yield x()}const v=new Kr(e.kind,D,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return v.options=t,e.sid=D.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:k,trackInfo:D})),Ot(e)?e.startMonitor(this.engine.client):Yt(e)&&e.startMonitor(),this.addTrackPublication(v),this.emit(A.LocalTrackPublished,v),v})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return f(this,void 0,void 0,function*(){var s;if(this.encryptionType!==xe.NONE)return;let r;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(r=p)}),!r)throw new dt("track is not published");if(!Ot(e))throw new dt("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=qp(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),X(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Ks({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ld(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new fe("cannot publish track when not connected");const l=()=>f(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),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:o,trackInfo:h}))})}unpublishTrack(e,t){return f(this,void 0,void 0,function*(){var i,s;if(bi(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),X(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?X(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));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 o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<oe.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Ot(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!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),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(A.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return f(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return f(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 Promise((r,a)=>f(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>f(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==C.Source.ScreenShare&&d.source!==C.Source.ScreenShareAudio&&(Yt(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(o){a(o)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return f(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?J.RELIABLE:J.LOSSY,a=s.destinationIdentities,o=s.topic,c=new _e({kind:r,value:{case:"user",value:new fo({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(c,r)}()})}publishDtmf(e,t){return f(this,void 0,void 0,function*(){const i=new _e({kind:J.RELIABLE,value:{case:"sipDtmf",value:new po({code:e,digit:t})}});yield this.engine.sendDataPacket(i,J.RELIABLE)})}sendChatMessage(e,t){return f(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 _e({value:{case:"chatMessage",value:new js(Object.assign(Object.assign({},i),{timestamp:se.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,J.RELIABLE),this.emit(A.ChatMessage,i),i})}editChatMessage(e,t){return f(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new _e({value:{case:"chatMessage",value:new js(Object.assign(Object.assign({},i),{timestamp:se.parse(i.timestamp),editTimestamp:se.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,J.RELIABLE),this.emit(A.ChatMessage,i),i})}sendText(e,t){return f(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var p;c[h]=u;const g=c.reduce((m,T)=>m+T,0);(p=t==null?void 0:t.onProgress)===null||p===void 0||p.call(t,g)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield l.write(e),d(1,0),yield l.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>f(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:p=>{d(p,h+1)}})})))),l.info})}streamText(e){return f(this,void 0,void 0,function*(){var t,i;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:s,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},a=new $s({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Jt(r.timestamp),totalLength:Jt(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Eo({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"?Fs.UPDATE:Fs.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new _e({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,J.RELIABLE);let d=0;const l=this,u=new WritableStream({write(g){return f(this,void 0,void 0,function*(){for(const m of up(g,vd)){yield l.engine.waitForBufferStatusLow(J.RELIABLE);const T=new Bs({content:m,streamId:s,chunkIndex:Jt(d)}),k=new _e({destinationIdentities:o,value:{case:"streamChunk",value:T}});yield l.engine.sendDataPacket(k,J.RELIABLE),d+=1}})},close(){return f(this,void 0,void 0,function*(){const g=new Vs({streamId:s}),m=new _e({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield l.engine.sendDataPacket(m,J.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>f(this,void 0,void 0,function*(){yield p.close()});l.engine.once(R.Closing,h);const p=new tm(u,r,()=>this.engine.off(R.Closing,h));return p})}sendFile(e,t){return f(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return f(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}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return f(this,void 0,void 0,function*(){var t,i,s,r,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,d={id:o,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"},l=new $s({totalLength:Jt((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:o,topic:d.topic,timestamp:Jt(Date.now()),contentHeader:{case:"byteHeader",value:new wo({name:d.name})}}),u=new _e({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,J.RELIABLE);let h=0;const p=new Se,g=this.engine,m=this.log,T=new WritableStream({write(x){return f(this,void 0,void 0,function*(){const D=yield p.lock();let v=0;try{for(;v<x.byteLength;){const y=x.slice(v,v+vd);yield g.waitForBufferStatusLow(J.RELIABLE);const E=new _e({destinationIdentities:c,value:{case:"streamChunk",value:new Bs({content:y,streamId:o,chunkIndex:Jt(h)})}});yield g.sendDataPacket(E,J.RELIABLE),h+=1,v+=y.byteLength}}finally{D()}})},close(){return f(this,void 0,void 0,function*(){const x=new Vs({streamId:o}),D=new _e({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield g.sendDataPacket(D,J.RELIABLE)})},abort(x){m.error("Sink error:",x)}});return new im(T,d)})}performRpc(e){return f(this,arguments,void 0,function(t){var i=this;let{destinationIdentity:s,method:r,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((d,l)=>f(i,void 0,void 0,function*(){var u,h,p,g;if(Lr(a)>nd){l(ce.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Zt((g=(p=this.engine.latestJoinResponse)===null||p===void 0?void 0:p.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){l(ce.builtIn("UNSUPPORTED_SERVER"));return}const m=crypto.randomUUID();yield this.publishRpcRequest(s,m,r,a,o-2e3);const T=setTimeout(()=>{this.pendingAcks.delete(m),l(ce.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(m),clearTimeout(k)},2e3);this.pendingAcks.set(m,{resolve:()=>{clearTimeout(T)},participantIdentity:s});const k=setTimeout(()=>{this.pendingResponses.delete(m),l(ce.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(m,{resolve:(x,D)=>{clearTimeout(k),this.pendingAcks.has(m)&&(console.warn("RPC response received before ack",m),this.pendingAcks.delete(m),clearTimeout(T)),D?l(D):d(x??"")},participantIdentity:s})}))}()})}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 f(this,void 0,void 0,function*(){const a=new _e({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcRequest",value:new mo({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,J.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,ce.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),X(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(Yt(s)||Ot(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return f(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[a]=r;return a.source===e});if(s)return s[1];yield Ee(20)}})}}class um extends ut{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ae.HIGH,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.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=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 Vn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new bo({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?ut.SubscriptionStatus.Unsubscribed:super.isSubscribed?ut.SubscriptionStatus.Subscribed:ut.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ut.PermissionStatus.Allowed:ut.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(_r(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&_r(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}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.kind===C.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return _r(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ro({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Ae.HIGH,this.emit(P.UpdateSettings,e)}}class ls extends gd{static fromParticipantInfo(e,t,i){return new ls(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,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Bn.STANDARD;super(t,i||"",s,r,a,o,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({},this.logContext),X(e))),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(A.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(A.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(A.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(A.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(A.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]:C.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]:C.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(A.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-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),X(o))),this.emit(A.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new sm(e,t,s,r):d=new nm(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&Cr(d)&&lt(d)&&d.setVolume(this.volumeMap.get(o.source)),o}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,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=C.kindFromProto(s.type);if(!c)return;o=new um(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));d&&o.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:X(d),newTrack:X(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),X(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(A.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 C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(A.TrackUnpublished,i)}setAudioOutput(e){return f(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;lt(i.track)&&Cr(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 Q;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Q||(Q={}));const hm=4*1e3;class Ci extends Qe.EventEmitter{constructor(e){var t,i,s,r;if(super(),t=this,this.state=Q.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=K,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(a,o,c)=>f(this,void 0,void 0,function*(){var d;if(!Xf())throw Xe()?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 l=yield this.disconnectLock.lock();if(this.state===Q.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(Q.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),yr(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Vr(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(p=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const u=(p,g,m)=>f(this,void 0,void 0,function*(){var T,k;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,l==null||l();try{yield this.attemptConnection(m??a,o,c,x),this.abortController=void 0,p()}catch(D){if(this.regionUrlProvider&&D instanceof te&&D.reason!==Z.Cancelled&&D.reason!==Z.NotAllowed){let v=null;try{v=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(y){if(y instanceof te&&(y.status===401||y.reason===Z.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(y);return}}v&&!(!((k=this.abortController)===null||k===void 0)&&k.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(D.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield u(p,g,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,$c(D)),g(D))}else{let v=Le.UNKNOWN_REASON;D instanceof te&&(v=$c(D)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),g(D)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Fc((p,g)=>{u(p,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,d,l,u)=>f(this,void 0,void 0,function*(){var h,p,g;const m=yield c.join(a,o,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},u.signal);let T=m.serverInfo;if(T||(T={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(k=>{let[x,D]=k;return"".concat(x,": ").concat(D)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(p=m.room)===null||p===void 0?void 0:p.sid,identity:(g=m.participant)===null||g===void 0?void 0:g.identity}),!T.version)throw new jf("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),m}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,d)=>f(this,void 0,void 0,function*(){var l,u;this.state===Q.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Nr),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const p=new te("could not establish signal connection",Z.ServerUnreachable);throw h instanceof Error&&(p.message="".concat(p.message,": ").concat(h.message)),h instanceof te&&(p.reason=h.reason,p.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),p}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new te("Connection attempt aborted",Z.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}we()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),we()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Q.Connected),this.emit(w.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return f(t,[...o],void 0,function(){var d=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,h,p,g;const m=yield d.disconnectLock.lock();try{if(d.state===Q.Disconnected){d.log.debug("already disconnected",d.logContext);return}d.log.info("disconnect from room",Object.assign({},d.logContext)),(d.state===Q.Connecting||d.state===Q.Reconnecting||d.isResuming)&&(d.log.warn("abort connection attempt",d.logContext),(u=d.abortController)===null||u===void 0||u.abort(),(p=(h=d.connectFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,new te("Client initiated disconnect",Z.Cancelled)),d.connectFuture=void 0),!((g=d.engine)===null||g===void 0)&&g.client.isDisconnected||(yield d.engine.client.sendLeave()),d.engine&&(yield d.engine.close()),d.handleDisconnect(l,Le.CLIENT_INITIATED),d.engine=void 0}finally{m()}}()})},this.onPageLeave=()=>f(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>f(this,void 0,void 0,function*(){const a=[],o=Fe();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let d=document.getElementById(c);if(!d){d=document.createElement("audio"),d.id=c,d.autoplay=!0,d.hidden=!0;const l=Tr();l.enabled=!0;const u=new MediaStream([l]);d.srcObject=u,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(w.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(l=>{a.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>f(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var d;(d=c.track)===null||d===void 0||d.attachedElements.forEach(l=>{a.includes(l)||a.push(l)})});yield Promise.all(a.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.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(Q.Reconnecting)&&this.emit(w.Reconnecting)},this.handleSignalRestarted=a=>f(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(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}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(Q.Connected),this.emit(w.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let d=this.remoteParticipants.get(o.identity);o.state===Us.DISCONNECTED?this.handleParticipantDisconnected(o.identity,d):d=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(d=>{if(c[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(d.sid);l&&(l.audioLevel=d.level,l.setIsSpeaking(!0),o.push(l))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{c[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(w.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(d=>{const l=this.remoteParticipants.get(d.identity);l&&l.sid!==d.sid||o.set(d.sid,d)}),a.forEach(d=>{let l=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=d.level,l.setIsSpeaking(d.active),d.active?o.set(d.sid,l):o.delete(d.sid))});const c=Array.from(o.values());c.sort((d,l)=>l.audioLevel-d.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(w.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);if(!d||!d.track)return;const l=C.streamStateFromProto(o.state);l!==d.track.streamState&&(d.track.streamState=l,c.emit(A.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(w.TrackStreamStateChanged,d,d.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);else if(a.value.case==="rpcRequest"){const c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(w.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(A.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(w.SipDTMFReceived,o,a),a==null||a.emit(A.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),d=c==null?void 0:c.trackPublications.get(o.trackId),l=op(o,this.transcriptionReceivedTimes);d==null||d.emit(P.TranscriptionReceived,l),c==null||c.emit(A.TranscriptionReceived,l,d),this.emit(w.TranscriptionReceived,l,c,d)},this.handleChatMessage=(a,o)=>{const c=cp(o);this.emit(w.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(w.MetricsReceived,a,o)},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=()=>f(this,void 0,void 0,function*(){var a,o,c;const d=pe.getInstance().previousDevices,l=yield pe.getInstance().getDevices(void 0,!1),u=Fe();if((u==null?void 0:u.name)==="Chrome"&&u.os!=="iOS")for(let p of l){const g=d.find(m=>m.deviceId===p.deviceId);g&&g.label!==""&&g.kind===p.kind&&g.label!==p.label&&this.getActiveDevice(p.kind)==="default"&&this.emit(w.ActiveDeviceChanged,p.kind,p.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let p of h){const g=hp(p),m=this.localParticipant.getTrackPublication(g);if(m&&(!((a=m.track)===null||a===void 0)&&a.isUserProvided))continue;const T=l.filter(x=>x.kind===p),k=this.getActiveDevice(p);if(k===((o=d.filter(x=>x.kind===p)[0])===null||o===void 0?void 0:o.deviceId)&&T.length>0&&((c=T[0])===null||c===void 0?void 0:c.deviceId)!==k){yield this.switchActiveDevice(p,T[0].deviceId);continue}p==="audioinput"&&!It()||p==="videoinput"||T.length>0&&!T.find(x=>x.deviceId===this.getActiveDevice(p))&&(yield this.switchActiveDevice(p,T[0].deviceId))}this.emit(w.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(w.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(w.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.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 o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>f(this,void 0,void 0,function*(){var o,c,d,l,u,h;(o=a.track)===null||o===void 0||o.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(P.Restarted,this.onLocalTrackRestarted),(u=(l=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||u===void 0||u.call(l,this),this.emit(w.LocalTrackPublished,a,this.localParticipant),Yt(a.track)&&(yield a.track.checkForSilence())&&this.emit(w.LocalAudioSilenceDetected,a);const p=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=zc(a.source);g&&p&&p!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,p),this.emit(w.ActiveDeviceChanged,g,p))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(P.Restarted,this.onLocalTrackRestarted),this.emit(w.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>f(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=zc(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(w.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(w.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(w.MediaDevicesError,a)},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({},Dp),e),this.log=ct((i=this.options.loggerName)!==null&&i!==void 0?i:je.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},td),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},id),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Op),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Se,this.localParticipant=new lm("","",this.engine,this.options,this.rpcHandlers),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)),this.options.e2ee&&this.setupE2EE(),we()){const a=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Ci.cleanupRegistry&&Ci.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(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)}handleIncomingRpcRequest(e,t,i,s,r,a){return f(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ce.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ce.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Lr(l)>nd?(c=ce.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ce?c=l:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ce.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}setE2EEEnabled(e){return f(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new yp(this.options.e2ee),this.e2eeManager.on(Rt.ParticipantEncryptionStatusChanged,(t,i)=>{lp(i)&&(this.isE2EEEnabled=t),this.emit(w.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(Rt.EncryptionError,t=>this.emit(w.EncryptionError,t)),(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 f(this,void 0,void 0,function*(){return this.state===Q.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(R.RoomUpdate,i),e(s.sid))};this.engine.on(R.RoomUpdate,i),this.once(w.Disconnected,()=>{this.engine.off(R.RoomUpdate,i),t("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 Zp(this.options),this.engine.on(R.ParticipantUpdate,this.handleParticipantUpdates).on(R.RoomUpdate,this.handleRoomUpdate).on(R.SpeakersChanged,this.handleSpeakersChanged).on(R.StreamStateChanged,this.handleStreamStateUpdate).on(R.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(R.SubscriptionError,this.handleSubscriptionError).on(R.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(R.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(R.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(R.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(R.DataPacketReceived,this.handleDataPacket).on(R.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Q.SignalReconnecting)&&this.emit(w.SignalReconnecting)}).on(R.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Q.Connected)&&this.emit(w.Reconnected)}).on(R.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Q.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(R.Restarting,this.handleRestarting).on(R.SignalRestarted,this.handleSignalRestarted).on(R.Offline,()=>{this.setAndEmitConnectionState(Q.Reconnecting)&&this.emit(w.Reconnecting)}).on(R.DCBufferStatusChanged,(e,t)=>{this.emit(w.DCBufferStatusChanged,e,t)}).on(R.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(A.LocalTrackSubscribed,t),this.emitWhenConnected(w.LocalTrackSubscribed,t,this.localParticipant)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return f(this,void 0,void 0,function*(){if(this.state===Q.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(yr(new URL(e))&&t){this.regionUrlProvider=new Vr(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Q.Disconnected&&(this.regionUrl=i,yield fetch(Sr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Sr(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 f(this,void 0,void 0,function*(){let i=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Ye({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ye({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ye({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ye({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=()=>f(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ye({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>f(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ye({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 Ye({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>f(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new qn({reason:Le.CLIENT_INITIATED,action:pi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ye({scenario:{case:"subscriberBandwidth",value:Jt(t)}});break;case"leave-full-reconnect":s=new Ye({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 f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,c,d,l,u,h,p,g;let m=!0,T=!1;const k=a?{exact:s}:s;if(i==="audioinput"){T=r.localParticipant.audioTrackPublications.size===0;const x=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=k;const D=Array.from(r.localParticipant.audioTrackPublications.values()).filter(v=>v.source===C.Source.Microphone);try{m=(yield Promise.all(D.map(v=>{var y;return(y=v.audioTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(v=>v===!0)}catch(v){throw r.options.audioCaptureDefaults.deviceId=x,v}}else if(i==="videoinput"){T=r.localParticipant.videoTrackPublications.size===0;const x=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=k;const D=Array.from(r.localParticipant.videoTrackPublications.values()).filter(v=>v.source===C.Source.Camera);try{m=(yield Promise.all(D.map(v=>{var y;return(y=v.videoTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(v=>v===!0)}catch(v){throw r.options.videoCaptureDefaults.deviceId=x,v}}else if(i==="audiooutput"){if(!vr()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(s=(d=yield pe.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(g=r.options).audioOutput)!==null&&l!==void 0||(g.audioOutput={});const x=(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(D=>D.setAudioOutput({deviceId:s})))}catch(D){throw r.options.audioOutput.deviceId=x,D}}return(T||i==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(i,i==="audiooutput"&&((p=r.options.audioOutput)===null||p===void 0?void 0:p.deviceId)||s),r.emit(w.ActiveDeviceChanged,i,s)),m}()})}setupLocalParticipantEvents(){this.localParticipant.on(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(A.AttributesChanged,this.onLocalAttributesChanged).on(A.TrackMuted,this.onLocalTrackMuted).on(A.TrackUnmuted,this.onLocalTrackUnmuted).on(A.LocalTrackPublished,this.onLocalTrackPublished).on(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(A.MediaDevicesError,this.onMediaDevicesError).on(A.AudioStreamAcquired,this.startAudio).on(A.ChatMessage,this.onLocalChatMessageSent).on(A.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===Q.Connecting||this.state===Q.Reconnecting){const l=()=>{this.onTrackAdded(e,t,i),u()},u=()=>{this.off(w.Reconnected,l),this.off(w.Connected,l),this.off(w.Disconnected,u)};this.once(w.Reconnected,l),this.once(w.Connected,l),this.once(w.Disconnected,u);return}if(this.state===Q.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=Jf(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),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(l=>l.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}let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={}),c.addSubscribedMediaTrack(e,o,t,i,d)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Q.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var r,a,o;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((r=s.track)===null||r===void 0||r.detach(),(a=s.track)===null||a===void 0||a.stop()):(o=s.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(A.AttributesChanged,this.onLocalAttributesChanged).off(A.TrackMuted,this.onLocalTrackMuted).off(A.TrackUnmuted,this.onLocalTrackUnmuted).off(A.LocalTrackPublished,this.onLocalTrackPublished).off(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(A.MediaDevicesError,this.onMediaDevicesError).off(A.AudioStreamAcquired,this.startAudio).off(A.ChatMessage,this.onLocalChatMessageSent).off(A.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),we()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Q.Disconnected),this.emit(w.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(w.ParticipantDisconnected,t),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return f(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:is(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{r=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now()})}});s(new Xp(a,o,is(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{r=c,this.textStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now()})}});s(new em(a,o,is(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return f(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=qc())!==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(),Ee(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=ls.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new ls(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(A.TrackPublished,s=>{this.emitWhenConnected(w.TrackPublished,s,i)}).on(A.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio?(s.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.Kind.Video&&(s.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(w.TrackSubscribed,s,r,i)}).on(A.TrackUnpublished,s=>{this.emit(w.TrackUnpublished,s,i)}).on(A.TrackUnsubscribed,(s,r)=>{this.emit(w.TrackUnsubscribed,s,r,i)}).on(A.TrackMuted,s=>{this.emitWhenConnected(w.TrackMuted,s,i)}).on(A.TrackUnmuted,s=>{this.emitWhenConnected(w.TrackUnmuted,s,i)}).on(A.ParticipantMetadataChanged,s=>{this.emitWhenConnected(w.ParticipantMetadataChanged,s,i)}).on(A.ParticipantNameChanged,s=>{this.emitWhenConnected(w.ParticipantNameChanged,s,i)}).on(A.AttributesChanged,s=>{this.emitWhenConnected(w.ParticipantAttributesChanged,s,i)}).on(A.ConnectionQualityChanged,s=>{this.emitWhenConnected(w.ConnectionQualityChanged,s,i)}).on(A.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(w.ParticipantPermissionsChanged,s,i)}).on(A.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionStatusChanged,s,r,i)}).on(A.TrackSubscriptionFailed,(s,r)=>{this.emit(w.TrackSubscriptionFailed,s,i,r)}).on(A.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionPermissionChanged,s,r,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&&dp(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=ve.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,Le.STATE_MISMATCH))):e=0},hm)}clearConnectionReconcile(){this.connectionReconcileInterval&&ve.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===Q.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Q.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return f(this,void 0,void 0,function*(){var t,i;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ls({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:se.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new nn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected),this.emit(w.Connected),this.setAndEmitConnectionState(Q.Connected),s.video){const a=new Kr(C.Kind.Video,new fi({source:he.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ne.AUDIO,name:"video-dummy"}),new cs(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:jc(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(A.LocalTrackPublished,a)}if(s.audio){const a=new Kr(C.Kind.Audio,new fi({source:he.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ne.AUDIO}),new as(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Tr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(A.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new nn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Us.ACTIVE,tracks:[],joinedAt:se.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const d=jc(160*((i=r.aspectRatios[a%r.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),l=new fi({source:he.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ne.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}if(r.audio){const d=Tr(),l=new fi({source:he.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ne.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}c.updateInfo(o)}})}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=yd(i).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Ci.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function yd(n){return n.map(e=>{if(e)return Array.isArray(e)?yd(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ve;(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"})(Ve||(Ve={}));class Nt extends Qe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ve.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ci(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return f(this,void 0,void 0,function*(){if(this.status!==Ve.IDLE)throw Error("check is running already");this.setStatus(Ve.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!==Ve.SKIPPED&&this.setStatus(this.isSuccess()?Ve.SUCCESS:Ve.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return f(this,void 0,void 0,function*(){return this.room.state===Q.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return f(this,void 0,void 0,function*(){this.room&&this.room.state!==Q.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ve.SKIPPED)}switchProtocol(e){return f(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 Ee(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 fm extends Nt{get description(){return"Cloud regions"}perform(){return f(this,void 0,void 0,function*(){const e=new Vr(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.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 f(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"}),a=1e3,c=1e6/a,d="A".repeat(a),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(),p={region:s,rtt:1e4,duration:u-l};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(p.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Gr=1e4;class pm extends Nt{get description(){return"Connection via UDP vs TCP"}perform(){return f(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/(Gr/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Gr/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return f(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 o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{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(()=>f(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(l.packetsSent=p.packetsSent,l.qualityLimitationDurations=p.qualityLimitationDurations,l.bitrateTotal+=p.targetBitrate,l.count++):p.type==="remote-inbound-rtp"&&(l.packetsLost=p.packetsLost,l.rttTotal+=p.roundTripTime,l.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Gr)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class mm extends Nt{get description(){return"Can publish audio"}perform(){return f(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield om();if(yield Vc(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,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 a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class gm extends Nt{get description(){return"Can publish video"}perform(){return f(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield am();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,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(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return f(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,yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const p=d.getContext("2d");p.drawImage(i,0,0);const m=p.getImageData(0,0,d.width,d.height).data;let T=!0;for(let k=0;k<m.length;k+=4)if(m[k]!==0||m[k+1]!==0||m[k+2]!==0){T=!1;break}T?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),i.remove()})}}class vm extends Nt{get description(){return"Resuming connection after interruption"}perform(){return f(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(w.SignalReconnecting,o).on(w.Reconnecting,o).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 a,i){if(!s||t.state!==Q.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 ym extends Nt{get description(){return"Can connect via TURN"}perform(){return f(this,void 0,void 0,function*(){var e,t;const i=new Rr,s=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,a=!1,o=!1;for(let c of s.iceServers)for(let d of c.urls)d.startsWith("turn:")?(a=!0,o=!0):d.startsWith("turns:")&&(a=!0,o=!0,r=!0),d.startsWith("stun:")&&(o=!0);o?a&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class bm extends Nt{get description(){return"Establishing WebRTC connection"}perform(){return f(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(w.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const a=new RTCIceCandidate(s);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(km(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(s,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),K.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 km(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 Tm extends Nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return f(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 Rr;const r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===ko.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)),yield s.close()})}}class Om extends Qe.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:Ve.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!==Ve.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return f(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(Tm)})}checkWebRTC(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(bm)})}checkTURN(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(ym)})}checkReconnect(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(vm)})}checkPublishAudio(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(mm)})}checkPublishVideo(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(gm)})}checkConnectionProtocol(){return f(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(pm);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(fm)})}}class Sm{constructor(e={}){this.currentState=$.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=Ia(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token){console.error("No token found"),this.emitter.emit("error",{session:this,error:new Error("No session token provided")});return}await this.requestMicrophone();try{this.room=new Ci({adaptiveStream:!0,dynacast:!0}),this.room.on(w.LocalTrackUnpublished,s=>{console.log("Local track unpublished",s.source),s.source===C.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(w.Disconnected,()=>{console.log("LiveKit room disconnected"),this.disconnect()}),this.room.on(w.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(w.TrackSubscribed,(s,r,a)=>{if(s.kind==="audio"&&s.attach(),s.source===C.Source.Microphone&&a.identity.includes("agent-")){const o=s.mediaStream;if(!o){console.error("No media stream available for assistant track");return}const c=new AudioContext,d=c.createAnalyser();c.createMediaStreamSource(o).connect(d),d.fftSize=2048;const u=new Uint8Array(d.frequencyBinCount);this.analyzeAudio(d,u,"ASSISTANT"),this.assistantAudioContext=c}}),this.room.on(w.ParticipantAttributesChanged,s=>{if(!s["lk.agent.state"]||this.currentState===$.RESEARCHING||this.currentState===$.PAUSED)return;const r=s["lk.agent.state"],a=mn(r).with("listening",()=>$.USER_SPEAKING).with("speaking",()=>$.AGENT_SPEAKING).with("thinking",()=>$.AGENT_SPEAKING).otherwise(()=>{});a&&this.setState(a)}),this.room.on(w.DataReceived,async s=>{try{const r=JSON.parse(new TextDecoder().decode(s)),a=r.status||r.request;mn(a).with("using_tool",()=>{const o=this.currentState;this.currentState=$.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:o})}).with("using_tool_ended",()=>{const o=this.currentState;this.currentState=$.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:o})}).with("share_screen",()=>{this.shareScreen()}).with("prompt_user",()=>{this.promptContinue()}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML",{session:this})}).otherwise(()=>{console.warn("Unknown data received:",r)})}catch(r){console.error("Error parsing data:",r)}});const t=`${this.apiBaseUrl}/join-token?token=${this.token}`,i=await fetch(t).then(s=>s.json());if(await this.room.connect(i.url,i.token),this.microphoneStream){const s=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(s,{name:"microphone",source:C.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){var e;this.room&&this.room.disconnect(!0),(e=this.screenStream)!=null&&e.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(t=>t.stop()),this.setState($.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),s=t.createMediaStreamSource(e),r=t.createGain();r.gain.value=1.5,s.connect(r),r.connect(i),i.fftSize=2048;const a=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,a,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){var e,t,i;this.room&&(this.setState($.PAUSED),this.room.localParticipant.getTrackPublications().forEach(s=>{var r,a;s.handleMuted(),(a=(r=s.track)==null?void 0:r.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!1)}),(e=this.microphoneStream)==null||e.getTracks().forEach(s=>s.enabled=!1),(i=(t=this.screenStream)==null?void 0:t.track)==null||i.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){var e,t,i;this.room&&(this.setState($.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach(s=>{var r,a;s.handleUnmuted(),(a=(r=s.track)==null?void 0:r.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!0)}),(e=this.microphoneStream)==null||e.getTracks().forEach(s=>s.enabled=!0),(i=(t=this.screenStream)==null?void 0:t.track)==null||i.unmute())}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const s=t.reduce((a,o)=>a+o,0)/t.length,r=Math.max(.01,Math.min(1,s/128));i==="USER"&&this.currentState===$.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:r}):i==="ASSISTANT"&&this.currentState===$.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:r}),setTimeout(()=>this.analyzeAudio(e,t,i),50)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to LiveKit room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},i=JSON.stringify(t),r=new TextEncoder().encode(i);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}}}const Cm=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:Sm},Symbol.toStringTag,{value:"Module"}));Ie.EventType=st,Ie.ObiAssistant=Uu,Ie.ObiSDK=Nu,Ie.ObiWidget=Te,Ie.SDKState=$,Ie.initObi=Vu,Object.defineProperty(Ie,Symbol.toStringTag,{value:"Module"})});
620
+ `},Mr}var ed;function Ip(){if(ed)return Be;ed=1;var n=Rp(),e=xp(),t=Dr();return Be.grammar=t,Be.write=e,Be.parse=n.parse,Be.parseParams=n.parseParams,Be.parseFmtpConfig=n.parseFmtpConfig,Be.parsePayloads=n.parsePayloads,Be.parseRemoteCandidates=n.parseRemoteCandidates,Be.parseImageAttributes=n.parseImageAttributes,Be.parseSimulcastStreamList=n.parseSimulcastStreamList,Be}var Mt=Ip();function Nr(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var p=Date.now()-d;if(p+e>=c)return c-p}return e}var h=function(){var p=[].slice.call(arguments),g=this;return new Promise(function(m,T){var k=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var D=n.apply(g,p);o&&o(D),l.forEach(function(v){return(0,v.resolve)(D)}),l=[]}},u()),k){var x=n.apply(g,p);return o&&o(x),m(x)}l.push({resolve:m,reject:T})})};return h.cancel=function(p){r!==void 0&&clearTimeout(r),l.forEach(function(g){return(0,g.reject)(p)}),l=[]},h}const Ap=.7,Op=20,Si={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class td extends Xe.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=K,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Nr(s=>f(this,void 0,void 0,function*(){this.emit(Si.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Op),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=dt((i=t.loggerName)!==null&&i!==void 0?i:je.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}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 f(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return f(this,void 0,void 0,function*(){var t;let i;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=Dp(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=Mt.parse((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||r.mid!=a.transceiver.mid)return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;let c=!1;for(const d of r.fmtp)if(d.payload===o){d.config=d.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Mt.write(s)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Si.NegotiationComplete),e.sdp&&Mt.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Si.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return f(this,void 0,void 0,function*(){var t;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 r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const s=Mt.parse((t=i.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{nd(r),r.type==="audio"?id(r,[],[]):r.type==="video"&&this.trackBitrates.some(a=>{if(!r.msid||!a.cid||!r.msid.includes(a.cid))return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0||(cn(a.codec)&&this.ensureVideoDDExtensionForSVC(r,s),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*Ap);for(const d of r.fmtp)if(d.payload===o){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(i,Mt.write(s)),this.onOffer(i)})}createAndSetAnswer(){return f(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Mt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{nd(s),s.type==="audio"&&id(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Mt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new fe("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 fe("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 f(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(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return f(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 a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new lr(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Mc))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Mc})}}}function id(n,e,t){let i=0;n.rtp.some(s=>s.codec==="opus"?(i=s.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(s=>s.payload===i&&s.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(s=>s.payload===i?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Dp(n){var e;const t=[],i=[],s=Mt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===r&&c.type==="nack")&&i.push(a.mid),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function nd(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)}}const Lr="vp8",Mp={audioPreset:pr.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:gr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Lr,backupCodec:!0},sd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},rd={deviceId:{ideal:"default"},resolution:on.h720.resolution},Np={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ef,disconnectOnPageLeave:!0,webAudioMix:!1},Ur={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var oe;(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"})(oe||(oe={}));class Lp{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var s;this.peerConnectionTimeout=Ur.peerConnectionTimeout,this.log=K,this.updateState=()=>{var r;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=oe.CONNECTED:o.some(c=>c==="failed")?this.state=oe.FAILED:o.some(c=>c==="connecting")?this.state=oe.CONNECTING:o.every(c=>c==="closed")?this.state=oe.CLOSED:o.some(c=>c==="closed")?this.state=oe.CLOSING:o.every(c=>c==="new")&&(this.state=oe.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(oe[a]," to ").concat(oe[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=dt((s=i.loggerName)!==null&&s!==void 0?s:je.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new td(e,i),this.subscriber=new td(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Fe.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Fe.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=r=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r)},this.state=oe.NEW,this.connectionLock=new Se,this.remoteOfferLock=new Se}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return f(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return f(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return f(this,void 0,void 0,function*(){t===Fe.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return f(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return f(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 f(this,void 0,void 0,function*(){return new Promise((t,i)=>f(this,void 0,void 0,function*(){const s=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Si.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Si.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),i(a)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Fe.PUBLISHER?this.publisher.getConnectedAddress():e===Fe.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>f(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),ve.clearTimeout(u),d(new te("room connection has been cancelled",Z.Cancelled))};s!=null&&s.signal.aborted&&l(),s==null||s.signal.addEventListener("abort",l);const u=ve.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",l),d(new te("could not establish pc connection",Z.InternalError))},a);for(;this.state!==oe.CONNECTED;)if(yield Ee(50),s!=null&&s.signal.aborted){d(new te("room connection has been cancelled",Z.Cancelled));return}ve.clearTimeout(u),s==null||s.signal.removeEventListener("abort",l),c()}))}()})}}class ce extends Error{constructor(e,t,i){super(t),this.code=e,this.message=od(t,ce.MAX_MESSAGE_BYTES),this.data=i?od(i,ce.MAX_DATA_BYTES):void 0}static fromProto(e){return new ce(e.code,e.message,e.data)}toProto(){return new To({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ce(ce.ErrorCode[e],ce.ErrorMessage[e],t)}}ce.MAX_MESSAGE_BYTES=256,ce.MAX_DATA_BYTES=15360,ce.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},ce.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ad=15360;function Fr(n){return new TextEncoder().encode(n).length}function od(n,e){if(Fr(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 jr=2e3;function os(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 Up=1e3;class cd extends C{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}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=Nr(()=>f(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>f(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 Se,this.pauseUpstreamLock=new Se,this.processorLock=new Se,this.restartLock=new Se,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.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 f(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{yi(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){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(vi(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}finally{r()}}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=>{vi(s??e,r)}))})}waitForDimensions(){return f(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Up;return function*(){var i;if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=$e())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Ee(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Ee(50)}throw new lt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return f(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ot(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ot(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return f(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===C.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?pe.getInstance().normalizeDeviceId(r,i,s):i}()})}mute(){return f(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return f(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return f(this,void 0,void 0,function*(){if(!this.sender)throw new lt("unable to replace an unpublished track");let i,s;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return f(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=wf(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===C.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(d=>{yi(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return 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 f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Nc()&&(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 f(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=$e();if((i==null?void 0:i.name)==="Safari"&&Jt(i.version,"12.0")<0)throw new dr("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 f(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 f(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 f(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 a=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(vi(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(yi(i._mediaStreamTrack,d),vi(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{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return f(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))}()})}}class cs extends cd{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,C.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>f(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=os(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,Ye.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,Ye.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return f(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===C.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 f(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!==Ot(this._constraints.deviceId);return this.source===C.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 f(this,void 0,void 0,function*(){let t;if(e){const i=Rr({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 f(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){we()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},jr)))}setProcessor(e){return f(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!et()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());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 f(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 f(this,void 0,void 0,function*(){const e=yield Kc(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}}function Fp(n,e,t){switch(n.kind){case"audio":return new cs(n,e,!1,void 0,t);case"video":return new ls(n,e,!1,t);default:throw new lt("unsupported track type: ".concat(n.kind))}}const jp=Object.values(on),$p=Object.values(mr),Bp=Object.values(gr),Vp=[on.h180,on.h360],qp=[mr.h180,mr.h360],zp=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new ee(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)}),$r=["q","h","f"];function Br(n,e,t,i){var s,r;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,d=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Gp(n,e,t,d),K.debug("using video encoding",a));const l=a.maxFramerate,u=new ee(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&cn(d)){const g=new ds(c),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const T=$e();if(At()||et()||(T==null?void 0:T.name)==="Chrome"&&Jt(T==null?void 0:T.version,"113")<0){const k=g.suffix=="h"?2:3;for(let x=0;x<g.spatial;x+=1)m.push({rid:$r[2-x],maxBitrate:a.maxBitrate/Math.pow(k,x),maxFramerate:u.encoding.maxFramerate});m[0].scalabilityMode=c}else m.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(m[0].priority=u.encoding.priority,m[0].networkPriority=u.encoding.priority),K.debug("using svc encoding",{encodings:m}),m}if(!o)return[a];let h=[];n?h=(s=ld(i==null?void 0:i.screenShareSimulcastLayers))!==null&&s!==void 0?s:dd(n,u):h=(r=ld(i==null?void 0:i.videoSimulcastLayers))!==null&&r!==void 0?r:dd(n,u);let p;if(h.length>0){const g=h[0];h.length>1&&([,p]=h);const m=Math.max(e,t);if(m>=960&&p)return Vr(e,t,[g,p,u],l);if(m>=480)return Vr(e,t,[g,u],l)}return Vr(e,t,[u])}function Kp(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&K.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Br(n.source===C.Source.ScreenShare,c,d,t)}function Gp(n,e,t,i){const s=Wp(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":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 Wp(n,e,t){if(n)return Bp;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?jp:$p}function dd(n,e){if(n)return zp(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)?Vp:qp}function Vr(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=$r.length)return;const o=Math.min(n,e),d={rid:$r[a],scaleResolutionDownBy:Math.max(1,o/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=bi()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),et()&&Uc()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,K.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),K.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function ld(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 ds{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 Hp(n){return n.source===C.Source.ScreenShare||n.constraints.height&&Ot(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Zp=5e3;class ls extends cd{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,C.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>f(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const a=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((c,d)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(d);o+=os(c,u)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new Se}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!we())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()},jr))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return f(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=Pt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!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 f(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=Pt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!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 f(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===C.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 f(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.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 f(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 a={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},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ae.LOW;i<=Ae.HIGH;i+=1)t.push(new Ys({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return f(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=Rr({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o);try{for(var c=!0,d=Pt(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.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 f(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,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,p=Pt(s.simulcastCodecs.values()),g;g=yield p.next(),a=g.done,!a;h=!0)d=g.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(m){o={error:m}}finally{try{!h&&!a&&(c=p.return)&&(yield c.call(p))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return f(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)},Zp))}setPublishingCodecs(e){return f(this,void 0,void 0,function*(){var t,i,s,r,a,o,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(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=Pt(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(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 ud(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e){return f(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield ud(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Nc()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ud(n,e,t,i,s,r){return f(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:c}=o;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:c,senderEncodings:e}));return}let d=!1;const l=$e();if((l==null?void 0:l.name)==="Chrome"&&Jt(l==null?void 0:l.version,"133")>0&&c[0].scalabilityMode){const h=c[0],p=new ds(h.scalabilityMode);let g=hi.OFF;if(t.forEach(m=>{m.enabled&&(g===hi.OFF||m.quality>g)&&(g=m.quality)}),g===hi.OFF)h.active&&(h.active=!1,d=!0);else if(!h.active||p.spatial!==g+1){d=!0,h.active=!0;const m=new ds(e[0].scalabilityMode);p.spatial=g+1,p.suffix=m.suffix,p.spatial===1&&(p.suffix=void 0),h.scalabilityMode=p.toString(),h.scaleResolutionDownBy=Math.pow(2,2-g),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else c.forEach((h,p)=>{var g;let m=(g=h.rid)!==null&&g!==void 0?g:"";m===""&&(m="q");const T=hd(m),k=t.find(x=>x.quality===T);k&&h.active!==k.enabled&&(d=!0,h.active=k.enabled,s.debug("setting layer ".concat(k.quality," to ").concat(h.active?"enabled":"disabled"),r),bi()&&(k.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))});d&&(o.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function hd(n){switch(n){case"f":return Ae.HIGH;case"h":return Ae.MEDIUM;case"q":return Ae.LOW;default:return Ae.HIGH}}function fd(n,e,t,i){if(!t)return[new Wt({quality:Ae.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new ds(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new Wt({quality:Math.min(Ae.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=hd((a=s.rid)!==null&&a!==void 0?a:"");return new Wt({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const pd="_lossy",md="_reliable",Jp=2*1e3,qr="leave-reconnect";var Ve;(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"})(Ve||(Ve={}));class Yp extends Xe.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ur.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ve.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=K,this.handleDataChannel=i=>f(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return function*(){if(a){if(a.label===md)r.reliableDCSub=a;else if(a.label===pd)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=i=>f(this,void 0,void 0,function*(){var s,r;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=_e.fromBinary(new Uint8Array(o));((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(R.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&Xp(c,c.value.value),this.emit(R.DataPacketReceived,c))}finally{a()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}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?J.LOSSY:J.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(R.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===qr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ve.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Ve.Connected&&i();const r=()=>{this.off(R.Disconnected,a),i()},a=()=>{this.off(R.Restarted,r),s()};this.once(R.Restarted,r),this.once(R.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(R.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ne.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(fi.RR_SIGNAL_DISCONNECTED))},this.log=dt((t=e.loggerName)!==null&&t!==void 0?t:je.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Ir(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Se,this.dataProcessLock=new Se,this.dcBufferStatus=new Map([[J.LOSSY,!0],[J.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(R.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(R.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(R.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(R.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(R.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(R.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(R.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(R.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a,o,c;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:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.sid}}join(e,t,i,s){return f(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,i,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(R.SignalConnected)},10),r}catch(r){if(r instanceof te&&r.reason===Z.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,s);throw r}})}close(){return f(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(R.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return f(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})}cleanupClient(){return f(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new lt("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new te("publication of local track timed out, no response from server",Z.InternalError))},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 f(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return f(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==oe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new Lp(s,e.subscriberPrimary,this.loggerOptions),this.emit(R.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,a)=>{this.client.sendIceCandidate(r,a)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,a,o)=>f(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),r===oe.CONNECTED){const l=this.pcState===Ve.New;this.pcState=Ve.Connected,l&&this.emit(R.Connected,e)}else r===oe.FAILED&&this.pcState===Ve.Connected&&(this.pcState=Ve.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?fi.RR_SUBSCRIBER_FAILED:fi.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===ne.RECONNECTING,d=[oe.FAILED,oe.CLOSING,oe.CLOSED].includes(r);c&&d&&!this._isClosed&&this.emit(R.Offline)}),this.pcManager.onTrack=r=>{this.emit(R.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Qp((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>f(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),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=>f(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(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(R.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(R.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(R.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(R.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",fi.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case mi.DISCONNECT:this.emit(R.Disconnected,e==null?void 0:e.reason),this.close();break;case mi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(qr);break;case mi.RESUME:this.handleDisconnect(qr)}}}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 a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===nn.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(pd,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(md,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,i){return f(this,void 0,void 0,function*(){if(vr())return yield this.createTransceiverRTCRtpSender(e,t,i);if(yr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new fe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return f(this,void 0,void 0,function*(){if(vr())return this.createSimulcastTransceiverSender(e,t,i,s);if(yr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new fe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Ti(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 f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return f(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){K.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===nn.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:oe.NEW)===oe.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 a=!0;r instanceof fe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Ci||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",fi.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(R.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 f(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new fe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(R.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 Ci;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof te&&a.reason===Z.NotAllowed?new fe("could not reconnect, token might be expired"):new Ci}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(R.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ne.CONNECTED)throw new Ci("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(R.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return f(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new fe("could not reconnect, url or token not saved");if(!this.pcManager)throw new fe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(R.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 te&&s.reason===Z.NotAllowed?new fe("could not reconnect, token might be expired"):s instanceof te&&s.reason===Z.LeaveRequest?s:new Ci(r)}if(this.emit(R.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s)}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!==ne.CONNECTED)throw new Ci("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(),this.emit(R.Resumed)})}waitForPCInitialConnection(e,t){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return f(this,void 0,void 0,function*(){this.pcState=Ve.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ee(Jp),!this.pcManager)throw new fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ve.Connected}catch(e){throw this.pcState=Ve.Disconnected,new te("could not establish PC connection, ".concat(e.message),Z.InternalError)}})}publishRpcResponse(e,t,i,s){return f(this,void 0,void 0,function*(){const r=new _e({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcResponse",value:new ko({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,J.RELIABLE)})}publishRpcAck(e,t){return f(this,void 0,void 0,function*(){const i=new _e({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcAck",value:new bo({requestId:t})}});yield this.sendDataPacket(i,J.RELIABLE)})}sendDataPacket(e,t){return f(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(i),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,i)=>f(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i("Engine closed");for(this.once(R.Closing,s);!this.dcBufferStatus.get(e);)yield Ee(10);this.off(R.Closing,s),t()}}))}ensureDataTransportConnected(e){return f(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 fe("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw new te("".concat(o," connection not set"),Z.InternalError);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();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(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Ee(50)}throw new te("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),Z.InternalError)}()})}ensurePublisherConnected(e){return f(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==oe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return f(this,void 0,void 0,function*(){return new Promise((e,t)=>f(this,void 0,void 0,function*(){if(!this.pcManager){t(new lr("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("cannot negotiate on closed engine"),this.on(R.Closing,s),this.pcManager.publisher.once(Si.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();op(c)&&a.set(o.payload,c)}),this.emit(R.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof lr&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",fi.RR_UNKNOWN),t(r)}finally{this.off(R.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===J.LOSSY)return this.lossyDCSub;if(e===J.RELIABLE)return this.reliableDCSub}else{if(e===J.LOSSY)return this.lossyDC;if(e===J.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(s=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,d=new Array;e.forEach(l=>{l.isDesired!==o&&c.push(l.trackSid),l.isEnabled||d.push(l.trackSid)}),this.client.sendSyncState(new Fo({answer:r?as({sdp:r.sdp,type:r.type}):void 0,offer:a?as({sdp:a.sdp,type:a.type}):void 0,subscription:new zn({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:gp(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:d}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new jo({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(J.LOSSY),Fe.PUBLISHER),t(this.dataChannelForKind(J.RELIABLE),Fe.PUBLISHER),t(this.dataChannelForKind(J.LOSSY,!0),Fe.SUBSCRIBER),t(this.dataChannelForKind(J.RELIABLE,!0),Fe.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ve.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){we()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){we()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Ci extends Error{}function Qp(n){return n!==void 0&&n>13}function Xp(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 zr{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return kr(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return f(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(s=>s.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),K.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return f(this,void 0,void 0,function*(){const t=yield fetch("".concat(em(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new te("Could not fetch region settings: ".concat(t.statusText),t.status===401?Z.NotAllowed:Z.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function em(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class gd{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class tm extends gd{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;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();return{next:()=>f(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return f(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return f(this,void 0,void 0,function*(){var e,t,i,s;let r=new Set;try{for(var a=!0,o=Pt(this),c;c=yield o.next(),e=c.done,!e;a=!0){s=c.value,a=!1;const d=s;r.add(d)}}catch(d){t={error:d}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(r)})}}class im extends gd{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=ss(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;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;return{next:()=>f(this,void 0,void 0,function*(){try{const{done:i,value:s}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(s),{done:!1,value:t.decode(s.content)})}catch{return{done:!0,value:void 0}}}),return(){return f(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return f(this,void 0,void 0,function*(){var e,t,i,s;let r="";try{for(var a=!0,o=Pt(this),c;c=yield o.next(),e=c.done,!e;a=!0)s=c.value,a=!1,r+=s}catch(d){t={error:d}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return r})}}class vd{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 f(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 nm extends vd{}class sm extends vd{}class yd extends C{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 f(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(),jr)),vp()&&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 rm extends yd{constructor(e,t,i,s,r,a){super(e,t,C.Kind.Audio,i,a),this.monitorReceiver=()=>f(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=os(o,this.prevStats)),this.prevStats=o}),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;et()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(et())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return f(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(br(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&br(e)&&e.setSinkId(this.sinkId),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 f(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 Kr=100;class am extends yd{constructor(e,t,i,s,r){super(e,t,C.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>f(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=os(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Nr(()=>{this.updateDimensions()},Kr),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?yi(this._mediaStreamTrack,t):vi(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 om(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 f(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 f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),s=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!s||r;if(this.lastVisible!==a){if(!a&&Date.now()-i<Kr){ve.setTimeout(()=>{this.updateVisibility()},Kr);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 a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,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"?Fc():t||(Fc()>2?2:1)}}class om{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=un(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=un(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=un(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Gr(e),this.isPiP=we()&&un(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Gr(this.element),this.isPiP=un(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,$c().observe(this.element),jc().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=$c())===null||e===void 0||e.unobserve(this.element),(t=jc())===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 un(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Gr(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Gr(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=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+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class ht extends Xe.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=xe.NONE,this.log=K,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=dt((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:je.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.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)),X(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==xe.NONE}get audioTrack(){if(ut(this.track))return this.track}get videoTrack(){if(Ti(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.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={}))})(ht||(ht={}));class Wr extends ht{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.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(P.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(P.Ended,this.handleTrackEnded)}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 f(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return f(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return f(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return f(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ut(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Ye.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Ye.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Ye.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Ye.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Ye.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ye.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function us(n,e){return f(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Hc(n);let a=r.audio,o=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,a=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,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(r.video===!0||typeof r.video=="object"&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=zc(r,sd,rd),d=Rr(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(pe.userMediaPromiseMap.set("audioinput",l),l.catch(()=>pe.userMediaPromiseMap.delete("audioinput"))),r.video&&(pe.userMediaPromiseMap.set("videoinput",l),l.catch(()=>pe.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>f(this,void 0,void 0,function*(){const p=h.kind==="audio";let g=p?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let m;const T=p?d.audio:d.video;typeof T!="boolean"&&(m=T);const k=h.getSettings().deviceId;m!=null&&m.deviceId&&Ot(m.deviceId)!==k?m.deviceId=k:m||(m={deviceId:k});const x=Fp(h,m,e);return x.kind===C.Kind.Video?x.source=C.Source.Camera:x.kind===C.Kind.Audio&&(x.source=C.Source.Microphone),x.mediaStream=u,ut(x)&&i?yield x.setProcessor(i):Ti(x)&&s&&(yield x.setProcessor(s)),x})))}catch(u){if(!t)throw u;return us(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function cm(n){return f(this,void 0,void 0,function*(){return(yield us({audio:!1,video:n??!0}))[0]})}function dm(n){return f(this,void 0,void 0,function*(){return(yield us({audio:n??!0,video:!1}))[0]})}var Nt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Nt||(Nt={}));function lm(n){switch(n){case tn.EXCELLENT:return Nt.Excellent;case tn.GOOD:return Nt.Good;case tn.POOR:return Nt.Poor;case tn.LOST:return Nt.Lost;default:return Nt.Unknown}}class bd extends Xe.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===qn.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:qn.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Nt.Unknown,this.log=K,this.log=dt((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:je.Participant),this.loggerOptions=a,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=o,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}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(C.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){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.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(A.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(A.ParticipantNameChanged,e)}_setAttributes(e){const t=yp(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(A.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;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!==((a=this.permissions)===null||a===void 0?void 0:a.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!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(A.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(A.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=lm(e),t!==this._connectionQuality&&this.emit(A.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ut(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(P.Muted,()=>{this.emit(A.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(A.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function um(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 Lo({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||[]})}const kd=15e3;class hm extends bd{constructor(e,t,i,s,r){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=xe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Vc)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(c=>this.log.warn(c.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:c,message:d}=a,l=this.pendingSignalRequests.get(o);l&&(c!==Qs.OK&&l.reject(new Ac(d,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,d=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(d=ce.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,d);break;case"rpcAck":let l=a.value.value;this.handleIncomingRpcAck(l.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=>um(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),X(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),X(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>f(this,void 0,void 0,function*(){var o,c,d,l,u,h;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const p=this.videoTrackPublications.get(a.trackSid);if(!p){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!p.videoTrack)return;const k=yield p.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var g=!0,m=Pt(k),T;T=yield m.next(),o=T.done,!o;g=!0){l=T.value,g=!1;const x=l;Jf(x)&&(this.log.debug("publish ".concat(x," for ").concat(p.videoTrack.sid),Object.assign(Object.assign({},this.logContext),X(p))),yield this.publishAdditionalCodecForTrack(p.videoTrack,x,p.options))}}catch(x){c={error:x}}finally{try{!g&&!o&&(d=m.return)&&(yield d.call(m))}finally{if(c)throw c.error}}}else a.subscribedQualities.length>0&&(yield(h=p.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>f(this,void 0,void 0,function*(){if(a.source===C.Source.ScreenShare||a.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),X(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Qt(a)||Dt(a))try{if(we())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===C.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),X(a))),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.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),X(a))),Qt(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),X(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}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==xe.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){this.engine=e,this.engine.on(R.RemoteMute,(t,i)=>{const s=this.trackPublications.get(t);!s||!s.track||(i?s.mute():s.unmute())}),this.engine.on(R.Connected,this.handleReconnected).on(R.SignalRestarted,this.handleReconnected).on(R.SignalResumed,this.handleReconnected).on(R.Restarting,this.handleReconnecting).on(R.Resuming,this.handleReconnecting).on(R.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(R.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(R.Disconnected,this.handleDisconnected).on(R.SignalRequestResponse,this.handleSignalRequestResponse).on(R.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return f(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return f(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return f(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return f(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return function*(){return new Promise((o,c)=>f(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:"",a),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-p<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(g=>{let[m,T]=g;return this.attributes[m]===T||T===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),o();return}yield Ee(50)}c(new Ac("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(C.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(C.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(A.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return f(this,void 0,void 0,function*(){this.encryptionType=e?xe.GCM:xe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return f(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.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 C.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new lt(e)}}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(A.MediaDevicesError,d),this.pendingPublishing.delete(e),d}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),X(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return f(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.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(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return f(this,void 0,void 0,function*(){var t,i;e??(e={});const s=zc(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 us(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(ut(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(A.AudioStreamAcquired)),Ti(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return f(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new dr("getDisplayMedia not supported");e.resolution===void 0&&!ip()&&(e.resolution=gr.h1080fps30.resolution);const t=mp(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new lt("no video track found");const r=new ls(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(A.AudioStreamAcquired);const o=new cs(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return f(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,d,l;Qt(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),ki(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let k;switch(i.source){case C.Source.Microphone:k="audioinput";break;case C.Source.Camera:k="videoinput"}k&&r.activeDeviceMap.has(k)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(k)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new cs(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new ls(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new lt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(k=>{k.track&&k.track===i&&(h=k)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),X(h))),h;const p="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=s==null?void 0:s.forceStereo)!==null&&c!==void 0?c:p;g&&(s||(s={}),s.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),X(i))),s.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=s.dtx)!==null&&d!==void 0||(s.dtx=!1),(l=s.red)!==null&&l!==void 0||(s.red=!1));const m=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s);!np()&&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)),m.simulcast=!1),m.source&&(i.source=m.source);const T=new Promise((k,x)=>f(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ne.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:X(i)}));const D=()=>f(this,void 0,void 0,function*(){try{const v=yield this.publish(i,m,g);k(v)}catch(v){x(v)}});setTimeout(()=>{this.engine.off(R.SignalConnected,D),x(new ur("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(R.SignalConnected,D),this.engine.on(R.Closing,()=>{this.engine.off(R.SignalConnected,D),x(new ur("publishing rejected as engine closed",499))})}else try{const D=yield this.publish(i,m,g);k(D)}catch(D){x(D)}}catch(D){x(D)}}));r.pendingPublishPromises.set(i,T);try{return yield T}catch(k){throw k}finally{r.pendingPublishPromises.delete(i)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),X(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>bp(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),X(e))),!1)}publish(e,t,i){return f(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(e))throw new ur("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(y=>ki(e)&&y.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),X(e))),t.stopMicTrackOnMute&&ut(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&bi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Xf()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!ep()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Lr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(y=>t.videoCodec===rs(y.mime))||(t.videoCodec=rs(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 T=new Ws({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:!(!((s=t.dtx)!==null&&s!==void 0)||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});let k;if(e.kind===C.Kind.Video){let y={width:0,height:0};try{y=yield e.waitForDimensions()}catch{const M=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:on.h720.resolution;y={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{dims:y}))}T.width=y.width,T.height=y.height,Dt(e)&&(cn(m)&&(e.source===C.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),X(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),T.simulcastCodecs=[new Gs({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Lr}),t.backupCodec&&m!==t.backupCodec.codec&&T.encryption===xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),T.simulcastCodecs.push(new Gs({codec:t.backupCodec.codec,cid:""})))),k=Br(e.source===C.Source.ScreenShare,T.width,T.height,t),T.layers=fd(T.width,T.height,k,cn(t.videoCodec))}else e.kind===C.Kind.Audio&&(k=[{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:(p=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new fe("cannot publish track when not connected");const x=()=>f(this,void 0,void 0,function*(){var y,E,M;if(!this.engine.pcManager)throw new fe("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,k),Dt(e)&&((y=t.degradationPreference)!==null&&y!==void 0||(t.degradationPreference=Hp(e)),e.setDegradationPreference(t.degradationPreference)),k)if(bi()&&e.kind===C.Kind.Audio){let U;for(const G of this.engine.pcManager.publisher.getTransceivers())if(G.sender===e.sender){U=G;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((E=k[0])===null||E===void 0)&&E.maxBitrate?k[0].maxBitrate/1e3:0})}else e.codec&&cn(e.codec)&&(!((M=k[0])===null||M===void 0)&&M.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:T.cid,codec:e.codec,maxbr:k[0].maxBitrate/1e3});yield this.engine.negotiate()});let D;if(this.enabledPublishVideoCodecs.length>0)D=(yield Promise.all([this.engine.addTrack(T),x()]))[0];else{D=yield this.engine.addTrack(T);let y;if(D.codecs.forEach(E=>{y===void 0&&(y=E.mimeType)}),y&&e.kind===C.Kind.Video){const E=rs(y);E!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{codec:E})),t.videoCodec=E,k=Br(e.source===C.Source.ScreenShare,T.width,T.height,t))}yield x()}const v=new Wr(e.kind,D,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return v.options=t,e.sid=D.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:k,trackInfo:D})),Dt(e)?e.startMonitor(this.engine.client):Qt(e)&&e.startMonitor(),this.addTrackPublication(v),this.emit(A.LocalTrackPublished,v),v})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return f(this,void 0,void 0,function*(){var s;if(this.encryptionType!==xe.NONE)return;let r;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(r=p)}),!r)throw new lt("track is not published");if(!Dt(e))throw new lt("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=Kp(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),X(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Ws({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=fd(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new fe("cannot publish track when not connected");const l=()=>f(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),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:o,trackInfo:h}))})}unpublishTrack(e,t){return f(this,void 0,void 0,function*(){var i,s;if(ki(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),X(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?X(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));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 o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<oe.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Dt(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!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),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(A.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return f(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return f(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 Promise((r,a)=>f(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>f(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==C.Source.ScreenShare&&d.source!==C.Source.ScreenShareAudio&&(Qt(d)||Dt(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(o){a(o)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return f(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?J.RELIABLE:J.LOSSY,a=s.destinationIdentities,o=s.topic,c=new _e({kind:r,value:{case:"user",value:new go({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(c,r)}()})}publishDtmf(e,t){return f(this,void 0,void 0,function*(){const i=new _e({kind:J.RELIABLE,value:{case:"sipDtmf",value:new vo({code:e,digit:t})}});yield this.engine.sendDataPacket(i,J.RELIABLE)})}sendChatMessage(e,t){return f(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 _e({value:{case:"chatMessage",value:new $s(Object.assign(Object.assign({},i),{timestamp:se.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,J.RELIABLE),this.emit(A.ChatMessage,i),i})}editChatMessage(e,t){return f(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new _e({value:{case:"chatMessage",value:new $s(Object.assign(Object.assign({},i),{timestamp:se.parse(i.timestamp),editTimestamp:se.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,J.RELIABLE),this.emit(A.ChatMessage,i),i})}sendText(e,t){return f(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var p;c[h]=u;const g=c.reduce((m,T)=>m+T,0);(p=t==null?void 0:t.onProgress)===null||p===void 0||p.call(t,g)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield l.write(e),d(1,0),yield l.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>f(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:p=>{d(p,h+1)}})})))),l.info})}streamText(e){return f(this,void 0,void 0,function*(){var t,i;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:s,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},a=new Vs({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Yt(r.timestamp),totalLength:Yt(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Ro({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"?Bs.UPDATE:Bs.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new _e({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,J.RELIABLE);let d=0;const l=this,u=new WritableStream({write(g){return f(this,void 0,void 0,function*(){for(const m of fp(g,kd)){yield l.engine.waitForBufferStatusLow(J.RELIABLE);const T=new qs({content:m,streamId:s,chunkIndex:Yt(d)}),k=new _e({destinationIdentities:o,value:{case:"streamChunk",value:T}});yield l.engine.sendDataPacket(k,J.RELIABLE),d+=1}})},close(){return f(this,void 0,void 0,function*(){const g=new zs({streamId:s}),m=new _e({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield l.engine.sendDataPacket(m,J.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>f(this,void 0,void 0,function*(){yield p.close()});l.engine.once(R.Closing,h);const p=new nm(u,r,()=>this.engine.off(R.Closing,h));return p})}sendFile(e,t){return f(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return f(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}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return f(this,void 0,void 0,function*(){var t,i,s,r,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,d={id:o,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"},l=new Vs({totalLength:Yt((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:o,topic:d.topic,timestamp:Yt(Date.now()),contentHeader:{case:"byteHeader",value:new xo({name:d.name})}}),u=new _e({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,J.RELIABLE);let h=0;const p=new Se,g=this.engine,m=this.log,T=new WritableStream({write(x){return f(this,void 0,void 0,function*(){const D=yield p.lock();let v=0;try{for(;v<x.byteLength;){const y=x.slice(v,v+kd);yield g.waitForBufferStatusLow(J.RELIABLE);const E=new _e({destinationIdentities:c,value:{case:"streamChunk",value:new qs({content:y,streamId:o,chunkIndex:Yt(h)})}});yield g.sendDataPacket(E,J.RELIABLE),h+=1,v+=y.byteLength}}finally{D()}})},close(){return f(this,void 0,void 0,function*(){const x=new zs({streamId:o}),D=new _e({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield g.sendDataPacket(D,J.RELIABLE)})},abort(x){m.error("Sink error:",x)}});return new sm(T,d)})}performRpc(e){return f(this,arguments,void 0,function(t){var i=this;let{destinationIdentity:s,method:r,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((d,l)=>f(i,void 0,void 0,function*(){var u,h,p,g;if(Fr(a)>ad){l(ce.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Jt((g=(p=this.engine.latestJoinResponse)===null||p===void 0?void 0:p.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){l(ce.builtIn("UNSUPPORTED_SERVER"));return}const m=crypto.randomUUID();yield this.publishRpcRequest(s,m,r,a,o-2e3);const T=setTimeout(()=>{this.pendingAcks.delete(m),l(ce.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(m),clearTimeout(k)},2e3);this.pendingAcks.set(m,{resolve:()=>{clearTimeout(T)},participantIdentity:s});const k=setTimeout(()=>{this.pendingResponses.delete(m),l(ce.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(m,{resolve:(x,D)=>{clearTimeout(k),this.pendingAcks.has(m)&&(console.warn("RPC response received before ack",m),this.pendingAcks.delete(m),clearTimeout(T)),D?l(D):d(x??"")},participantIdentity:s})}))}()})}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 f(this,void 0,void 0,function*(){const a=new _e({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcRequest",value:new yo({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,J.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,ce.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),X(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(Qt(s)||Dt(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return f(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[a]=r;return a.source===e});if(s)return s[1];yield Ee(20)}})}}class fm extends ht{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ae.HIGH,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.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=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 zn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new So({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?ht.SubscriptionStatus.Unsubscribed:super.isSubscribed?ht.SubscriptionStatus.Subscribed:ht.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ht.PermissionStatus.Allowed:ht.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(wr(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&wr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}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.kind===C.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return wr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ao({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Ae.HIGH,this.emit(P.UpdateSettings,e)}}class hs extends bd{static fromParticipantInfo(e,t,i){return new hs(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,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:qn.STANDARD;super(t,i||"",s,r,a,o,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({},this.logContext),X(e))),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(A.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(A.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(A.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(A.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(A.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]:C.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]:C.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(A.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-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),X(o))),this.emit(A.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new am(e,t,s,r):d=new rm(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&Er(d)&&ut(d)&&d.setVolume(this.volumeMap.get(o.source)),o}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,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=C.kindFromProto(s.type);if(!c)return;o=new fm(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));d&&o.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:X(d),newTrack:X(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),X(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(A.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 C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(A.TrackUnpublished,i)}setAudioOutput(e){return f(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;ut(i.track)&&Er(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 Q;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Q||(Q={}));const pm=4*1e3;class _i extends Xe.EventEmitter{constructor(e){var t,i,s,r;if(super(),t=this,this.state=Q.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=K,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(a,o,c)=>f(this,void 0,void 0,function*(){var d;if(!tp())throw et()?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 l=yield this.disconnectLock.lock();if(this.state===Q.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(Q.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),kr(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new zr(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(p=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const u=(p,g,m)=>f(this,void 0,void 0,function*(){var T,k;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,l==null||l();try{yield this.attemptConnection(m??a,o,c,x),this.abortController=void 0,p()}catch(D){if(this.regionUrlProvider&&D instanceof te&&D.reason!==Z.Cancelled&&D.reason!==Z.NotAllowed){let v=null;try{v=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(y){if(y instanceof te&&(y.status===401||y.reason===Z.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(y);return}}v&&!(!((k=this.abortController)===null||k===void 0)&&k.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(D.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield u(p,g,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,qc(D)),g(D))}else{let v=Ue.UNKNOWN_REASON;D instanceof te&&(v=qc(D)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),g(D)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Vc((p,g)=>{u(p,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,d,l,u)=>f(this,void 0,void 0,function*(){var h,p,g;const m=yield c.join(a,o,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},u.signal);let T=m.serverInfo;if(T||(T={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(k=>{let[x,D]=k;return"".concat(x,": ").concat(D)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(p=m.room)===null||p===void 0?void 0:p.sid,identity:(g=m.participant)===null||g===void 0?void 0:g.identity}),!T.version)throw new $f("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),m}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,d)=>f(this,void 0,void 0,function*(){var l,u;this.state===Q.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ur),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const p=new te("could not establish signal connection",Z.ServerUnreachable);throw h instanceof Error&&(p.message="".concat(p.message,": ").concat(h.message)),h instanceof te&&(p.reason=h.reason,p.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),p}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new te("Connection attempt aborted",Z.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}we()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),we()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Q.Connected),this.emit(w.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return f(t,[...o],void 0,function(){var d=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,h,p,g;const m=yield d.disconnectLock.lock();try{if(d.state===Q.Disconnected){d.log.debug("already disconnected",d.logContext);return}d.log.info("disconnect from room",Object.assign({},d.logContext)),(d.state===Q.Connecting||d.state===Q.Reconnecting||d.isResuming)&&(d.log.warn("abort connection attempt",d.logContext),(u=d.abortController)===null||u===void 0||u.abort(),(p=(h=d.connectFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,new te("Client initiated disconnect",Z.Cancelled)),d.connectFuture=void 0),!((g=d.engine)===null||g===void 0)&&g.client.isDisconnected||(yield d.engine.client.sendLeave()),d.engine&&(yield d.engine.close()),d.handleDisconnect(l,Ue.CLIENT_INITIATED),d.engine=void 0}finally{m()}}()})},this.onPageLeave=()=>f(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>f(this,void 0,void 0,function*(){const a=[],o=$e();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let d=document.getElementById(c);if(!d){d=document.createElement("audio"),d.id=c,d.autoplay=!0,d.hidden=!0;const l=Cr();l.enabled=!0;const u=new MediaStream([l]);d.srcObject=u,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(w.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(l=>{a.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>f(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var d;(d=c.track)===null||d===void 0||d.attachedElements.forEach(l=>{a.includes(l)||a.push(l)})});yield Promise.all(a.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.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(Q.Reconnecting)&&this.emit(w.Reconnecting)},this.handleSignalRestarted=a=>f(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(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}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(Q.Connected),this.emit(w.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let d=this.remoteParticipants.get(o.identity);o.state===js.DISCONNECTED?this.handleParticipantDisconnected(o.identity,d):d=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(d=>{if(c[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(d.sid);l&&(l.audioLevel=d.level,l.setIsSpeaking(!0),o.push(l))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{c[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(w.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(d=>{const l=this.remoteParticipants.get(d.identity);l&&l.sid!==d.sid||o.set(d.sid,d)}),a.forEach(d=>{let l=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=d.level,l.setIsSpeaking(d.active),d.active?o.set(d.sid,l):o.delete(d.sid))});const c=Array.from(o.values());c.sort((d,l)=>l.audioLevel-d.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(w.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);if(!d||!d.track)return;const l=C.streamStateFromProto(o.state);l!==d.track.streamState&&(d.track.streamState=l,c.emit(A.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(w.TrackStreamStateChanged,d,d.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);else if(a.value.case==="rpcRequest"){const c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(w.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(A.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(w.SipDTMFReceived,o,a),a==null||a.emit(A.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),d=c==null?void 0:c.trackPublications.get(o.trackId),l=dp(o,this.transcriptionReceivedTimes);d==null||d.emit(P.TranscriptionReceived,l),c==null||c.emit(A.TranscriptionReceived,l,d),this.emit(w.TranscriptionReceived,l,c,d)},this.handleChatMessage=(a,o)=>{const c=lp(o);this.emit(w.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(w.MetricsReceived,a,o)},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=()=>f(this,void 0,void 0,function*(){var a,o,c;const d=pe.getInstance().previousDevices,l=yield pe.getInstance().getDevices(void 0,!1),u=$e();if((u==null?void 0:u.name)==="Chrome"&&u.os!=="iOS")for(let p of l){const g=d.find(m=>m.deviceId===p.deviceId);g&&g.label!==""&&g.kind===p.kind&&g.label!==p.label&&this.getActiveDevice(p.kind)==="default"&&this.emit(w.ActiveDeviceChanged,p.kind,p.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let p of h){const g=pp(p),m=this.localParticipant.getTrackPublication(g);if(m&&(!((a=m.track)===null||a===void 0)&&a.isUserProvided))continue;const T=l.filter(x=>x.kind===p),k=this.getActiveDevice(p);if(k===((o=d.filter(x=>x.kind===p)[0])===null||o===void 0?void 0:o.deviceId)&&T.length>0&&((c=T[0])===null||c===void 0?void 0:c.deviceId)!==k){yield this.switchActiveDevice(p,T[0].deviceId);continue}p==="audioinput"&&!At()||p==="videoinput"||T.length>0&&!T.find(x=>x.deviceId===this.getActiveDevice(p))&&(yield this.switchActiveDevice(p,T[0].deviceId))}this.emit(w.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(w.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(w.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.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 o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>f(this,void 0,void 0,function*(){var o,c,d,l,u,h;(o=a.track)===null||o===void 0||o.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(P.Restarted,this.onLocalTrackRestarted),(u=(l=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||u===void 0||u.call(l,this),this.emit(w.LocalTrackPublished,a,this.localParticipant),Qt(a.track)&&(yield a.track.checkForSilence())&&this.emit(w.LocalAudioSilenceDetected,a);const p=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Wc(a.source);g&&p&&p!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,p),this.emit(w.ActiveDeviceChanged,g,p))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(P.Restarted,this.onLocalTrackRestarted),this.emit(w.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>f(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=Wc(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(w.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(w.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(w.MediaDevicesError,a)},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({},Np),e),this.log=dt((i=this.options.loggerName)!==null&&i!==void 0?i:je.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},sd),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},rd),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Mp),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Se,this.localParticipant=new hm("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ot(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ot(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Ot(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),we()){const a=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),_i.cleanupRegistry&&_i.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(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)}handleIncomingRpcRequest(e,t,i,s,r,a){return f(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ce.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ce.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Fr(l)>ad?(c=ce.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ce?c=l:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ce.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}setE2EEEnabled(e){return f(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new kp(this.options.e2ee),this.e2eeManager.on(xt.ParticipantEncryptionStatusChanged,(t,i)=>{hp(i)&&(this.isE2EEEnabled=t),this.emit(w.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(xt.EncryptionError,t=>this.emit(w.EncryptionError,t)),(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 f(this,void 0,void 0,function*(){return this.state===Q.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(R.RoomUpdate,i),e(s.sid))};this.engine.on(R.RoomUpdate,i),this.once(w.Disconnected,()=>{this.engine.off(R.RoomUpdate,i),t("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 Yp(this.options),this.engine.on(R.ParticipantUpdate,this.handleParticipantUpdates).on(R.RoomUpdate,this.handleRoomUpdate).on(R.SpeakersChanged,this.handleSpeakersChanged).on(R.StreamStateChanged,this.handleStreamStateUpdate).on(R.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(R.SubscriptionError,this.handleSubscriptionError).on(R.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(R.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(R.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(R.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(R.DataPacketReceived,this.handleDataPacket).on(R.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Q.SignalReconnecting)&&this.emit(w.SignalReconnecting)}).on(R.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Q.Connected)&&this.emit(w.Reconnected)}).on(R.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Q.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(R.Restarting,this.handleRestarting).on(R.SignalRestarted,this.handleSignalRestarted).on(R.Offline,()=>{this.setAndEmitConnectionState(Q.Reconnecting)&&this.emit(w.Reconnecting)}).on(R.DCBufferStatusChanged,(e,t)=>{this.emit(w.DCBufferStatusChanged,e,t)}).on(R.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(A.LocalTrackSubscribed,t),this.emitWhenConnected(w.LocalTrackSubscribed,t,this.localParticipant)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return f(this,void 0,void 0,function*(){if(this.state===Q.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(kr(new URL(e))&&t){this.regionUrlProvider=new zr(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Q.Disconnected&&(this.regionUrl=i,yield fetch(_r(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(_r(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 f(this,void 0,void 0,function*(){let i=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Qe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Qe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Qe({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Qe({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=()=>f(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Qe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>f(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Qe({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 Qe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>f(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Kn({reason:Ue.CLIENT_INITIATED,action:mi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Qe({scenario:{case:"subscriberBandwidth",value:Yt(t)}});break;case"leave-full-reconnect":s=new Qe({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 f(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,c,d,l,u,h,p,g;let m=!0,T=!1;const k=a?{exact:s}:s;if(i==="audioinput"){T=r.localParticipant.audioTrackPublications.size===0;const x=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=k;const D=Array.from(r.localParticipant.audioTrackPublications.values()).filter(v=>v.source===C.Source.Microphone);try{m=(yield Promise.all(D.map(v=>{var y;return(y=v.audioTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(v=>v===!0)}catch(v){throw r.options.audioCaptureDefaults.deviceId=x,v}}else if(i==="videoinput"){T=r.localParticipant.videoTrackPublications.size===0;const x=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=k;const D=Array.from(r.localParticipant.videoTrackPublications.values()).filter(v=>v.source===C.Source.Camera);try{m=(yield Promise.all(D.map(v=>{var y;return(y=v.videoTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(v=>v===!0)}catch(v){throw r.options.videoCaptureDefaults.deviceId=x,v}}else if(i==="audiooutput"){if(!br()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(s=(d=yield pe.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(g=r.options).audioOutput)!==null&&l!==void 0||(g.audioOutput={});const x=(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(D=>D.setAudioOutput({deviceId:s})))}catch(D){throw r.options.audioOutput.deviceId=x,D}}return(T||i==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(i,i==="audiooutput"&&((p=r.options.audioOutput)===null||p===void 0?void 0:p.deviceId)||s),r.emit(w.ActiveDeviceChanged,i,s)),m}()})}setupLocalParticipantEvents(){this.localParticipant.on(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(A.AttributesChanged,this.onLocalAttributesChanged).on(A.TrackMuted,this.onLocalTrackMuted).on(A.TrackUnmuted,this.onLocalTrackUnmuted).on(A.LocalTrackPublished,this.onLocalTrackPublished).on(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(A.MediaDevicesError,this.onMediaDevicesError).on(A.AudioStreamAcquired,this.startAudio).on(A.ChatMessage,this.onLocalChatMessageSent).on(A.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===Q.Connecting||this.state===Q.Reconnecting){const l=()=>{this.onTrackAdded(e,t,i),u()},u=()=>{this.off(w.Reconnected,l),this.off(w.Connected,l),this.off(w.Disconnected,u)};this.once(w.Reconnected,l),this.once(w.Connected,l),this.once(w.Disconnected,u);return}if(this.state===Q.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=Qf(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),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(l=>l.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}let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={}),c.addSubscribedMediaTrack(e,o,t,i,d)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Q.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var r,a,o;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((r=s.track)===null||r===void 0||r.detach(),(a=s.track)===null||a===void 0||a.stop()):(o=s.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(A.AttributesChanged,this.onLocalAttributesChanged).off(A.TrackMuted,this.onLocalTrackMuted).off(A.TrackUnmuted,this.onLocalTrackUnmuted).off(A.LocalTrackPublished,this.onLocalTrackPublished).off(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(A.MediaDevicesError,this.onMediaDevicesError).off(A.AudioStreamAcquired,this.startAudio).off(A.ChatMessage,this.onLocalChatMessageSent).off(A.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),we()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Q.Disconnected),this.emit(w.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(w.ParticipantDisconnected,t),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return f(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ss(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{r=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now()})}});s(new tm(a,o,ss(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{r=c,this.textStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now()})}});s(new im(a,o,ss(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return f(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=Gc())!==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(),Ee(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=hs.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new hs(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(A.TrackPublished,s=>{this.emitWhenConnected(w.TrackPublished,s,i)}).on(A.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio?(s.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.Kind.Video&&(s.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(w.TrackSubscribed,s,r,i)}).on(A.TrackUnpublished,s=>{this.emit(w.TrackUnpublished,s,i)}).on(A.TrackUnsubscribed,(s,r)=>{this.emit(w.TrackUnsubscribed,s,r,i)}).on(A.TrackMuted,s=>{this.emitWhenConnected(w.TrackMuted,s,i)}).on(A.TrackUnmuted,s=>{this.emitWhenConnected(w.TrackUnmuted,s,i)}).on(A.ParticipantMetadataChanged,s=>{this.emitWhenConnected(w.ParticipantMetadataChanged,s,i)}).on(A.ParticipantNameChanged,s=>{this.emitWhenConnected(w.ParticipantNameChanged,s,i)}).on(A.AttributesChanged,s=>{this.emitWhenConnected(w.ParticipantAttributesChanged,s,i)}).on(A.ConnectionQualityChanged,s=>{this.emitWhenConnected(w.ConnectionQualityChanged,s,i)}).on(A.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(w.ParticipantPermissionsChanged,s,i)}).on(A.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionStatusChanged,s,r,i)}).on(A.TrackSubscriptionFailed,(s,r)=>{this.emit(w.TrackSubscriptionFailed,s,i,r)}).on(A.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionPermissionChanged,s,r,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&&up(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=ve.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,Ue.STATE_MISMATCH))):e=0},pm)}clearConnectionReconcile(){this.connectionReconcileInterval&&ve.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===Q.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Q.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return f(this,void 0,void 0,function*(){var t,i;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Fs({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:se.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new sn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected),this.emit(w.Connected),this.setAndEmitConnectionState(Q.Connected),s.video){const a=new Wr(C.Kind.Video,new pi({source:he.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO,name:"video-dummy"}),new ls(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Bc(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(A.LocalTrackPublished,a)}if(s.audio){const a=new Wr(C.Kind.Audio,new pi({source:he.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO}),new cs(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Cr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(A.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new sn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:js.ACTIVE,tracks:[],joinedAt:se.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const d=Bc(160*((i=r.aspectRatios[a%r.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),l=new pi({source:he.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}if(r.audio){const d=Cr(),l=new pi({source:he.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}c.updateInfo(o)}})}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=Td(i).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}_i.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Td(n){return n.map(e=>{if(e)return Array.isArray(e)?Td(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var qe;(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"})(qe||(qe={}));class Lt extends Xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new _i(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return f(this,void 0,void 0,function*(){if(this.status!==qe.IDLE)throw Error("check is running already");this.setStatus(qe.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!==qe.SKIPPED&&this.setStatus(this.isSuccess()?qe.SUCCESS:qe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return f(this,void 0,void 0,function*(){return this.room.state===Q.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return f(this,void 0,void 0,function*(){this.room&&this.room.state!==Q.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(qe.SKIPPED)}switchProtocol(e){return f(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 Ee(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 mm extends Lt{get description(){return"Cloud regions"}perform(){return f(this,void 0,void 0,function*(){const e=new zr(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.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 f(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"}),a=1e3,c=1e6/a,d="A".repeat(a),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(),p={region:s,rtt:1e4,duration:u-l};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(p.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Hr=1e4;class gm extends Lt{get description(){return"Connection via UDP vs TCP"}perform(){return f(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/(Hr/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Hr/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return f(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 o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{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(()=>f(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(l.packetsSent=p.packetsSent,l.qualityLimitationDurations=p.qualityLimitationDurations,l.bitrateTotal+=p.targetBitrate,l.count++):p.type==="remote-inbound-rtp"&&(l.packetsLost=p.packetsLost,l.rttTotal+=p.roundTripTime,l.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Hr)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class vm extends Lt{get description(){return"Can publish audio"}perform(){return f(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield dm();if(yield Kc(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,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 a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class ym extends Lt{get description(){return"Can publish video"}perform(){return f(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield cm();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,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(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return f(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,yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const p=d.getContext("2d");p.drawImage(i,0,0);const m=p.getImageData(0,0,d.width,d.height).data;let T=!0;for(let k=0;k<m.length;k+=4)if(m[k]!==0||m[k+1]!==0||m[k+2]!==0){T=!1;break}T?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),i.remove()})}}class bm extends Lt{get description(){return"Resuming connection after interruption"}perform(){return f(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(w.SignalReconnecting,o).on(w.Reconnecting,o).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 a,i){if(!s||t.state!==Q.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 km extends Lt{get description(){return"Can connect via TURN"}perform(){return f(this,void 0,void 0,function*(){var e,t;const i=new Ir,s=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,a=!1,o=!1;for(let c of s.iceServers)for(let d of c.urls)d.startsWith("turn:")?(a=!0,o=!0):d.startsWith("turns:")&&(a=!0,o=!0,r=!0),d.startsWith("stun:")&&(o=!0);o?a&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class Tm extends Lt{get description(){return"Establishing WebRTC connection"}perform(){return f(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(w.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const a=new RTCIceCandidate(s);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(Sm(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(s,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),K.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 Sm(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 Cm extends Lt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return f(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 Ir;const r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Co.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)),yield s.close()})}}class Mm extends Xe.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:qe.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!==qe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return f(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(Cm)})}checkWebRTC(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(Tm)})}checkTURN(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(km)})}checkReconnect(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(bm)})}checkPublishAudio(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(vm)})}checkPublishVideo(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(ym)})}checkConnectionProtocol(){return f(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(gm);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(mm)})}}class _m{constructor(e={}){this.currentState=$.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=Oa(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token){console.error("No token found"),this.emitter.emit("error",{session:this,error:new Error("No session token provided")});return}await this.requestMicrophone();try{this.room=new _i({adaptiveStream:!0,dynacast:!0}),this.room.on(w.LocalTrackUnpublished,s=>{console.log("Local track unpublished",s.source),s.source===C.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(w.Disconnected,()=>{console.log("LiveKit room disconnected"),this.disconnect()}),this.room.on(w.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(w.TrackSubscribed,(s,r,a)=>{if(s.kind==="audio"&&s.attach(),s.source===C.Source.Microphone&&a.identity.includes("agent-")){const o=s.mediaStream;if(!o){console.error("No media stream available for assistant track");return}const c=new AudioContext,d=c.createAnalyser();c.createMediaStreamSource(o).connect(d),d.fftSize=2048;const u=new Uint8Array(d.frequencyBinCount);this.analyzeAudio(d,u,"ASSISTANT"),this.assistantAudioContext=c}}),this.room.on(w.ParticipantAttributesChanged,s=>{if(!s["lk.agent.state"]||this.currentState===$.RESEARCHING||this.currentState===$.PAUSED)return;const r=s["lk.agent.state"],a=gn(r).with("listening",()=>$.USER_SPEAKING).with("speaking",()=>$.AGENT_SPEAKING).with("thinking",()=>$.AGENT_SPEAKING).otherwise(()=>{});a&&this.setState(a)}),this.room.on(w.DataReceived,async s=>{try{const r=JSON.parse(new TextDecoder().decode(s)),a=r.status||r.request;gn(a).with("using_tool",()=>{const o=this.currentState;this.currentState=$.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:o})}).with("using_tool_ended",()=>{const o=this.currentState;this.currentState=$.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:o})}).with("share_screen",()=>{this.shareScreen()}).with("prompt_user",()=>{this.promptContinue()}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML",{session:this})}).otherwise(()=>{console.warn("Unknown data received:",r)})}catch(r){console.error("Error parsing data:",r)}});const t=`${this.apiBaseUrl}/join-token?token=${this.token}`,i=await fetch(t).then(s=>s.json());if(await this.room.connect(i.url,i.token),this.microphoneStream){const s=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(s,{name:"microphone",source:C.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){var e;this.room&&this.room.disconnect(!0),(e=this.screenStream)!=null&&e.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(t=>t.stop()),this.setState($.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),s=t.createMediaStreamSource(e),r=t.createGain();r.gain.value=1.5,s.connect(r),r.connect(i),i.fftSize=2048;const a=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,a,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){var e,t,i;this.room&&(this.setState($.PAUSED),this.room.localParticipant.getTrackPublications().forEach(s=>{var r,a;s.handleMuted(),(a=(r=s.track)==null?void 0:r.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!1)}),(e=this.microphoneStream)==null||e.getTracks().forEach(s=>s.enabled=!1),(i=(t=this.screenStream)==null?void 0:t.track)==null||i.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){var e,t,i;this.room&&(this.setState($.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach(s=>{var r,a;s.handleUnmuted(),(a=(r=s.track)==null?void 0:r.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!0)}),(e=this.microphoneStream)==null||e.getTracks().forEach(s=>s.enabled=!0),(i=(t=this.screenStream)==null?void 0:t.track)==null||i.unmute())}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const s=t.reduce((a,o)=>a+o,0)/t.length,r=Math.max(.01,Math.min(1,s/128));i==="USER"&&this.currentState===$.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:r}):i==="ASSISTANT"&&this.currentState===$.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:r}),setTimeout(()=>this.analyzeAudio(e,t,i),50)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to LiveKit room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},i=JSON.stringify(t),r=new TextEncoder().encode(i);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}}}const Em=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:_m},Symbol.toStringTag,{value:"Module"}));Ie.EventType=rt,Ie.ObiAssistant=$u,Ie.ObiSDK=Fu,Ie.ObiWidget=Te,Ie.SDKState=$,Ie.initObi=Vu,Object.defineProperty(Ie,Symbol.toStringTag,{value:"Module"})});