@signalwire/web-components 1.0.0-dev-20260427214957 → 1.0.0-dev-20260428062741

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.
@@ -0,0 +1,2475 @@
1
+ var SignalWireUI=(function(u){"use strict";/**
2
+ * @license
3
+ * Copyright 2019 Google LLC
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ */var Dn,ne,it,$e;const zt=globalThis,gi=zt.ShadowRoot&&(zt.ShadyCSS===void 0||zt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,bi=Symbol(),ar=new WeakMap;let cr=class{constructor(t,i,r){if(this._$cssResult$=!0,r!==bi)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(gi&&t===void 0){const r=i!==void 0&&i.length===1;r&&(t=ar.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&ar.set(i,t))}return t}toString(){return this.cssText}};const Pn=e=>new cr(typeof e=="string"?e:e+"",void 0,bi),ce=(e,...t)=>{const i=e.length===1?e[0]:t.reduce(((r,s,n)=>r+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[n+1]),e[0]);return new cr(i,e,bi)},On=(e,t)=>{if(gi)e.adoptedStyleSheets=t.map((i=>i instanceof CSSStyleSheet?i:i.styleSheet));else for(const i of t){const r=document.createElement("style"),s=zt.litNonce;s!==void 0&&r.setAttribute("nonce",s),r.textContent=i.cssText,e.appendChild(r)}},lr=gi?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const r of t.cssRules)i+=r.cssText;return Pn(i)})(e):e;/**
6
+ * @license
7
+ * Copyright 2017 Google LLC
8
+ * SPDX-License-Identifier: BSD-3-Clause
9
+ */const{is:Vn,defineProperty:Ln,getOwnPropertyDescriptor:Bn,getOwnPropertyNames:Nn,getOwnPropertySymbols:Un,getPrototypeOf:zn}=Object,Ie=globalThis,dr=Ie.trustedTypes,Fn=dr?dr.emptyScript:"",mi=Ie.reactiveElementPolyfillSupport,$t=(e,t)=>e,Ft={toAttribute(e,t){switch(t){case Boolean:e=e?Fn:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},yi=(e,t)=>!Vn(e,t),ur={attribute:!0,type:String,converter:Ft,reflect:!1,useDefault:!1,hasChanged:yi};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ie.litPropertyMetadata??(Ie.litPropertyMetadata=new WeakMap);let st=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=ur){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const r=Symbol(),s=this.getPropertyDescriptor(t,r,i);s!==void 0&&Ln(this.prototype,t,s)}}static getPropertyDescriptor(t,i,r){const{get:s,set:n}=Bn(this.prototype,t)??{get(){return this[i]},set(o){this[i]=o}};return{get:s,set(o){const a=s==null?void 0:s.call(this);n==null||n.call(this,o),this.requestUpdate(t,a,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ur}static _$Ei(){if(this.hasOwnProperty($t("elementProperties")))return;const t=zn(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty($t("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty($t("properties"))){const i=this.properties,r=[...Nn(i),...Un(i)];for(const s of r)this.createProperty(s,i[s])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[r,s]of i)this.elementProperties.set(r,s)}this._$Eh=new Map;for(const[i,r]of this.elementProperties){const s=this._$Eu(i,r);s!==void 0&&this._$Eh.set(s,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const r=new Set(t.flat(1/0).reverse());for(const s of r)i.unshift(lr(s))}else t!==void 0&&i.push(lr(t));return i}static _$Eu(t,i){const r=i.attribute;return r===!1?void 0:typeof r=="string"?r:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$ES=new Promise((i=>this.enableUpdating=i)),this._$AL=new Map,this._$E_(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach((i=>i(this)))}addController(t){var i;(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&((i=t.hostConnected)==null||i.call(t))}removeController(t){var i;(i=this._$EO)==null||i.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const r of i.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return On(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$EO)==null||t.forEach((i=>{var r;return(r=i.hostConnected)==null?void 0:r.call(i)}))}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$EO)==null||t.forEach((i=>{var r;return(r=i.hostDisconnected)==null?void 0:r.call(i)}))}attributeChangedCallback(t,i,r){this._$AK(t,r)}_$ET(t,i){var n;const r=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,r);if(s!==void 0&&r.reflect===!0){const o=(((n=r.converter)==null?void 0:n.toAttribute)!==void 0?r.converter:Ft).toAttribute(i,r.type);this._$Em=t,o==null?this.removeAttribute(s):this.setAttribute(s,o),this._$Em=null}}_$AK(t,i){var n,o;const r=this.constructor,s=r._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=r.getPropertyOptions(s),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((n=a.converter)==null?void 0:n.fromAttribute)!==void 0?a.converter:Ft;this._$Em=s;const l=c.fromAttribute(i,a.type);this[s]=l??((o=this._$Ej)==null?void 0:o.get(s))??l,this._$Em=null}}requestUpdate(t,i,r){var s;if(t!==void 0){const n=this.constructor,o=this[t];if(r??(r=n.getPropertyOptions(t)),!((r.hasChanged??yi)(o,i)||r.useDefault&&r.reflect&&o===((s=this._$Ej)==null?void 0:s.get(t))&&!this.hasAttribute(n._$Eu(t,r))))return;this.C(t,i,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:r,reflect:s,wrapped:n},o){r&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??i??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||r||(i=void 0),this._$AL.set(t,i)),s===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var r;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[n,o]of this._$Ep)this[n]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[n,o]of s){const{wrapped:a}=o,c=this[n];a!==!0||this._$AL.has(n)||c===void 0||this.C(n,void 0,o,c)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),(r=this._$EO)==null||r.forEach((s=>{var n;return(n=s.hostUpdate)==null?void 0:n.call(s)})),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){var i;(i=this._$EO)==null||i.forEach((r=>{var s;return(s=r.hostUpdated)==null?void 0:s.call(r)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((i=>this._$ET(i,this[i])))),this._$EM()}updated(t){}firstUpdated(t){}};st.elementStyles=[],st.shadowRootOptions={mode:"open"},st[$t("elementProperties")]=new Map,st[$t("finalized")]=new Map,mi==null||mi({ReactiveElement:st}),(Ie.reactiveElementVersions??(Ie.reactiveElementVersions=[])).push("2.1.1");/**
10
+ * @license
11
+ * Copyright 2017 Google LLC
12
+ * SPDX-License-Identifier: BSD-3-Clause
13
+ */const Tt=globalThis,jt=Tt.trustedTypes,hr=jt?jt.createPolicy("lit-html",{createHTML:e=>e}):void 0,pr="$lit$",Re=`lit$${Math.random().toFixed(9).slice(2)}$`,vr="?"+Re,jn=`<${vr}>`,Be=document,Et=()=>Be.createComment(""),Mt=e=>e===null||typeof e!="object"&&typeof e!="function",_i=Array.isArray,Hn=e=>_i(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",wi=`[
14
+ \f\r]`,kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,fr=/-->/g,gr=/>/g,Ne=RegExp(`>|${wi}(?:([^\\s"'>=/]+)(${wi}*=${wi}*(?:[^
15
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),br=/'/g,mr=/"/g,yr=/^(?:script|style|textarea|title)$/i,Wn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),g=Wn(1),nt=Symbol.for("lit-noChange"),N=Symbol.for("lit-nothing"),_r=new WeakMap,Ue=Be.createTreeWalker(Be,129);function wr(e,t){if(!_i(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return hr!==void 0?hr.createHTML(t):t}const Gn=(e,t)=>{const i=e.length-1,r=[];let s,n=t===2?"<svg>":t===3?"<math>":"",o=kt;for(let a=0;a<i;a++){const c=e[a];let l,h,p=-1,b=0;for(;b<c.length&&(o.lastIndex=b,h=o.exec(c),h!==null);)b=o.lastIndex,o===kt?h[1]==="!--"?o=fr:h[1]!==void 0?o=gr:h[2]!==void 0?(yr.test(h[2])&&(s=RegExp("</"+h[2],"g")),o=Ne):h[3]!==void 0&&(o=Ne):o===Ne?h[0]===">"?(o=s??kt,p=-1):h[1]===void 0?p=-2:(p=o.lastIndex-h[2].length,l=h[1],o=h[3]===void 0?Ne:h[3]==='"'?mr:br):o===mr||o===br?o=Ne:o===fr||o===gr?o=kt:(o=Ne,s=void 0);const _=o===Ne&&e[a+1].startsWith("/>")?" ":"";n+=o===kt?c+jn:p>=0?(r.push(l),c.slice(0,p)+pr+c.slice(p)+Re+_):c+Re+(p===-2?a:_)}return[wr(e,n+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]};class At{constructor({strings:t,_$litType$:i},r){let s;this.parts=[];let n=0,o=0;const a=t.length-1,c=this.parts,[l,h]=Gn(t,i);if(this.el=At.createElement(l,r),Ue.currentNode=this.el.content,i===2||i===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(s=Ue.nextNode())!==null&&c.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const p of s.getAttributeNames())if(p.endsWith(pr)){const b=h[o++],_=s.getAttribute(p).split(Re),T=/([.?@])?(.*)/.exec(b);c.push({type:1,index:n,name:T[2],strings:_,ctor:T[1]==="."?Kn:T[1]==="?"?Jn:T[1]==="@"?Yn:Ht}),s.removeAttribute(p)}else p.startsWith(Re)&&(c.push({type:6,index:n}),s.removeAttribute(p));if(yr.test(s.tagName)){const p=s.textContent.split(Re),b=p.length-1;if(b>0){s.textContent=jt?jt.emptyScript:"";for(let _=0;_<b;_++)s.append(p[_],Et()),Ue.nextNode(),c.push({type:2,index:++n});s.append(p[b],Et())}}}else if(s.nodeType===8)if(s.data===vr)c.push({type:2,index:n});else{let p=-1;for(;(p=s.data.indexOf(Re,p+1))!==-1;)c.push({type:7,index:n}),p+=Re.length-1}n++}}static createElement(t,i){const r=Be.createElement("template");return r.innerHTML=t,r}}function ot(e,t,i=e,r){var o,a;if(t===nt)return t;let s=r!==void 0?(o=i._$Co)==null?void 0:o[r]:i._$Cl;const n=Mt(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==n&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),n===void 0?s=void 0:(s=new n(e),s._$AT(e,i,r)),r!==void 0?(i._$Co??(i._$Co=[]))[r]=s:i._$Cl=s),s!==void 0&&(t=ot(e,s._$AS(e,t.values),s,r)),t}class qn{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:r}=this._$AD,s=((t==null?void 0:t.creationScope)??Be).importNode(i,!0);Ue.currentNode=s;let n=Ue.nextNode(),o=0,a=0,c=r[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new xt(n,n.nextSibling,this,t):c.type===1?l=new c.ctor(n,c.name,c.strings,this,t):c.type===6&&(l=new Xn(n,this,t)),this._$AV.push(l),c=r[++a]}o!==(c==null?void 0:c.index)&&(n=Ue.nextNode(),o++)}return Ue.currentNode=Be,s}p(t){let i=0;for(const r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,i),i+=r.strings.length-2):r._$AI(t[i])),i++}}class xt{get _$AU(){var t;return((t=this._$AM)==null?void 0:t._$AU)??this._$Cv}constructor(t,i,r,s){this.type=2,this._$AH=N,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=r,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&(t==null?void 0:t.nodeType)===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=ot(this,t,i),Mt(t)?t===N||t==null||t===""?(this._$AH!==N&&this._$AR(),this._$AH=N):t!==this._$AH&&t!==nt&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Hn(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==N&&Mt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Be.createTextNode(t)),this._$AH=t}$(t){var n;const{values:i,_$litType$:r}=t,s=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=At.createElement(wr(r.h,r.h[0]),this.options)),r);if(((n=this._$AH)==null?void 0:n._$AD)===s)this._$AH.p(i);else{const o=new qn(s,this),a=o.u(this.options);o.p(i),this.T(a),this._$AH=o}}_$AC(t){let i=_r.get(t.strings);return i===void 0&&_r.set(t.strings,i=new At(t)),i}k(t){_i(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let r,s=0;for(const n of t)s===i.length?i.push(r=new xt(this.O(Et()),this.O(Et()),this,this.options)):r=i[s],r._$AI(n),s++;s<i.length&&(this._$AR(r&&r._$AB.nextSibling,s),i.length=s)}_$AR(t=this._$AA.nextSibling,i){var r;for((r=this._$AP)==null?void 0:r.call(this,!1,!0,i);t!==this._$AB;){const s=t.nextSibling;t.remove(),t=s}}setConnected(t){var i;this._$AM===void 0&&(this._$Cv=t,(i=this._$AP)==null||i.call(this,t))}}class Ht{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,r,s,n){this.type=1,this._$AH=N,this._$AN=void 0,this.element=t,this.name=i,this._$AM=s,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=N}_$AI(t,i=this,r,s){const n=this.strings;let o=!1;if(n===void 0)t=ot(this,t,i,0),o=!Mt(t)||t!==this._$AH&&t!==nt,o&&(this._$AH=t);else{const a=t;let c,l;for(t=n[0],c=0;c<n.length-1;c++)l=ot(this,a[r+c],i,c),l===nt&&(l=this._$AH[c]),o||(o=!Mt(l)||l!==this._$AH[c]),l===N?t=N:t!==N&&(t+=(l??"")+n[c+1]),this._$AH[c]=l}o&&!s&&this.j(t)}j(t){t===N?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class Kn extends Ht{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===N?void 0:t}}class Jn extends Ht{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==N)}}class Yn extends Ht{constructor(t,i,r,s,n){super(t,i,r,s,n),this.type=5}_$AI(t,i=this){if((t=ot(this,t,i,0)??N)===nt)return;const r=this._$AH,s=t===N&&r!==N||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,n=t!==N&&(r===N||s);s&&this.element.removeEventListener(this.name,this,r),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var i;typeof this._$AH=="function"?this._$AH.call(((i=this.options)==null?void 0:i.host)??this.element,t):this._$AH.handleEvent(t)}}class Xn{constructor(t,i,r){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(t){ot(this,t)}}const Ci=Tt.litHtmlPolyfillSupport;Ci==null||Ci(At,xt),(Tt.litHtmlVersions??(Tt.litHtmlVersions=[])).push("3.3.1");const Qn=(e,t,i)=>{const r=(i==null?void 0:i.renderBefore)??t;let s=r._$litPart$;if(s===void 0){const n=(i==null?void 0:i.renderBefore)??null;r._$litPart$=s=new xt(t.insertBefore(Et(),n),n,void 0,i??{})}return s._$AI(e),s};/**
16
+ * @license
17
+ * Copyright 2017 Google LLC
18
+ * SPDX-License-Identifier: BSD-3-Clause
19
+ */const ze=globalThis;let X=class extends st{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var i;const t=super.createRenderRoot();return(i=this.renderOptions).renderBefore??(i.renderBefore=t.firstChild),t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Qn(i,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)==null||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)==null||t.setConnected(!1)}render(){return nt}};X._$litElement$=!0,X.finalized=!0,(Dn=ze.litElementHydrateSupport)==null||Dn.call(ze,{LitElement:X});const Si=ze.litElementPolyfillSupport;Si==null||Si({LitElement:X}),(ze.litElementVersions??(ze.litElementVersions=[])).push("4.2.1");/**
20
+ * @license
21
+ * Copyright 2017 Google LLC
22
+ * SPDX-License-Identifier: BSD-3-Clause
23
+ */const ue=e=>(t,i)=>{i!==void 0?i.addInitializer((()=>{customElements.define(e,t)})):customElements.define(e,t)};/**
24
+ * @license
25
+ * Copyright 2017 Google LLC
26
+ * SPDX-License-Identifier: BSD-3-Clause
27
+ */const Zn={attribute:!0,type:String,converter:Ft,reflect:!1,hasChanged:yi},eo=(e=Zn,t,i)=>{const{kind:r,metadata:s}=i;let n=globalThis.litPropertyMetadata.get(s);if(n===void 0&&globalThis.litPropertyMetadata.set(s,n=new Map),r==="setter"&&((e=Object.create(e)).wrapped=!0),n.set(i.name,e),r==="accessor"){const{name:o}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(o,c,e)},init(a){return a!==void 0&&this.C(o,void 0,e,a),a}}}if(r==="setter"){const{name:o}=i;return function(a){const c=this[o];t.call(this,a),this.requestUpdate(o,c,e)}}throw Error("Unsupported decorator location: "+r)};function I(e){return(t,i)=>typeof i=="object"?eo(e,t,i):((r,s,n)=>{const o=s.hasOwnProperty(n);return s.constructor.createProperty(n,r),o?Object.getOwnPropertyDescriptor(s,n):void 0})(e,t,i)}/**
28
+ * @license
29
+ * Copyright 2017 Google LLC
30
+ * SPDX-License-Identifier: BSD-3-Clause
31
+ */function E(e){return I({...e,state:!0,attribute:!1})}var to=Object.defineProperty,io=Object.getOwnPropertyDescriptor,$i=(e,t,i,r)=>{for(var s=r>1?void 0:r?io(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&to(t,i,s),s};u.ExampleButton=class extends X{constructor(){super(...arguments),this.disabled=!1,this.variant="primary"}_handleClick(t){if(this.disabled){t.preventDefault(),t.stopPropagation();return}this.dispatchEvent(new CustomEvent("sw-click",{detail:{originalEvent:t},bubbles:!0,composed:!0}))}render(){return g`
32
+ <button part="button" ?disabled=${this.disabled} @click=${this._handleClick}>
33
+ <slot></slot>
34
+ </button>
35
+ `}},u.ExampleButton.styles=ce`
36
+ :host {
37
+ display: inline-block;
38
+ }
39
+
40
+ button {
41
+ padding: 0.5rem 1rem;
42
+ font-size: 1rem;
43
+ border: none;
44
+ border-radius: 4px;
45
+ background-color: #0066cc;
46
+ color: white;
47
+ cursor: pointer;
48
+ transition: background-color 0.2s;
49
+ }
50
+
51
+ button:hover {
52
+ background-color: #0052a3;
53
+ }
54
+
55
+ button:active {
56
+ background-color: #003d7a;
57
+ }
58
+
59
+ button:disabled {
60
+ background-color: #cccccc;
61
+ cursor: not-allowed;
62
+ }
63
+ `,$i([I({type:Boolean})],u.ExampleButton.prototype,"disabled",2),$i([I({type:String})],u.ExampleButton.prototype,"variant",2),u.ExampleButton=$i([ue("sw-example-button")],u.ExampleButton);/**
64
+ * @license
65
+ * Copyright 2021 Google LLC
66
+ * SPDX-License-Identifier: BSD-3-Clause
67
+ */let Cr=class extends Event{constructor(t,i,r,s){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=i,this.callback=r,this.subscribe=s??!1}};/**
68
+ * @license
69
+ * Copyright 2021 Google LLC
70
+ * SPDX-License-Identifier: BSD-3-Clause
71
+ */function Sh(e){return e}/**
72
+ * @license
73
+ * Copyright 2021 Google LLC
74
+ * SPDX-License-Identifier: BSD-3-Clause
75
+ */let Sr=class{constructor(t,i,r,s){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,i.context!==void 0){const n=i;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=i,this.callback=r,this.subscribe=s??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new Cr(this.context,this.host,this.t,this.subscribe))}};/**
76
+ * @license
77
+ * Copyright 2021 Google LLC
78
+ * SPDX-License-Identifier: BSD-3-Clause
79
+ */class ro{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,i=!1){const r=i||!Object.is(t,this.o);this.o=t,r&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(const[i,{disposer:r}]of this.subscriptions)i(this.o,r)},t!==void 0&&(this.value=t)}addCallback(t,i,r){if(!r)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:i});const{disposer:s}=this.subscriptions.get(t);t(this.value,s)}clearCallbacks(){this.subscriptions.clear()}}/**
80
+ * @license
81
+ * Copyright 2021 Google LLC
82
+ * SPDX-License-Identifier: BSD-3-Clause
83
+ */let so=class extends Event{constructor(t,i){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=i}};class $r extends ro{constructor(t,i,r){var s,n;super(i.context!==void 0?i.initialValue:r),this.onContextRequest=o=>{if(o.context!==this.context)return;const a=o.contextTarget??o.composedPath()[0];a!==this.host&&(o.stopPropagation(),this.addCallback(o.callback,a,o.subscribe))},this.onProviderRequest=o=>{if(o.context!==this.context||(o.contextTarget??o.composedPath()[0])===this.host)return;const a=new Set;for(const[c,{consumerHost:l}]of this.subscriptions)a.has(c)||(a.add(c),l.dispatchEvent(new Cr(this.context,l,c,!0)));o.stopPropagation()},this.host=t,i.context!==void 0?this.context=i.context:this.context=i,this.attachListeners(),(n=(s=this.host).addController)==null||n.call(s,this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new so(this.context,this.host))}}/**
84
+ * @license
85
+ * Copyright 2017 Google LLC
86
+ * SPDX-License-Identifier: BSD-3-Clause
87
+ */function no({context:e}){return(t,i)=>{const r=new WeakMap;if(typeof i=="object")return{get(){return t.get.call(this)},set(s){return r.get(this).setValue(s),t.set.call(this,s)},init(s){return r.set(this,new $r(this,{context:e,initialValue:s})),s}};{t.constructor.addInitializer((o=>{r.set(o,new $r(o,{context:e}))}));const s=Object.getOwnPropertyDescriptor(t,i);let n;if(s===void 0){const o=new WeakMap;n={get(){return o.get(this)},set(a){r.get(this).setValue(a),o.set(this,a)},configurable:!0,enumerable:!0}}else{const o=s.set;n={...s,set(a){r.get(this).setValue(a),o==null||o.call(this,a)}}}return void Object.defineProperty(t,i,n)}}}/**
88
+ * @license
89
+ * Copyright 2022 Google LLC
90
+ * SPDX-License-Identifier: BSD-3-Clause
91
+ */function Dt({context:e,subscribe:t}){return(i,r)=>{typeof r=="object"?r.addInitializer((function(){new Sr(this,{context:e,callback:s=>{i.set.call(this,s)},subscribe:t})})):i.constructor.addInitializer((s=>{new Sr(s,{context:e,callback:n=>{s[r]=n},subscribe:t})}))}}const Fe="call";function oo(e,t){let i=null;return function(...s){const n=()=>{i=null,e(...s)};i!==null&&clearTimeout(i),i=setTimeout(n,t)}}const ao=2e3;function co(e){return new Promise(t=>{if(e.readyState>=HTMLMediaElement.HAVE_METADATA){t();return}let i=!1;const r=()=>{i||(i=!0,clearTimeout(s),e.removeEventListener("canplay",r),e.removeEventListener("resize",r),t())},s=setTimeout(r,ao);e.addEventListener("canplay",r),e.addEventListener("resize",r)})}function lo(e,t){e.srcObject=t}function uo(e){e.srcObject&&(e.srcObject=null)}var ho=Object.defineProperty,po=Object.getOwnPropertyDescriptor,Ti=(e,t,i,r)=>{for(var s=r>1?void 0:r?po(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&ho(t,i,s),s};u.CallMedia=class extends X{constructor(){super(...arguments),this._remoteStreamValue=null,this.subscriptions=[]}connectedCallback(){super.connectedCallback(),this._providedCall=this.call,this.setupSubscriptions()}updated(t){super.updated(t),t.has("call")&&(this.cleanupSubscriptions(),this._providedCall=this.call,this.setupSubscriptions())}disconnectedCallback(){super.disconnectedCallback(),this.cleanupSubscriptions(),this.cleanupResizeObserver(),this.cleanupVideoElement()}firstUpdated(){var i;const t=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");t&&co(t).then(()=>{this.isConnected&&this.setupResizeObserver()})}setupSubscriptions(){this.call&&this.subscriptions.push(this.call.remoteStream$.subscribe(t=>{var r;this._remoteStreamValue=t,this.requestUpdate();const i=(r=this.shadowRoot)==null?void 0:r.querySelector("video.mcu-video");i&&lo(i,t)}))}cleanupSubscriptions(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[]}setupResizeObserver(){var r,s;const t=(r=this.shadowRoot)==null?void 0:r.querySelector("video.mcu-video"),i=(s=this.shadowRoot)==null?void 0:s.querySelector(".padding-wrapper");!t||!i||(this._videoElement=t,this._paddingWrapper=i,this.resizeObserver=new ResizeObserver(oo(()=>{this.recalculateDimensions()},50)),this.resizeObserver.observe(this),this.videoResizeHandler=()=>{this.recalculateDimensions()},t.addEventListener("resize",this.videoResizeHandler),this.windowResizeHandler=()=>{requestAnimationFrame(()=>{this.recalculateDimensions()})},window.addEventListener("resize",this.windowResizeHandler),this.recalculateDimensions())}recalculateDimensions(){const t=this._videoElement,i=this._paddingWrapper;if(!t||!i)return;if(!t.videoWidth||!t.videoHeight){i.style.width="100%",i.style.height="100%",i.style.paddingBottom="0",i.style.transform="none";return}const r=window.innerWidth,s=window.innerHeight,n=this.getBoundingClientRect(),o=n.width,a=n.height;if(o<=0||a<=0)return;const c=Math.min(1,(r-n.left)/o),l=Math.min(1,(s-n.top)/a),h=Math.min(c,l),p=o*h,b=a*h;if(p<=0||b<=0)return;const _=t.videoWidth,T=t.videoHeight,m=_/T,x=p/b;let w,G;m>x?(w=p,G=w/m):(G=b,w=G*m);const de=Math.max(0,n.left),Te=Math.max(0,n.top),J=Math.min(r,n.right),Le=Math.min(s,n.bottom),pi=(de+J)/2,or=(Te+Le)/2,rt=n.left+o/2,vi=n.top+a/2,V=pi-rt,Y=or-vi;i.style.width=`${w}px`,i.style.height=`${G}px`,i.style.paddingBottom="0",i.style.transform=`translate(${V}px, ${Y}px)`}cleanupResizeObserver(){var i;this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0);const t=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");t&&this.videoResizeHandler&&(t.removeEventListener("resize",this.videoResizeHandler),this.videoResizeHandler=void 0),this.windowResizeHandler&&(window.removeEventListener("resize",this.windowResizeHandler),this.windowResizeHandler=void 0)}cleanupVideoElement(){var i;const t=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");t&&uo(t)}render(){return g`
92
+ <div class="mcu-content" part="container">
93
+ <div class="padding-wrapper">
94
+ <div class="mcu-wrapper">
95
+ <video
96
+ class="mcu-video"
97
+ part="video"
98
+ autoplay
99
+ playsinline
100
+ muted
101
+ .srcObject=${this._remoteStreamValue}
102
+ ></video>
103
+ </div>
104
+ <div class="mcu-layers">
105
+ <slot></slot>
106
+ </div>
107
+ </div>
108
+ </div>
109
+ `}},u.CallMedia.styles=ce`
110
+ :host {
111
+ /* CSS Custom Properties for theming */
112
+ --sw-color-primary: #044cf6;
113
+ --sw-color-background: #000000;
114
+ --sw-border-radius: 0px;
115
+
116
+ display: block;
117
+ width: 100%;
118
+ height: 100%;
119
+ overflow: hidden;
120
+ }
121
+
122
+ .mcu-content {
123
+ position: relative;
124
+ width: 100%;
125
+ height: 100%;
126
+ margin: 0 auto;
127
+ display: flex;
128
+ align-items: center;
129
+ justify-content: center;
130
+ background-color: var(--sw-color-background);
131
+ border-radius: var(--sw-border-radius);
132
+ overflow: hidden;
133
+ }
134
+
135
+ .padding-wrapper {
136
+ position: relative;
137
+ max-width: 100%;
138
+ max-height: 100%;
139
+ transition:
140
+ width 0.3s ease,
141
+ height 0.3s ease;
142
+ }
143
+
144
+ .mcu-wrapper {
145
+ position: absolute;
146
+ top: 0;
147
+ left: 0;
148
+ right: 0;
149
+ bottom: 0;
150
+ border-radius: var(--sw-border-radius);
151
+ overflow: hidden;
152
+ }
153
+
154
+ .mcu-video {
155
+ width: 100%;
156
+ height: 100%;
157
+ display: block;
158
+ object-fit: contain;
159
+ }
160
+
161
+ .mcu-layers {
162
+ position: absolute;
163
+ top: 0;
164
+ left: 0;
165
+ width: 100%;
166
+ height: 100%;
167
+ pointer-events: none;
168
+ }
169
+ `,Ti([I({type:Object})],u.CallMedia.prototype,"call",2),Ti([no({context:Fe})],u.CallMedia.prototype,"_providedCall",2),u.CallMedia=Ti([ue("sw-call-media")],u.CallMedia);function Tr(e){var t;return(t=e==null?void 0:e.self)==null?void 0:t.id}function $h(e){return e}var vo=Object.defineProperty,fo=Object.getOwnPropertyDescriptor,Wt=(e,t,i,r)=>{for(var s=r>1?void 0:r?fo(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&vo(t,i,s),s};u.Participants=class extends X{constructor(){super(...arguments),this._layoutLayersValue=[],this._participantsValue=[],this._openMenuId=null,this.subscriptions=[]}set call(t){this._call=t,this.cleanupSubscriptions(),this.setupSubscriptions()}get call(){return this._call}connectedCallback(){super.connectedCallback(),this.setupSubscriptions()}updated(t){super.updated(t),t.has("_call")&&this._call&&(this.cleanupSubscriptions(),this.setupSubscriptions())}disconnectedCallback(){super.disconnectedCallback(),this.cleanupSubscriptions()}setupSubscriptions(){this._call&&(this.subscriptions.push(this._call.layoutLayers$.subscribe(t=>{this._layoutLayersValue=t,this.requestUpdate()})),this._call.participants$&&this.subscriptions.push(this._call.participants$.subscribe(t=>{this._participantsValue=t,this.requestUpdate()})),this._handleOutsideClick=this._handleOutsideClick.bind(this),document.addEventListener("click",this._handleOutsideClick))}_handleOutsideClick(t){const i=t.target;!i.closest(".menu-trigger")&&!i.closest(".menu-dropdown")&&(this._openMenuId=null)}_toggleMenu(t,i){i.stopPropagation(),this._openMenuId=this._openMenuId===t?null:t}_getParticipant(t){return this._participantsValue.find(i=>i.id===t)}async _handleMuteAudio(t,i){i.stopPropagation();const r=this._getParticipant(t);if(r){try{r.audioMuted&&r.unmute?await r.unmute():!r.audioMuted&&r.mute&&await r.mute(),this.dispatchEvent(new CustomEvent("sw-participant-mute-audio",{detail:{participant:r,memberId:t},bubbles:!0,composed:!0}))}catch{}this._openMenuId=null}}async _handleMuteVideo(t,i){i.stopPropagation();const r=this._getParticipant(t);if(r){try{r.videoMuted&&r.unmuteVideo?await r.unmuteVideo():!r.videoMuted&&r.muteVideo&&await r.muteVideo(),this.dispatchEvent(new CustomEvent("sw-participant-mute-video",{detail:{participant:r,memberId:t},bubbles:!0,composed:!0}))}catch{}this._openMenuId=null}}async _handleRemove(t,i){i.stopPropagation();const r=this._getParticipant(t);if(r!=null&&r.remove){try{await r.remove(),this.dispatchEvent(new CustomEvent("sw-participant-remove",{detail:{participant:r,memberId:t},bubbles:!0,composed:!0}))}catch{}this._openMenuId=null}}cleanupSubscriptions(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[],document.removeEventListener("click",this._handleOutsideClick)}renderMemberOverlays(){if(!this._layoutLayersValue||this._layoutLayersValue.length===0)return null;const t=Tr(this._call);return this._layoutLayersValue.filter(i=>i.member_id).map(i=>this.renderOverlay(i,i.member_id===t))}renderMenuIcon(){return g`
170
+ <svg viewBox="0 0 24 24" fill="currentColor">
171
+ <circle cx="12" cy="6" r="2" />
172
+ <circle cx="12" cy="12" r="2" />
173
+ <circle cx="12" cy="18" r="2" />
174
+ </svg>
175
+ `}renderMenuDropdown(t){const i=this._getParticipant(t),r=this._openMenuId===t;return g`
176
+ <div class="menu-dropdown ${r?"open":""}">
177
+ <button
178
+ class="menu-item"
179
+ @click=${s=>this._handleMuteAudio(t,s)}
180
+ aria-label="${i!=null&&i.audioMuted?"Unmute audio":"Mute audio"}"
181
+ >
182
+ ${i!=null&&i.audioMuted?g`<svg viewBox="0 0 24 24" fill="currentColor">
183
+ <path
184
+ d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"
185
+ />
186
+ </svg>`:g`<svg viewBox="0 0 24 24" fill="currentColor">
187
+ <path
188
+ d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"
189
+ />
190
+ </svg>`}
191
+ ${i!=null&&i.audioMuted?"Unmute":"Mute"}
192
+ </button>
193
+ <button
194
+ class="menu-item"
195
+ @click=${s=>this._handleMuteVideo(t,s)}
196
+ aria-label="${i!=null&&i.videoMuted?"Enable video":"Disable video"}"
197
+ >
198
+ ${i!=null&&i.videoMuted?g`<svg viewBox="0 0 24 24" fill="currentColor">
199
+ <path
200
+ d="M21 6.5l-4 4V7c0-.55-.45-1-1-1H9.82L21 17.18V6.5zM3.27 2L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73 3.27 2z"
201
+ />
202
+ </svg>`:g`<svg viewBox="0 0 24 24" fill="currentColor">
203
+ <path
204
+ d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"
205
+ />
206
+ </svg>`}
207
+ ${i!=null&&i.videoMuted?"Enable video":"Disable video"}
208
+ </button>
209
+ <button
210
+ class="menu-item danger"
211
+ @click=${s=>this._handleRemove(t,s)}
212
+ aria-label="Remove participant"
213
+ >
214
+ <svg viewBox="0 0 24 24" fill="currentColor">
215
+ <path
216
+ d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
217
+ />
218
+ </svg>
219
+ Remove
220
+ </button>
221
+ </div>
222
+ `}renderOverlay(t,i=!1){const r=`
223
+ position: absolute;
224
+ top: ${t.y}%;
225
+ left: ${t.x}%;
226
+ width: ${t.width}%;
227
+ height: ${t.height}%;
228
+ opacity: ${t.visible?1:0};
229
+ overflow: visible;
230
+ transition: top 0.3s ease, left 0.3s ease, width 0.3s ease, height 0.3s ease, opacity 0.3s ease;
231
+ pointer-events: auto;
232
+ z-index: 10;
233
+ `,s=t.member_id,n=`member-overlay member-overlay-${s}${i?" is-self":""}`;return g`
234
+ <div class="${n}" part="overlay" style="${r}">
235
+ ${i?null:g`
236
+ <button
237
+ class="menu-trigger"
238
+ part="menu-trigger"
239
+ @click=${o=>this._toggleMenu(s,o)}
240
+ aria-label="Participant menu"
241
+ aria-expanded="${this._openMenuId===s}"
242
+ aria-haspopup="menu"
243
+ >
244
+ ${this.renderMenuIcon()}
245
+ </button>
246
+ ${this.renderMenuDropdown(s)}
247
+ `}
248
+ <span class="member-name" part="name"></span>
249
+ <span class="member-indicators" part="indicators"></span>
250
+ <slot name="controls-${s}"></slot>
251
+ </div>
252
+ `}render(){return g`
253
+ ${this.renderMemberOverlays()}
254
+ <slot></slot>
255
+ `}},u.Participants.styles=ce`
256
+ :host {
257
+ display: contents; /* Doesn't create a box, children inherit positioning */
258
+ }
259
+
260
+ .member-overlay {
261
+ box-sizing: border-box;
262
+ /* Thick inset box-shadow with semi-transparent background for debugging */
263
+ box-shadow: inset 0 0 0 8px rgba(255, 0, 0, 0.8);
264
+ background-color: rgba(255, 0, 0, 0.1);
265
+ }
266
+
267
+ .member-overlay.is-self {
268
+ /* Self overlay uses blue border to distinguish from other participants */
269
+ box-shadow: inset 0 0 0 8px rgba(0, 0, 255, 0.8);
270
+ background-color: rgba(0, 0, 255, 0.1);
271
+ }
272
+
273
+ /* Circular menu trigger button */
274
+ .menu-trigger {
275
+ position: absolute;
276
+ top: 12px;
277
+ left: 12px;
278
+ width: 36px;
279
+ height: 36px;
280
+ border-radius: 50%;
281
+ background: rgba(0, 0, 0, 0.6);
282
+ border: 2px solid rgba(255, 255, 255, 0.3);
283
+ color: white;
284
+ cursor: pointer;
285
+ display: flex;
286
+ align-items: center;
287
+ justify-content: center;
288
+ transition:
289
+ background 0.2s ease,
290
+ transform 0.2s ease,
291
+ border-color 0.2s ease;
292
+ z-index: 20;
293
+ }
294
+
295
+ .menu-trigger:hover {
296
+ background: rgba(0, 0, 0, 0.8);
297
+ border-color: rgba(255, 255, 255, 0.6);
298
+ transform: scale(1.1);
299
+ }
300
+
301
+ .menu-trigger:focus {
302
+ outline: none;
303
+ border-color: #044cf6;
304
+ box-shadow: 0 0 0 3px rgba(4, 78, 246, 0.4);
305
+ }
306
+
307
+ .menu-trigger svg {
308
+ width: 20px;
309
+ height: 20px;
310
+ }
311
+
312
+ /* Dropdown menu */
313
+ .menu-dropdown {
314
+ position: absolute;
315
+ top: 12px;
316
+ left: 56px;
317
+ background: rgba(31, 41, 55, 0.95);
318
+ backdrop-filter: blur(8px);
319
+ border-radius: 8px;
320
+ padding: 8px 0;
321
+ min-width: 160px;
322
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
323
+ z-index: 30;
324
+ opacity: 0;
325
+ visibility: hidden;
326
+ transform: translateX(-10px);
327
+ transition:
328
+ opacity 0.2s ease,
329
+ transform 0.2s ease,
330
+ visibility 0.2s ease;
331
+ }
332
+
333
+ .menu-dropdown.open {
334
+ opacity: 1;
335
+ visibility: visible;
336
+ transform: translateX(0);
337
+ }
338
+
339
+ .menu-item {
340
+ display: flex;
341
+ align-items: center;
342
+ gap: 8px;
343
+ padding: 8px 16px;
344
+ color: white;
345
+ font-size: 14px;
346
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
347
+ cursor: pointer;
348
+ transition: background 0.15s ease;
349
+ border: none;
350
+ background: none;
351
+ width: 100%;
352
+ text-align: left;
353
+ }
354
+
355
+ .menu-item:hover {
356
+ background: rgba(255, 255, 255, 0.1);
357
+ }
358
+
359
+ .menu-item svg {
360
+ width: 16px;
361
+ height: 16px;
362
+ flex-shrink: 0;
363
+ }
364
+
365
+ .menu-item.danger {
366
+ color: #ef4444;
367
+ }
368
+
369
+ .menu-item.danger:hover {
370
+ background: rgba(239, 68, 68, 0.2);
371
+ }
372
+ `,Wt([Dt({context:Fe,subscribe:!0}),I({attribute:!1})],u.Participants.prototype,"_call",2),Wt([I({attribute:!1})],u.Participants.prototype,"call",1),Wt([E()],u.Participants.prototype,"_openMenuId",2),u.Participants=Wt([ue("sw-participants")],u.Participants);var go=Object.defineProperty,bo=Object.getOwnPropertyDescriptor,Gt=(e,t,i,r)=>{for(var s=r>1?void 0:r?bo(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&go(t,i,s),s};u.SelfMedia=class extends X{constructor(){super(...arguments),this.mirror=!1,this._localStreamValue=null,this._layoutLayersValue=[],this.subscriptions=[]}set call(t){this._call=t,this.cleanupSubscriptions(),this.setupSubscriptions()}get call(){return this._call}connectedCallback(){super.connectedCallback(),this.setupSubscriptions()}updated(t){super.updated(t),t.has("_call")&&this._call&&(this.cleanupSubscriptions(),this.setupSubscriptions())}disconnectedCallback(){super.disconnectedCallback(),this.cleanupSubscriptions()}setupSubscriptions(){this._call&&(this.subscriptions.push(this._call.localStream$.subscribe(t=>{this._localStreamValue=t,this.requestUpdate()})),this.subscriptions.push(this._call.layoutLayers$.subscribe(t=>{this._layoutLayersValue=t,this.requestUpdate()})))}cleanupSubscriptions(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[]}getSelfLayer(){const t=Tr(this._call);return this._layoutLayersValue.find(i=>i.member_id===t)}render(){var n;const t=this.getSelfLayer();if(!t||!((((n=this._localStreamValue)==null?void 0:n.getVideoTracks().length)??0)>0))return null;const r=`
373
+ position: absolute;
374
+ top: ${t.y}%;
375
+ left: ${t.x}%;
376
+ width: ${t.width}%;
377
+ height: ${t.height}%;
378
+ opacity: ${t.visible?1:0};
379
+ overflow: hidden;
380
+ transition: top 0.3s ease, left 0.3s ease, width 0.3s ease, height 0.3s ease, opacity 0.3s ease;
381
+ pointer-events: none;
382
+ `,s=this.mirror?"transform: scale(-1, 1); -webkit-transform: scale(-1, 1);":"";return g`
383
+ <div class="local-overlay" part="container" style="${r}">
384
+ <video
385
+ class="local-video"
386
+ part="video"
387
+ style="width: 100%; height: 100%; object-fit: cover; ${s}"
388
+ autoplay
389
+ playsinline
390
+ muted
391
+ disablePictureInPicture
392
+ .srcObject=${this._localStreamValue}
393
+ ></video>
394
+ </div>
395
+ `}},u.SelfMedia.styles=ce`
396
+ :host {
397
+ display: contents; /* Doesn't create a box, children inherit positioning */
398
+ }
399
+
400
+ .local-overlay {
401
+ box-sizing: border-box;
402
+ }
403
+
404
+ video {
405
+ display: block;
406
+ }
407
+ `,Gt([I({type:Boolean})],u.SelfMedia.prototype,"mirror",2),Gt([Dt({context:Fe,subscribe:!0}),I({attribute:!1})],u.SelfMedia.prototype,"_call",2),Gt([I({attribute:!1})],u.SelfMedia.prototype,"call",1),u.SelfMedia=Gt([ue("sw-self-media")],u.SelfMedia);var mo=Object.defineProperty,yo=Object.getOwnPropertyDescriptor,at=(e,t,i,r)=>{for(var s=r>1?void 0:r?yo(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&mo(t,i,s),s};u.AudioLevel=class extends X{constructor(){super(...arguments),this.bars=5,this.orientation="vertical",this.maxSize=32,this._levels=[]}connectedCallback(){super.connectedCallback(),this._levels=new Array(this.bars).fill(0),this.stream&&this.setupAudioAnalysis()}updated(t){super.updated(t),t.has("stream")&&(this.cleanupAudioAnalysis(),this.stream&&this.setupAudioAnalysis()),t.has("bars")&&(this._levels=new Array(this.bars).fill(0))}disconnectedCallback(){super.disconnectedCallback(),this.cleanupAudioAnalysis()}releaseResources(){this.cleanupAudioAnalysis(),this.stream=void 0}setupAudioAnalysis(){if(!this.stream)return;if(this.stream.getAudioTracks().length===0){console.warn("sw-audio-level: MediaStream has no audio tracks");return}try{this._audioContext=new AudioContext,this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=256,this._analyser.smoothingTimeConstant=.8,this._source=this._audioContext.createMediaStreamSource(this.stream),this._source.connect(this._analyser);const i=this._analyser.frequencyBinCount;this._dataArray=new Uint8Array(i),this.startAnimationLoop()}catch(i){console.error("sw-audio-level: Failed to setup audio analysis:",i)}}cleanupAudioAnalysis(){this._animationFrameId!==void 0&&(cancelAnimationFrame(this._animationFrameId),this._animationFrameId=void 0),this._source&&(this._source.disconnect(),this._source=void 0),this._analyser&&(this._analyser.disconnect(),this._analyser=void 0),this._audioContext&&this._audioContext.state!=="closed"&&(this._audioContext.close().catch(console.error),this._audioContext=void 0),this._dataArray=void 0,this._levels=new Array(this.bars).fill(0)}startAnimationLoop(){const t=()=>{const i=this._analyser,r=this._dataArray;if(!i||!r)return;i.getByteFrequencyData(r);const s=[],n=r.length,o=Math.floor(n/this.bars);for(let a=0;a<this.bars;a++){const c=a*o,l=Math.min(c+o,n);let h=0;for(let b=c;b<l;b++)h+=r[b]??0;const p=h/(l-c);s.push(p/255)}this._levels=s,this.requestUpdate(),this._animationFrameId=requestAnimationFrame(t)};this._animationFrameId=requestAnimationFrame(t)}getLevelClass(t){return t>.7?"level-high":t>.4?"level-medium":t>.05?"level-low":""}isActive(t){return t>.05}render(){const t=this._levels.length===this.bars?this._levels:new Array(this.bars).fill(0);return g`
408
+ <div class="container" part="container">
409
+ ${t.map((i,r)=>{const s=this.isActive(i),n=this.getLevelClass(i),o=Math.max(4,i*this.maxSize),a=this.orientation==="horizontal"?`width: ${o}px;`:`height: ${o}px;`;return g`
410
+ <div
411
+ class="bar ${s?"active":""} ${n}"
412
+ part="bar ${s?"bar-active":""}"
413
+ style="${a}"
414
+ data-bar-index="${r}"
415
+ ></div>
416
+ `})}
417
+ </div>
418
+ `}},u.AudioLevel.styles=ce`
419
+ :host {
420
+ /* CSS Custom Properties for theming */
421
+ --sw-color-success: #10b981;
422
+ --sw-color-warning: #f59e0b;
423
+ --sw-color-danger: #ef4444;
424
+ --sw-audio-bar-width: 4px;
425
+ --sw-audio-bar-gap: 2px;
426
+ --sw-audio-bar-radius: 2px;
427
+ --sw-audio-bar-background: rgba(255, 255, 255, 0.2);
428
+
429
+ display: inline-flex;
430
+ }
431
+
432
+ .container {
433
+ display: flex;
434
+ align-items: flex-end;
435
+ justify-content: center;
436
+ gap: var(--sw-audio-bar-gap);
437
+ }
438
+
439
+ :host([orientation='horizontal']) .container {
440
+ flex-direction: row;
441
+ align-items: center;
442
+ }
443
+
444
+ :host([orientation='vertical']) .container,
445
+ .container {
446
+ flex-direction: row;
447
+ align-items: flex-end;
448
+ }
449
+
450
+ .bar {
451
+ width: var(--sw-audio-bar-width);
452
+ background: var(--sw-audio-bar-background);
453
+ border-radius: var(--sw-audio-bar-radius);
454
+ transition:
455
+ height 0.05s ease-out,
456
+ width 0.05s ease-out,
457
+ background-color 0.1s ease;
458
+ min-height: 4px;
459
+ }
460
+
461
+ :host([orientation='horizontal']) .bar {
462
+ height: var(--sw-audio-bar-width);
463
+ width: 4px;
464
+ min-width: 4px;
465
+ min-height: auto;
466
+ }
467
+
468
+ .bar.active {
469
+ /* Color is set dynamically via inline style */
470
+ }
471
+
472
+ .bar.level-low {
473
+ background-color: var(--sw-color-success);
474
+ }
475
+
476
+ .bar.level-medium {
477
+ background-color: var(--sw-color-warning);
478
+ }
479
+
480
+ .bar.level-high {
481
+ background-color: var(--sw-color-danger);
482
+ }
483
+ `,at([I({type:Object})],u.AudioLevel.prototype,"stream",2),at([I({type:Number})],u.AudioLevel.prototype,"bars",2),at([I({type:String,reflect:!0})],u.AudioLevel.prototype,"orientation",2),at([I({type:Number})],u.AudioLevel.prototype,"maxSize",2),at([E()],u.AudioLevel.prototype,"_levels",2),u.AudioLevel=at([ue("sw-audio-level")],u.AudioLevel);var _o=Object.defineProperty,wo=Object.getOwnPropertyDescriptor,he=(e,t,i,r)=>{for(var s=r>1?void 0:r?wo(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&_o(t,i,s),s};u.DeviceSelector=class extends X{constructor(){super(...arguments),this.showPreview=!1,this._audioInputDevices=[],this._videoInputDevices=[],this._audioOutputDevices=[],this._selectedAudioInput=null,this._selectedVideoInput=null,this._selectedAudioOutput=null,this._videoPreviewStream=null,this._audioPreviewStream=null,this._isTestingAudio=!1,this._isComponentVisible=!1,this._isInViewport=!1,this._isDocumentVisible=!0,this._isCSSVisible=!0,this.subscriptions=[],this._boundHandleDocumentVisibility=this.handleDocumentVisibilityChange.bind(this),this._isInitializingPreviews=!1}connectedCallback(){super.connectedCallback(),this.setupSubscriptions(),this.setupVisibilityObservers()}updated(t){super.updated(t),t.has("deviceController")&&(this.cleanupSubscriptions(),this.setupSubscriptions()),t.has("showPreview")&&(this.showPreview&&this._isComponentVisible?this.initializePreviews():this.showPreview||(this.cleanupVideoPreviewStream(),this.cleanupAudioPreviewStream()))}disconnectedCallback(){super.disconnectedCallback(),this.cleanupSubscriptions(),this.cleanupVisibilityObservers(),this.cleanupVideoPreviewStream(),this.cleanupAudioPreviewStream(),this.stopTestAudio()}setupVisibilityObservers(){this.cleanupVisibilityObservers(),this._intersectionObserver=new IntersectionObserver(t=>{const i=t[0];i&&(this._isInViewport=i.isIntersecting,this.updateVisibilityState())},{threshold:0}),this._intersectionObserver.observe(this),this._isDocumentVisible=document.visibilityState==="visible",document.addEventListener("visibilitychange",this._boundHandleDocumentVisibility),this._isCSSVisible=this.checkCSSVisibility(),this._cssVisibilityCheckInterval=setInterval(()=>{const t=this._isCSSVisible;this._isCSSVisible=this.checkCSSVisibility(),t!==this._isCSSVisible&&this.updateVisibilityState()},u.DeviceSelector.CSS_VISIBILITY_CHECK_INTERVAL_MS)}cleanupVisibilityObservers(){this._intersectionObserver&&(this._intersectionObserver.disconnect(),this._intersectionObserver=void 0),document.removeEventListener("visibilitychange",this._boundHandleDocumentVisibility),this._cssVisibilityCheckInterval&&(clearInterval(this._cssVisibilityCheckInterval),this._cssVisibilityCheckInterval=void 0)}handleDocumentVisibilityChange(){this._isDocumentVisible=document.visibilityState==="visible",this.updateVisibilityState()}checkCSSVisibility(){if(!this.isConnected)return!1;let t=this;for(;t;){const i=getComputedStyle(t);if(i.display==="none"||i.visibility==="hidden"||parseFloat(i.opacity)===0)return!1;if(t.parentElement)t=t.parentElement;else{const r=t.getRootNode();t=r instanceof ShadowRoot?r.host:null}}return!0}updateVisibilityState(){const t=this._isComponentVisible;this._isComponentVisible=this._isInViewport&&this._isDocumentVisible&&this._isCSSVisible,t!==this._isComponentVisible&&(this._isComponentVisible&&this.showPreview?this.initializePreviews():this._isComponentVisible||(this.cleanupVideoPreviewStream(),this.cleanupAudioPreviewStream()))}setupSubscriptions(){this.deviceController&&(this.subscriptions.push(this.deviceController.audioInputDevices$.subscribe(t=>{this._audioInputDevices=t})),this.subscriptions.push(this.deviceController.videoInputDevices$.subscribe(t=>{this._videoInputDevices=t})),this.subscriptions.push(this.deviceController.audioOutputDevices$.subscribe(t=>{this._audioOutputDevices=t})),this.deviceController.selectedAudioInputDevice$&&this.subscriptions.push(this.deviceController.selectedAudioInputDevice$.subscribe(t=>{this._selectedAudioInput=t})),this.deviceController.selectedVideoInputDevice$&&this.subscriptions.push(this.deviceController.selectedVideoInputDevice$.subscribe(t=>{this._selectedVideoInput=t})),this.deviceController.selectedAudioOutputDevice$&&this.subscriptions.push(this.deviceController.selectedAudioOutputDevice$.subscribe(t=>{this._selectedAudioOutput=t})))}cleanupSubscriptions(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[]}cleanupVideoPreviewStream(){var i;this._videoElement&&(this._videoElement.pause(),this._videoElement.srcObject=null,this._videoElement=void 0);const t=(i=this.shadowRoot)==null?void 0:i.querySelector("video");t&&(t.pause(),t.srcObject=null),this._videoPreviewStream&&(this._videoPreviewStream.getTracks().forEach(s=>{var n;(n=this._videoPreviewStream)==null||n.removeTrack(s),s.stop()}),this._videoPreviewStream=null)}cleanupAudioPreviewStream(){var i;const t=(i=this.shadowRoot)==null?void 0:i.querySelectorAll("sw-audio-level");t==null||t.forEach(r=>{const s=r;s.releaseResources?s.releaseResources():s.stream=void 0}),this._audioPreviewStream&&(this._audioPreviewStream.getTracks().forEach(s=>{var n;(n=this._audioPreviewStream)==null||n.removeTrack(s),s.stop()}),this._audioPreviewStream=null)}async getVideoPreviewStream(t){if(this.cleanupVideoPreviewStream(),!!this.showPreview)try{const i={video:t?{deviceId:{exact:t}}:!0,audio:!1};this._videoPreviewStream=await navigator.mediaDevices.getUserMedia(i),this.updateVideoElement()}catch(i){console.warn("Failed to get video preview stream:",i),this._videoPreviewStream=null}}async getAudioPreviewStream(t){if(this.cleanupAudioPreviewStream(),!!this.showPreview)try{const i={video:!1,audio:t?{deviceId:{exact:t}}:!0};this._audioPreviewStream=await navigator.mediaDevices.getUserMedia(i)}catch(i){console.warn("Failed to get audio preview stream:",i),this._audioPreviewStream=null}}updateVideoElement(){this._videoElement&&this._videoPreviewStream&&(this._videoElement.srcObject=this._videoPreviewStream)}async initializePreviews(){var t,i;if(!(!this.showPreview||this._isInitializingPreviews)){this._isInitializingPreviews=!0;try{if(this._videoInputDevices.length>0){const r=(t=this._selectedVideoInput)==null?void 0:t.deviceId;await this.getVideoPreviewStream(r)}if(this._audioInputDevices.length>0){const r=(i=this._selectedAudioInput)==null?void 0:i.deviceId;await this.getAudioPreviewStream(r)}}finally{this._isInitializingPreviews=!1}}}handleDeviceChange(t,i){var o,a,c,l,h,p;if(!this.deviceController)return;const s=t.target.value;let n=null;switch(i){case"microphone":n=this._audioInputDevices.find(b=>b.deviceId===s)||null,this._selectedAudioInput=n,(a=(o=this.deviceController).selectAudioInputDevice)==null||a.call(o,n),this.showPreview&&this.getAudioPreviewStream(s);break;case"camera":n=this._videoInputDevices.find(b=>b.deviceId===s)||null,this._selectedVideoInput=n,(l=(c=this.deviceController).selectVideoInputDevice)==null||l.call(c,n),this.showPreview&&this.getVideoPreviewStream(s);break;case"speaker":n=this._audioOutputDevices.find(b=>b.deviceId===s)||null,this._selectedAudioOutput=n,(p=(h=this.deviceController).selectAudioOutputDevice)==null||p.call(h,n);break}n&&this.dispatchEvent(new CustomEvent("sw-device-change",{detail:{device:n,deviceType:i},bubbles:!0,composed:!0}))}async testSpeaker(){if(this._isTestingAudio){this.stopTestAudio();return}try{this._isTestingAudio=!0;const t=new AudioContext,i=t.createOscillator(),r=t.createGain();i.type="sine",i.frequency.value=440,r.gain.value=.3,i.connect(r),r.connect(t.destination),i.start(),setTimeout(()=>{i.stop(),t.close(),this._isTestingAudio=!1},1e3),this.dispatchEvent(new CustomEvent("sw-test-speaker",{bubbles:!0,composed:!0}))}catch(t){console.error("Failed to play test audio:",t),this._isTestingAudio=!1}}stopTestAudio(){this._testAudioElement&&(this._testAudioElement.pause(),this._testAudioElement=void 0),this._isTestingAudio=!1}renderDeviceIcon(t){switch(t){case"microphone":return g`<svg class="device-icon" viewBox="0 0 24 24" fill="currentColor">
484
+ <path
485
+ d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.91-3c-.49 0-.9.36-.98.85C16.52 14.2 14.47 16 12 16s-4.52-1.8-4.93-4.15c-.08-.49-.49-.85-.98-.85-.61 0-1.09.54-1 1.14.49 3 2.89 5.35 5.91 5.78V20c0 .55.45 1 1 1s1-.45 1-1v-2.08c3.02-.43 5.42-2.78 5.91-5.78.1-.6-.39-1.14-1-1.14z"
486
+ />
487
+ </svg>`;case"camera":return g`<svg class="device-icon" viewBox="0 0 24 24" fill="currentColor">
488
+ <path
489
+ d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"
490
+ />
491
+ </svg>`;case"speaker":return g`<svg class="device-icon" viewBox="0 0 24 24" fill="currentColor">
492
+ <path
493
+ d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"
494
+ />
495
+ </svg>`}}renderSelectArrow(){return g`<svg class="select-arrow" viewBox="0 0 24 24" fill="currentColor">
496
+ <path d="M7 10l5 5 5-5z" />
497
+ </svg>`}renderDeviceSection(t,i,r,s){return g`
498
+ <div class="device-section" part="device-section">
499
+ <label class="device-label" for="select-${t}">
500
+ ${this.renderDeviceIcon(t)}
501
+ <span>${i}</span>
502
+ </label>
503
+ ${r.length===0?g`<div class="no-devices">No ${i.toLowerCase()} found</div>`:g`
504
+ <div class="device-select-wrapper">
505
+ <select
506
+ id="select-${t}"
507
+ class="device-select"
508
+ part="device-select"
509
+ aria-label="${i}"
510
+ .value=${(s==null?void 0:s.deviceId)||""}
511
+ @change=${n=>this.handleDeviceChange(n,t)}
512
+ >
513
+ ${r.map(n=>g`
514
+ <option
515
+ value="${n.deviceId}"
516
+ ?selected=${(s==null?void 0:s.deviceId)===n.deviceId}
517
+ >
518
+ ${n.label||`Device ${n.deviceId.slice(0,8)}`}
519
+ </option>
520
+ `)}
521
+ </select>
522
+ ${this.renderSelectArrow()}
523
+ </div>
524
+ `}
525
+ </div>
526
+ `}renderVideoPreview(){return!this.showPreview||this._videoInputDevices.length===0?N:g`
527
+ <div class="device-preview">
528
+ ${this._videoPreviewStream?g`
529
+ <div class="video-preview">
530
+ <video
531
+ autoplay
532
+ playsinline
533
+ muted
534
+ .srcObject=${this._videoPreviewStream}
535
+ @loadedmetadata=${t=>{const i=t.target;this._videoElement=i,i.play().catch(()=>{})}}
536
+ ></video>
537
+ </div>
538
+ `:g` <div class="video-preview-placeholder">Click to enable camera preview</div> `}
539
+ </div>
540
+ `}renderAudioPreview(){return!this.showPreview||this._audioInputDevices.length===0?N:g`
541
+ <div class="device-preview">
542
+ <div class="audio-preview">
543
+ <span class="audio-preview-label">Level:</span>
544
+ <div class="audio-level-wrapper">
545
+ ${this._audioPreviewStream?g`
546
+ <sw-audio-level
547
+ .stream=${this._audioPreviewStream}
548
+ bars="10"
549
+ orientation="horizontal"
550
+ maxSize="20"
551
+ ></sw-audio-level>
552
+ `:g`
553
+ <span style="color: var(--sw-color-text-muted); font-size: 12px;"
554
+ >No audio input</span
555
+ >
556
+ `}
557
+ </div>
558
+ </div>
559
+ </div>
560
+ `}render(){return g`
561
+ <div class="container" part="container">
562
+ ${this.renderDeviceSection("microphone","Microphone",this._audioInputDevices,this._selectedAudioInput)}
563
+ ${this.renderAudioPreview()}
564
+ ${this.renderDeviceSection("camera","Camera",this._videoInputDevices,this._selectedVideoInput)}
565
+ ${this.renderVideoPreview()}
566
+ ${this.renderDeviceSection("speaker","Speaker",this._audioOutputDevices,this._selectedAudioOutput)}
567
+
568
+ <div class="device-section">
569
+ <button
570
+ class="test-speaker-btn"
571
+ @click=${this.testSpeaker}
572
+ ?disabled=${this._isTestingAudio}
573
+ aria-label="Test speaker"
574
+ >
575
+ ${this._isTestingAudio?"Playing...":"Test Speaker"}
576
+ </button>
577
+ </div>
578
+ </div>
579
+ `}},u.DeviceSelector.styles=ce`
580
+ :host {
581
+ /* CSS Custom Properties for theming */
582
+ --sw-color-primary: #044cf6;
583
+ --sw-color-primary-hover: #0339c4;
584
+ --sw-color-background: #1a1a1a;
585
+ --sw-color-surface: #2a2a2a;
586
+ --sw-color-surface-hover: #3a3a3a;
587
+ --sw-color-text: #ffffff;
588
+ --sw-color-text-muted: #a0a0a0;
589
+ --sw-color-border: #404040;
590
+ --sw-color-success: #10b981;
591
+ --sw-border-radius: 8px;
592
+ --sw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
593
+ --sw-space-1: 4px;
594
+ --sw-space-2: 8px;
595
+ --sw-space-3: 12px;
596
+ --sw-space-4: 16px;
597
+ --sw-space-6: 24px;
598
+
599
+ display: block;
600
+ font-family: var(--sw-font-family);
601
+ color: var(--sw-color-text);
602
+ }
603
+
604
+ .container {
605
+ background: var(--sw-color-background);
606
+ border-radius: var(--sw-border-radius);
607
+ border: 1px solid var(--sw-color-border);
608
+ overflow: hidden;
609
+ min-width: 300px;
610
+ padding: var(--sw-space-4);
611
+ }
612
+
613
+ .device-section {
614
+ margin-bottom: var(--sw-space-4);
615
+ }
616
+
617
+ .device-section:last-of-type {
618
+ margin-bottom: 0;
619
+ }
620
+
621
+ .device-label {
622
+ display: flex;
623
+ align-items: center;
624
+ gap: var(--sw-space-2);
625
+ font-size: 14px;
626
+ font-weight: 500;
627
+ color: var(--sw-color-text);
628
+ margin-bottom: var(--sw-space-2);
629
+ }
630
+
631
+ .device-icon {
632
+ width: 18px;
633
+ height: 18px;
634
+ flex-shrink: 0;
635
+ color: var(--sw-color-text-muted);
636
+ }
637
+
638
+ .device-select-wrapper {
639
+ position: relative;
640
+ }
641
+
642
+ .device-select {
643
+ width: 100%;
644
+ padding: var(--sw-space-3) var(--sw-space-4);
645
+ padding-right: 36px;
646
+ background: var(--sw-color-surface);
647
+ border: 1px solid var(--sw-color-border);
648
+ border-radius: calc(var(--sw-border-radius) - 4px);
649
+ color: var(--sw-color-text);
650
+ font-size: 14px;
651
+ font-family: var(--sw-font-family);
652
+ cursor: pointer;
653
+ appearance: none;
654
+ -webkit-appearance: none;
655
+ -moz-appearance: none;
656
+ transition:
657
+ border-color 0.2s ease,
658
+ background-color 0.2s ease;
659
+ }
660
+
661
+ .device-select:hover {
662
+ background: var(--sw-color-surface-hover);
663
+ }
664
+
665
+ .device-select:focus {
666
+ outline: none;
667
+ border-color: var(--sw-color-primary);
668
+ box-shadow: 0 0 0 2px rgba(4, 76, 246, 0.2);
669
+ }
670
+
671
+ .device-select:disabled {
672
+ opacity: 0.5;
673
+ cursor: not-allowed;
674
+ }
675
+
676
+ .device-select option {
677
+ background: var(--sw-color-surface);
678
+ color: var(--sw-color-text);
679
+ padding: var(--sw-space-2);
680
+ }
681
+
682
+ .select-arrow {
683
+ position: absolute;
684
+ right: var(--sw-space-3);
685
+ top: 50%;
686
+ transform: translateY(-50%);
687
+ width: 16px;
688
+ height: 16px;
689
+ color: var(--sw-color-text-muted);
690
+ pointer-events: none;
691
+ }
692
+
693
+ .no-devices {
694
+ padding: var(--sw-space-3) var(--sw-space-4);
695
+ background: var(--sw-color-surface);
696
+ border: 1px solid var(--sw-color-border);
697
+ border-radius: calc(var(--sw-border-radius) - 4px);
698
+ color: var(--sw-color-text-muted);
699
+ font-size: 14px;
700
+ }
701
+
702
+ .device-preview {
703
+ margin-top: var(--sw-space-3);
704
+ }
705
+
706
+ .video-preview {
707
+ width: 100%;
708
+ aspect-ratio: 16/9;
709
+ background: #000;
710
+ border-radius: calc(var(--sw-border-radius) - 4px);
711
+ overflow: hidden;
712
+ }
713
+
714
+ .video-preview video {
715
+ width: 100%;
716
+ height: 100%;
717
+ object-fit: cover;
718
+ transform: scaleX(-1);
719
+ }
720
+
721
+ .video-preview-placeholder {
722
+ width: 100%;
723
+ aspect-ratio: 16/9;
724
+ background: var(--sw-color-surface);
725
+ border-radius: calc(var(--sw-border-radius) - 4px);
726
+ display: flex;
727
+ align-items: center;
728
+ justify-content: center;
729
+ color: var(--sw-color-text-muted);
730
+ font-size: 14px;
731
+ }
732
+
733
+ .audio-preview {
734
+ display: flex;
735
+ align-items: center;
736
+ gap: var(--sw-space-3);
737
+ padding: var(--sw-space-3);
738
+ background: var(--sw-color-surface);
739
+ border-radius: calc(var(--sw-border-radius) - 4px);
740
+ }
741
+
742
+ .audio-preview-label {
743
+ font-size: 12px;
744
+ color: var(--sw-color-text-muted);
745
+ flex-shrink: 0;
746
+ }
747
+
748
+ .audio-level-wrapper {
749
+ flex: 1;
750
+ display: flex;
751
+ justify-content: center;
752
+ }
753
+
754
+ .test-speaker-btn {
755
+ padding: var(--sw-space-2) var(--sw-space-4);
756
+ background: var(--sw-color-primary);
757
+ color: white;
758
+ border: none;
759
+ border-radius: calc(var(--sw-border-radius) - 4px);
760
+ font-size: 14px;
761
+ cursor: pointer;
762
+ transition: background-color 0.2s ease;
763
+ }
764
+
765
+ .test-speaker-btn:hover {
766
+ background: var(--sw-color-primary-hover);
767
+ }
768
+
769
+ .test-speaker-btn:focus {
770
+ outline: none;
771
+ box-shadow:
772
+ 0 0 0 2px var(--sw-color-background),
773
+ 0 0 0 4px var(--sw-color-primary);
774
+ }
775
+
776
+ .test-speaker-btn:disabled {
777
+ opacity: 0.5;
778
+ cursor: not-allowed;
779
+ }
780
+
781
+ /* Scrollbar styling for select on some browsers */
782
+ .device-select::-webkit-scrollbar {
783
+ width: 8px;
784
+ }
785
+
786
+ .device-select::-webkit-scrollbar-track {
787
+ background: var(--sw-color-background);
788
+ }
789
+
790
+ .device-select::-webkit-scrollbar-thumb {
791
+ background: var(--sw-color-border);
792
+ border-radius: 4px;
793
+ }
794
+
795
+ .device-select::-webkit-scrollbar-thumb:hover {
796
+ background: var(--sw-color-text-muted);
797
+ }
798
+ `,u.DeviceSelector.CSS_VISIBILITY_CHECK_INTERVAL_MS=200,he([I({type:Object})],u.DeviceSelector.prototype,"deviceController",2),he([I({type:Boolean,attribute:"show-preview"})],u.DeviceSelector.prototype,"showPreview",2),he([E()],u.DeviceSelector.prototype,"_audioInputDevices",2),he([E()],u.DeviceSelector.prototype,"_videoInputDevices",2),he([E()],u.DeviceSelector.prototype,"_audioOutputDevices",2),he([E()],u.DeviceSelector.prototype,"_selectedAudioInput",2),he([E()],u.DeviceSelector.prototype,"_selectedVideoInput",2),he([E()],u.DeviceSelector.prototype,"_selectedAudioOutput",2),he([E()],u.DeviceSelector.prototype,"_videoPreviewStream",2),he([E()],u.DeviceSelector.prototype,"_audioPreviewStream",2),he([E()],u.DeviceSelector.prototype,"_isTestingAudio",2),u.DeviceSelector=he([ue("sw-device-selector")],u.DeviceSelector);var Ei=function(e,t){return Ei=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,r){i.__proto__=r}||function(i,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[s]=r[s])},Ei(e,t)};function oe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Ei(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}function Co(e,t,i,r){function s(n){return n instanceof i?n:new i(function(o){o(n)})}return new(i||(i=Promise))(function(n,o){function a(h){try{l(r.next(h))}catch(p){o(p)}}function c(h){try{l(r.throw(h))}catch(p){o(p)}}function l(h){h.done?n(h.value):s(h.value).then(a,c)}l((r=r.apply(e,t||[])).next())})}function Er(e,t){var i={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},r,s,n,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(h){return c([l,h])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(i=0)),i;)try{if(r=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,s=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(n=i.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){i=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){i.label=l[1];break}if(l[0]===6&&i.label<n[1]){i.label=n[1],n=l;break}if(n&&i.label<n[2]){i.label=n[2],i.ops.push(l);break}n[2]&&i.ops.pop(),i.trys.pop();continue}l=t.call(e,i)}catch(h){l=[6,h],s=0}finally{r=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ct(e){var t=typeof Symbol=="function"&&Symbol.iterator,i=t&&e[t],r=0;if(i)return i.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function ye(e,t){var i=typeof Symbol=="function"&&e[Symbol.iterator];if(!i)return e;var r=i.call(e),s,n=[],o;try{for(;(t===void 0||t-- >0)&&!(s=r.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(o)throw o.error}}return n}function _e(e,t,i){if(i||arguments.length===2)for(var r=0,s=t.length,n;r<s;r++)(n||!(r in t))&&(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}function lt(e){return this instanceof lt?(this.v=e,this):new lt(e)}function So(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=i.apply(e,t||[]),s,n=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(_){return function(T){return Promise.resolve(T).then(_,p)}}function a(_,T){r[_]&&(s[_]=function(m){return new Promise(function(x,w){n.push([_,m,x,w])>1||c(_,m)})},T&&(s[_]=T(s[_])))}function c(_,T){try{l(r[_](T))}catch(m){b(n[0][3],m)}}function l(_){_.value instanceof lt?Promise.resolve(_.value.v).then(h,p):b(n[0][2],_)}function h(_){c("next",_)}function p(_){c("throw",_)}function b(_,T){_(T),n.shift(),n.length&&c(n[0][0],n[0][1])}}function $o(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],i;return t?t.call(e):(e=typeof ct=="function"?ct(e):e[Symbol.iterator](),i={},r("next"),r("throw"),r("return"),i[Symbol.asyncIterator]=function(){return this},i);function r(n){i[n]=e[n]&&function(o){return new Promise(function(a,c){o=e[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;function U(e){return typeof e=="function"}function qt(e){var t=function(r){Error.call(r),r.stack=new Error().stack},i=e(t);return i.prototype=Object.create(Error.prototype),i.prototype.constructor=i,i}var Mi=qt(function(e){return function(i){e(this),this.message=i?i.length+` errors occurred during unsubscription:
799
+ `+i.map(function(r,s){return s+1+") "+r.toString()}).join(`
800
+ `):"",this.name="UnsubscriptionError",this.errors=i}});function Kt(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var dt=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,i,r,s,n;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=ct(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(t)throw t.error}}else o.remove(this);var h=this.initialTeardown;if(U(h))try{h()}catch(m){n=m instanceof Mi?m.errors:[m]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var b=ct(p),_=b.next();!_.done;_=b.next()){var T=_.value;try{Ar(T)}catch(m){n=n??[],m instanceof Mi?n=_e(_e([],ye(n)),ye(m.errors)):n.push(m)}}}catch(m){r={error:m}}finally{try{_&&!_.done&&(s=b.return)&&s.call(b)}finally{if(r)throw r.error}}}if(n)throw new Mi(n)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)Ar(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(i=this._finalizers)!==null&&i!==void 0?i:[]).push(t)}},e.prototype._hasParent=function(t){var i=this._parentage;return i===t||Array.isArray(i)&&i.includes(t)},e.prototype._addParent=function(t){var i=this._parentage;this._parentage=Array.isArray(i)?(i.push(t),i):i?[i,t]:t},e.prototype._removeParent=function(t){var i=this._parentage;i===t?this._parentage=null:Array.isArray(i)&&Kt(i,t)},e.prototype.remove=function(t){var i=this._finalizers;i&&Kt(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),Mr=dt.EMPTY;function kr(e){return e instanceof dt||e&&"closed"in e&&U(e.remove)&&U(e.add)&&U(e.unsubscribe)}function Ar(e){U(e)?e():e.unsubscribe()}var To={Promise:void 0},Eo={setTimeout:function(e,t){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return setTimeout.apply(void 0,_e([e,t],ye(i)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function xr(e){Eo.setTimeout(function(){throw e})}function It(){}function Jt(e){e()}var ki=(function(e){oe(t,e);function t(i){var r=e.call(this)||this;return r.isStopped=!1,i?(r.destination=i,kr(i)&&i.add(r)):r.destination=Ao,r}return t.create=function(i,r,s){return new ut(i,r,s)},t.prototype.next=function(i){this.isStopped||this._next(i)},t.prototype.error=function(i){this.isStopped||(this.isStopped=!0,this._error(i))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(i){this.destination.next(i)},t.prototype._error=function(i){try{this.destination.error(i)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(dt),Mo=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var i=this.partialObserver;if(i.next)try{i.next(t)}catch(r){Yt(r)}},e.prototype.error=function(t){var i=this.partialObserver;if(i.error)try{i.error(t)}catch(r){Yt(r)}else Yt(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(i){Yt(i)}},e})(),ut=(function(e){oe(t,e);function t(i,r,s){var n=e.call(this)||this,o;return U(i)||!i?o={next:i??void 0,error:r??void 0,complete:s??void 0}:o=i,n.destination=new Mo(o),n}return t})(ki);function Yt(e){xr(e)}function ko(e){throw e}var Ao={closed:!0,next:It,error:ko,complete:It},Ai=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function je(e){return e}function Xt(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Dr(e)}function Dr(e){return e.length===0?je:e.length===1?e[0]:function(i){return e.reduce(function(r,s){return s(r)},i)}}var j=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var i=new e;return i.source=this,i.operator=t,i},e.prototype.subscribe=function(t,i,r){var s=this,n=Do(t)?t:new ut(t,i,r);return Jt(function(){var o=s,a=o.operator,c=o.source;n.add(a?a.call(n,c):c?s._subscribe(n):s._trySubscribe(n))}),n},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(i){t.error(i)}},e.prototype.forEach=function(t,i){var r=this;return i=Ir(i),new i(function(s,n){var o=new ut({next:function(a){try{t(a)}catch(c){n(c),o.unsubscribe()}},error:n,complete:s});r.subscribe(o)})},e.prototype._subscribe=function(t){var i;return(i=this.source)===null||i===void 0?void 0:i.subscribe(t)},e.prototype[Ai]=function(){return this},e.prototype.pipe=function(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];return Dr(t)(this)},e.prototype.toPromise=function(t){var i=this;return t=Ir(t),new t(function(r,s){var n;i.subscribe(function(o){return n=o},function(o){return s(o)},function(){return r(n)})})},e.create=function(t){return new e(t)},e})();function Ir(e){var t;return(t=e??To.Promise)!==null&&t!==void 0?t:Promise}function xo(e){return e&&U(e.next)&&U(e.error)&&U(e.complete)}function Do(e){return e&&e instanceof ki||xo(e)&&kr(e)}function Io(e){return U(e==null?void 0:e.lift)}function z(e){return function(t){if(Io(t))return t.lift(function(i){try{return e(i,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function L(e,t,i,r,s){return new Ro(e,t,i,r,s)}var Ro=(function(e){oe(t,e);function t(i,r,s,n,o,a){var c=e.call(this,i)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(l){try{r(l)}catch(h){i.error(h)}}:e.prototype._next,c._error=n?function(l){try{n(l)}catch(h){i.error(h)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=s?function(){try{s()}catch(l){i.error(l)}finally{this.unsubscribe()}}:e.prototype._complete,c}return t.prototype.unsubscribe=function(){var i;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&((i=this.onFinalize)===null||i===void 0||i.call(this))}},t})(ki),Rr={schedule:function(e){var t=requestAnimationFrame,i=cancelAnimationFrame,r=t(function(s){i=void 0,e(s)});return new dt(function(){return i==null?void 0:i(r)})},requestAnimationFrame:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return requestAnimationFrame.apply(void 0,_e([],ye(e)))},cancelAnimationFrame:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return cancelAnimationFrame.apply(void 0,_e([],ye(e)))},delegate:void 0},Po=qt(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ht=(function(e){oe(t,e);function t(){var i=e.call(this)||this;return i.closed=!1,i.currentObservers=null,i.observers=[],i.isStopped=!1,i.hasError=!1,i.thrownError=null,i}return t.prototype.lift=function(i){var r=new Pr(this,this);return r.operator=i,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new Po},t.prototype.next=function(i){var r=this;Jt(function(){var s,n;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=ct(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(i)}}catch(l){s={error:l}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}}})},t.prototype.error=function(i){var r=this;Jt(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=i;for(var s=r.observers;s.length;)s.shift().error(i)}})},t.prototype.complete=function(){var i=this;Jt(function(){if(i._throwIfClosed(),!i.isStopped){i.isStopped=!0;for(var r=i.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var i;return((i=this.observers)===null||i===void 0?void 0:i.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(i){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,i)},t.prototype._subscribe=function(i){return this._throwIfClosed(),this._checkFinalizedStatuses(i),this._innerSubscribe(i)},t.prototype._innerSubscribe=function(i){var r=this,s=this,n=s.hasError,o=s.isStopped,a=s.observers;return n||o?Mr:(this.currentObservers=null,a.push(i),new dt(function(){r.currentObservers=null,Kt(a,i)}))},t.prototype._checkFinalizedStatuses=function(i){var r=this,s=r.hasError,n=r.thrownError,o=r.isStopped;s?i.error(n):o&&i.complete()},t.prototype.asObservable=function(){var i=new j;return i.source=this,i},t.create=function(i,r){return new Pr(i,r)},t})(j),Pr=(function(e){oe(t,e);function t(i,r){var s=e.call(this)||this;return s.destination=i,s.source=r,s}return t.prototype.next=function(i){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,i)},t.prototype.error=function(i){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,i)},t.prototype.complete=function(){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.complete)===null||r===void 0||r.call(i)},t.prototype._subscribe=function(i){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(i))!==null&&s!==void 0?s:Mr},t})(ht),Oo=(function(e){oe(t,e);function t(i){var r=e.call(this)||this;return r._value=i,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(i){var r=e.prototype._subscribe.call(this,i);return!r.closed&&i.next(this._value),r},t.prototype.getValue=function(){var i=this,r=i.hasError,s=i.thrownError,n=i._value;if(r)throw s;return this._throwIfClosed(),n},t.prototype.next=function(i){e.prototype.next.call(this,this._value=i)},t})(ht),xi={now:function(){return(xi.delegate||Date).now()},delegate:void 0},Di=(function(e){oe(t,e);function t(i,r,s){i===void 0&&(i=1/0),r===void 0&&(r=1/0),s===void 0&&(s=xi);var n=e.call(this)||this;return n._bufferSize=i,n._windowTime=r,n._timestampProvider=s,n._buffer=[],n._infiniteTimeWindow=!0,n._infiniteTimeWindow=r===1/0,n._bufferSize=Math.max(1,i),n._windowTime=Math.max(1,r),n}return t.prototype.next=function(i){var r=this,s=r.isStopped,n=r._buffer,o=r._infiniteTimeWindow,a=r._timestampProvider,c=r._windowTime;s||(n.push(i),!o&&n.push(a.now()+c)),this._trimBuffer(),e.prototype.next.call(this,i)},t.prototype._subscribe=function(i){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(i),s=this,n=s._infiniteTimeWindow,o=s._buffer,a=o.slice(),c=0;c<a.length&&!i.closed;c+=n?1:2)i.next(a[c]);return this._checkFinalizedStatuses(i),r},t.prototype._trimBuffer=function(){var i=this,r=i._bufferSize,s=i._timestampProvider,n=i._buffer,o=i._infiniteTimeWindow,a=(o?1:2)*r;if(r<1/0&&a<n.length&&n.splice(0,n.length-a),!o){for(var c=s.now(),l=0,h=1;h<n.length&&n[h]<=c;h+=2)l=h;l&&n.splice(0,l+1)}},t})(ht),Vo=(function(e){oe(t,e);function t(i,r){return e.call(this)||this}return t.prototype.schedule=function(i,r){return this},t})(dt),Or={setInterval:function(e,t){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return setInterval.apply(void 0,_e([e,t],ye(i)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},Ii=(function(e){oe(t,e);function t(i,r){var s=e.call(this,i,r)||this;return s.scheduler=i,s.work=r,s.pending=!1,s}return t.prototype.schedule=function(i,r){var s;if(r===void 0&&(r=0),this.closed)return this;this.state=i;var n=this.id,o=this.scheduler;return n!=null&&(this.id=this.recycleAsyncId(o,n,r)),this.pending=!0,this.delay=r,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(o,this.id,r),this},t.prototype.requestAsyncId=function(i,r,s){return s===void 0&&(s=0),Or.setInterval(i.flush.bind(i,this),s)},t.prototype.recycleAsyncId=function(i,r,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return r;r!=null&&Or.clearInterval(r)},t.prototype.execute=function(i,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(i,r);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(i,r){var s=!1,n;try{this.work(i)}catch(o){s=!0,n=o||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),n},t.prototype.unsubscribe=function(){if(!this.closed){var i=this,r=i.id,s=i.scheduler,n=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Kt(n,this),r!=null&&(this.id=this.recycleAsyncId(s,r,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t})(Vo),Lo=1,Ri,Pi={};function Vr(e){return e in Pi?(delete Pi[e],!0):!1}var Lr={setImmediate:function(e){var t=Lo++;return Pi[t]=!0,Ri||(Ri=Promise.resolve()),Ri.then(function(){return Vr(t)&&e()}),t},clearImmediate:function(e){Vr(e)}},Bo=Lr.setImmediate,No=Lr.clearImmediate,Br={setImmediate:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Bo.apply(void 0,_e([],ye(e)))},clearImmediate:function(e){return No(e)},delegate:void 0},Uo=(function(e){oe(t,e);function t(i,r){var s=e.call(this,i,r)||this;return s.scheduler=i,s.work=r,s}return t.prototype.requestAsyncId=function(i,r,s){return s===void 0&&(s=0),s!==null&&s>0?e.prototype.requestAsyncId.call(this,i,r,s):(i.actions.push(this),i._scheduled||(i._scheduled=Br.setImmediate(i.flush.bind(i,void 0))))},t.prototype.recycleAsyncId=function(i,r,s){var n;if(s===void 0&&(s=0),s!=null?s>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,i,r,s);var o=i.actions;r!=null&&((n=o[o.length-1])===null||n===void 0?void 0:n.id)!==r&&(Br.clearImmediate(r),i._scheduled===r&&(i._scheduled=void 0))},t})(Ii),Nr=(function(){function e(t,i){i===void 0&&(i=e.now),this.schedulerActionCtor=t,this.now=i}return e.prototype.schedule=function(t,i,r){return i===void 0&&(i=0),new this.schedulerActionCtor(this,t).schedule(r,i)},e.now=xi.now,e})(),Oi=(function(e){oe(t,e);function t(i,r){r===void 0&&(r=Nr.now);var s=e.call(this,i,r)||this;return s.actions=[],s._active=!1,s}return t.prototype.flush=function(i){var r=this.actions;if(this._active){r.push(i);return}var s;this._active=!0;do if(s=i.execute(i.state,i.delay))break;while(i=r.shift());if(this._active=!1,s){for(;i=r.shift();)i.unsubscribe();throw s}},t})(Nr),zo=(function(e){oe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(i){this._active=!0;var r=this._scheduled;this._scheduled=void 0;var s=this.actions,n;i=i||s.shift();do if(n=i.execute(i.state,i.delay))break;while((i=s[0])&&i.id===r&&s.shift());if(this._active=!1,n){for(;(i=s[0])&&i.id===r&&s.shift();)i.unsubscribe();throw n}},t})(Oi),Ur=new zo(Uo),Rt=new Oi(Ii),Fo=Rt,jo=(function(e){oe(t,e);function t(i,r){var s=e.call(this,i,r)||this;return s.scheduler=i,s.work=r,s}return t.prototype.requestAsyncId=function(i,r,s){return s===void 0&&(s=0),s!==null&&s>0?e.prototype.requestAsyncId.call(this,i,r,s):(i.actions.push(this),i._scheduled||(i._scheduled=Rr.requestAnimationFrame(function(){return i.flush(void 0)})))},t.prototype.recycleAsyncId=function(i,r,s){var n;if(s===void 0&&(s=0),s!=null?s>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,i,r,s);var o=i.actions;r!=null&&r===i._scheduled&&((n=o[o.length-1])===null||n===void 0?void 0:n.id)!==r&&(Rr.cancelAnimationFrame(r),i._scheduled=void 0)},t})(Ii),Ho=(function(e){oe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(i){this._active=!0;var r;i?r=i.id:(r=this._scheduled,this._scheduled=void 0);var s=this.actions,n;i=i||s.shift();do if(n=i.execute(i.state,i.delay))break;while((i=s[0])&&i.id===r&&s.shift());if(this._active=!1,n){for(;(i=s[0])&&i.id===r&&s.shift();)i.unsubscribe();throw n}},t})(Oi),zr=new Ho(jo),He=new j(function(e){return e.complete()});function Fr(e){return e&&U(e.schedule)}function Vi(e){return e[e.length-1]}function jr(e){return U(Vi(e))?e.pop():void 0}function Pt(e){return Fr(Vi(e))?e.pop():void 0}function Wo(e,t){return typeof Vi(e)=="number"?e.pop():t}var Hr=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function Wr(e){return U(e==null?void 0:e.then)}function Gr(e){return U(e[Ai])}function qr(e){return Symbol.asyncIterator&&U(e==null?void 0:e[Symbol.asyncIterator])}function Kr(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Go(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Jr=Go();function Yr(e){return U(e==null?void 0:e[Jr])}function Xr(e){return So(this,arguments,function(){var i,r,s,n;return Er(this,function(o){switch(o.label){case 0:i=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,lt(i.read())];case 3:return r=o.sent(),s=r.value,n=r.done,n?[4,lt(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,lt(s)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return i.releaseLock(),[7];case 10:return[2]}})})}function Qr(e){return U(e==null?void 0:e.getReader)}function q(e){if(e instanceof j)return e;if(e!=null){if(Gr(e))return qo(e);if(Hr(e))return Ko(e);if(Wr(e))return Jo(e);if(qr(e))return Zr(e);if(Yr(e))return Yo(e);if(Qr(e))return Xo(e)}throw Kr(e)}function qo(e){return new j(function(t){var i=e[Ai]();if(U(i.subscribe))return i.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ko(e){return new j(function(t){for(var i=0;i<e.length&&!t.closed;i++)t.next(e[i]);t.complete()})}function Jo(e){return new j(function(t){e.then(function(i){t.closed||(t.next(i),t.complete())},function(i){return t.error(i)}).then(null,xr)})}function Yo(e){return new j(function(t){var i,r;try{for(var s=ct(e),n=s.next();!n.done;n=s.next()){var o=n.value;if(t.next(o),t.closed)return}}catch(a){i={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(i)throw i.error}}t.complete()})}function Zr(e){return new j(function(t){Qo(e,t).catch(function(i){return t.error(i)})})}function Xo(e){return Zr(Xr(e))}function Qo(e,t){var i,r,s,n;return Co(this,void 0,void 0,function(){var o,a;return Er(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),i=$o(e),c.label=1;case 1:return[4,i.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),s={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(n=i.return)?[4,n.call(i)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function Ae(e,t,i,r,s){r===void 0&&(r=0),s===void 0&&(s=!1);var n=t.schedule(function(){i(),s?e.add(this.schedule(null,r)):this.unsubscribe()},r);if(e.add(n),!s)return n}function Qt(e,t){return t===void 0&&(t=0),z(function(i,r){i.subscribe(L(r,function(s){return Ae(r,e,function(){return r.next(s)},t)},function(){return Ae(r,e,function(){return r.complete()},t)},function(s){return Ae(r,e,function(){return r.error(s)},t)}))})}function es(e,t){return t===void 0&&(t=0),z(function(i,r){r.add(e.schedule(function(){return i.subscribe(r)},t))})}function Zo(e,t){return q(e).pipe(es(t),Qt(t))}function ea(e,t){return q(e).pipe(es(t),Qt(t))}function ta(e,t){return new j(function(i){var r=0;return t.schedule(function(){r===e.length?i.complete():(i.next(e[r++]),i.closed||this.schedule())})})}function ia(e,t){return new j(function(i){var r;return Ae(i,t,function(){r=e[Jr](),Ae(i,t,function(){var s,n,o;try{s=r.next(),n=s.value,o=s.done}catch(a){i.error(a);return}o?i.complete():i.next(n)},0,!0)}),function(){return U(r==null?void 0:r.return)&&r.return()}})}function ts(e,t){if(!e)throw new Error("Iterable cannot be null");return new j(function(i){Ae(i,t,function(){var r=e[Symbol.asyncIterator]();Ae(i,t,function(){r.next().then(function(s){s.done?i.complete():i.next(s.value)})},0,!0)})})}function ra(e,t){return ts(Xr(e),t)}function sa(e,t){if(e!=null){if(Gr(e))return Zo(e,t);if(Hr(e))return ta(e,t);if(Wr(e))return ea(e,t);if(qr(e))return ts(e,t);if(Yr(e))return ia(e,t);if(Qr(e))return ra(e,t)}throw Kr(e)}function Q(e,t){return t?sa(e,t):q(e)}function Ot(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=Pt(e);return Q(e,i)}function na(e,t){var i=U(e)?e:function(){return e},r=function(s){return s.error(i())};return new j(r)}var is=qt(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function rs(e,t){return new Promise(function(i,r){var s=!1,n;e.subscribe({next:function(o){n=o,s=!0},error:r,complete:function(){s?i(n):r(new is)}})})}function ae(e,t){return new Promise(function(i,r){var s=new ut({next:function(n){i(n),s.unsubscribe()},error:r,complete:function(){r(new is)}});e.subscribe(s)})}function ss(e){return e instanceof Date&&!isNaN(e)}var ns=qt(function(e){return function(i){i===void 0&&(i=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=i}});function Vt(e,t){var i=ss(e)?{first:e}:typeof e=="number"?{each:e}:e,r=i.first,s=i.each,n=i.with,o=n===void 0?oa:n,a=i.scheduler,c=a===void 0?Rt:a,l=i.meta,h=l===void 0?null:l;if(r==null&&s==null)throw new TypeError("No timeout provided.");return z(function(p,b){var _,T,m=null,x=0,w=function(G){T=Ae(b,c,function(){try{_.unsubscribe(),q(o({meta:h,lastValue:m,seen:x})).subscribe(b)}catch(de){b.error(de)}},G)};_=p.subscribe(L(b,function(G){T==null||T.unsubscribe(),x++,b.next(m=G),s>0&&w(s)},void 0,void 0,function(){T!=null&&T.closed||T==null||T.unsubscribe(),m=null})),!x&&w(r!=null?typeof r=="number"?r:+r-c.now():s)})}function oa(e){throw new ns(e)}function f(e,t){return z(function(i,r){var s=0;i.subscribe(L(r,function(n){r.next(e.call(t,n,s++))}))})}var aa=Array.isArray;function ca(e,t){return aa(t)?e.apply(void 0,_e([],ye(t))):e(t)}function la(e){return f(function(t){return ca(e,t)})}var da=Array.isArray,ua=Object.getPrototypeOf,ha=Object.prototype,pa=Object.keys;function va(e){if(e.length===1){var t=e[0];if(da(t))return{args:t,keys:null};if(fa(t)){var i=pa(t);return{args:i.map(function(r){return t[r]}),keys:i}}}return{args:e,keys:null}}function fa(e){return e&&typeof e=="object"&&ua(e)===ha}function ga(e,t){return e.reduce(function(i,r,s){return i[r]=t[s],i},{})}function os(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=Pt(e),r=jr(e),s=va(e),n=s.args,o=s.keys;if(n.length===0)return Q([],i);var a=new j(ba(n,i,o?function(c){return ga(o,c)}:je));return r?a.pipe(la(r)):a}function ba(e,t,i){return i===void 0&&(i=je),function(r){as(t,function(){for(var s=e.length,n=new Array(s),o=s,a=s,c=function(h){as(t,function(){var p=Q(e[h],t),b=!1;p.subscribe(L(r,function(_){n[h]=_,b||(b=!0,a--),a||r.next(i(n.slice()))},function(){--o||r.complete()}))},r)},l=0;l<s;l++)c(l)},r)}}function as(e,t,i){e?Ae(i,e,t):t()}function ma(e,t,i,r,s,n,o,a){var c=[],l=0,h=0,p=!1,b=function(){p&&!c.length&&!l&&t.complete()},_=function(m){return l<r?T(m):c.push(m)},T=function(m){l++;var x=!1;q(i(m,h++)).subscribe(L(t,function(w){t.next(w)},function(){x=!0},void 0,function(){if(x)try{l--;for(var w=function(){var G=c.shift();o||T(G)};c.length&&l<r;)w();b()}catch(G){t.error(G)}}))};return e.subscribe(L(t,_,function(){p=!0,b()})),function(){}}function Li(e,t,i){return i===void 0&&(i=1/0),U(t)?Li(function(r,s){return f(function(n,o){return t(r,n,s,o)})(q(e(r,s)))},i):(typeof t=="number"&&(i=t),z(function(r,s){return ma(r,s,e,i)}))}function cs(e){return e===void 0&&(e=1/0),Li(je,e)}function ya(){return cs(1)}function ls(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ya()(Q(e,Pt(e)))}function We(e){return new j(function(t){q(e()).subscribe(t)})}function pt(e,t,i){e===void 0&&(e=0),i===void 0&&(i=Fo);var r=-1;return t!=null&&(Fr(t)?i=t:r=t),new j(function(s){var n=ss(e)?+e-i.now():e;n<0&&(n=0);var o=0;return i.schedule(function(){s.closed||(s.next(o++),0<=r?this.schedule(void 0,r):s.complete())},n)})}function Zt(e,t){return e===void 0&&(e=0),t===void 0&&(t=Rt),e<0&&(e=0),pt(e,e,t)}function vt(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=Pt(e),r=Wo(e,1/0),s=e;return s.length?s.length===1?q(s[0]):cs(r)(Q(s,i)):He}var _a=new j(It),wa=Array.isArray;function Ca(e){return e.length===1&&wa(e[0])?e[0]:e}function C(e,t){return z(function(i,r){var s=0;i.subscribe(L(r,function(n){return e.call(t,n,s++)&&r.next(n)}))})}function Lt(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return e=Ca(e),e.length===1?q(e[0]):new j(Sa(e))}function Sa(e){return function(t){for(var i=[],r=function(n){i.push(q(e[n]).subscribe(L(t,function(o){if(i){for(var a=0;a<i.length;a++)a!==n&&i[a].unsubscribe();i=null}t.next(o)})))},s=0;i&&!t.closed&&s<e.length;s++)r(s)}}function $a(e){return z(function(t,i){var r=!1,s=null,n=null,o=!1,a=function(){if(n==null||n.unsubscribe(),n=null,r){r=!1;var l=s;s=null,i.next(l)}o&&i.complete()},c=function(){n=null,o&&i.complete()};t.subscribe(L(i,function(l){r=!0,s=l,n||q(e(l)).subscribe(n=L(i,a,c))},function(){o=!0,(!r||!n||n.closed)&&i.complete()}))})}function Ta(e,t){return t===void 0&&(t=Rt),$a(function(){return pt(e,t)})}function Ge(e){return z(function(t,i){var r=null,s=!1,n;r=t.subscribe(L(i,void 0,void 0,function(o){n=q(e(o,Ge(e)(t))),r?(r.unsubscribe(),r=null,n.subscribe(i)):s=!0})),s&&(r.unsubscribe(),r=null,n.subscribe(i))})}function ds(e,t,i,r,s){return function(n,o){var a=i,c=t,l=0;n.subscribe(L(o,function(h){var p=l++;c=a?e(c,h,p):(a=!0,h),r&&o.next(c)},s&&(function(){a&&o.next(c),o.complete()})))}}function Ea(e,t){return z(ds(e,t,arguments.length>=2,!1,!0))}var Ma=function(e,t){return e.push(t),e};function ka(){return z(function(e,t){Ea(Ma,[])(e).subscribe(t)})}function us(e,t){return t===void 0&&(t=Rt),z(function(i,r){var s=null,n=null,o=null,a=function(){if(s){s.unsubscribe(),s=null;var l=n;n=null,r.next(l)}};function c(){var l=o+e,h=t.now();if(h<l){s=this.schedule(void 0,l-h),r.add(s);return}a()}i.subscribe(L(r,function(l){n=l,o=t.now(),s||(s=t.schedule(c,e),r.add(s))},function(){a(),r.complete()},void 0,function(){n=s=null}))})}function te(e){return e<=0?function(){return He}:z(function(t,i){var r=0;t.subscribe(L(i,function(s){++r<=e&&(i.next(s),e<=r&&i.complete())}))})}function y(e,t){return t===void 0&&(t=je),e=e??Aa,z(function(i,r){var s,n=!0;i.subscribe(L(r,function(o){var a=t(o);(n||!e(s,a))&&(n=!1,s=a,r.next(o))}))})}function Aa(e,t){return e===t}function Bi(e,t){return z(function(i,r){var s=0,n=null,o=!1;i.subscribe(L(r,function(a){n||(n=L(r,void 0,function(){n=null,o&&r.complete()}),q(e(a,s++)).subscribe(n))},function(){o=!0,!n&&r.complete()}))})}function hs(e,t){return z(ds(e,t,arguments.length>=2,!0))}function qe(e){e===void 0&&(e={});var t=e.connector,i=t===void 0?function(){return new ht}:t,r=e.resetOnError,s=r===void 0?!0:r,n=e.resetOnComplete,o=n===void 0?!0:n,a=e.resetOnRefCountZero,c=a===void 0?!0:a;return function(l){var h,p,b,_=0,T=!1,m=!1,x=function(){p==null||p.unsubscribe(),p=void 0},w=function(){x(),h=b=void 0,T=m=!1},G=function(){var de=h;w(),de==null||de.unsubscribe()};return z(function(de,Te){_++,!m&&!T&&x();var J=b=b??i();Te.add(function(){_--,_===0&&!m&&!T&&(p=Ni(G,c))}),J.subscribe(Te),!h&&_>0&&(h=new ut({next:function(Le){return J.next(Le)},error:function(Le){m=!0,x(),p=Ni(w,s,Le),J.error(Le)},complete:function(){T=!0,x(),p=Ni(w,o),J.complete()}}),q(de).subscribe(h))})(l)}}function Ni(e,t){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];if(t===!0){e();return}if(t!==!1){var s=new ut({next:function(){s.unsubscribe(),e()}});return q(t.apply(void 0,_e([],ye(i)))).subscribe(s)}}function pe(e,t,i){var r,s=!1;return r=e,qe({connector:function(){return new Di(r,t,i)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:s})}function ei(e){return C(function(t,i){return e<=i})}function xa(e){return z(function(t,i){var r=!1,s=0;t.subscribe(L(i,function(n){return(r||(r=!e(n,s++)))&&i.next(n)}))})}function Da(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=Pt(e);return z(function(r,s){(i?ls(e,r,i):ls(e,r)).subscribe(s)})}function we(e,t){return z(function(i,r){var s=null,n=0,o=!1,a=function(){return o&&!s&&r.complete()};i.subscribe(L(r,function(c){s==null||s.unsubscribe();var l=0,h=n++;q(e(c,h)).subscribe(s=L(r,function(p){return r.next(t?t(c,p,h,l++):p)},function(){s=null,a()}))},function(){o=!0,a()}))})}function v(e){return z(function(t,i){q(e).subscribe(L(i,function(){return i.complete()},It)),!i.closed&&t.subscribe(i)})}function W(e,t,i){var r=U(e)||t||i?{next:e,error:t,complete:i}:e;return r?z(function(s,n){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var a=!0;s.subscribe(L(n,function(c){var l;(l=r.next)===null||l===void 0||l.call(r,c),n.next(c)},function(){var c;a=!1,(c=r.complete)===null||c===void 0||c.call(r),n.complete()},function(c){var l;a=!1,(l=r.error)===null||l===void 0||l.call(r,c),n.error(c)},function(){var c,l;a&&((c=r.unsubscribe)===null||c===void 0||c.call(r)),(l=r.finalize)===null||l===void 0||l.call(r)}))}):je}function ps(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=jr(e);return z(function(r,s){for(var n=e.length,o=new Array(n),a=e.map(function(){return!1}),c=!1,l=function(p){q(e[p]).subscribe(L(s,function(b){o[p]=b,!c&&!a[p]&&(a[p]=!0,(c=a.every(je))&&(a=null))},It))},h=0;h<n;h++)l(h);r.subscribe(L(s,function(p){if(c){var b=_e([p],ye(o));s.next(i?i.apply(void 0,_e([],ye(b))):b)}}))})}var Ia=Object.defineProperty,Ra=Object.getOwnPropertyDescriptor,Ce=(e,t,i,r)=>{for(var s=r>1?void 0:r?Ra(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&Ia(t,i,s),s};u.CallControls=class extends X{constructor(){super(...arguments),this.orientation="horizontal",this.showTooltips=!0,this._audioMuted=!1,this._videoMuted=!1,this._screenShareStatus="inactive",this._capabilities=[],this._overflowOpen=!1,this.subscriptions=[]}get effectiveCall(){return this.call||this._contextCall}connectedCallback(){super.connectedCallback(),this.setupSubscriptions()}updated(t){super.updated(t),(t.has("call")||t.has("_contextCall"))&&(this.cleanupSubscriptions(),this.setupSubscriptions())}disconnectedCallback(){super.disconnectedCallback(),this.cleanupSubscriptions()}setupSubscriptions(){const t=this.effectiveCall;if(t){if(t.self$){const i=t.self$.pipe(C(o=>o!==null)),r=i.pipe(we(o=>(this.selfParticipant=o,o.audioMuted$))).subscribe(o=>{o!==void 0&&(this._audioMuted=o)});this.subscriptions.push(r);const s=i.pipe(we(o=>o.videoMuted$)).subscribe(o=>{o!==void 0&&(this._videoMuted=o)});this.subscriptions.push(s);const n=i.pipe(we(o=>o.screenShareStatus$??Ot("inactive"))).subscribe(o=>{this._screenShareStatus=o});this.subscriptions.push(n)}else t.self&&(this.selfParticipant=t.self,t.self.audioMuted$&&this.subscriptions.push(t.self.audioMuted$.subscribe(i=>{i!==void 0&&(this._audioMuted=i)})),t.self.videoMuted$&&this.subscriptions.push(t.self.videoMuted$.subscribe(i=>{i!==void 0&&(this._videoMuted=i)})),t.self.screenShareStatus$&&this.subscriptions.push(t.self.screenShareStatus$.subscribe(i=>{this._screenShareStatus=i})));t.capabilities$&&this.subscriptions.push(t.capabilities$.subscribe(i=>{this._capabilities=i}))}}cleanupSubscriptions(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[],this.selfParticipant=void 0}hasCapability(t){return!this._capabilities||this._capabilities.length===0?!0:this._capabilities.includes(t)}async handleMuteAudio(){var r;const t=this.selfParticipant??((r=this.effectiveCall)==null?void 0:r.self);if(!t)return;const i=!this._audioMuted;try{this._audioMuted?await t.unmute():await t.mute(),this.dispatchEvent(new CustomEvent("sw-mute-audio",{detail:{muted:i},bubbles:!0,composed:!0}))}catch(s){console.error("Failed to toggle audio mute:",s)}}async handleMuteVideo(){var r;const t=this.selfParticipant??((r=this.effectiveCall)==null?void 0:r.self);if(!t)return;const i=!this._videoMuted;try{this._videoMuted?await t.unmuteVideo():await t.muteVideo(),this.dispatchEvent(new CustomEvent("sw-mute-video",{detail:{muted:i},bubbles:!0,composed:!0}))}catch(s){console.error("Failed to toggle video mute:",s)}}async handleScreenShare(){var r,s,n;const t=this.selfParticipant??((r=this.effectiveCall)==null?void 0:r.self);if(!t)return;const i=this._screenShareStatus!=="active";try{this._screenShareStatus==="active"?await((s=t.stopScreenShare)==null?void 0:s.call(t)):await((n=t.startScreenShare)==null?void 0:n.call(t)),this.dispatchEvent(new CustomEvent("sw-screen-share",{detail:{active:i},bubbles:!0,composed:!0}))}catch(o){console.error("Failed to toggle screen share:",o)}}async handleHangup(){const t=this.effectiveCall;if(t)try{await t.hangup(),this.dispatchEvent(new CustomEvent("sw-hangup",{bubbles:!0,composed:!0}))}catch(i){console.error("Failed to hangup:",i)}}toggleOverflow(){this._overflowOpen=!this._overflowOpen}getTooltipText(t){switch(t){case"mute-audio":return this._audioMuted?"Unmute Audio":"Mute Audio";case"mute-video":return this._videoMuted?"Turn On Camera":"Turn Off Camera";case"screen-share":return this._screenShareStatus==="active"?"Stop Sharing":"Share Screen";case"hangup":return"End Call"}}renderIcon(t){switch(t){case"mute-audio":return this._audioMuted?g`<svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
801
+ <path
802
+ d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"
803
+ />
804
+ </svg>`:g`<svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
805
+ <path
806
+ d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.91-3c-.49 0-.9.36-.98.85C16.52 14.2 14.47 16 12 16s-4.52-1.8-4.93-4.15c-.08-.49-.49-.85-.98-.85-.61 0-1.09.54-1 1.14.49 3 2.89 5.35 5.91 5.78V20c0 .55.45 1 1 1s1-.45 1-1v-2.08c3.02-.43 5.42-2.78 5.91-5.78.1-.6-.39-1.14-1-1.14z"
807
+ />
808
+ </svg>`;case"mute-video":return this._videoMuted?g`<svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
809
+ <path
810
+ d="M21 6.5l-4 4V7c0-.55-.45-1-1-1H9.82L21 17.18V6.5zM3.27 2L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73 3.27 2z"
811
+ />
812
+ </svg>`:g`<svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
813
+ <path
814
+ d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"
815
+ />
816
+ </svg>`;case"screen-share":return this._screenShareStatus==="active"?g`<svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
817
+ <path
818
+ d="M21.22 18.02l2 2H24v-2h-2.78zm.77-2l.01-10c0-1.11-.9-2-2-2H7.22l5.23 5.23c.18-.04.36-.07.55-.1V7.02l4 3.73-1.58 1.47 5.54 5.54c.61-.33 1.03-.99 1.03-1.74zM2.39 1.73L1.11 3l1.54 1.54c-.4.36-.65.89-.65 1.48v10c0 1.1.89 2 2 2H0v2h18.13l2.71 2.71 1.27-1.27L2.39 1.73zM7 15.02c.31-1.48.92-2.95 2.07-4.06l1.59 1.59c-1.54.38-2.7 1.18-3.66 2.47z"
819
+ />
820
+ </svg>`:g`<svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
821
+ <path
822
+ d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6zm9 9v-4h3l-4-4-4 4h3v4h2z"
823
+ />
824
+ </svg>`;case"hangup":return g`<svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
825
+ <path
826
+ d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"
827
+ />
828
+ </svg>`}}renderButton(t,i){const{onClick:r,active:s=!1,disabled:n=!1,className:o=""}=i,a=this.getTooltipText(t);return g`
829
+ <button
830
+ class="control-button ${t} ${s?"active":""} ${o}"
831
+ part="button ${s?"button-active":""} ${n?"button-disabled":""}"
832
+ aria-label="${a}"
833
+ aria-pressed="${t!=="hangup"?s:N}"
834
+ ?disabled=${n}
835
+ @click=${r}
836
+ >
837
+ ${this.renderIcon(t)}
838
+ ${this.showTooltips?g` <span class="tooltip" part="tooltip">${a}</span> `:N}
839
+ </button>
840
+ `}render(){var a,c;const t=this.effectiveCall,i=!!(this.selfParticipant??(t==null?void 0:t.self)),r=this.hasCapability("self"),s=r||this.hasCapability("selfMuteAudio")||this.hasCapability("muteAudio"),n=r||this.hasCapability("vmuted")||this.hasCapability("selfMuteVideo")||this.hasCapability("muteVideo"),o=(this.hasCapability("screenshare")||this.hasCapability("screenShare"))&&!!(((a=this.selfParticipant)==null?void 0:a.startScreenShare)??((c=t==null?void 0:t.self)==null?void 0:c.startScreenShare));return g`
841
+ <div
842
+ class="container ${this.orientation==="vertical"?"vertical":""}"
843
+ part="container"
844
+ role="toolbar"
845
+ aria-label="Call controls"
846
+ >
847
+ ${this.renderButton("mute-audio",{onClick:()=>this.handleMuteAudio(),active:this._audioMuted,disabled:!i||!s})}
848
+ ${this.renderButton("mute-video",{onClick:()=>this.handleMuteVideo(),active:this._videoMuted,disabled:!i||!n})}
849
+ ${this.renderButton("screen-share",{onClick:()=>this.handleScreenShare(),active:this._screenShareStatus==="active",disabled:!i||!o})}
850
+ ${this.renderButton("hangup",{onClick:()=>this.handleHangup(),disabled:!t||!1,className:"hangup"})}
851
+
852
+ <!-- Overflow menu for responsive collapse -->
853
+ <div class="overflow-menu ${this._overflowOpen?"open":""}">
854
+ <button
855
+ class="control-button overflow-button"
856
+ aria-label="More options"
857
+ aria-expanded="${this._overflowOpen}"
858
+ @click=${this.toggleOverflow}
859
+ >
860
+ <svg class="button-icon" viewBox="0 0 24 24" fill="currentColor">
861
+ <path
862
+ d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
863
+ />
864
+ </svg>
865
+ </button>
866
+ <div class="overflow-content">
867
+ ${this.renderButton("mute-audio",{onClick:()=>this.handleMuteAudio(),active:this._audioMuted,disabled:!i||!s})}
868
+ ${this.renderButton("mute-video",{onClick:()=>this.handleMuteVideo(),active:this._videoMuted,disabled:!i||!n})}
869
+ ${this.renderButton("screen-share",{onClick:()=>this.handleScreenShare(),active:this._screenShareStatus==="active",disabled:!i||!o})}
870
+ </div>
871
+ </div>
872
+ </div>
873
+ `}},u.CallControls.styles=ce`
874
+ :host {
875
+ /* CSS Custom Properties for theming */
876
+ --sw-color-primary: #044cf6;
877
+ --sw-color-primary-hover: #0339c4;
878
+ --sw-color-danger: #ef4444;
879
+ --sw-color-danger-hover: #dc2626;
880
+ --sw-color-background: #1a1a1a;
881
+ --sw-color-surface: #2a2a2a;
882
+ --sw-color-surface-hover: #3a3a3a;
883
+ --sw-color-text: #ffffff;
884
+ --sw-color-text-muted: #a0a0a0;
885
+ --sw-color-border: #404040;
886
+ --sw-color-active: #ef4444;
887
+ --sw-border-radius: 8px;
888
+ --sw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
889
+ --sw-space-1: 4px;
890
+ --sw-space-2: 8px;
891
+ --sw-space-3: 12px;
892
+ --sw-space-4: 16px;
893
+ --sw-space-6: 24px;
894
+
895
+ display: block;
896
+ font-family: var(--sw-font-family);
897
+ color: var(--sw-color-text);
898
+ }
899
+
900
+ .container {
901
+ display: flex;
902
+ align-items: center;
903
+ justify-content: center;
904
+ gap: var(--sw-space-3);
905
+ padding: var(--sw-space-3);
906
+ background: var(--sw-color-background);
907
+ border-radius: var(--sw-border-radius);
908
+ flex-wrap: wrap;
909
+ }
910
+
911
+ .container.vertical {
912
+ flex-direction: column;
913
+ }
914
+
915
+ .control-button {
916
+ position: relative;
917
+ display: flex;
918
+ align-items: center;
919
+ justify-content: center;
920
+ width: 48px;
921
+ height: 48px;
922
+ min-width: 44px;
923
+ min-height: 44px;
924
+ padding: 0;
925
+ background: var(--sw-color-surface);
926
+ border: 1px solid var(--sw-color-border);
927
+ border-radius: 50%;
928
+ color: var(--sw-color-text);
929
+ cursor: pointer;
930
+ transition:
931
+ background-color 0.2s ease,
932
+ border-color 0.2s ease,
933
+ transform 0.1s ease;
934
+ }
935
+
936
+ .control-button:hover:not(:disabled) {
937
+ background: var(--sw-color-surface-hover);
938
+ border-color: var(--sw-color-text-muted);
939
+ }
940
+
941
+ .control-button:focus {
942
+ outline: none;
943
+ box-shadow:
944
+ 0 0 0 2px var(--sw-color-background),
945
+ 0 0 0 4px var(--sw-color-primary);
946
+ }
947
+
948
+ .control-button:focus-visible {
949
+ outline: 2px solid var(--sw-color-primary);
950
+ outline-offset: 2px;
951
+ }
952
+
953
+ .control-button:active:not(:disabled) {
954
+ transform: scale(0.95);
955
+ }
956
+
957
+ .control-button:disabled {
958
+ opacity: 0.4;
959
+ cursor: not-allowed;
960
+ }
961
+
962
+ .control-button.active {
963
+ background: var(--sw-color-active);
964
+ border-color: var(--sw-color-active);
965
+ color: white;
966
+ }
967
+
968
+ .control-button.active:hover:not(:disabled) {
969
+ background: var(--sw-color-danger-hover);
970
+ border-color: var(--sw-color-danger-hover);
971
+ }
972
+
973
+ .control-button.hangup {
974
+ background: var(--sw-color-danger);
975
+ border-color: var(--sw-color-danger);
976
+ color: white;
977
+ }
978
+
979
+ .control-button.hangup:hover:not(:disabled) {
980
+ background: var(--sw-color-danger-hover);
981
+ border-color: var(--sw-color-danger-hover);
982
+ }
983
+
984
+ .control-button.screen-share.active {
985
+ background: var(--sw-color-primary);
986
+ border-color: var(--sw-color-primary);
987
+ }
988
+
989
+ .control-button.screen-share.active:hover:not(:disabled) {
990
+ background: var(--sw-color-primary-hover);
991
+ border-color: var(--sw-color-primary-hover);
992
+ }
993
+
994
+ .button-icon {
995
+ width: 24px;
996
+ height: 24px;
997
+ flex-shrink: 0;
998
+ }
999
+
1000
+ .tooltip {
1001
+ position: absolute;
1002
+ bottom: calc(100% + 8px);
1003
+ left: 50%;
1004
+ transform: translateX(-50%);
1005
+ padding: var(--sw-space-1) var(--sw-space-2);
1006
+ background: var(--sw-color-surface);
1007
+ border: 1px solid var(--sw-color-border);
1008
+ border-radius: 4px;
1009
+ font-size: 12px;
1010
+ white-space: nowrap;
1011
+ opacity: 0;
1012
+ visibility: hidden;
1013
+ transition:
1014
+ opacity 0.2s ease,
1015
+ visibility 0.2s ease;
1016
+ pointer-events: none;
1017
+ z-index: 10;
1018
+ }
1019
+
1020
+ .tooltip::after {
1021
+ content: '';
1022
+ position: absolute;
1023
+ top: 100%;
1024
+ left: 50%;
1025
+ transform: translateX(-50%);
1026
+ border: 6px solid transparent;
1027
+ border-top-color: var(--sw-color-border);
1028
+ }
1029
+
1030
+ .control-button:hover .tooltip,
1031
+ .control-button:focus .tooltip {
1032
+ opacity: 1;
1033
+ visibility: visible;
1034
+ }
1035
+
1036
+ /* Vertical orientation tooltip positioning */
1037
+ .container.vertical .tooltip {
1038
+ bottom: auto;
1039
+ left: calc(100% + 8px);
1040
+ top: 50%;
1041
+ transform: translateY(-50%);
1042
+ }
1043
+
1044
+ .container.vertical .tooltip::after {
1045
+ top: 50%;
1046
+ left: auto;
1047
+ right: 100%;
1048
+ transform: translateY(-50%);
1049
+ border: 6px solid transparent;
1050
+ border-right-color: var(--sw-color-border);
1051
+ }
1052
+
1053
+ /* Overflow menu for responsive collapse */
1054
+ .overflow-menu {
1055
+ position: relative;
1056
+ }
1057
+
1058
+ .overflow-button {
1059
+ display: none;
1060
+ }
1061
+
1062
+ .overflow-content {
1063
+ display: none;
1064
+ position: absolute;
1065
+ bottom: calc(100% + 8px);
1066
+ right: 0;
1067
+ background: var(--sw-color-background);
1068
+ border: 1px solid var(--sw-color-border);
1069
+ border-radius: var(--sw-border-radius);
1070
+ padding: var(--sw-space-2);
1071
+ gap: var(--sw-space-2);
1072
+ flex-direction: column;
1073
+ z-index: 20;
1074
+ }
1075
+
1076
+ .overflow-menu.open .overflow-content {
1077
+ display: flex;
1078
+ }
1079
+
1080
+ /* Responsive collapse at small widths */
1081
+ @media (max-width: 320px) {
1082
+ .container:not(.vertical) > .control-button:not(.hangup):not(.overflow-button) {
1083
+ display: none;
1084
+ }
1085
+
1086
+ .container:not(.vertical) .overflow-button {
1087
+ display: flex;
1088
+ }
1089
+
1090
+ /* Ensure overflow content buttons remain visible when menu is open */
1091
+ .container:not(.vertical) .overflow-content .control-button {
1092
+ display: flex;
1093
+ }
1094
+ }
1095
+
1096
+ /* Dark mode adjustments */
1097
+ @media (prefers-color-scheme: light) {
1098
+ :host {
1099
+ --sw-color-background: #ffffff;
1100
+ --sw-color-surface: #f5f5f5;
1101
+ --sw-color-surface-hover: #e5e5e5;
1102
+ --sw-color-text: #1a1a1a;
1103
+ --sw-color-text-muted: #666666;
1104
+ --sw-color-border: #d4d4d4;
1105
+ }
1106
+ }
1107
+
1108
+ :host([data-theme='light']) {
1109
+ --sw-color-background: #ffffff;
1110
+ --sw-color-surface: #f5f5f5;
1111
+ --sw-color-surface-hover: #e5e5e5;
1112
+ --sw-color-text: #1a1a1a;
1113
+ --sw-color-text-muted: #666666;
1114
+ --sw-color-border: #d4d4d4;
1115
+ }
1116
+ `,Ce([I({type:Object})],u.CallControls.prototype,"call",2),Ce([Dt({context:Fe,subscribe:!0}),E()],u.CallControls.prototype,"_contextCall",2),Ce([I({type:String})],u.CallControls.prototype,"orientation",2),Ce([I({type:Boolean,attribute:"show-tooltips"})],u.CallControls.prototype,"showTooltips",2),Ce([E()],u.CallControls.prototype,"_audioMuted",2),Ce([E()],u.CallControls.prototype,"_videoMuted",2),Ce([E()],u.CallControls.prototype,"_screenShareStatus",2),Ce([E()],u.CallControls.prototype,"_capabilities",2),Ce([E()],u.CallControls.prototype,"_overflowOpen",2),Ce([E()],u.CallControls.prototype,"selfParticipant",2),u.CallControls=Ce([ue("sw-call-controls")],u.CallControls);var Pa=Object.defineProperty,Oa=Object.getOwnPropertyDescriptor,ft=(e,t,i,r)=>{for(var s=r>1?void 0:r?Oa(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&Pa(t,i,s),s};u.CallStatusComponent=class extends X{constructor(){super(...arguments),this.call=null,this.status="new",this.callStartTime=null,this.duration="0:00",this.subscriptions=[],this.durationInterval=null}connectedCallback(){super.connectedCallback(),this.subscribeToCall()}disconnectedCallback(){super.disconnectedCallback(),this.cleanup()}updated(t){(t.has("call")||t.has("contextCall"))&&(this.cleanup(),this.subscribeToCall())}get activeCall(){return this.call||this.contextCall||null}subscribeToCall(){const t=this.activeCall;if(!(t!=null&&t.status$))return;const i=t.status$.subscribe(r=>{const s=this.status;this.status=r,r==="connected"&&s!=="connected"?this.startDurationTimer():r!=="connected"&&this.stopDurationTimer()});this.subscriptions.push(i)}startDurationTimer(){this.callStartTime=Date.now(),this.duration="0:00",this.durationInterval=window.setInterval(()=>{if(this.callStartTime){const t=Math.floor((Date.now()-this.callStartTime)/1e3);this.duration=this.formatDuration(t)}},1e3)}stopDurationTimer(){this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null),this.callStartTime=null,this.duration="0:00"}formatDuration(t){const i=Math.floor(t/3600),r=Math.floor(t%3600/60),s=t%60;return i>0?`${i}:${r.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${r}:${s.toString().padStart(2,"0")}`}cleanup(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[],this.stopDurationTimer()}getStatusText(){switch(this.status){case"new":return"Ready";case"trying":return"Trying...";case"connecting":return"Connecting...";case"ringing":return"Ringing...";case"connected":return"Connected";case"recovering":return"Reconnecting...";case"disconnecting":return"Disconnecting...";case"disconnected":return"Disconnected";case"failed":return"Failed";case"destroyed":return"Ended";default:{const t=this.status;return String(t)}}}render(){const t=this.getStatusText(),i=this.status==="connected";return g`
1117
+ <div class="container" part="container">
1118
+ <span class="status-indicator ${this.status}" aria-hidden="true"></span>
1119
+ <span
1120
+ class="status-text ${this.status}"
1121
+ part="status-text"
1122
+ role="status"
1123
+ aria-live="polite"
1124
+ >
1125
+ ${t}
1126
+ </span>
1127
+ ${i?g`<span class="duration" part="duration">${this.duration}</span>`:null}
1128
+ </div>
1129
+ `}},u.CallStatusComponent.styles=ce`
1130
+ :host {
1131
+ /* CSS Custom Properties for theming */
1132
+ --sw-color-primary: #044cf6;
1133
+ --sw-color-success: #10b981;
1134
+ --sw-color-warning: #f59e0b;
1135
+ --sw-color-danger: #ef4444;
1136
+ --sw-color-text: #1f2937;
1137
+ --sw-color-text-muted: #6b7280;
1138
+ --sw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1139
+ --sw-font-size-sm: 14px;
1140
+ --sw-font-size-base: 16px;
1141
+ --sw-font-size-lg: 18px;
1142
+ --sw-space-1: 4px;
1143
+ --sw-space-2: 8px;
1144
+ --sw-space-3: 12px;
1145
+ --sw-border-radius: 8px;
1146
+
1147
+ display: inline-flex;
1148
+ align-items: center;
1149
+ gap: var(--sw-space-2);
1150
+ font-family: var(--sw-font-family);
1151
+ font-size: var(--sw-font-size-base);
1152
+ }
1153
+
1154
+ /* Dark mode support */
1155
+ :host([data-theme='dark']) {
1156
+ --sw-color-text: #f9fafb;
1157
+ --sw-color-text-muted: #9ca3af;
1158
+ }
1159
+
1160
+ @media (prefers-color-scheme: dark) {
1161
+ :host(:not([data-theme='light'])) {
1162
+ --sw-color-text: #f9fafb;
1163
+ --sw-color-text-muted: #9ca3af;
1164
+ }
1165
+ }
1166
+
1167
+ .container {
1168
+ display: inline-flex;
1169
+ align-items: center;
1170
+ gap: var(--sw-space-2);
1171
+ padding: var(--sw-space-2) var(--sw-space-3);
1172
+ border-radius: var(--sw-border-radius);
1173
+ color: var(--sw-color-text);
1174
+ }
1175
+
1176
+ .status-indicator {
1177
+ width: 10px;
1178
+ height: 10px;
1179
+ border-radius: 50%;
1180
+ flex-shrink: 0;
1181
+ }
1182
+
1183
+ .status-indicator.new {
1184
+ background-color: var(--sw-color-text-muted);
1185
+ }
1186
+
1187
+ .status-indicator.connecting,
1188
+ .status-indicator.ringing {
1189
+ background-color: var(--sw-color-warning);
1190
+ animation: pulse 1.5s ease-in-out infinite;
1191
+ }
1192
+
1193
+ .status-indicator.connected {
1194
+ background-color: var(--sw-color-success);
1195
+ }
1196
+
1197
+ .status-indicator.disconnecting {
1198
+ background-color: var(--sw-color-danger);
1199
+ animation: pulse 1s ease-in-out infinite;
1200
+ }
1201
+
1202
+ .status-indicator.trying {
1203
+ background-color: var(--sw-color-warning);
1204
+ animation: pulse 1.5s ease-in-out infinite;
1205
+ }
1206
+
1207
+ .status-indicator.disconnected,
1208
+ .status-indicator.failed {
1209
+ background-color: var(--sw-color-danger);
1210
+ }
1211
+
1212
+ .status-indicator.destroyed {
1213
+ background-color: var(--sw-color-text-muted);
1214
+ }
1215
+
1216
+ @keyframes pulse {
1217
+ 0%,
1218
+ 100% {
1219
+ opacity: 1;
1220
+ transform: scale(1);
1221
+ }
1222
+ 50% {
1223
+ opacity: 0.5;
1224
+ transform: scale(1.1);
1225
+ }
1226
+ }
1227
+
1228
+ .status-text {
1229
+ font-weight: 500;
1230
+ white-space: nowrap;
1231
+ }
1232
+
1233
+ .status-text.trying,
1234
+ .status-text.connecting,
1235
+ .status-text.ringing {
1236
+ color: var(--sw-color-warning);
1237
+ }
1238
+
1239
+ .status-text.disconnecting {
1240
+ color: var(--sw-color-danger);
1241
+ }
1242
+
1243
+ .status-text.connected {
1244
+ color: var(--sw-color-success);
1245
+ }
1246
+
1247
+ .status-text.disconnected,
1248
+ .status-text.failed {
1249
+ color: var(--sw-color-danger);
1250
+ }
1251
+
1252
+ .status-text.new,
1253
+ .status-text.destroyed {
1254
+ color: var(--sw-color-text-muted);
1255
+ }
1256
+
1257
+ .duration {
1258
+ font-variant-numeric: tabular-nums;
1259
+ color: var(--sw-color-text-muted);
1260
+ font-size: var(--sw-font-size-sm);
1261
+ }
1262
+ `,ft([I({attribute:!1})],u.CallStatusComponent.prototype,"call",2),ft([Dt({context:Fe,subscribe:!0}),E()],u.CallStatusComponent.prototype,"contextCall",2),ft([E()],u.CallStatusComponent.prototype,"status",2),ft([E()],u.CallStatusComponent.prototype,"callStartTime",2),ft([E()],u.CallStatusComponent.prototype,"duration",2),u.CallStatusComponent=ft([ue("sw-call-status")],u.CallStatusComponent);var Va=Object.defineProperty,La=Object.getOwnPropertyDescriptor,Ke=(e,t,i,r)=>{for(var s=r>1?void 0:r?La(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&Va(t,i,s),s};const Ba=[{digit:"1",letters:""},{digit:"2",letters:"ABC"},{digit:"3",letters:"DEF"},{digit:"4",letters:"GHI"},{digit:"5",letters:"JKL"},{digit:"6",letters:"MNO"},{digit:"7",letters:"PQRS"},{digit:"8",letters:"TUV"},{digit:"9",letters:"WXYZ"},{digit:"*",letters:""},{digit:"0",letters:"+"},{digit:"#",letters:""}];u.DialpadComponent=class extends X{constructor(){super(...arguments),this.call=null,this.digits="",this.pressedKey=null,this.showCallButton=!1,this.placeholder="Enter number"}get activeCall(){return this.call||this.contextCall||null}handleKeyPress(t){var i;this.digits+=t,this.pressedKey=t,(i=this.activeCall)!=null&&i.sendDigits&&this.activeCall.sendDigits(t).catch(r=>{console.error("Failed to send DTMF:",r)}),this.dispatchEvent(new CustomEvent("sw-digit-press",{detail:{digit:t,digits:this.digits},bubbles:!0,composed:!0})),setTimeout(()=>{this.pressedKey=null},100)}handleBackspace(){this.digits.length>0&&(this.digits=this.digits.slice(0,-1),this.dispatchEvent(new CustomEvent("sw-backspace",{detail:{digits:this.digits},bubbles:!0,composed:!0})))}handleCall(){this.digits.length>0&&this.dispatchEvent(new CustomEvent("sw-dial",{detail:{digits:this.digits},bubbles:!0,composed:!0}))}handleInputChange(t){const i=t.target;this.digits=i.value.replace(/[^0-9*#]/g,"")}handleKeyDown(t){const i=t.key;/^[0-9*#]$/.test(i)?this.handleKeyPress(i):i==="Backspace"?this.handleBackspace():i==="Enter"&&this.showCallButton&&this.handleCall()}render(){return g`
1263
+ <div class="container" part="container">
1264
+ <div class="display" part="display">
1265
+ <input
1266
+ type="tel"
1267
+ class="display-input"
1268
+ .value=${this.digits}
1269
+ placeholder=${this.placeholder}
1270
+ @input=${this.handleInputChange}
1271
+ @keydown=${this.handleKeyDown}
1272
+ aria-label="Phone number input"
1273
+ />
1274
+ <button
1275
+ class="backspace-button"
1276
+ @click=${this.handleBackspace}
1277
+ ?disabled=${this.digits.length===0}
1278
+ aria-label="Delete last digit"
1279
+ >
1280
+ <svg
1281
+ xmlns="http://www.w3.org/2000/svg"
1282
+ width="24"
1283
+ height="24"
1284
+ viewBox="0 0 24 24"
1285
+ fill="none"
1286
+ stroke="currentColor"
1287
+ stroke-width="2"
1288
+ stroke-linecap="round"
1289
+ stroke-linejoin="round"
1290
+ >
1291
+ <path d="M21 4H8l-7 8 7 8h13a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z"></path>
1292
+ <line x1="18" y1="9" x2="12" y2="15"></line>
1293
+ <line x1="12" y1="9" x2="18" y2="15"></line>
1294
+ </svg>
1295
+ </button>
1296
+ </div>
1297
+
1298
+ <div class="keypad" part="keypad" role="group" aria-label="Telephone keypad">
1299
+ ${Ba.map(t=>g`
1300
+ <button
1301
+ class="key ${this.pressedKey===t.digit?"pressed":""}"
1302
+ part="key ${this.pressedKey===t.digit?"key-pressed":""}"
1303
+ @click=${()=>this.handleKeyPress(t.digit)}
1304
+ aria-label="${t.digit}${t.letters?`, ${t.letters}`:""}"
1305
+ >
1306
+ <span class="key-digit">${t.digit}</span>
1307
+ <span class="key-letters">${t.letters}</span>
1308
+ </button>
1309
+ `)}
1310
+ </div>
1311
+
1312
+ ${this.showCallButton?g`
1313
+ <button
1314
+ class="call-button"
1315
+ part="call-button"
1316
+ @click=${this.handleCall}
1317
+ ?disabled=${this.digits.length===0}
1318
+ aria-label="Call ${this.digits}"
1319
+ >
1320
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
1321
+ <path
1322
+ d="M6.62 10.79c1.44 2.83 3.76 5.15 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"
1323
+ />
1324
+ </svg>
1325
+ Call
1326
+ </button>
1327
+ `:null}
1328
+ </div>
1329
+ `}},u.DialpadComponent.styles=ce`
1330
+ :host {
1331
+ /* CSS Custom Properties for theming */
1332
+ --sw-color-primary: #044cf6;
1333
+ --sw-color-primary-hover: #0339c4;
1334
+ --sw-color-primary-active: #022b92;
1335
+ --sw-color-success: #10b981;
1336
+ --sw-color-danger: #ef4444;
1337
+ --sw-color-text: #1f2937;
1338
+ --sw-color-text-muted: #6b7280;
1339
+ --sw-color-border: #e5e7eb;
1340
+ --sw-color-background: #ffffff;
1341
+ --sw-color-background-hover: #f3f4f6;
1342
+ --sw-color-background-active: #e5e7eb;
1343
+ --sw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1344
+ --sw-font-size-sm: 12px;
1345
+ --sw-font-size-base: 16px;
1346
+ --sw-font-size-lg: 24px;
1347
+ --sw-font-size-xl: 32px;
1348
+ --sw-space-1: 4px;
1349
+ --sw-space-2: 8px;
1350
+ --sw-space-3: 12px;
1351
+ --sw-space-4: 16px;
1352
+ --sw-border-radius: 8px;
1353
+ --sw-border-radius-full: 9999px;
1354
+
1355
+ display: block;
1356
+ font-family: var(--sw-font-family);
1357
+ }
1358
+
1359
+ /* Dark mode support */
1360
+ :host([data-theme='dark']) {
1361
+ --sw-color-text: #f9fafb;
1362
+ --sw-color-text-muted: #9ca3af;
1363
+ --sw-color-border: #374151;
1364
+ --sw-color-background: #1f2937;
1365
+ --sw-color-background-hover: #374151;
1366
+ --sw-color-background-active: #4b5563;
1367
+ }
1368
+
1369
+ @media (prefers-color-scheme: dark) {
1370
+ :host(:not([data-theme='light'])) {
1371
+ --sw-color-text: #f9fafb;
1372
+ --sw-color-text-muted: #9ca3af;
1373
+ --sw-color-border: #374151;
1374
+ --sw-color-background: #1f2937;
1375
+ --sw-color-background-hover: #374151;
1376
+ --sw-color-background-active: #4b5563;
1377
+ }
1378
+ }
1379
+
1380
+ .container {
1381
+ display: flex;
1382
+ flex-direction: column;
1383
+ gap: var(--sw-space-3);
1384
+ padding: var(--sw-space-4);
1385
+ max-width: 280px;
1386
+ background: var(--sw-color-background);
1387
+ border-radius: var(--sw-border-radius);
1388
+ }
1389
+
1390
+ .display {
1391
+ display: flex;
1392
+ align-items: center;
1393
+ justify-content: space-between;
1394
+ padding: var(--sw-space-3) var(--sw-space-4);
1395
+ background: var(--sw-color-background-hover);
1396
+ border-radius: var(--sw-border-radius);
1397
+ min-height: 48px;
1398
+ }
1399
+
1400
+ .display-input {
1401
+ flex: 1;
1402
+ font-size: var(--sw-font-size-xl);
1403
+ font-weight: 500;
1404
+ font-family: var(--sw-font-family);
1405
+ color: var(--sw-color-text);
1406
+ background: transparent;
1407
+ border: none;
1408
+ outline: none;
1409
+ letter-spacing: 2px;
1410
+ text-align: center;
1411
+ }
1412
+
1413
+ .display-input::placeholder {
1414
+ color: var(--sw-color-text-muted);
1415
+ font-size: var(--sw-font-size-base);
1416
+ letter-spacing: normal;
1417
+ }
1418
+
1419
+ .backspace-button {
1420
+ display: flex;
1421
+ align-items: center;
1422
+ justify-content: center;
1423
+ width: 40px;
1424
+ height: 40px;
1425
+ background: transparent;
1426
+ border: none;
1427
+ border-radius: var(--sw-border-radius);
1428
+ cursor: pointer;
1429
+ color: var(--sw-color-text-muted);
1430
+ transition:
1431
+ background-color 0.15s ease,
1432
+ color 0.15s ease;
1433
+ }
1434
+
1435
+ .backspace-button:hover {
1436
+ background: var(--sw-color-background-active);
1437
+ color: var(--sw-color-text);
1438
+ }
1439
+
1440
+ .backspace-button:disabled {
1441
+ opacity: 0.3;
1442
+ cursor: not-allowed;
1443
+ }
1444
+
1445
+ .keypad {
1446
+ display: grid;
1447
+ grid-template-columns: repeat(3, 1fr);
1448
+ gap: var(--sw-space-2);
1449
+ }
1450
+
1451
+ .key {
1452
+ display: flex;
1453
+ flex-direction: column;
1454
+ align-items: center;
1455
+ justify-content: center;
1456
+ width: 72px;
1457
+ height: 72px;
1458
+ background: var(--sw-color-background);
1459
+ border: 1px solid var(--sw-color-border);
1460
+ border-radius: var(--sw-border-radius-full);
1461
+ cursor: pointer;
1462
+ transition:
1463
+ background-color 0.1s ease,
1464
+ transform 0.1s ease;
1465
+ user-select: none;
1466
+ -webkit-user-select: none;
1467
+ -webkit-tap-highlight-color: transparent;
1468
+ }
1469
+
1470
+ .key:hover {
1471
+ background: var(--sw-color-background-hover);
1472
+ }
1473
+
1474
+ .key:active,
1475
+ .key.pressed {
1476
+ background: var(--sw-color-background-active);
1477
+ transform: scale(0.95);
1478
+ }
1479
+
1480
+ .key-digit {
1481
+ font-size: var(--sw-font-size-lg);
1482
+ font-weight: 500;
1483
+ color: var(--sw-color-text);
1484
+ line-height: 1;
1485
+ }
1486
+
1487
+ .key-letters {
1488
+ font-size: var(--sw-font-size-sm);
1489
+ color: var(--sw-color-text-muted);
1490
+ text-transform: uppercase;
1491
+ letter-spacing: 1px;
1492
+ margin-top: 2px;
1493
+ min-height: 14px;
1494
+ }
1495
+
1496
+ .call-button {
1497
+ display: flex;
1498
+ align-items: center;
1499
+ justify-content: center;
1500
+ width: 100%;
1501
+ height: 56px;
1502
+ background: var(--sw-color-success);
1503
+ border: none;
1504
+ border-radius: var(--sw-border-radius);
1505
+ cursor: pointer;
1506
+ color: white;
1507
+ font-size: var(--sw-font-size-base);
1508
+ font-weight: 600;
1509
+ font-family: var(--sw-font-family);
1510
+ transition: background-color 0.15s ease;
1511
+ gap: var(--sw-space-2);
1512
+ }
1513
+
1514
+ .call-button:hover {
1515
+ background: #0ea472;
1516
+ }
1517
+
1518
+ .call-button:active {
1519
+ background: #0d9668;
1520
+ }
1521
+
1522
+ .call-button:disabled {
1523
+ opacity: 0.5;
1524
+ cursor: not-allowed;
1525
+ }
1526
+
1527
+ .call-button svg {
1528
+ width: 20px;
1529
+ height: 20px;
1530
+ }
1531
+ `,Ke([I({attribute:!1})],u.DialpadComponent.prototype,"call",2),Ke([Dt({context:Fe,subscribe:!0}),E()],u.DialpadComponent.prototype,"contextCall",2),Ke([E()],u.DialpadComponent.prototype,"digits",2),Ke([E()],u.DialpadComponent.prototype,"pressedKey",2),Ke([I({type:Boolean,attribute:"show-call-button"})],u.DialpadComponent.prototype,"showCallButton",2),Ke([I({type:String})],u.DialpadComponent.prototype,"placeholder",2),u.DialpadComponent=Ke([ue("sw-dialpad")],u.DialpadComponent);var Na=Object.defineProperty,Ua=Object.getOwnPropertyDescriptor,Ee=(e,t,i,r)=>{for(var s=r>1?void 0:r?Ua(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&Na(t,i,s),s};u.ClickToCallComponent=class extends X{constructor(){super(...arguments),this.client=null,this.destination="",this.label="Call",this.audioOnly=!0,this.status="idle",this.call=null,this.audioMuted=!1,this.selfParticipant=null,this.callDuration=0,this.errorMessage="",this.subscriptions=[],this.durationInterval=null,this.callStartTime=null}disconnectedCallback(){super.disconnectedCallback(),this.cleanup()}async initiateCall(){if(!this.client||!this.destination){this.errorMessage="No client or destination configured",this.status="error";return}try{this.status="connecting",this.errorMessage="",this.dispatchEvent(new CustomEvent("sw-dial",{detail:{destination:this.destination},bubbles:!0,composed:!0}));const t=await this.client.dial(this.destination,{audio:!0,video:!this.audioOnly});this.call=t,this.subscribeToCall(t)}catch(t){this.status="error",this.errorMessage=t instanceof Error?t.message:"Failed to connect",console.error("Click-to-call error:",t)}}subscribeToCall(t){if(t.status$){const i=t.status$.subscribe(r=>{r==="active"||r==="connected"?(this.status="connected",this.startDurationTimer()):r==="disconnecting"?this.status="disconnecting":(r==="disconnected"||r==="destroyed"||r==="failed")&&this.handleCallEnded()});this.subscriptions.push(i)}if(t.self$){const i=t.self$.pipe(we(r=>(this.selfParticipant=r,r.audioMuted$))).subscribe(r=>{r!==void 0&&(this.audioMuted=r)});this.subscriptions.push(i)}}startDurationTimer(){this.callStartTime=Date.now(),this.callDuration=0,this.durationInterval=window.setInterval(()=>{this.callStartTime&&(this.callDuration=Math.floor((Date.now()-this.callStartTime)/1e3))},1e3)}stopDurationTimer(){this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null),this.callStartTime=null}formatDuration(t){const i=Math.floor(t/60),r=t%60;return`${i}:${r.toString().padStart(2,"0")}`}handleCallEnded(){this.cleanup(),this.status="idle",this.call=null,this.selfParticipant=null,this.audioMuted=!1,this.callDuration=0,this.dispatchEvent(new CustomEvent("sw-hangup",{bubbles:!0,composed:!0}))}async toggleMute(){if(this.selfParticipant)try{this.audioMuted?await this.selfParticipant.unmute():await this.selfParticipant.mute(),this.dispatchEvent(new CustomEvent("sw-mute-toggle",{detail:{muted:!this.audioMuted},bubbles:!0,composed:!0}))}catch(t){console.error("Failed to toggle mute:",t)}}async hangup(){if(this.call)try{this.status="disconnecting",await this.call.hangup()}catch(t){console.error("Failed to hangup:",t),this.handleCallEnded()}}cleanup(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[],this.stopDurationTimer()}renderIdleState(){return g`
1532
+ <button
1533
+ class="call-button"
1534
+ part="button"
1535
+ @click=${this.initiateCall}
1536
+ ?disabled=${!this.client||!this.destination}
1537
+ aria-label="${this.label}"
1538
+ >
1539
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
1540
+ <path
1541
+ d="M6.62 10.79c1.44 2.83 3.76 5.15 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"
1542
+ />
1543
+ </svg>
1544
+ ${this.label}
1545
+ </button>
1546
+ `}renderConnectingState(){return g`
1547
+ <div class="active-call" part="controls">
1548
+ <div class="status-row">
1549
+ <div class="status" part="status">
1550
+ <span class="status-indicator connecting"></span>
1551
+ Connecting...
1552
+ </div>
1553
+ </div>
1554
+ </div>
1555
+ `}renderConnectedState(){return g`
1556
+ <div class="active-call" part="controls">
1557
+ <div class="status-row">
1558
+ <div class="status" part="status">
1559
+ <span class="status-indicator"></span>
1560
+ Connected
1561
+ </div>
1562
+ <span class="duration" part="duration">${this.formatDuration(this.callDuration)}</span>
1563
+ </div>
1564
+ <div class="controls-row">
1565
+ <button
1566
+ class="control-button ${this.audioMuted?"active":""}"
1567
+ @click=${this.toggleMute}
1568
+ aria-label="${this.audioMuted?"Unmute":"Mute"}"
1569
+ aria-pressed="${this.audioMuted}"
1570
+ >
1571
+ ${this.audioMuted?g`<svg
1572
+ xmlns="http://www.w3.org/2000/svg"
1573
+ viewBox="0 0 24 24"
1574
+ fill="currentColor"
1575
+ >
1576
+ <path
1577
+ d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"
1578
+ />
1579
+ </svg>`:g`<svg
1580
+ xmlns="http://www.w3.org/2000/svg"
1581
+ viewBox="0 0 24 24"
1582
+ fill="currentColor"
1583
+ >
1584
+ <path
1585
+ d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"
1586
+ />
1587
+ </svg>`}
1588
+ </button>
1589
+ <button class="control-button hangup-button" @click=${this.hangup} aria-label="Hang up">
1590
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
1591
+ <path
1592
+ d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"
1593
+ />
1594
+ </svg>
1595
+ </button>
1596
+ </div>
1597
+ </div>
1598
+ `}renderErrorState(){return g`
1599
+ <div class="container" part="container">
1600
+ ${this.renderIdleState()}
1601
+ ${this.errorMessage?g`<div class="error-message">${this.errorMessage}</div>`:null}
1602
+ </div>
1603
+ `}render(){return this.status==="error"?this.renderErrorState():this.status==="connecting"?g` <div class="container" part="container">${this.renderConnectingState()}</div> `:this.status==="connected"||this.status==="disconnecting"?g` <div class="container" part="container">${this.renderConnectedState()}</div> `:g` <div class="container" part="container">${this.renderIdleState()}</div> `}},u.ClickToCallComponent.styles=ce`
1604
+ :host {
1605
+ /* CSS Custom Properties for theming */
1606
+ --sw-color-primary: #044cf6;
1607
+ --sw-color-primary-hover: #0339c4;
1608
+ --sw-color-success: #10b981;
1609
+ --sw-color-success-hover: #0ea472;
1610
+ --sw-color-danger: #ef4444;
1611
+ --sw-color-danger-hover: #dc2626;
1612
+ --sw-color-warning: #f59e0b;
1613
+ --sw-color-text: #1f2937;
1614
+ --sw-color-text-muted: #6b7280;
1615
+ --sw-color-text-inverse: #ffffff;
1616
+ --sw-color-background: #ffffff;
1617
+ --sw-color-background-hover: #f3f4f6;
1618
+ --sw-color-border: #e5e7eb;
1619
+ --sw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1620
+ --sw-font-size-sm: 12px;
1621
+ --sw-font-size-base: 14px;
1622
+ --sw-font-size-lg: 16px;
1623
+ --sw-space-1: 4px;
1624
+ --sw-space-2: 8px;
1625
+ --sw-space-3: 12px;
1626
+ --sw-space-4: 16px;
1627
+ --sw-border-radius: 8px;
1628
+ --sw-border-radius-full: 9999px;
1629
+
1630
+ display: inline-block;
1631
+ font-family: var(--sw-font-family);
1632
+ }
1633
+
1634
+ /* Dark mode support */
1635
+ :host([data-theme='dark']) {
1636
+ --sw-color-text: #f9fafb;
1637
+ --sw-color-text-muted: #9ca3af;
1638
+ --sw-color-background: #1f2937;
1639
+ --sw-color-background-hover: #374151;
1640
+ --sw-color-border: #374151;
1641
+ }
1642
+
1643
+ @media (prefers-color-scheme: dark) {
1644
+ :host(:not([data-theme='light'])) {
1645
+ --sw-color-text: #f9fafb;
1646
+ --sw-color-text-muted: #9ca3af;
1647
+ --sw-color-background: #1f2937;
1648
+ --sw-color-background-hover: #374151;
1649
+ --sw-color-border: #374151;
1650
+ }
1651
+ }
1652
+
1653
+ .container {
1654
+ display: flex;
1655
+ flex-direction: column;
1656
+ gap: var(--sw-space-2);
1657
+ }
1658
+
1659
+ /* Idle state - call button */
1660
+ .call-button {
1661
+ display: inline-flex;
1662
+ align-items: center;
1663
+ justify-content: center;
1664
+ gap: var(--sw-space-2);
1665
+ padding: var(--sw-space-3) var(--sw-space-4);
1666
+ min-width: 120px;
1667
+ min-height: 44px;
1668
+ background: var(--sw-color-success);
1669
+ color: var(--sw-color-text-inverse);
1670
+ border: none;
1671
+ border-radius: var(--sw-border-radius);
1672
+ font-family: var(--sw-font-family);
1673
+ font-size: var(--sw-font-size-lg);
1674
+ font-weight: 600;
1675
+ cursor: pointer;
1676
+ transition:
1677
+ background-color 0.15s ease,
1678
+ transform 0.1s ease;
1679
+ }
1680
+
1681
+ .call-button:hover {
1682
+ background: var(--sw-color-success-hover);
1683
+ }
1684
+
1685
+ .call-button:active {
1686
+ transform: scale(0.98);
1687
+ }
1688
+
1689
+ .call-button:disabled {
1690
+ opacity: 0.5;
1691
+ cursor: not-allowed;
1692
+ }
1693
+
1694
+ .call-button svg {
1695
+ width: 20px;
1696
+ height: 20px;
1697
+ }
1698
+
1699
+ /* Connected state - expanded controls */
1700
+ .active-call {
1701
+ display: flex;
1702
+ flex-direction: column;
1703
+ gap: var(--sw-space-3);
1704
+ padding: var(--sw-space-4);
1705
+ background: var(--sw-color-background);
1706
+ border: 1px solid var(--sw-color-border);
1707
+ border-radius: var(--sw-border-radius);
1708
+ min-width: 200px;
1709
+ }
1710
+
1711
+ .status-row {
1712
+ display: flex;
1713
+ align-items: center;
1714
+ justify-content: space-between;
1715
+ gap: var(--sw-space-3);
1716
+ }
1717
+
1718
+ .status {
1719
+ display: flex;
1720
+ align-items: center;
1721
+ gap: var(--sw-space-2);
1722
+ font-size: var(--sw-font-size-base);
1723
+ color: var(--sw-color-text);
1724
+ }
1725
+
1726
+ .status-indicator {
1727
+ width: 8px;
1728
+ height: 8px;
1729
+ border-radius: 50%;
1730
+ background: var(--sw-color-success);
1731
+ }
1732
+
1733
+ .status-indicator.connecting {
1734
+ background: var(--sw-color-warning);
1735
+ animation: pulse 1.5s ease-in-out infinite;
1736
+ }
1737
+
1738
+ .status-indicator.error {
1739
+ background: var(--sw-color-danger);
1740
+ }
1741
+
1742
+ @keyframes pulse {
1743
+ 0%,
1744
+ 100% {
1745
+ opacity: 1;
1746
+ }
1747
+ 50% {
1748
+ opacity: 0.5;
1749
+ }
1750
+ }
1751
+
1752
+ .duration {
1753
+ font-variant-numeric: tabular-nums;
1754
+ color: var(--sw-color-text-muted);
1755
+ font-size: var(--sw-font-size-sm);
1756
+ }
1757
+
1758
+ .controls-row {
1759
+ display: flex;
1760
+ align-items: center;
1761
+ justify-content: center;
1762
+ gap: var(--sw-space-2);
1763
+ }
1764
+
1765
+ .control-button {
1766
+ display: flex;
1767
+ align-items: center;
1768
+ justify-content: center;
1769
+ width: 44px;
1770
+ height: 44px;
1771
+ background: var(--sw-color-background-hover);
1772
+ border: 1px solid var(--sw-color-border);
1773
+ border-radius: var(--sw-border-radius-full);
1774
+ cursor: pointer;
1775
+ color: var(--sw-color-text);
1776
+ transition: background-color 0.15s ease;
1777
+ }
1778
+
1779
+ .control-button:hover {
1780
+ background: var(--sw-color-border);
1781
+ }
1782
+
1783
+ .control-button.active {
1784
+ background: var(--sw-color-danger);
1785
+ border-color: var(--sw-color-danger);
1786
+ color: var(--sw-color-text-inverse);
1787
+ }
1788
+
1789
+ .control-button svg {
1790
+ width: 20px;
1791
+ height: 20px;
1792
+ }
1793
+
1794
+ .hangup-button {
1795
+ background: var(--sw-color-danger);
1796
+ border-color: var(--sw-color-danger);
1797
+ color: var(--sw-color-text-inverse);
1798
+ }
1799
+
1800
+ .hangup-button:hover {
1801
+ background: var(--sw-color-danger-hover);
1802
+ }
1803
+
1804
+ /* Error state */
1805
+ .error-message {
1806
+ color: var(--sw-color-danger);
1807
+ font-size: var(--sw-font-size-sm);
1808
+ text-align: center;
1809
+ }
1810
+ `,Ee([I({attribute:!1})],u.ClickToCallComponent.prototype,"client",2),Ee([I({type:String})],u.ClickToCallComponent.prototype,"destination",2),Ee([I({type:String})],u.ClickToCallComponent.prototype,"label",2),Ee([I({type:Boolean,attribute:"audio-only"})],u.ClickToCallComponent.prototype,"audioOnly",2),Ee([E()],u.ClickToCallComponent.prototype,"status",2),Ee([E()],u.ClickToCallComponent.prototype,"call",2),Ee([E()],u.ClickToCallComponent.prototype,"audioMuted",2),Ee([E()],u.ClickToCallComponent.prototype,"callDuration",2),Ee([E()],u.ClickToCallComponent.prototype,"errorMessage",2),u.ClickToCallComponent=Ee([ue("sw-click-to-call")],u.ClickToCallComponent);var za=Object.defineProperty,Fa=Object.getOwnPropertyDescriptor,Pe=(e,t,i,r)=>{for(var s=r>1?void 0:r?Fa(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&za(t,i,s),s};u.DirectoryComponent=class extends X{constructor(){super(...arguments),this.directory=null,this.selectedAddress=null,this.searchQuery="",this.addresses=[],this.loading=!1,this.hasMore=!1,this.subscriptions=[],this.searchDebounceTimer=null,this.intersectionObserver=null,this.isAutoLoadingForSearch=!1}connectedCallback(){super.connectedCallback(),this.subscribeToDirectory()}disconnectedCallback(){super.disconnectedCallback(),this.cleanup()}subscribeToDirectory(){if(this.directory){if(this.directory.addresses$){const t=this.directory.addresses$.subscribe(i=>{this.addresses=i});this.subscriptions.push(t)}if(this.directory.loading$){const t=this.directory.loading$.subscribe(i=>{this.loading=i});this.subscriptions.push(t)}if(this.directory.hasMore$){const t=this.directory.hasMore$.subscribe(i=>{this.hasMore=i});this.subscriptions.push(t)}this.directory.loadMore&&this.directory.loadMore()}}cleanup(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[],this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null)}firstUpdated(){this.setupInfiniteScroll()}setupInfiniteScroll(){var i,r;const t=(i=this.shadowRoot)==null?void 0:i.querySelector(".scroll-sentinel");t&&(this.intersectionObserver=new IntersectionObserver(s=>{const n=s[0];n!=null&&n.isIntersecting&&this.hasMore&&!this.loading&&this.handleLoadMore()},{root:(r=this.shadowRoot)==null?void 0:r.querySelector(".list"),rootMargin:"100px",threshold:0}),this.intersectionObserver.observe(t))}updated(t){super.updated(t),t.has("directory")&&(this.cleanup(),this.subscribeToDirectory()),this.intersectionObserver||this.setupInfiniteScroll(),(t.has("addresses")||t.has("searchQuery")||t.has("loading"))&&this.checkAutoLoadForSearch()}async checkAutoLoadForSearch(){this.searchQuery.trim()&&this.filteredAddresses.length===0&&this.hasMore&&!this.loading?(this.isAutoLoadingForSearch=!0,await this.handleLoadMore()):(this.filteredAddresses.length>0||!this.hasMore)&&(this.isAutoLoadingForSearch=!1)}get filteredAddresses(){if(!this.searchQuery.trim())return this.addresses;const t=this.searchQuery.toLowerCase();return this.addresses.filter(i=>i.name.toLowerCase().includes(t)||i.displayName&&i.displayName.toLowerCase().includes(t))}handleSearchInput(t){const i=t.target;this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=window.setTimeout(()=>{this.searchQuery=i.value},200)}handleItemClick(t){this.selectedAddress=t,this.dispatchEvent(new CustomEvent("sw-address-select",{detail:{address:t},bubbles:!0,composed:!0}))}handleItemDoubleClick(t){this.handleDial(t)}handleDial(t){this.dispatchEvent(new CustomEvent("sw-dial",{detail:{address:t},bubbles:!0,composed:!0}))}async handleLoadMore(){var t;(t=this.directory)!=null&&t.loadMore&&await this.directory.loadMore()}renderAddressIcon(t){return t.type==="room"?g`
1811
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
1812
+ <path
1813
+ d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 3c1.93 0 3.5 1.57 3.5 3.5S13.93 13 12 13s-3.5-1.57-3.5-3.5S10.07 6 12 6zm7 13H5v-.23c0-.62.28-1.2.76-1.58C7.47 15.82 9.64 15 12 15s4.53.82 6.24 2.19c.48.38.76.97.76 1.58V19z"
1814
+ />
1815
+ </svg>
1816
+ `:g`
1817
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
1818
+ <path
1819
+ d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"
1820
+ />
1821
+ </svg>
1822
+ `}renderChannelIcons(t){const i=t.channels||{};return g`
1823
+ <div class="item-channels">
1824
+ <svg
1825
+ xmlns="http://www.w3.org/2000/svg"
1826
+ viewBox="0 0 24 24"
1827
+ fill="currentColor"
1828
+ class="${i.audio?"active":""}"
1829
+ title="Audio"
1830
+ >
1831
+ <path
1832
+ d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"
1833
+ />
1834
+ </svg>
1835
+ <svg
1836
+ xmlns="http://www.w3.org/2000/svg"
1837
+ viewBox="0 0 24 24"
1838
+ fill="currentColor"
1839
+ class="${i.video?"active":""}"
1840
+ title="Video"
1841
+ >
1842
+ <path
1843
+ d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"
1844
+ />
1845
+ </svg>
1846
+ </div>
1847
+ `}renderLoadingIndicator(){return g`
1848
+ <div class="scroll-loading">
1849
+ <div class="spinner"></div>
1850
+ <span>${this.isAutoLoadingForSearch?"Searching...":"Loading more..."}</span>
1851
+ </div>
1852
+ `}render(){const t=this.loading&&this.addresses.length===0,i=!this.loading&&this.filteredAddresses.length===0&&!this.hasMore,r=this.isAutoLoadingForSearch&&this.filteredAddresses.length===0;return g`
1853
+ <div class="container" part="container">
1854
+ <div class="search" part="search">
1855
+ <input
1856
+ type="text"
1857
+ class="search-input"
1858
+ placeholder="Search addresses..."
1859
+ @input=${this.handleSearchInput}
1860
+ aria-label="Search addresses"
1861
+ />
1862
+ </div>
1863
+
1864
+ <div class="list" part="list" role="listbox">
1865
+ ${t?g`<div class="loading">Loading...</div>`:r?this.renderLoadingIndicator():i?g`<div class="empty">No addresses found</div>`:g`
1866
+ ${this.filteredAddresses.map(s=>{var n,o,a;return g`
1867
+ <div
1868
+ class="item ${((n=this.selectedAddress)==null?void 0:n.id)===s.id?"selected":""}"
1869
+ part="item ${((o=this.selectedAddress)==null?void 0:o.id)===s.id?"item-selected":""}"
1870
+ role="option"
1871
+ aria-selected="${((a=this.selectedAddress)==null?void 0:a.id)===s.id}"
1872
+ @click=${()=>this.handleItemClick(s)}
1873
+ @dblclick=${()=>this.handleItemDoubleClick(s)}
1874
+ >
1875
+ <div class="item-icon">${this.renderAddressIcon(s)}</div>
1876
+ <div class="item-content">
1877
+ <div class="item-name" part="item-name">
1878
+ ${s.displayName||s.name}
1879
+ </div>
1880
+ <div class="item-type" part="item-type">
1881
+ ${s.type||"address"}
1882
+ </div>
1883
+ </div>
1884
+ ${this.renderChannelIcons(s)}
1885
+ <button
1886
+ class="dial-button"
1887
+ @click=${c=>{c.stopPropagation(),this.handleDial(s)}}
1888
+ aria-label="Call ${s.displayName||s.name}"
1889
+ >
1890
+ <svg
1891
+ xmlns="http://www.w3.org/2000/svg"
1892
+ viewBox="0 0 24 24"
1893
+ fill="currentColor"
1894
+ >
1895
+ <path
1896
+ d="M6.62 10.79c1.44 2.83 3.76 5.15 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"
1897
+ />
1898
+ </svg>
1899
+ </button>
1900
+ </div>
1901
+ `})}
1902
+ <!-- Scroll sentinel for infinite scroll -->
1903
+ <div class="scroll-sentinel">
1904
+ ${this.loading&&!this.isAutoLoadingForSearch?this.renderLoadingIndicator():null}
1905
+ </div>
1906
+ `}
1907
+ </div>
1908
+ </div>
1909
+ `}},u.DirectoryComponent.styles=ce`
1910
+ :host {
1911
+ /* CSS Custom Properties for theming */
1912
+ --sw-color-primary: #044cf6;
1913
+ --sw-color-primary-hover: #0339c4;
1914
+ --sw-color-success: #10b981;
1915
+ --sw-color-text: #1f2937;
1916
+ --sw-color-text-muted: #6b7280;
1917
+ --sw-color-background: #ffffff;
1918
+ --sw-color-background-hover: #f3f4f6;
1919
+ --sw-color-background-active: #e5e7eb;
1920
+ --sw-color-border: #e5e7eb;
1921
+ --sw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1922
+ --sw-font-size-sm: 12px;
1923
+ --sw-font-size-base: 14px;
1924
+ --sw-font-size-lg: 16px;
1925
+ --sw-space-1: 4px;
1926
+ --sw-space-2: 8px;
1927
+ --sw-space-3: 12px;
1928
+ --sw-space-4: 16px;
1929
+ --sw-border-radius: 8px;
1930
+
1931
+ display: block;
1932
+ font-family: var(--sw-font-family);
1933
+ }
1934
+
1935
+ /* Dark mode support */
1936
+ :host([data-theme='dark']) {
1937
+ --sw-color-text: #f9fafb;
1938
+ --sw-color-text-muted: #9ca3af;
1939
+ --sw-color-background: #1f2937;
1940
+ --sw-color-background-hover: #374151;
1941
+ --sw-color-background-active: #4b5563;
1942
+ --sw-color-border: #374151;
1943
+ }
1944
+
1945
+ @media (prefers-color-scheme: dark) {
1946
+ :host(:not([data-theme='light'])) {
1947
+ --sw-color-text: #f9fafb;
1948
+ --sw-color-text-muted: #9ca3af;
1949
+ --sw-color-background: #1f2937;
1950
+ --sw-color-background-hover: #374151;
1951
+ --sw-color-background-active: #4b5563;
1952
+ --sw-color-border: #374151;
1953
+ }
1954
+ }
1955
+
1956
+ .container {
1957
+ display: flex;
1958
+ flex-direction: column;
1959
+ background: var(--sw-color-background);
1960
+ border: 1px solid var(--sw-color-border);
1961
+ border-radius: var(--sw-border-radius);
1962
+ overflow: hidden;
1963
+ }
1964
+
1965
+ .search {
1966
+ display: flex;
1967
+ align-items: center;
1968
+ gap: var(--sw-space-2);
1969
+ padding: var(--sw-space-3);
1970
+ border-bottom: 1px solid var(--sw-color-border);
1971
+ }
1972
+
1973
+ .search-input {
1974
+ flex: 1;
1975
+ padding: var(--sw-space-2) var(--sw-space-3);
1976
+ border: 1px solid var(--sw-color-border);
1977
+ border-radius: var(--sw-border-radius);
1978
+ background: var(--sw-color-background);
1979
+ color: var(--sw-color-text);
1980
+ font-family: var(--sw-font-family);
1981
+ font-size: var(--sw-font-size-base);
1982
+ outline: none;
1983
+ transition: border-color 0.15s ease;
1984
+ }
1985
+
1986
+ .search-input:focus {
1987
+ border-color: var(--sw-color-primary);
1988
+ }
1989
+
1990
+ .search-input::placeholder {
1991
+ color: var(--sw-color-text-muted);
1992
+ }
1993
+
1994
+ .list {
1995
+ display: flex;
1996
+ flex-direction: column;
1997
+ max-height: 400px;
1998
+ overflow-y: auto;
1999
+ }
2000
+
2001
+ .item {
2002
+ display: flex;
2003
+ align-items: center;
2004
+ gap: var(--sw-space-3);
2005
+ padding: var(--sw-space-3) var(--sw-space-4);
2006
+ border-bottom: 1px solid var(--sw-color-border);
2007
+ cursor: pointer;
2008
+ transition: background-color 0.15s ease;
2009
+ }
2010
+
2011
+ .item:last-child {
2012
+ border-bottom: none;
2013
+ }
2014
+
2015
+ .item:hover {
2016
+ background: var(--sw-color-background-hover);
2017
+ }
2018
+
2019
+ .item:active {
2020
+ background: var(--sw-color-background-active);
2021
+ }
2022
+
2023
+ .item.selected {
2024
+ background: var(--sw-color-primary);
2025
+ color: white;
2026
+ }
2027
+
2028
+ .item.selected .item-type,
2029
+ .item.selected .item-channels {
2030
+ color: rgba(255, 255, 255, 0.8);
2031
+ }
2032
+
2033
+ .item-icon {
2034
+ display: flex;
2035
+ align-items: center;
2036
+ justify-content: center;
2037
+ width: 40px;
2038
+ height: 40px;
2039
+ border-radius: 50%;
2040
+ background: var(--sw-color-background-hover);
2041
+ color: var(--sw-color-text-muted);
2042
+ flex-shrink: 0;
2043
+ }
2044
+
2045
+ .item.selected .item-icon {
2046
+ background: rgba(255, 255, 255, 0.2);
2047
+ color: white;
2048
+ }
2049
+
2050
+ .item-icon svg {
2051
+ width: 20px;
2052
+ height: 20px;
2053
+ }
2054
+
2055
+ .item-content {
2056
+ flex: 1;
2057
+ min-width: 0;
2058
+ }
2059
+
2060
+ .item-name {
2061
+ font-size: var(--sw-font-size-base);
2062
+ font-weight: 500;
2063
+ color: inherit;
2064
+ white-space: nowrap;
2065
+ overflow: hidden;
2066
+ text-overflow: ellipsis;
2067
+ }
2068
+
2069
+ .item-type {
2070
+ font-size: var(--sw-font-size-sm);
2071
+ color: var(--sw-color-text-muted);
2072
+ text-transform: capitalize;
2073
+ }
2074
+
2075
+ .item-channels {
2076
+ display: flex;
2077
+ gap: var(--sw-space-1);
2078
+ color: var(--sw-color-text-muted);
2079
+ }
2080
+
2081
+ .item-channels svg {
2082
+ width: 16px;
2083
+ height: 16px;
2084
+ }
2085
+
2086
+ .item-channels .active {
2087
+ color: var(--sw-color-success);
2088
+ }
2089
+
2090
+ .loading,
2091
+ .empty {
2092
+ display: flex;
2093
+ align-items: center;
2094
+ justify-content: center;
2095
+ padding: var(--sw-space-4);
2096
+ color: var(--sw-color-text-muted);
2097
+ font-size: var(--sw-font-size-base);
2098
+ }
2099
+
2100
+ .scroll-sentinel {
2101
+ display: flex;
2102
+ align-items: center;
2103
+ justify-content: center;
2104
+ padding: var(--sw-space-3);
2105
+ min-height: 1px;
2106
+ }
2107
+
2108
+ .scroll-loading {
2109
+ display: flex;
2110
+ align-items: center;
2111
+ justify-content: center;
2112
+ gap: var(--sw-space-2);
2113
+ padding: var(--sw-space-3);
2114
+ color: var(--sw-color-text-muted);
2115
+ font-size: var(--sw-font-size-sm);
2116
+ }
2117
+
2118
+ .spinner {
2119
+ width: 16px;
2120
+ height: 16px;
2121
+ border: 2px solid var(--sw-color-border);
2122
+ border-top-color: var(--sw-color-primary);
2123
+ border-radius: 50%;
2124
+ animation: spin 0.8s linear infinite;
2125
+ }
2126
+
2127
+ @keyframes spin {
2128
+ to {
2129
+ transform: rotate(360deg);
2130
+ }
2131
+ }
2132
+
2133
+ .dial-button {
2134
+ display: flex;
2135
+ align-items: center;
2136
+ justify-content: center;
2137
+ width: 36px;
2138
+ height: 36px;
2139
+ background: var(--sw-color-success);
2140
+ border: none;
2141
+ border-radius: 50%;
2142
+ color: white;
2143
+ cursor: pointer;
2144
+ flex-shrink: 0;
2145
+ transition: background-color 0.15s ease;
2146
+ }
2147
+
2148
+ .dial-button:hover {
2149
+ background: #0ea472;
2150
+ }
2151
+
2152
+ .dial-button svg {
2153
+ width: 18px;
2154
+ height: 18px;
2155
+ }
2156
+ `,Pe([I({type:Object})],u.DirectoryComponent.prototype,"directory",2),Pe([E()],u.DirectoryComponent.prototype,"selectedAddress",2),Pe([E()],u.DirectoryComponent.prototype,"searchQuery",2),Pe([E()],u.DirectoryComponent.prototype,"addresses",2),Pe([E()],u.DirectoryComponent.prototype,"loading",2),Pe([E()],u.DirectoryComponent.prototype,"hasMore",2),Pe([E()],u.DirectoryComponent.prototype,"isAutoLoadingForSearch",2),u.DirectoryComponent=Pe([ue("sw-directory")],u.DirectoryComponent);var ja=Object.defineProperty,Ha=Object.getOwnPropertyDescriptor,Me=(e,t,i,r)=>{for(var s=r>1?void 0:r?Ha(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&ja(t,i,s),s};u.ParticipantControlsComponent=class extends X{constructor(){super(...arguments),this.participant=null,this.capabilities=[],this.showVolume=!1,this.showPin=!1,this.volume=100,this.participantName="Participant",this.audioMuted=!1,this.videoMuted=!1,this.isPinned=!1,this.subscriptions=[]}connectedCallback(){super.connectedCallback(),this.subscribeToParticipant()}disconnectedCallback(){super.disconnectedCallback(),this.cleanup()}updated(t){t.has("participant")&&(this.cleanup(),this.subscribeToParticipant())}subscribeToParticipant(){if(this.participant){if(this.participant.name$){const t=this.participant.name$.subscribe(i=>{i!==void 0&&(this.participantName=i)});this.subscriptions.push(t)}if(this.participant.audioMuted$){const t=this.participant.audioMuted$.subscribe(i=>{i!==void 0&&(this.audioMuted=i)});this.subscriptions.push(t)}if(this.participant.videoMuted$){const t=this.participant.videoMuted$.subscribe(i=>{i!==void 0&&(this.videoMuted=i)});this.subscriptions.push(t)}}}cleanup(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[]}get canMuteAudio(){return this.capabilities.includes("memberMuteAudio")}get canMuteVideo(){return this.capabilities.includes("memberMuteVideo")}get canRemove(){return this.capabilities.includes("memberRemove")}get hasAnyCapability(){return this.canMuteAudio||this.canMuteVideo||this.canRemove||this.showVolume||this.showPin}async handleToggleAudioMute(){if(this.participant)try{this.audioMuted&&this.participant.unmute?await this.participant.unmute():!this.audioMuted&&this.participant.mute&&await this.participant.mute(),this.dispatchEvent(new CustomEvent("sw-participant-mute-audio",{detail:{participant:this.participant,muted:!this.audioMuted},bubbles:!0,composed:!0}))}catch(t){console.error("Failed to toggle audio mute:",t)}}async handleToggleVideoMute(){if(this.participant)try{this.videoMuted&&this.participant.unmuteVideo?await this.participant.unmuteVideo():!this.videoMuted&&this.participant.muteVideo&&await this.participant.muteVideo(),this.dispatchEvent(new CustomEvent("sw-participant-mute-video",{detail:{participant:this.participant,muted:!this.videoMuted},bubbles:!0,composed:!0}))}catch(t){console.error("Failed to toggle video mute:",t)}}async handleRemove(){var t;if((t=this.participant)!=null&&t.remove)try{await this.participant.remove(),this.dispatchEvent(new CustomEvent("sw-participant-remove",{detail:{participant:this.participant},bubbles:!0,composed:!0}))}catch(i){console.error("Failed to remove participant:",i)}}handleVolumeChange(t){const i=t.target;this.volume=parseInt(i.value,10),this.dispatchEvent(new CustomEvent("sw-participant-volume",{detail:{participant:this.participant,volume:this.volume},bubbles:!0,composed:!0}))}handleTogglePin(){this.isPinned=!this.isPinned,this.dispatchEvent(new CustomEvent("sw-participant-pin",{detail:{participant:this.participant,pinned:this.isPinned},bubbles:!0,composed:!0}))}render(){return g`
2157
+ <div class="container" part="container">
2158
+ <div class="header">
2159
+ <span class="participant-name">${this.participantName}</span>
2160
+ </div>
2161
+
2162
+ <div class="actions">
2163
+ ${this.hasAnyCapability?null:g`<div class="no-actions">No actions available</div>`}
2164
+ ${this.canMuteAudio?g`
2165
+ <button
2166
+ class="action-button ${this.audioMuted?"active":""}"
2167
+ part="action-button"
2168
+ @click=${this.handleToggleAudioMute}
2169
+ aria-label="${this.audioMuted?"Unmute audio":"Mute audio"}"
2170
+ >
2171
+ ${this.audioMuted?g`<svg
2172
+ xmlns="http://www.w3.org/2000/svg"
2173
+ viewBox="0 0 24 24"
2174
+ fill="currentColor"
2175
+ >
2176
+ <path
2177
+ d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"
2178
+ />
2179
+ </svg>`:g`<svg
2180
+ xmlns="http://www.w3.org/2000/svg"
2181
+ viewBox="0 0 24 24"
2182
+ fill="currentColor"
2183
+ >
2184
+ <path
2185
+ d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"
2186
+ />
2187
+ </svg>`}
2188
+ ${this.audioMuted?"Unmute":"Mute"}
2189
+ </button>
2190
+ `:null}
2191
+ ${this.canMuteVideo?g`
2192
+ <button
2193
+ class="action-button ${this.videoMuted?"active":""}"
2194
+ part="action-button"
2195
+ @click=${this.handleToggleVideoMute}
2196
+ aria-label="${this.videoMuted?"Unmute video":"Mute video"}"
2197
+ >
2198
+ ${this.videoMuted?g`<svg
2199
+ xmlns="http://www.w3.org/2000/svg"
2200
+ viewBox="0 0 24 24"
2201
+ fill="currentColor"
2202
+ >
2203
+ <path
2204
+ d="M21 6.5l-4 4V7c0-.55-.45-1-1-1H9.82L21 17.18V6.5zM3.27 2L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73 3.27 2z"
2205
+ />
2206
+ </svg>`:g`<svg
2207
+ xmlns="http://www.w3.org/2000/svg"
2208
+ viewBox="0 0 24 24"
2209
+ fill="currentColor"
2210
+ >
2211
+ <path
2212
+ d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"
2213
+ />
2214
+ </svg>`}
2215
+ ${this.videoMuted?"Enable video":"Disable video"}
2216
+ </button>
2217
+ `:null}
2218
+ ${this.showVolume?g`
2219
+ <div class="volume-control" part="slider">
2220
+ <label class="volume-label">
2221
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
2222
+ <path
2223
+ d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"
2224
+ />
2225
+ </svg>
2226
+ Volume: ${this.volume}%
2227
+ </label>
2228
+ <input
2229
+ type="range"
2230
+ class="volume-slider"
2231
+ min="0"
2232
+ max="100"
2233
+ .value=${String(this.volume)}
2234
+ @input=${this.handleVolumeChange}
2235
+ aria-label="Participant volume"
2236
+ />
2237
+ </div>
2238
+ `:null}
2239
+ ${this.showPin?g`
2240
+ <button
2241
+ class="action-button ${this.isPinned?"active":""}"
2242
+ part="action-button"
2243
+ @click=${this.handleTogglePin}
2244
+ aria-label="${this.isPinned?"Unpin":"Pin"}"
2245
+ aria-pressed="${this.isPinned}"
2246
+ >
2247
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
2248
+ <path d="M16 12V4h1V2H7v2h1v8l-2 2v2h5.2v6h1.6v-6H18v-2l-2-2z" />
2249
+ </svg>
2250
+ ${this.isPinned?"Unpin":"Pin"}
2251
+ </button>
2252
+ `:null}
2253
+ ${this.canRemove?g`
2254
+ <button
2255
+ class="action-button danger"
2256
+ part="action-button"
2257
+ @click=${this.handleRemove}
2258
+ aria-label="Remove participant"
2259
+ >
2260
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
2261
+ <path
2262
+ d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
2263
+ />
2264
+ </svg>
2265
+ Remove
2266
+ </button>
2267
+ `:null}
2268
+ </div>
2269
+ </div>
2270
+ `}},u.ParticipantControlsComponent.styles=ce`
2271
+ :host {
2272
+ /* CSS Custom Properties for theming */
2273
+ --sw-color-primary: #044cf6;
2274
+ --sw-color-primary-hover: #0339c4;
2275
+ --sw-color-success: #10b981;
2276
+ --sw-color-danger: #ef4444;
2277
+ --sw-color-danger-hover: #dc2626;
2278
+ --sw-color-warning: #f59e0b;
2279
+ --sw-color-text: #1f2937;
2280
+ --sw-color-text-muted: #6b7280;
2281
+ --sw-color-text-inverse: #ffffff;
2282
+ --sw-color-background: #ffffff;
2283
+ --sw-color-background-hover: #f3f4f6;
2284
+ --sw-color-background-active: #e5e7eb;
2285
+ --sw-color-border: #e5e7eb;
2286
+ --sw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
2287
+ --sw-font-size-xs: 11px;
2288
+ --sw-font-size-sm: 12px;
2289
+ --sw-font-size-base: 14px;
2290
+ --sw-space-1: 4px;
2291
+ --sw-space-2: 8px;
2292
+ --sw-space-3: 12px;
2293
+ --sw-space-4: 16px;
2294
+ --sw-border-radius: 8px;
2295
+
2296
+ display: block;
2297
+ font-family: var(--sw-font-family);
2298
+ }
2299
+
2300
+ /* Dark mode support */
2301
+ :host([data-theme='dark']) {
2302
+ --sw-color-text: #f9fafb;
2303
+ --sw-color-text-muted: #9ca3af;
2304
+ --sw-color-background: #1f2937;
2305
+ --sw-color-background-hover: #374151;
2306
+ --sw-color-background-active: #4b5563;
2307
+ --sw-color-border: #374151;
2308
+ }
2309
+
2310
+ @media (prefers-color-scheme: dark) {
2311
+ :host(:not([data-theme='light'])) {
2312
+ --sw-color-text: #f9fafb;
2313
+ --sw-color-text-muted: #9ca3af;
2314
+ --sw-color-background: #1f2937;
2315
+ --sw-color-background-hover: #374151;
2316
+ --sw-color-background-active: #4b5563;
2317
+ --sw-color-border: #374151;
2318
+ }
2319
+ }
2320
+
2321
+ .container {
2322
+ display: flex;
2323
+ flex-direction: column;
2324
+ gap: var(--sw-space-2);
2325
+ padding: var(--sw-space-3);
2326
+ background: var(--sw-color-background);
2327
+ border: 1px solid var(--sw-color-border);
2328
+ border-radius: var(--sw-border-radius);
2329
+ min-width: 200px;
2330
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
2331
+ }
2332
+
2333
+ .header {
2334
+ display: flex;
2335
+ align-items: center;
2336
+ gap: var(--sw-space-2);
2337
+ padding-bottom: var(--sw-space-2);
2338
+ border-bottom: 1px solid var(--sw-color-border);
2339
+ }
2340
+
2341
+ .participant-name {
2342
+ flex: 1;
2343
+ font-size: var(--sw-font-size-base);
2344
+ font-weight: 500;
2345
+ color: var(--sw-color-text);
2346
+ overflow: hidden;
2347
+ text-overflow: ellipsis;
2348
+ white-space: nowrap;
2349
+ }
2350
+
2351
+ .actions {
2352
+ display: flex;
2353
+ flex-direction: column;
2354
+ gap: var(--sw-space-2);
2355
+ }
2356
+
2357
+ .action-button {
2358
+ display: flex;
2359
+ align-items: center;
2360
+ gap: var(--sw-space-2);
2361
+ padding: var(--sw-space-2) var(--sw-space-3);
2362
+ background: var(--sw-color-background-hover);
2363
+ border: none;
2364
+ border-radius: var(--sw-border-radius);
2365
+ color: var(--sw-color-text);
2366
+ font-family: var(--sw-font-family);
2367
+ font-size: var(--sw-font-size-sm);
2368
+ cursor: pointer;
2369
+ transition: background-color 0.15s ease;
2370
+ text-align: left;
2371
+ }
2372
+
2373
+ .action-button:hover {
2374
+ background: var(--sw-color-background-active);
2375
+ }
2376
+
2377
+ .action-button:disabled {
2378
+ opacity: 0.5;
2379
+ cursor: not-allowed;
2380
+ }
2381
+
2382
+ .action-button.active {
2383
+ background: var(--sw-color-danger);
2384
+ color: var(--sw-color-text-inverse);
2385
+ }
2386
+
2387
+ .action-button.active:hover {
2388
+ background: var(--sw-color-danger-hover);
2389
+ }
2390
+
2391
+ .action-button.danger {
2392
+ color: var(--sw-color-danger);
2393
+ }
2394
+
2395
+ .action-button.danger:hover {
2396
+ background: var(--sw-color-danger);
2397
+ color: var(--sw-color-text-inverse);
2398
+ }
2399
+
2400
+ .action-button svg {
2401
+ width: 16px;
2402
+ height: 16px;
2403
+ flex-shrink: 0;
2404
+ }
2405
+
2406
+ .volume-control {
2407
+ display: flex;
2408
+ flex-direction: column;
2409
+ gap: var(--sw-space-1);
2410
+ }
2411
+
2412
+ .volume-label {
2413
+ display: flex;
2414
+ align-items: center;
2415
+ gap: var(--sw-space-2);
2416
+ font-size: var(--sw-font-size-sm);
2417
+ color: var(--sw-color-text-muted);
2418
+ }
2419
+
2420
+ .volume-label svg {
2421
+ width: 14px;
2422
+ height: 14px;
2423
+ }
2424
+
2425
+ .volume-slider {
2426
+ width: 100%;
2427
+ height: 4px;
2428
+ -webkit-appearance: none;
2429
+ appearance: none;
2430
+ background: var(--sw-color-border);
2431
+ border-radius: 2px;
2432
+ outline: none;
2433
+ cursor: pointer;
2434
+ }
2435
+
2436
+ .volume-slider::-webkit-slider-thumb {
2437
+ -webkit-appearance: none;
2438
+ appearance: none;
2439
+ width: 14px;
2440
+ height: 14px;
2441
+ background: var(--sw-color-primary);
2442
+ border-radius: 50%;
2443
+ cursor: pointer;
2444
+ transition: transform 0.1s ease;
2445
+ }
2446
+
2447
+ .volume-slider::-webkit-slider-thumb:hover {
2448
+ transform: scale(1.2);
2449
+ }
2450
+
2451
+ .volume-slider::-moz-range-thumb {
2452
+ width: 14px;
2453
+ height: 14px;
2454
+ background: var(--sw-color-primary);
2455
+ border-radius: 50%;
2456
+ border: none;
2457
+ cursor: pointer;
2458
+ }
2459
+
2460
+ .no-actions {
2461
+ color: var(--sw-color-text-muted);
2462
+ font-size: var(--sw-font-size-sm);
2463
+ text-align: center;
2464
+ padding: var(--sw-space-2);
2465
+ }
2466
+ `,Me([I({attribute:!1})],u.ParticipantControlsComponent.prototype,"participant",2),Me([I({attribute:!1})],u.ParticipantControlsComponent.prototype,"capabilities",2),Me([I({type:Boolean,attribute:"show-volume"})],u.ParticipantControlsComponent.prototype,"showVolume",2),Me([I({type:Boolean,attribute:"show-pin"})],u.ParticipantControlsComponent.prototype,"showPin",2),Me([E()],u.ParticipantControlsComponent.prototype,"volume",2),Me([E()],u.ParticipantControlsComponent.prototype,"participantName",2),Me([E()],u.ParticipantControlsComponent.prototype,"audioMuted",2),Me([E()],u.ParticipantControlsComponent.prototype,"videoMuted",2),Me([E()],u.ParticipantControlsComponent.prototype,"isPinned",2),u.ParticipantControlsComponent=Me([ue("sw-participant-controls")],u.ParticipantControlsComponent);const Wa="1.0.0-rc.0",Ga=!0;(()=>{if(typeof window<"u"){const e=new CustomEvent("signalwire:web-components:ready",{detail:{version:"1.0.0-rc.0"}});window.dispatchEvent(e)}})();function qa(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ti={exports:{}},Ka=ti.exports,vs;function Ja(){return vs||(vs=1,(function(e){(function(t,i){e.exports?e.exports=i():t.log=i()})(Ka,function(){var t=function(){},i="undefined",r=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],n={},o=null;function a(m,x){var w=m[x];if(typeof w.bind=="function")return w.bind(m);try{return Function.prototype.bind.call(w,m)}catch{return function(){return Function.prototype.apply.apply(w,[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 l(m){return m==="debug"&&(m="log"),typeof console===i?!1:m==="trace"&&r?c:console[m]!==void 0?a(console,m):console.log!==void 0?a(console,"log"):t}function h(){for(var m=this.getLevel(),x=0;x<s.length;x++){var w=s[x];this[w]=x<m?t:this.methodFactory(w,m,this.name)}if(this.log=this.debug,typeof console===i&&m<this.levels.SILENT)return"No console available for logging"}function p(m){return function(){typeof console!==i&&(h.call(this),this[m].apply(this,arguments))}}function b(m,x,w){return l(m)||p.apply(this,arguments)}function _(m,x){var w=this,G,de,Te,J="loglevel";typeof m=="string"?J+=":"+m:typeof m=="symbol"&&(J=void 0);function Le(V){var Y=(s[V]||"silent").toUpperCase();if(!(typeof window===i||!J)){try{window.localStorage[J]=Y;return}catch{}try{window.document.cookie=encodeURIComponent(J)+"="+Y+";"}catch{}}}function pi(){var V;if(!(typeof window===i||!J)){try{V=window.localStorage[J]}catch{}if(typeof V===i)try{var Y=window.document.cookie,fi=encodeURIComponent(J),In=Y.indexOf(fi+"=");In!==-1&&(V=/^([^;]+)/.exec(Y.slice(In+fi.length+1))[1])}catch{}return w.levels[V]===void 0&&(V=void 0),V}}function or(){if(!(typeof window===i||!J)){try{window.localStorage.removeItem(J)}catch{}try{window.document.cookie=encodeURIComponent(J)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function rt(V){var Y=V;if(typeof Y=="string"&&w.levels[Y.toUpperCase()]!==void 0&&(Y=w.levels[Y.toUpperCase()]),typeof Y=="number"&&Y>=0&&Y<=w.levels.SILENT)return Y;throw new TypeError("log.setLevel() called with invalid level: "+V)}w.name=m,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=x||b,w.getLevel=function(){return Te??de??G},w.setLevel=function(V,Y){return Te=rt(V),Y!==!1&&Le(Te),h.call(w)},w.setDefaultLevel=function(V){de=rt(V),pi()||w.setLevel(V,!1)},w.resetLevel=function(){Te=null,or(),h.call(w)},w.enableAll=function(V){w.setLevel(w.levels.TRACE,V)},w.disableAll=function(V){w.setLevel(w.levels.SILENT,V)},w.rebuild=function(){if(o!==w&&(G=rt(o.getLevel())),h.call(w),o===w)for(var V in n)n[V].rebuild()},G=rt(o?o.getLevel():"WARN");var vi=pi();vi!=null&&(Te=rt(vi)),h.call(w)}o=new _,o.getLogger=function(x){if(typeof x!="symbol"&&typeof x!="string"||x==="")throw new TypeError("You must supply a name when creating a logger.");var w=n[x];return w||(w=n[x]=new _(x,o.methodFactory)),w};var T=typeof window!==i?window.log:void 0;return o.noConflict=function(){return typeof window!==i&&window.log===o&&(window.log=T),o},o.getLoggers=function(){return n},o.default=o,o})})(ti)),ti.exports}var Ya=Ja();const Xa=qa(Ya);var gt=class extends Error{constructor(e,t){super(`Unexpected Error${e?` at ${e}`:""}`,t),this.at=e,this.name="UnexpectedError"}},Se=class extends Error{constructor(e="Not Implemented",t){super(e,t),this.reason=e,this.name="UnimplementedError"}},Je=class extends Error{constructor(e="Invalid Credentials",t){super(e,t),this.reason=e,this.name="InvalidCredentialsError"}},fs=class extends Error{constructor(e,t){super(e,t),this.name="WebSocketConnectionError"}},gs=class extends Error{constructor(e,t){super(e,t),this.name="TransportConnectionError"}},Qa=class extends Error{constructor(e,t){super(e,t),this.name="WebSocketTimeoutError"}},Za=class extends Error{constructor(e,t){super(e,t),this.name="RequestTimeoutError"}},ii=class extends Error{constructor(e,t,i){super(`RPC request ${e} timed out after ${t}ms`,i),this.requestId=e,this.timeoutMs=t,this.name="RPCTimeoutError"}},Ui=class extends Error{constructor(e=null,t){super("Error handling authorization state update",{...t,cause:(t==null?void 0:t.cause)??(e instanceof Error?e:void 0)}),this.error=e,this.name="AuthStateHandlerError"}},zi=class extends Error{constructor(e="localStorage",t){super(`${e} is not available in this environment`,t),this.storageType=e,this.name="StorageNotAvailableError"}},ec=class extends Error{constructor(e,t){super(`Failed to serialize value for key "${e}": ${t.message}`,{cause:t}),this.key=e,this.originalError=t,this.name="SerializationError"}},tc=class extends Error{constructor(e,t){super(`Failed to deserialize value for key "${e}": ${t.message}`,{cause:t}),this.key=e,this.originalError=t,this.name="DeserializationError"}},Fi=class extends Error{constructor(e,t){super(`Failed to write to storage for key "${e}": ${t.message}`,{cause:t}),this.key=e,this.originalError=t,this.name="StorageWriteError"}},ic=class extends Error{constructor(e,t){super(`Failed to read from storage "${e}": ${t.message}`,{cause:t}),this.key=e,this.originalError=t,this.name="StorageReadError"}},R=class extends Error{constructor(e,t){super(`Dependency ${e} is not set or available.`,t),this.description=e,this.name="DependencyError"}},bs=class extends Error{constructor(e,t=null,i="outbound",r){super(e,{...r,cause:(r==null?void 0:r.cause)??(t instanceof Error?t:void 0)}),this.message=e,this.error=t,this.direction=i,this.name="CallCreateError"}},xe=class extends Error{constructor(e,t,i,r,s){super(t,r),this.code=e,this.data=i,this.requestId=s,this.name="JSONRPCError"}},ms=class extends Error{constructor(e,t){super(e,t),this.message=e,this.name="InvalidParams"}},ys=class extends Error{constructor(e,t){super(e,t),this.message=e,this.name="ConversationError"}},rc=class extends Error{constructor(e=null,t){super("Error handling Verto invite",{...t,cause:(t==null?void 0:t.cause)??(e instanceof Error?e:void 0)}),this.error=e,this.name="VertoInviteHandlerError"}},sc=class extends Error{constructor(e=null,t){super("Error handling Verto attach",{...t,cause:(t==null?void 0:t.cause)??(e instanceof Error?e:void 0)}),this.error=e,this.name="VertoAttachHandlerError"}},ri=class extends Error{constructor(e,t){super(e,t),this.name="ValidationError"}},_s=class extends Error{constructor(e){super("Failed to send Verto pong - call may disconnect",{cause:e instanceof Error?e:void 0}),this.originalError=e,this.name="VertoPongError"}},nc=class extends Error{constructor(e){super("Failed to parse incoming WebSocket message",{cause:e instanceof Error?e:void 0}),this.originalError=e,this.name="MessageParseError"}},ws=class extends Error{constructor(e,t){super(`Collection fetch failed during ${e}`,{cause:t instanceof Error?t:void 0}),this.operation=e,this.originalError=t,this.name="CollectionFetchError"}},bt=class extends Error{constructor(e,t,i){super(`Media track ${e} failed for ${t}`,{cause:i instanceof Error?i:void 0}),this.operation=e,this.kind=t,this.originalError=i,this.name="MediaTrackError"}},si=class extends Error{constructor(e,t="Failed to initialize DPoP key pair"){super(t,{cause:e instanceof Error?e:void 0}),this.originalError=e,this.name="DPoPInitError"}},oc=class extends Error{constructor(e,t){super(`Preflight test failed during ${e}`,{cause:t instanceof Error?t:void 0}),this.phase=e,this.originalError=t,this.name="PreflightError"}},Cs=class extends Error{constructor(e,t){super(e,{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="DeviceTokenError"}},Ye=class extends Error{constructor(e,t){super(e,{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="TokenRefreshError"}};const ac=()=>new Date().toISOString(),mt=Xa.getLogger("signalwire"),cc=mt.methodFactory;mt.methodFactory=(e,t,i)=>{const r=cc(e,t,i);return function(...s){const n=[ac(),"-",...s];r.apply(void 0,n)}};const lc=mt.levels.WARN;mt.setLevel(lc);let Ss=null;const dc=e=>{Ss=e};let ni={};const uc=e=>{if(e==null){ni={};return}ni={...ni,...e}},hc=e=>{mt.setLevel(e)},ji=()=>Ss??mt,pc=e=>e!=null&&typeof e=="object"&&"method"in e?e.method!=="signalwire.ping":!0,vc=e=>{const{logWsTraffic:t}=ni;if(!t)return;const i=ji();let r;if("raw"in e)try{r=JSON.parse(e.raw)}catch{i.debug(`[WebSocket] ${e.type.toUpperCase()}: non-JSON message`);return}else r=e.payload;const s=pc(r)?JSON.stringify(r,null,2):r;i.debug(`${e.type.toUpperCase()}:
2467
+ `,s,`
2468
+ `)},D=()=>{const e=ji();return new Proxy(e,{get(t,i,r){if(i==="wsTraffic")return vc;const s=ji(),n=Reflect.get(s,i);return typeof n=="function"?n.bind(s):n}})};function B(){return C(e=>e!=null)}const ve=(e,t,i)=>{const r=t.split(".");let s=e;for(const n of r)if(s&&typeof s=="object"&&n in s)s=s[n];else return i;return s===void 0?i:s};function fc(e,t){return Xt(C(e),f(t))}function F(e,t){return Xt(fc(e,i=>ve(i,t)),C(i=>i!==void 0))}const $s=D();function Ts(){return f(e=>{if(e.error)throw $s.error("[throwOnRPCError] RPC error response:",{code:e.error.code,message:e.error.message,data:e.error.data}),new xe(e.error.code,e.error.message,e.error.data);return $s.debug("[throwOnRPCError] RPC successful response:",e),e})}class Bt extends Error{}Bt.prototype.name="InvalidTokenError";function gc(e){return decodeURIComponent(atob(e).replace(/(.)/g,(t,i)=>{let r=i.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function bc(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return gc(t)}catch{return atob(t)}}function mc(e,t){if(typeof e!="string")throw new Bt("Invalid token specified: must be a string");t||(t={});const i=t.header===!0?0:1,r=e.split(".")[i];if(typeof r!="string")throw new Bt(`Invalid token specified: missing part #${i+1}`);let s;try{s=bc(r)}catch(n){throw new Bt(`Invalid token specified: invalid base64 for part #${i+1} (${n.message})`)}try{return JSON.parse(s)}catch(n){throw new Bt(`Invalid token specified: invalid json for part #${i+1} (${n.message})`)}}const Z=[];for(let e=0;e<256;++e)Z.push((e+256).toString(16).slice(1));function yc(e,t=0){return(Z[e[t+0]]+Z[e[t+1]]+Z[e[t+2]]+Z[e[t+3]]+"-"+Z[e[t+4]]+Z[e[t+5]]+"-"+Z[e[t+6]]+Z[e[t+7]]+"-"+Z[e[t+8]]+Z[e[t+9]]+"-"+Z[e[t+10]]+Z[e[t+11]]+Z[e[t+12]]+Z[e[t+13]]+Z[e[t+14]]+Z[e[t+15]]).toLowerCase()}let Hi;const _c=new Uint8Array(16);function wc(){if(!Hi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Hi=crypto.getRandomValues.bind(crypto)}return Hi(_c)}const Es={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Cc(e,t,i){var s;e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??wc();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,yc(r)}function oi(e,t,i){return Es.randomUUID&&!e?Es.randomUUID():Cc(e)}var P=class{constructor(){this.subscriptions=[],this.subjects=[],this._destroyed$=new ht}destroy(){var e;(e=this._observableCache)==null||e.clear(),this.subscriptions.forEach(t=>t.unsubscribe()),this.subjects.forEach(t=>t.complete()),this._destroyed$.next(),this._destroyed$.complete()}cachedObservable(e,t){this._observableCache??(this._observableCache=new Map);let i=this._observableCache.get(e);return i||(i=t(),this._observableCache.set(e,i)),i}publicCachedObservable(e,t){const i=`public:${e}`;this._observableCache??(this._observableCache=new Map);let r=this._observableCache.get(i);return r||(r=t().pipe(Qt(Ur)),this._observableCache.set(i,r)),r}deferEmission(e){return e.pipe(Qt(Ur))}subscribeTo(e,t){const i=e.subscribe(t);this.subscriptions.push(i)}createSubject(){const e=new ht;return this.subjects.push(e),e}createReplaySubject(e,t){const i=new Di(e,t);return this.subjects.push(i),i}createBehaviorSubject(e){const t=new Oo(e);return this.subjects.push(t),t}get destroyed$(){return this._destroyed$.asObservable()}};const Sc=10,$c=100,Tc=1,Ec=({delayLimit:e=Number.MAX_SAFE_INTEGER,initialDelay:t=$c,variation:i=Tc})=>{if(t<0)throw new ri("initialDelay must be gte 0");if(e<0)throw new ri("upperDelayLimit must be gte 0");if(i<0)throw new ri("variation must be gte 0");if(t>e)throw new ri("initialDelay must be lte delayLimit");let r=Math.min(t,e);return()=>{if(r===e)return e;const s=r;return r=Math.min(r+i,e),s}},Mc=async({asyncCallable:e,maxRetries:t=Sc,delayFn:i,validator:r,expectedErrorHandler:s})=>{let n=t-1,o=0;const a=async()=>{try{let c;return o<=0?c=await e():c=await new Promise((l,h)=>setTimeout(()=>{e().then(l).catch(h)},o)),n&&(r==null||r(c)),c}catch(c){if(n-- >0&&!(s!=null&&s(c)))return o=(i==null?void 0:i())??0,D().debug(`Retrying request: ${t-n} of ${t}`),a();throw c}};return a()},yt=D(),Wi={method:"GET",headers:{Accept:"application/json"}},ai={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};var kc=(ne=class extends P{constructor(t,i,r={}){super(),this.baseURL=t,this.getCredential=i,this._responses$=this.createSubject(),this._errors$=this.createSubject(),this._status$=this.createBehaviorSubject("idle"),this.maxRetries=r.maxRetries??ne.defaultMaxRetries,this.retryDelayMin=r.retryDelayMin??ne.defaultRetryDelayMinMs,this.retryDelayMax=r.retryDelayMax??ne.defaultRetryDelayMaxMs,this.requestTimeout=r.requestTimeout??ne.defaultRequestTimeoutMs}get status$(){return this._status$.asObservable()}get status(){return this._status$.value}get responses$(){return this._responses$.asObservable()}get errors$(){return this._errors$.asObservable()}async request(t){this._status$.next("requesting");try{const i=await this.executeWithRetry(t);return this._status$.next("success"),this._responses$.next(i),i}catch(i){yt.error("[HTTPRequestController] Request error:",i),this._status$.next("error");const r=i instanceof Error?i:new Error("HTTP request failed",{cause:i});throw this._errors$.next(r),r}}async executeWithRetry(t){const i=Math.ceil((this.retryDelayMax-this.retryDelayMin)/Math.max(this.maxRetries-1,1)),r=Ec({initialDelay:this.retryDelayMin,variation:i,delayLimit:this.retryDelayMax});return Mc({asyncCallable:async()=>this.executeRequest(t),maxRetries:this.maxRetries,delayFn:r,validator:s=>{if(s.status>=500&&s.status<600)throw new gt(`Server error: ${s.status} ${s.statusText}`)}})}async executeRequest(t){const i=this.buildURL(t.url),r=this.buildHeaders(t.headers),s=t.timeout??this.requestTimeout;yt.debug("[HTTPRequestController] Executing request:",{method:t.method,url:i,headers:Object.keys(r).reduce((a,c)=>(a[c]=c==="Authorization"?`${r[c].substring(0,20)}...`:r[c],a),{}),body:this.sanitizeBody(t.body)});const n=new AbortController,o=setTimeout(()=>n.abort(),s);try{const a=await fetch(i,{method:t.method,headers:r,body:t.body,signal:n.signal});clearTimeout(o);const c=await this.convertResponse(a);return yt.debug("[HTTPRequestController] Response received:",{status:a.status,statusText:a.statusText,headers:[...a.headers.entries()],body:c.body?c.body.substring(0,200):"(empty)"}),c}catch(a){throw clearTimeout(o),a instanceof Error&&a.name==="AbortError"?new Za(`Request timeout after ${s}ms`,{cause:a}):(yt.error("[HTTPRequestController] Request failed:",a),a)}}buildURL(t){const i=typeof t=="string"?t:t.toString();return i.startsWith("http://")||i.startsWith("https://")?i:`${this.baseURL.endsWith("/")?this.baseURL.slice(0,-1):this.baseURL}${i.startsWith("/")?i:`/${i}`}`}buildHeaders(t){const i={...t??{}},r=this.getCredential();return r.token?(i.Authorization=`Bearer ${r.token}`,yt.debug("[HTTPRequestController] Using Bearer token auth, token length:",r.token.length)):yt.warn("[HTTPRequestController] No credentials available for authentication"),i}sanitizeBody(t){if(!t||typeof t!="string")return t?"(non-string body)":void 0;try{const i={...JSON.parse(t)};for(const r of Object.keys(i))ne.SENSITIVE_BODY_FIELDS.has(r)&&typeof i[r]=="string"&&(i[r]=`${i[r].substring(0,20)}...[redacted]`);return JSON.stringify(i)}catch{return t.length>200?`${t.substring(0,200)}...`:t}}async convertResponse(t){const i={};t.headers.forEach((s,n)=>{i[n]=s});const r=await t.text();return{status:t.status,statusText:t.statusText,headers:i,body:r,ok:t.ok,url:t.url}}},ne.defaultMaxRetries=3,ne.defaultRetryDelayMinMs=1e3,ne.defaultRetryDelayMaxMs=3e4,ne.defaultRequestTimeoutMs=3e4,ne.SENSITIVE_BODY_FIELDS=new Set(["dpop_token","token","jwt_token"]),ne);const Ac=5,xc=(e,t)=>({deviceId:e.deviceId,label:e.label,groupId:e.groupId,kind:t});var Dc=class{constructor(){this._stacks={audioinput:[],audiooutput:[],videoinput:[]}}push(e,t){const i=xc(t,e),r=this._stacks[e];if(r.length>0&&r[0].deviceId===i.deviceId)return;const s=r.filter(n=>n.deviceId!==i.deviceId);this._stacks[e]=[i,...s].slice(0,Ac)}pop(e){const t=this._stacks[e];if(t.length===0)return;const[i,...r]=t;return this._stacks[e]=r,i}findInHistory(e,t){const i=this._stacks[e];for(const r of i){const s=t.find(o=>o.deviceId===r.deviceId);if(s)return s;const n=t.find(o=>o.groupId===r.groupId&&o.label===r.label);if(n)return n}}getHistory(e){return this._stacks[e]}clear(){this._stacks.audioinput=[],this._stacks.audiooutput=[],this._stacks.videoinput=[]}};const Ic=1e3,Ms=600,ks=6e3,Rc=300*1e3,Pc=1e4,Oc=100,Vc=3e3,Lc=1500,Bc=0,As="sw:preferences",Nc="sat:refresh",xs="/api/fabric/subscriber/devices/token",Ds="/api/fabric/subscriber/devices/refresh",Nt=900,Uc=3e4,Is=3,zc=1e3,Rs=5,Fc=1e3,jc=3e4,Hc=5e3,Ps=-32003,Os=-32602,Vs=-32002,Wc=1e3,Gc=10,qc=2e3,Kc=3,Jc=.05,Yc=4,Xc=30,Qc=3,Zc=3e3,el=1e4,tl=1e4,il=3,rl=5e3,sl=2e3,nl=1e4,ol=3e3,al=5e3,cl=3,ll=1e4,dl=5e3,ul=100,Ls=33,hl=.03,pl=250,vl=!0,fl=!0,gl="sw:device:audioinput",bl="sw:device:audiooutput",ml="sw:device:videoinput",yl=!1,_l=!0,wl=!0,Cl=!0,Sl=150,$l=300,Tl=!0,El=!0,Ml=!0,kl=!1,Al=51e4;function fe(e){return e*1e3}function ge(e){return Math.round(e/100)/10}const Bs=D();var d=class Rn{static get instance(){return this._instance??(this._instance=new Rn),this._instance}constructor(){this.deviceDebounceTime=Lc,this.devicePollingInterval=Bc,this.reconnectCallsTimeout=Rc,this.connectionTimeout=Pc,this.reconnectDelayMin=Oc,this.reconnectDelayMax=Vc,this.disableUdpIceServers=!1,this.relayOnly=!1,this.iceCandidateTimeout=Ms,this.iceGatheringTimeout=ks,this.defaultSignalWireOptions={skipConnection:!1,skipRegister:!1,reconnectAttachedCalls:!1,skipDeviceMonitoring:!1,savePreferences:!1},this.receiveVideo=!1,this.receiveAudio=!0,this.preferredAudioInput=null,this.preferredAudioOutput=null,this.preferredVideoInput=null,this.inviteSubscribeScreenshare=["video.room.screenshare"],this.inviteSubscribeAdditionalDevice=[],this.inviteSubscribeMainDevice=["track","destroy","member.updated.videoMuted","layout.changed","room.subscribed","member.updated.audioMuted","media.connected","room.updated","call.joined"],this.userVariables={},this.statsPollingInterval=Wc,this.statsBaselineSamples=Gc,this.statsNoPacketThreshold=qc,this.statsRttSpikeMultiplier=Kc,this.statsPacketLossThreshold=Jc,this.statsJitterSpikeMultiplier=Yc,this.statsHistorySize=Xc,this.keyframeMaxBurst=Qc,this.keyframeBurstWindow=Zc,this.keyframeCooldown=el,this.reinviteDebounceTime=tl,this.reinviteMaxAttempts=il,this.reinviteTimeout=rl,this.recoveryDebounceTime=sl,this.recoveryCooldown=nl,this.iceDisconnectedGracePeriod=ol,this.iceRestartTimeout=al,this.maxRecoveryAttempts=cl,this.enableRelayFallback=Tl,this.enableNetworkChangeDetection=El,this.enableServerHangupInterception=Ml,this.persistDeviceSelection=vl,this.syncDevicesToActiveCalls=fl,this.autoMuteVideoOnHidden=yl,this.refreshDevicesOnVisible=_l,this.checkConnectionOnVisible=wl,this.defaultAudioConstraints=void 0,this.defaultVideoConstraints=void 0,this.stereoAudio=kl,this.enableAutoDegradation=Cl,this.degradationBitrateThreshold=Sl,this.degradationRecoveryThreshold=$l,this.preferredVideoCodecs=[],this.preferredAudioCodecs=[]}get preferredMediaOptions(){return{receiveVideo:this.receiveVideo,receiveAudio:this.receiveAudio,inputAudioDeviceConstraints:this.inputAudioDeviceConstraints,inputVideoDeviceConstraints:this.inputVideoDeviceConstraints}}get inputAudioDeviceConstraints(){return this._inputAudioDeviceConstraints}set inputAudioDeviceConstraints(t){this._inputAudioDeviceConstraints=t}get inputVideoDeviceConstraints(){return this._inputVideoDeviceConstraints}set inputVideoDeviceConstraints(t){this._inputVideoDeviceConstraints=t}};const xl=["connectionTimeout","reconnectCallsTimeout","reconnectDelayMin","reconnectDelayMax","iceCandidateTimeout","iceGatheringTimeout","deviceDebounceTime","devicePollingInterval","statsPollingInterval","statsBaselineSamples","statsNoPacketThreshold","statsRttSpikeMultiplier","statsPacketLossThreshold","statsJitterSpikeMultiplier","statsHistorySize","keyframeMaxBurst","keyframeBurstWindow","keyframeCooldown","reinviteDebounceTime","reinviteMaxAttempts","reinviteTimeout","recoveryDebounceTime","recoveryCooldown","iceDisconnectedGracePeriod","iceRestartTimeout","maxRecoveryAttempts","degradationBitrateThreshold","degradationRecoveryThreshold"],Dl=["receiveVideo","receiveAudio","disableUdpIceServers","relayOnly","enableRelayFallback","enableNetworkChangeDetection","enableServerHangupInterception","persistDeviceSelection","syncDevicesToActiveCalls","autoMuteVideoOnHidden","refreshDevicesOnVisible","checkConnectionOnVisible","stereoAudio","enableAutoDegradation"];function Il(){const e=d.instance;return{connectionTimeout:e.connectionTimeout,reconnectCallsTimeout:e.reconnectCallsTimeout,reconnectDelayMin:e.reconnectDelayMin,reconnectDelayMax:e.reconnectDelayMax,relayHost:e.relayHost,receiveVideo:e.receiveVideo,receiveAudio:e.receiveAudio,disableUdpIceServers:e.disableUdpIceServers,relayOnly:e.relayOnly,iceCandidateTimeout:e.iceCandidateTimeout,iceGatheringTimeout:e.iceGatheringTimeout,deviceDebounceTime:e.deviceDebounceTime,devicePollingInterval:e.devicePollingInterval,iceServers:e.iceServers,userVariables:e.userVariables,statsPollingInterval:e.statsPollingInterval,statsBaselineSamples:e.statsBaselineSamples,statsNoPacketThreshold:e.statsNoPacketThreshold,statsRttSpikeMultiplier:e.statsRttSpikeMultiplier,statsPacketLossThreshold:e.statsPacketLossThreshold,statsJitterSpikeMultiplier:e.statsJitterSpikeMultiplier,statsHistorySize:e.statsHistorySize,keyframeMaxBurst:e.keyframeMaxBurst,keyframeBurstWindow:e.keyframeBurstWindow,keyframeCooldown:e.keyframeCooldown,reinviteDebounceTime:e.reinviteDebounceTime,reinviteMaxAttempts:e.reinviteMaxAttempts,reinviteTimeout:e.reinviteTimeout,recoveryDebounceTime:e.recoveryDebounceTime,recoveryCooldown:e.recoveryCooldown,iceDisconnectedGracePeriod:e.iceDisconnectedGracePeriod,iceRestartTimeout:e.iceRestartTimeout,maxRecoveryAttempts:e.maxRecoveryAttempts,enableRelayFallback:e.enableRelayFallback,enableNetworkChangeDetection:e.enableNetworkChangeDetection,enableServerHangupInterception:e.enableServerHangupInterception,persistDeviceSelection:e.persistDeviceSelection,syncDevicesToActiveCalls:e.syncDevicesToActiveCalls,autoMuteVideoOnHidden:e.autoMuteVideoOnHidden,refreshDevicesOnVisible:e.refreshDevicesOnVisible,checkConnectionOnVisible:e.checkConnectionOnVisible,stereoAudio:e.stereoAudio,enableAutoDegradation:e.enableAutoDegradation,degradationBitrateThreshold:e.degradationBitrateThreshold,degradationRecoveryThreshold:e.degradationRecoveryThreshold,preferredVideoCodecs:e.preferredVideoCodecs,preferredAudioCodecs:e.preferredAudioCodecs}}function Rl(e){const t=d.instance;for(const i of xl)e[i]!==void 0&&(t[i]=e[i]);for(const i of Dl)e[i]!==void 0&&(t[i]=e[i]);e.relayHost!==void 0&&(t.relayHost=e.relayHost),e.iceServers!==void 0&&(t.iceServers=e.iceServers),e.userVariables!==void 0&&(t.userVariables=e.userVariables),e.preferredVideoCodecs!==void 0&&(t.preferredVideoCodecs=e.preferredVideoCodecs),e.preferredAudioCodecs!==void 0&&(t.preferredAudioCodecs=e.preferredAudioCodecs)}var Pl=class{constructor(){this._storage=null}enableSavePreferences(e){this._storage=e,this._loadFromStorage()}get connectionTimeout(){return ge(d.instance.connectionTimeout)}set connectionTimeout(e){d.instance.connectionTimeout=fe(e),this._saveToStorage()}get reconnectCallsTimeout(){return ge(d.instance.reconnectCallsTimeout)}set reconnectCallsTimeout(e){d.instance.reconnectCallsTimeout=fe(e),this._saveToStorage()}get reconnectDelayMin(){return ge(d.instance.reconnectDelayMin)}set reconnectDelayMin(e){d.instance.reconnectDelayMin=fe(e),this._saveToStorage()}get reconnectDelayMax(){return ge(d.instance.reconnectDelayMax)}set reconnectDelayMax(e){d.instance.reconnectDelayMax=fe(e),this._saveToStorage()}get relayHost(){return d.instance.relayHost??""}set relayHost(e){d.instance.relayHost=e,this._saveToStorage()}get receiveVideo(){return d.instance.receiveVideo}set receiveVideo(e){d.instance.receiveVideo=e,this._saveToStorage()}get receiveAudio(){return d.instance.receiveAudio}set receiveAudio(e){d.instance.receiveAudio=e,this._saveToStorage()}get preferredAudioInput(){return d.instance.preferredAudioInput}set preferredAudioInput(e){d.instance.preferredAudioInput=e}get preferredAudioOutput(){return d.instance.preferredAudioOutput}set preferredAudioOutput(e){d.instance.preferredAudioOutput=e}get preferredVideoInput(){return d.instance.preferredVideoInput}set preferredVideoInput(e){d.instance.preferredVideoInput=e}get inputAudioConstraints(){return d.instance.inputAudioDeviceConstraints}set inputAudioConstraints(e){d.instance.inputAudioDeviceConstraints=e}get inputVideoConstraints(){return d.instance.inputVideoDeviceConstraints}set inputVideoConstraints(e){d.instance.inputVideoDeviceConstraints=e}get deviceDebounceTime(){return ge(d.instance.deviceDebounceTime)}set deviceDebounceTime(e){d.instance.deviceDebounceTime=fe(e),this._saveToStorage()}get devicePollingInterval(){return ge(d.instance.devicePollingInterval)}set devicePollingInterval(e){d.instance.devicePollingInterval=fe(e),this._saveToStorage()}get disableUdpIceServers(){return d.instance.disableUdpIceServers}set disableUdpIceServers(e){d.instance.disableUdpIceServers=e,this._saveToStorage()}get relayOnly(){return d.instance.relayOnly}set relayOnly(e){d.instance.relayOnly=e,this._saveToStorage()}get iceCandidateTimeout(){return ge(d.instance.iceCandidateTimeout)}set iceCandidateTimeout(e){d.instance.iceCandidateTimeout=fe(e),this._saveToStorage()}get iceGatheringTimeout(){return ge(d.instance.iceGatheringTimeout)}set iceGatheringTimeout(e){d.instance.iceGatheringTimeout=fe(e),this._saveToStorage()}get iceServers(){return d.instance.iceServers}set iceServers(e){d.instance.iceServers=e,this._saveToStorage()}get userVariables(){return d.instance.userVariables}set userVariables(e){d.instance.userVariables=e,this._saveToStorage()}get statsPollingInterval(){return d.instance.statsPollingInterval}set statsPollingInterval(e){d.instance.statsPollingInterval=e,this._saveToStorage()}get statsBaselineSamples(){return d.instance.statsBaselineSamples}set statsBaselineSamples(e){d.instance.statsBaselineSamples=e,this._saveToStorage()}get statsNoPacketThreshold(){return d.instance.statsNoPacketThreshold}set statsNoPacketThreshold(e){d.instance.statsNoPacketThreshold=e,this._saveToStorage()}get statsRttSpikeMultiplier(){return d.instance.statsRttSpikeMultiplier}set statsRttSpikeMultiplier(e){d.instance.statsRttSpikeMultiplier=e,this._saveToStorage()}get statsPacketLossThreshold(){return d.instance.statsPacketLossThreshold}set statsPacketLossThreshold(e){d.instance.statsPacketLossThreshold=e,this._saveToStorage()}get statsJitterSpikeMultiplier(){return d.instance.statsJitterSpikeMultiplier}set statsJitterSpikeMultiplier(e){d.instance.statsJitterSpikeMultiplier=e,this._saveToStorage()}get statsHistorySize(){return d.instance.statsHistorySize}set statsHistorySize(e){d.instance.statsHistorySize=e,this._saveToStorage()}get keyframeMaxBurst(){return d.instance.keyframeMaxBurst}set keyframeMaxBurst(e){d.instance.keyframeMaxBurst=e,this._saveToStorage()}get keyframeBurstWindow(){return d.instance.keyframeBurstWindow}set keyframeBurstWindow(e){d.instance.keyframeBurstWindow=e,this._saveToStorage()}get keyframeCooldown(){return d.instance.keyframeCooldown}set keyframeCooldown(e){d.instance.keyframeCooldown=e,this._saveToStorage()}get reinviteDebounceTime(){return d.instance.reinviteDebounceTime}set reinviteDebounceTime(e){d.instance.reinviteDebounceTime=e,this._saveToStorage()}get reinviteMaxAttempts(){return d.instance.reinviteMaxAttempts}set reinviteMaxAttempts(e){d.instance.reinviteMaxAttempts=e,this._saveToStorage()}get reinviteTimeout(){return d.instance.reinviteTimeout}set reinviteTimeout(e){d.instance.reinviteTimeout=e,this._saveToStorage()}get recoveryDebounceTime(){return ge(d.instance.recoveryDebounceTime)}set recoveryDebounceTime(e){d.instance.recoveryDebounceTime=fe(e),this._saveToStorage()}get recoveryCooldown(){return ge(d.instance.recoveryCooldown)}set recoveryCooldown(e){d.instance.recoveryCooldown=fe(e),this._saveToStorage()}get iceDisconnectedGracePeriod(){return ge(d.instance.iceDisconnectedGracePeriod)}set iceDisconnectedGracePeriod(e){d.instance.iceDisconnectedGracePeriod=fe(e),this._saveToStorage()}get iceRestartTimeout(){return ge(d.instance.iceRestartTimeout)}set iceRestartTimeout(e){d.instance.iceRestartTimeout=fe(e),this._saveToStorage()}get maxRecoveryAttempts(){return d.instance.maxRecoveryAttempts}set maxRecoveryAttempts(e){d.instance.maxRecoveryAttempts=e,this._saveToStorage()}get enableRelayFallback(){return d.instance.enableRelayFallback}set enableRelayFallback(e){d.instance.enableRelayFallback=e,this._saveToStorage()}get enableNetworkChangeDetection(){return d.instance.enableNetworkChangeDetection}set enableNetworkChangeDetection(e){d.instance.enableNetworkChangeDetection=e,this._saveToStorage()}get enableServerHangupInterception(){return d.instance.enableServerHangupInterception}set enableServerHangupInterception(e){d.instance.enableServerHangupInterception=e,this._saveToStorage()}get persistDeviceSelection(){return d.instance.persistDeviceSelection}set persistDeviceSelection(e){d.instance.persistDeviceSelection=e,this._saveToStorage()}get syncDevicesToActiveCalls(){return d.instance.syncDevicesToActiveCalls}set syncDevicesToActiveCalls(e){d.instance.syncDevicesToActiveCalls=e,this._saveToStorage()}get autoMuteVideoOnHidden(){return d.instance.autoMuteVideoOnHidden}set autoMuteVideoOnHidden(e){d.instance.autoMuteVideoOnHidden=e,this._saveToStorage()}get refreshDevicesOnVisible(){return d.instance.refreshDevicesOnVisible}set refreshDevicesOnVisible(e){d.instance.refreshDevicesOnVisible=e,this._saveToStorage()}get checkConnectionOnVisible(){return d.instance.checkConnectionOnVisible}set checkConnectionOnVisible(e){d.instance.checkConnectionOnVisible=e,this._saveToStorage()}get defaultAudioConstraints(){return d.instance.defaultAudioConstraints}set defaultAudioConstraints(e){d.instance.defaultAudioConstraints=e}get defaultVideoConstraints(){return d.instance.defaultVideoConstraints}set defaultVideoConstraints(e){d.instance.defaultVideoConstraints=e}get stereoAudio(){return d.instance.stereoAudio}set stereoAudio(e){d.instance.stereoAudio=e,this._saveToStorage()}get enableAutoDegradation(){return d.instance.enableAutoDegradation}set enableAutoDegradation(e){d.instance.enableAutoDegradation=e,this._saveToStorage()}get degradationBitrateThreshold(){return d.instance.degradationBitrateThreshold}set degradationBitrateThreshold(e){d.instance.degradationBitrateThreshold=e,this._saveToStorage()}get degradationRecoveryThreshold(){return d.instance.degradationRecoveryThreshold}set degradationRecoveryThreshold(e){d.instance.degradationRecoveryThreshold=e,this._saveToStorage()}get preferredVideoCodecs(){return d.instance.preferredVideoCodecs}set preferredVideoCodecs(e){d.instance.preferredVideoCodecs=e,this._saveToStorage()}get preferredAudioCodecs(){return d.instance.preferredAudioCodecs}set preferredAudioCodecs(e){d.instance.preferredAudioCodecs=e,this._saveToStorage()}_saveToStorage(){if(!this._storage)return;const e=Il();this._storage.setItem(As,e,"local").catch(t=>{Bs.error(`[ClientPreferences] Failed to save preferences: ${String(t)}`)})}_loadFromStorage(){this._storage&&this._storage.getItem(As,"local").then(e=>{e&&Rl(e)}).catch(e=>{Bs.error(`[ClientPreferences] Failed to load preferences: ${String(e)}`)})}};function ke(e){return e instanceof Error?e:new Error(String(e))}const be=D(),Ns={audioinput:gl,audiooutput:bl,videoinput:ml},Ol={audioinput:[],audiooutput:[],videoinput:[]},Us={audioinput:null,audiooutput:null,videoinput:null};var Vl=class extends P{constructor(e,t){super(),this.webRTCApiProvider=e,this.deviceChangeHandler=()=>{be.debug("[DeviceController] Device change detected"),this.enumerateDevices()},this._devicesState$=this.createBehaviorSubject(Ol),this._selectedDevicesState$=this.createBehaviorSubject(Us),this._errors$=this.createReplaySubject(1),this._deviceHistory=new Dc,this._deviceRecovered$=this.createSubject(),this._audioInputDisabled$=this.createBehaviorSubject(!1),this._videoInputDisabled$=this.createBehaviorSubject(!1),this._lastAudioInputBeforeDisable=null,this._lastVideoInputBeforeDisable=null,this._persistedDevices={},this._storageManager=t,this.init()}setStorageManager(e){this._storageManager=e,this.loadPersistedDevices()}get selectedAudioInputDeviceConstraints(){return this._audioInputDisabled$.value?!1:this.deviceInfoToConstraints(this.selectedAudioInputDevice)}get selectedVideoInputDeviceConstraints(){return this._videoInputDisabled$.value?!1:this.deviceInfoToConstraints(this.selectedVideoInputDevice)}deviceInfoToConstraints(e){if(!(e!=null&&e.deviceId)||e.deviceId.trim()==="")return{};const t=e.kind==="audioinput"?this.audioInputDevices:this.videoInputDevices,i=t.find(r=>r.deviceId===e.deviceId)??t.find(r=>r.label===e.label);return i?{deviceId:{exact:i.deviceId}}:{}}get errors$(){return this.cachedObservable("errors$",()=>this._errors$.asObservable().pipe(v(this.destroyed$)))}get deviceRecovered$(){return this._deviceRecovered$.asObservable().pipe(v(this.destroyed$))}get videoInputDisabled$(){return this.cachedObservable("videoInputDisabled$",()=>this._videoInputDisabled$.asObservable().pipe(y(),v(this.destroyed$)))}get audioInputDisabled$(){return this.cachedObservable("audioInputDisabled$",()=>this._audioInputDisabled$.asObservable().pipe(y(),v(this.destroyed$)))}get videoInputDisabled(){return this._videoInputDisabled$.value}get audioInputDisabled(){return this._audioInputDisabled$.value}get audioInputDevices$(){return this.cachedObservable("audioInputDevices$",()=>this._devicesState$.pipe(f(e=>e.audioinput),y(),v(this.destroyed$)))}get audioOutputDevices$(){return this.cachedObservable("audioOutputDevices$",()=>this._devicesState$.pipe(f(e=>e.audiooutput),y(),v(this.destroyed$)))}get videoInputDevices$(){return this.cachedObservable("videoInputDevices$",()=>this._devicesState$.pipe(f(e=>e.videoinput),y(),v(this.destroyed$)))}get selectedAudioInputDevice$(){return this.cachedObservable("selectedAudioInputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(f(e=>e.audioinput),y(),v(this.destroyed$),W(e=>be.debug("[DeviceController] Selected audio input device changed:",e))))}get selectedAudioOutputDevice$(){return this.cachedObservable("selectedAudioOutputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(f(e=>e.audiooutput),y(),v(this.destroyed$),W(e=>be.debug("[DeviceController] Selected audio output device changed:",e))))}get selectedVideoInputDevice$(){return this.cachedObservable("selectedVideoInputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(f(e=>e.videoinput),y(),v(this.destroyed$),W(e=>be.debug("[DeviceController] Selected video input device changed:",e))))}get selectedAudioInputDevice(){return this._audioInputDisabled$.value?null:this._selectedDevicesState$.value.audioinput}get selectedAudioOutputDevice(){return this._selectedDevicesState$.value.audiooutput}get selectedVideoInputDevice(){return this._videoInputDisabled$.value?null:this._selectedDevicesState$.value.videoinput}get audioInputDevices(){return this._devicesState$.value.audioinput}get audioOutputDevices(){return this._devicesState$.value.audiooutput}get videoInputDevices(){return this._devicesState$.value.videoinput}disableAudioInput(){this._audioInputDisabled$.value||(this._lastAudioInputBeforeDisable=this._selectedDevicesState$.value.audioinput,this._audioInputDisabled$.next(!0),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audioinput:null}))}enableAudioInput(){if(this._audioInputDisabled$.value){this._audioInputDisabled$.next(!1);const e=this._lastAudioInputBeforeDisable??this.audioInputDevices[0];this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audioinput:e}),this._lastAudioInputBeforeDisable=null}}disableVideoInput(){this._videoInputDisabled$.value||(this._lastVideoInputBeforeDisable=this._selectedDevicesState$.value.videoinput,this._videoInputDisabled$.next(!0),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,videoinput:null}))}enableVideoInput(){if(this._videoInputDisabled$.value){this._videoInputDisabled$.next(!1);const e=this._lastVideoInputBeforeDisable??this.videoInputDevices[0];this._selectedDevicesState$.next({...this._selectedDevicesState$.value,videoinput:e}),this._lastVideoInputBeforeDisable=null}}selectAudioInputDevice(e){this._audioInputDisabled$.value&&e&&this._audioInputDisabled$.next(!1);const t=this._selectedDevicesState$.value.audioinput;t&&t.deviceId!==(e==null?void 0:e.deviceId)&&this._deviceHistory.push("audioinput",t),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audioinput:e}),e&&this.persistDeviceSelection("audioinput",e)}selectVideoInputDevice(e){be.debug("[DeviceController] Setting selected video input device:",e),this._videoInputDisabled$.value&&e&&this._videoInputDisabled$.next(!1);const t=this._selectedDevicesState$.value.videoinput;t&&t.deviceId!==(e==null?void 0:e.deviceId)&&this._deviceHistory.push("videoinput",t),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,videoinput:e}),e&&this.persistDeviceSelection("videoinput",e)}selectAudioOutputDevice(e){const t=this._selectedDevicesState$.value.audiooutput;t&&t.deviceId!==(e==null?void 0:e.deviceId)&&this._deviceHistory.push("audiooutput",t),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audiooutput:e}),e&&this.persistDeviceSelection("audiooutput",e)}init(){this.loadPersistedDevices(),this.subscribeTo(this._devicesState$.pipe(us(d.instance.deviceDebounceTime)),e=>{const t=this._selectedDevicesState$.value,i=this._audioInputDisabled$.value?null:this.resolveDevice("audioinput",e.audioinput,t.audioinput,d.instance.preferredAudioInput),r=this.resolveDevice("audiooutput",e.audiooutput,t.audiooutput,d.instance.preferredAudioOutput),s=this._videoInputDisabled$.value?null:this.resolveDevice("videoinput",e.videoinput,t.videoinput,d.instance.preferredVideoInput);if(i!==t.audioinput||r!==t.audiooutput||s!==t.videoinput){const n=d.instance.syncDevicesToActiveCalls;this._selectedDevicesState$.next({audioinput:n||!t.audioinput?i:t.audioinput,audiooutput:n||!t.audiooutput?r:t.audiooutput,videoinput:n||!t.videoinput?s:t.videoinput})}}),this.enumerateDevices()}resolveDevice(e,t,i,r){if(t.length===0)return null;if(i){if(t.find(c=>c.deviceId===i.deviceId))return i;const n=t.filter(c=>c.label===i.label);if(n.length===1)return n[0];if(n.length>1){const c=n.find(l=>l.groupId===i.groupId);return c||(this.emitDeviceRecovered(e,i,null,"ambiguous_match"),null)}const o=this._deviceHistory.findInHistory(e,t);if(o)return be.debug(`[DeviceController] Device disappeared, falling back to history: ${o.label}`),this.emitDeviceRecovered(e,i,o,"device_disconnected"),o;const a=(r?t.find(c=>c.deviceId===r.deviceId||c.label===r.label):void 0)??t[0];return this.emitDeviceRecovered(e,i,a,"fallback_to_default"),a}const s=this._persistedDevices[e];if(s){const n=this.resolvePersistedDevice(e,s,t);if(n)return n}if(r){const n=t.find(o=>o.deviceId===r.deviceId||o.label===r.label);if(n)return n}return t[0]}resolvePersistedDevice(e,t,i){const r=i.find(o=>o.deviceId===t.deviceId);if(r)return r;const s=i.find(o=>o.groupId===t.groupId&&o.label===t.label);if(s)return s;const n=i.filter(o=>o.label===t.label);return n.length===1?n[0]:null}emitDeviceRecovered(e,t,i,r){try{this._deviceRecovered$.next({kind:e,previousDevice:t,newDevice:i,reason:r})}catch{}}async persistDeviceSelection(e,t){if(!this._storageManager||!d.instance.persistDeviceSelection)return;const i={deviceId:t.deviceId,label:t.label,kind:t.kind,groupId:t.groupId};try{await this._storageManager.setItem(Ns[e],i,"local")}catch(r){be.error(`[DeviceController] Failed to persist device selection for ${e}:`,r)}}async loadPersistedDevices(){if(!(!this._storageManager||!d.instance.persistDeviceSelection))for(const e of["audioinput","audiooutput","videoinput"])try{const t=await this._storageManager.getItem(Ns[e],"local");t&&(this._persistedDevices={...this._persistedDevices,[e]:t})}catch(t){be.error(`[DeviceController] Failed to load persisted device for ${e}:`,t)}}async clearDeviceState(){this._deviceHistory.clear(),this._persistedDevices={},this._lastAudioInputBeforeDisable=null,this._lastVideoInputBeforeDisable=null,this._audioInputDisabled$.next(!1),this._videoInputDisabled$.next(!1),this._selectedDevicesState$.next(Us),await this.enumerateDevices()}enableDeviceMonitoring(){this.disableDeviceMonitoring(),this.webRTCApiProvider.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler),d.instance.devicePollingInterval>0&&(this._devicesPoolingSubscription=Zt(d.instance.devicePollingInterval).subscribe(()=>{be.debug("[DeviceController] Polling devices due to interval"),this.enumerateDevices()})),this.enumerateDevices()}disableDeviceMonitoring(){this.webRTCApiProvider.mediaDevices.removeEventListener("devicechange",this.deviceChangeHandler),this._devicesPoolingSubscription&&(this._devicesPoolingSubscription.unsubscribe(),this._devicesPoolingSubscription=void 0)}async enumerateDevices(){try{const e=(await this.webRTCApiProvider.mediaDevices.enumerateDevices()).reduce((t,i)=>{const r=i.kind;return{...t,[r]:[...t[r],i]}},{audioinput:[],audiooutput:[],videoinput:[]});this._devicesState$.next(e),be.debug("[DeviceController] Devices enumerated:",{audioInputs:e.audioinput.length,audioOutputs:e.audiooutput.length,videoInputs:e.videoinput.length})}catch(e){be.error("[DeviceController] Failed to enumerate devices:",e),this._errors$.next(ke(e))}}async getDeviceCapabilities(e){if(e.kind==="audiooutput")return null;try{const t=this.deviceInfoToConstraints(e),i=await this.webRTCApiProvider.mediaDevices.getUserMedia({audio:e.kind==="audioinput"?t:!1,video:e.kind==="videoinput"?t:!1}),r=(e.kind==="audioinput"?i.getAudioTracks()[0]:i.getVideoTracks()[0]).getCapabilities();return i.getTracks().forEach(s=>s.stop()),r}catch(t){throw be.error("[DeviceController] Failed to get device capabilities:",t),this._errors$.next(ke(t)),t}}async isValidDevice(e){if(!e||e.kind==="audiooutput")return!1;try{return await this.getDeviceCapabilities(e)!==null}catch{return!1}}destroy(){this.disableDeviceMonitoring(),super.destroy()}},zs=class{constructor(){if(typeof localStorage>"u")throw new zi("localStorage");if(typeof sessionStorage>"u")throw new zi("sessionStorage");try{const e="__storage_test__";localStorage.setItem(e,"test"),localStorage.removeItem(e)}catch(e){throw D().error("LocalStorage is not accessible:",e),new zi("localStorage")}}storage(e){return e==="local"?localStorage:sessionStorage}async setItem(e,t,i="session"){return this.storage(i).setItem(e,t),Promise.resolve()}async getItem(e,t="session"){return Promise.resolve(this.storage(t).getItem(e))}async removeItem(e,t="session"){return this.storage(t).removeItem(e),Promise.resolve()}async clear(e="session"){const t=this.storage(e),i=[];for(let r=0;r<t.length;r++){const s=t.key(r);s!=null&&s.startsWith("sw:")&&i.push(s)}for(const r of i)t.removeItem(r);return Promise.resolve()}},Ll=class{constructor(e=new zs){this.storageImpl=e}serialize(e,t){if(e==null)return null;try{return JSON.stringify(e)}catch(i){throw new ec(t??"unknown",i)}}async setItem(e,t,i="session"){const r=this.serialize(t,e);try{await this.storageImpl.setItem(e,r,i)}catch(s){throw new Fi(e,s)}}async getItem(e,t="session"){let i;try{i=await this.storageImpl.getItem(e,t)}catch(r){throw new ic(e,r)}if(!i)return null;try{return JSON.parse(i)}catch(r){throw new tc(e,r)}}async removeItem(e,t="session"){try{await this.storageImpl.removeItem(e,t)}catch(i){throw new Fi(e,i)}}async clearAll(){try{await this.storageImpl.clear("local"),await this.storageImpl.clear("session")}catch(e){throw new Fi("clearAll",e)}}},Bl=class{constructor(){this.persistSession=!1,this._webSocketConstructor=typeof WebSocket<"u"?WebSocket:void 0,this._baseURL=this.apiHost,this._credential={}}get subscriberId(){return this.subscriber.id}get subscriber(){if(!this._subscriber)throw new R("Subscriber");return this._subscriber}set subscriber(e){this._subscriber=e}get storage(){return this._storageManager||(this._storageImpl??(this._storageImpl=new zs),this._storageManager=new Ll(this._storageImpl)),this._storageManager}get http(){return this._httpRequestController??(this._httpRequestController=new kc(this._baseURL,()=>this._credential)),this._httpRequestController}get conversationManager(){if(!this._conversationManager)throw new R("ConversationsManager");return this._conversationManager}set conversationManager(e){this._conversationManager=e}get WebSocket(){if(!this._webSocketConstructor)throw new R("WebSocket constructor");return this._webSocketConstructor}set WebSocket(e){this._webSocketConstructor=e}get deviceController(){return this._deviceController??(this._deviceController=new Vl(this.webRTCApiProvider,this.storage)),this._deviceController}get webRTCApiProvider(){if(!this._webRTCApiProvider){if(typeof RTCPeerConnection>"u"||typeof navigator>"u")throw new R("WebRTCApiProvider: RTCPeerConnection or navigator.mediaDevices is not available. Please provide a custom webRTCApiProvider in SignalWireOptions.");this._webRTCApiProvider={RTCPeerConnection,mediaDevices:navigator.mediaDevices}}return this._webRTCApiProvider}set webRTCApiProvider(e){this._webRTCApiProvider=e,this._deviceController=void 0}get authorizationStateKey(){return`sw:${this.subscriberId}:as`}get protocolKey(){return`sw:${this.subscriberId}:pt`}get attachedCallsKey(){return`sw:${this.subscriberId}:att`}getSubscriberFromAddressId(){var e;return((e=this.subscriber.addresses[0])==null?void 0:e.id)??""}set baseURL(e){this._baseURL=e,this._httpRequestController=void 0}get credential(){return this._credential}set credential(e){this._credential=e}set storageImpl(e){this._storageImpl=e,this._storageManager=void 0}set ch(e){if(!e)return;const t=e.indexOf(".");t!==-1&&(this._host=e.substring(0,t),this._domain=e.substring(t+1)),this._baseURL=this.apiHost,this._httpRequestController=void 0}get relayHost(){return`wss://${this._host??"puc"}.${this._domain??"signalwire.com"}`}get apiHost(){return`https://fabric.${this._domain??"signalwire.com"}`}};const Oe=D(),Nl="sw-dpop",Ul=1,Ve="keys",Gi="dpop-keypair",ci=e=>{const t=new Uint8Array(e);let i="";for(const r of t)i+=String.fromCharCode(r);return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},Fs=e=>ci(new TextEncoder().encode(e).buffer),js=async e=>{if(e.kty!=="RSA")throw new Error(`Unsupported key type for JWK Thumbprint: ${e.kty}. Only RSA is supported.`);const t=JSON.stringify({e:e.e,kty:e.kty,n:e.n});return ci(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))};async function qi(){return new Promise((e,t)=>{const i=indexedDB.open(Nl,Ul);i.onupgradeneeded=()=>{const r=i.result;r.objectStoreNames.contains(Ve)||r.createObjectStore(Ve)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error??new Error("Failed to open IndexedDB"))})}async function zl(){try{const e=await qi();return await new Promise((t,i)=>{const r=e.transaction(Ve,"readonly"),s=r.objectStore(Ve).get(Gi);s.onsuccess=()=>t(s.result??null),s.onerror=()=>i(s.error??new Error("Failed to load key pair from IndexedDB")),r.oncomplete=()=>e.close()})}catch(e){return Oe.warn("[DPoP] Failed to load key pair from IndexedDB:",e),null}}async function Fl(e){try{const t=await qi();await new Promise((i,r)=>{const s=t.transaction(Ve,"readwrite");s.objectStore(Ve).put(e,Gi),s.oncomplete=()=>{t.close(),i()},s.onerror=()=>{t.close(),r(s.error??new Error("Failed to save key pair to IndexedDB"))}})}catch(t){Oe.warn("[DPoP] Failed to save key pair to IndexedDB:",t)}}async function Hs(){try{const e=await qi();await new Promise((t,i)=>{const r=e.transaction(Ve,"readwrite");r.objectStore(Ve).delete(Gi),r.oncomplete=()=>{e.close(),t()},r.onerror=()=>{e.close(),i(r.error??new Error("Failed to delete key pair from IndexedDB"))}})}catch(e){Oe.warn("[DPoP] Failed to delete key pair from IndexedDB:",e)}}var jl=class{constructor(){this._keyPair=null,this._publicJwk=null,this._fingerprint=null,this._initialized=!1}async init(){if(this._initialized)return this.fingerprint;const e=await zl();if(e)try{const t=new TextEncoder().encode("dpop-key-check");return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",e.privateKey,t),this._keyPair=e,this._publicJwk=await crypto.subtle.exportKey("jwk",e.publicKey),this._fingerprint=await js(this._publicJwk),this._initialized=!0,Oe.debug("[DPoP] Key pair restored from IndexedDB, fingerprint:",this._fingerprint),this._fingerprint}catch(t){Oe.warn("[DPoP] Stored key pair unusable, generating new one:",t),await Hs()}return Oe.debug("[DPoP] Generating RSA key pair"),this._keyPair=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,["sign","verify"]),this._publicJwk=await crypto.subtle.exportKey("jwk",this._keyPair.publicKey),this._fingerprint=await js(this._publicJwk),this._initialized=!0,await Fl(this._keyPair),Oe.debug("[DPoP] Key pair generated and persisted, fingerprint:",this._fingerprint),this._fingerprint}get fingerprint(){if(!this._fingerprint)throw new si("CryptoController not initialized. Call init() first.");return this._fingerprint}get initialized(){return this._initialized}async createHttpProof(e){const t={jti:crypto.randomUUID(),htm:e.method,htu:e.uri,iat:Math.floor(Date.now()/1e3)};return e.accessToken&&(t.ath=ci(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e.accessToken)))),this.signProof(t)}async createRpcProof(e){const t={jti:crypto.randomUUID(),rpc:"request",mth:e.method,iat:Math.floor(Date.now()/1e3)};return this.signProof(t)}destroy(){this._keyPair=null,this._publicJwk=null,this._fingerprint=null,this._initialized=!1,Hs(),Oe.debug("[DPoP] Controller destroyed")}get publicJwk(){if(!this._publicJwk)throw new si("CryptoController not initialized. Call init() first.");return this._publicJwk}get privateKey(){if(!this._keyPair)throw new si("CryptoController not initialized. Call init() first.");return this._keyPair.privateKey}async signProof(e){const t={typ:"dpop+jwt",alg:"RS256",jwk:this.publicJwk},i=`${Fs(JSON.stringify(t))}.${Fs(JSON.stringify(e))}`;return`${i}.${ci(await crypto.subtle.sign("RSASSA-PKCS1-v1_5",this.privateKey,new TextEncoder().encode(i)))}`}};const _t=D();function Ws(){return typeof window<"u"&&typeof window.addEventListener=="function"}function Gs(){if(typeof navigator>"u")return;const{connection:e}=navigator;return(e==null?void 0:e.effectiveType)??void 0}function qs(){if(!(typeof navigator>"u"))return navigator.connection??void 0}var Hl=class extends P{constructor(){super(),this._isOnline$=this.createBehaviorSubject(typeof navigator<"u"?navigator.onLine:!0),this._networkChange$=this.createSubject(),this._onOnline=this.handleOnline.bind(this),this._onOffline=this.handleOffline.bind(this),this._onConnectionChange=this.handleConnectionChange.bind(this),this._listenersAttached=!1,this.attachListeners()}get isOnline$(){return this._isOnline$.asObservable().pipe(v(this._destroyed$))}get isOnline(){return this._isOnline$.value}get networkChange$(){return this._networkChange$.asObservable().pipe(v(this._destroyed$))}destroy(){this.removeListeners(),super.destroy()}attachListeners(){if(!Ws()){_t.debug("NetworkMonitor: no browser environment detected, skipping event listeners");return}window.addEventListener("online",this._onOnline),window.addEventListener("offline",this._onOffline);const e=qs();e&&e.addEventListener("change",this._onConnectionChange),this._listenersAttached=!0,_t.debug("NetworkMonitor: event listeners attached")}removeListeners(){if(this._listenersAttached){if(Ws()){window.removeEventListener("online",this._onOnline),window.removeEventListener("offline",this._onOffline);const e=qs();e&&e.removeEventListener("change",this._onConnectionChange)}this._listenersAttached=!1,_t.debug("NetworkMonitor: event listeners removed")}}handleOnline(){_t.info("NetworkMonitor: browser went online"),this._isOnline$.next(!0),this._networkChange$.next({type:"online",timestamp:Date.now(),networkType:Gs()})}handleOffline(){_t.info("NetworkMonitor: browser went offline"),this._isOnline$.next(!1),this._networkChange$.next({type:"offline",timestamp:Date.now()})}handleConnectionChange(){const e=Gs();_t.info(`NetworkMonitor: connection changed — effectiveType=${e??"unknown"}`),this._networkChange$.next({type:"connection_change",timestamp:Date.now(),networkType:e})}};function Ks(e){if(typeof RTCRtpSender>"u"||typeof RTCRtpSender.getCapabilities!="function")return[];const t=RTCRtpSender.getCapabilities(e);if(!t)return[];const i=new Set,r=[];for(const s of t.codecs){const n=Wl(s.mimeType);n&&!i.has(n)&&(i.add(n),r.push(n))}return r}function Wl(e){const t=e.indexOf("/");return t>=0?e.substring(t+1):e}function Gl(){return typeof globalThis>"u"?!1:"RTCRtpScriptTransform"in globalThis||"MediaStreamTrackProcessor"in globalThis}function ql(){return typeof HTMLMediaElement>"u"?!1:"setSinkId"in HTMLMediaElement.prototype}function Kl(){return typeof RTCRtpSender>"u"?!1:typeof RTCRtpSender.prototype.setParameters=="function"}function Js(e){const t=(e==null?void 0:e.mediaDevices)??Ys(),i=typeof(t==null?void 0:t.getUserMedia)=="function",r=typeof(t==null?void 0:t.getDisplayMedia)=="function",s={webrtc:e?typeof e.RTCPeerConnection=="function":typeof globalThis<"u"&&"RTCPeerConnection"in globalThis,getUserMedia:i,getDisplayMedia:r,screenShare:r,screenShareAudio:Jl(),simulcast:Kl(),insertableStreams:Gl(),audioOutputSelection:ql(),videoCodecs:Ks("video"),audioCodecs:Ks("audio")};return Object.freeze(s)}function Jl(){if(typeof navigator>"u")return!1;const e=Ys();return!e||typeof e.getDisplayMedia!="function"?!1:navigator.userAgent.includes("Chrome/")}function Ys(){return typeof navigator<"u"?navigator.mediaDevices:null}const li=D(),Yl=10,Xl=1e4,Ql=5e3,Zl=5e3;var ed=class extends P{constructor(e,t,i,r,s,n={}){super(),this.deviceController=e,this.iceServers=t,this.isConnected=i,this.transportRttMs=r,this.dialFn=s,this._options={duration:n.duration??Yl,skipMediaTest:n.skipMediaTest??!1,audioDevice:n.audioDevice,videoDevice:n.videoDevice}}async run(e){const t=[];try{const i=this.testSignaling();i.reachable||t.push("WebSocket not connected");const r=await this.testDevices();r.audioInput.working||t.push("Audio input device not working"),r.videoInput.working||t.push("Video input device not working");const s=await this.testIceConnectivity();s.type==="failed"?t.push("No ICE connectivity (neither STUN nor TURN reachable)"):s.type==="relay"&&t.push("Only TURN relay connectivity available (no direct path)"),s.turnReachable||t.push("TURN servers not reachable");let n=null;if(!this._options.skipMediaTest)try{n=await this.testMediaBandwidth(e)}catch(o){li.warn("[PreflightRunner] Media bandwidth test failed:",o),t.push("Media bandwidth test failed")}return{ok:i.reachable&&s.type!=="failed"&&r.audioInput.working,signaling:i,connectivity:s,bandwidth:n,devices:r,warnings:t}}catch(i){throw li.error("[PreflightRunner] Preflight test failed:",i),new oc("preflight",i instanceof Error?i:new Error(String(i)))}finally{this.destroy()}}testSignaling(){return{reachable:this.isConnected,rttMs:this.transportRttMs}}async testDevices(){const e=this._options.audioDevice??this.deviceController.selectedAudioInputDevice,t=this._options.videoDevice??this.deviceController.selectedVideoInputDevice,i=this.deviceController.selectedAudioOutputDevice;let r=!1,s=!1,n;try{const o={};e?o.audio={deviceId:{exact:e.deviceId}}:o.audio=!0,t?o.video={deviceId:{exact:t.deviceId}}:o.video=!0,n=await Promise.race([navigator.mediaDevices.getUserMedia(o),new Promise((a,c)=>setTimeout(()=>c(new Error("getUserMedia timeout")),Zl))]);for(const a of n.getTracks())a.kind==="audio"&&a.readyState==="live"&&(r=!0),a.kind==="video"&&a.readyState==="live"&&(s=!0)}catch(o){li.warn("[PreflightRunner] Device test failed:",o)}finally{n&&n.getTracks().forEach(o=>o.stop())}return{audioInput:{working:r,device:e},videoInput:{working:s,device:t},audioOutput:{available:!!i,device:i}}}async testIceConnectivity(){let e;try{e=new RTCPeerConnection({iceServers:this.iceServers});const t=e,i=new Set,r=Date.now(),s=new Promise(p=>{const b=setTimeout(p,Xl);t.onicecandidate=_=>{if(_.candidate){const T=_.candidate.candidate;T.includes("typ host")&&i.add("host"),T.includes("typ srflx")&&i.add("srflx"),T.includes("typ relay")&&i.add("relay")}else clearTimeout(b),p()}});e.createDataChannel("preflight-test");const n=await e.createOffer();await e.setLocalDescription(n),await s;const o=Date.now()-r,a=i.has("srflx"),c=i.has("relay"),l=i.has("host");let h="failed";return l||a?h="direct":c&&(h="relay"),{type:h,turnReachable:c,stunReachable:a,rttMs:o}}catch(t){return li.warn("[PreflightRunner] ICE connectivity test failed:",t),{type:"failed",turnReachable:!1,stunReachable:!1,rttMs:0}}finally{e&&e.close()}}async testMediaBandwidth(e){let t;try{t=await this.dialFn(e,{audio:!0,video:!1}),await ae(t.status$.pipe(C(o=>o==="connected"),te(1),Vt(Ql)));const i=this._options.duration*1e3;await new Promise(o=>setTimeout(o,i));const r=t.networkMetrics;let s=0,n=0;if(r.length>0){const o=r[r.length-1];o.availableOutgoingBitrate!==void 0&&(s=Math.round(o.availableOutgoingBitrate/1e3));const a=o.audio.packetsReceived+o.video.packetsReceived;i>0&&a>0&&(n=s)}return{uploadKbps:s,downloadKbps:n}}finally{if(t)try{await t.hangup()}catch{}}}destroy(){super.destroy()}};const di=D();function td(){try{return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.visibilityState=="string"}catch{return!1}}function Xs(){try{if(typeof document<"u"&&typeof document.visibilityState=="string")return document.visibilityState==="visible"?"visible":"hidden"}catch{}return"visible"}var id=class extends P{constructor(){super(),this._visibility$=this.createBehaviorSubject(Xs()),this._visibilityChange$=this.createSubject(),this._hasVisibilityApi=td(),this._boundHandler=this._handleVisibilityChange.bind(this),this._hasVisibilityApi?(document.addEventListener("visibilitychange",this._boundHandler),di.debug("VisibilityController: listening for visibilitychange events")):di.debug("VisibilityController: document visibility API not available, defaulting to visible")}get visibility$(){return this._visibility$.pipe(v(this._destroyed$))}get visibility(){return this._visibility$.value}get visibilityChange$(){return this._visibilityChange$.pipe(v(this._destroyed$))}destroy(){this._hasVisibilityApi&&(document.removeEventListener("visibilitychange",this._boundHandler),di.debug("VisibilityController: removed visibilitychange listener")),super.destroy()}_handleVisibilityChange(){const e=Xs(),t=this._visibility$.value;if(e===t)return;this._visibility$.next(e);const i={from:t,to:e,timestamp:Date.now()};this._visibilityChange$.next(i),di.debug("VisibilityController: visibility changed",{from:t,to:e})}},rd=class extends P{constructor(e,t){super(),this.fromPath=e,this.http=t,this.fetched$=We(()=>Q(this.fetch())).pipe(pe(1),v(this.destroyed$))}async fetch(){const e=await this.http.request({url:this.fromPath,method:"GET",headers:{Accept:"application/json"}});if(e.ok&&e.body){const t=JSON.parse(e.body);return this.populateInstance(t),!0}return!1}},sd=class extends rd{constructor(e){super("/api/fabric/subscriber/info",e)}populateInstance(e){this.id=e.id,this.email=e.email,this.firstName=e.first_name,this.lastName=e.last_name,this.displayName=e.display_name,this.jobTitle=e.job_title,this.timeZone=e.time_zone,this.country=e.country,this.region=e.region,this.companyName=e.company_name,this.pushNotificationKey=e.push_notification_key,this.appSettings=e.app_settings?{displayName:e.app_settings.display_name,scopes:e.app_settings.scopes}:void 0,this.addresses=e.fabric_addresses,this.satClaims=e.sat_claims}};const wt=e=>({jsonrpc:"2.0",id:e.id??oi(),...e}),Qs=e=>({jsonrpc:"2.0",...e}),nd={major:4,minor:0,revision:0},od=e=>wt({method:"signalwire.connect",params:{version:nd,event_acks:!0,...e}}),ad=e=>{const{dpop_token:t,...i}=e;return wt({method:"signalwire.reauthenticate",params:{authentication:i,...t?{dpop_token:t}:{}}})},cd=(e,t)=>Qs({id:e,result:{timestamp:Date.now()/1e3}}),Ki=({method:e,params:t})=>wt({method:e,params:t}),ld={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",fromCallAddressId:"from_fabric_address_id"},dd=new Set(["remoteSdp","localStream","remoteStream"]),ud=e=>{if(!Object.prototype.hasOwnProperty.call(e,"dialogParams"))return e;const t=e.dialogParams,i=Object.entries(t).reduce((r,[s,n])=>{if(dd.has(s))return r;const o=ld[s]??s;return{...r,[o]:n}},{});return{...e,dialogParams:i}},Xe=e=>(t={})=>wt({method:e,params:ud(t)}),Zs=e=>wt({method:"webrtc.verto",params:e}),hd=Xe("verto.invite"),pd=Xe("verto.bye"),ui=Xe("verto.modify"),vd=Xe("verto.info"),fd=Xe("verto.answer"),gd=Xe("verto.subscribe"),bd=Xe("verto.pong"),md={NORMAL_CLEARING:"16",USER_BUSY:"17",MEDIA_TIMEOUT:"804"},yd=e=>Qs({id:e,result:{}}),Ct=D();var _d=class{constructor(e,t,i,r){this.storage=e,this.deviceController=t,this.reconnectCallsTimeout=i,this.attachKey=r,this.writeQueue=Promise.resolve()}async detachAll(){await this.mutate(e=>({}))}setSession(e){this.session=e}async readAttached(){try{return await this.storage.getItem(this.attachKey)??{}}catch(e){return Ct.warn("[AttachManager] Failed to retrieve attached calls from storage",e),{}}}async writeAttached(e){try{await this.storage.setItem(this.attachKey,e)}catch(t){Ct.warn("[AttachManager] Failed to write attached calls to storage",t)}}async mutate(e){const t=this.writeQueue.then(async()=>{const i=await e(await this.readAttached());await this.writeAttached(i)});return this.writeQueue=t.catch(()=>{}),t}async attach(e){if(!e.to){Ct.warn("[AttachManager] Skip attach for calls with no destination");return}const t=e.to,i={nodeId:e.nodeId,destination:t,mediaDirections:e.mediaDirections,audioInputDevice:e.mediaDirections.audio!=="inactive"?this.deviceController.selectedAudioInputDevice:null,videoInputDevice:e.mediaDirections.video!=="inactive"?this.deviceController.selectedVideoInputDevice:null,attachedAt:Date.now()};await this.mutate(r=>({...r,[e.id]:i}))}async detach(e){await this.mutate(t=>{const{[e.id]:i,...r}=t;return r})}async flush(){await this.mutate(()=>({}))}async reattachCalls(){const e=await this.readAttached();await this.detachExpired();for(const[t,i]of Object.entries(e)){const{destination:r}=i,s=this.buildCallOptions(i);let n=!1;for(let o=1;o<=3;o++)try{await this.session.createOutboundCall(r,{callId:t,...s}),Ct.info(`[AttachManager] Reattached call ${t} (attempt ${o})`),n=!0;break}catch(a){Ct.warn(`[AttachManager] Reattach attempt ${o}/3 failed for call ${t}:`,a),o<3&&await new Promise(c=>setTimeout(c,(o+1)*1e3))}n||(Ct.warn(`[AttachManager] Reattach failed after 3 attempts for call ${t}, removing reference`),await this.detach({id:t,mediaDirections:i.mediaDirections}))}}buildCallOptions(e){const{audio:t,video:i}=e.mediaDirections,{audioInputDevice:r,videoInputDevice:s,nodeId:n}=e,o=t.includes("recv"),a=i.includes("recv"),c=t.includes("send"),l=i.includes("send");return{nodeId:n,receiveAudio:o,receiveVideo:a,inputAudioDeviceConstraints:c?{audio:!0,...this.deviceController.deviceInfoToConstraints(r)}:void 0,inputVideoDeviceConstraints:l?{video:!0,...this.deviceController.deviceInfoToConstraints(s)}:void 0,reattach:!0}}async consumePendingAttachment(e){const t=(await this.readAttached())[e];if(t)return this.buildCallOptions(t)}async detachExpired(){const e=Date.now(),t=this.reconnectCallsTimeout;await this.mutate(i=>{const r={...i};let s=!1;for(const[n,o]of Object.entries(i))e-o.attachedAt>t&&(delete r[n],s=!0);return s?r:i})}};const Qe={on:!1,off:!1},Ji={muteAudio:Qe,muteVideo:Qe,deaf:Qe,raisehand:Qe,microphoneVolume:!1,microphoneSensitivity:!1,speakerVolume:!1,position:!1,meta:!1,remove:!1,audioFlags:!1},en={self:Ji,member:Ji,end:!1,setLayout:!1,sendDigit:!1,vmutedHide:Qe,lock:Qe,device:!1,screenshare:!1};function St(e){return e.length===0?Qe:{on:e.some(t=>!t.endsWith(".off")),off:e.some(t=>!t.endsWith(".on"))}}function tn(e,t,i,r){return e.filter(s=>s===t||s===`${t}.${i}`||s.startsWith(`${t}.${i}.${r}`))}function Ze(e,t,i,r){return e.some(s=>s===t||i!==null&&s===`${t}.${i}`||s.startsWith(`${t}.${i?`${i}.`:""}${r}`))}function rn(e,t){return e.filter(i=>i.startsWith(t)||i===t).length===0?Ji:{muteAudio:St(tn(e,t,"mute","audio")),muteVideo:St(tn(e,t,"mute","video")),deaf:St(e.filter(i=>i===t||i.startsWith(`${t}.deaf`))),raisehand:St(e.filter(i=>i===t||i.startsWith(`${t}.raisehand`))),microphoneVolume:Ze(e,t,"microphone","volume"),microphoneSensitivity:Ze(e,t,"microphone","sensitivity"),speakerVolume:Ze(e,t,"speaker","volume"),position:Ze(e,t,null,"position"),meta:Ze(e,t,null,"meta"),remove:Ze(e,t,null,"remove"),audioFlags:Ze(e,t,null,"audioflags")}}function wd(e){return e.length===0?en:{self:rn(e,"self"),member:rn(e,"member"),end:e.some(t=>t==="end"),setLayout:e.some(t=>t.startsWith("layout")),sendDigit:e.some(t=>t.startsWith("digit")),vmutedHide:St(e.filter(t=>t.startsWith("vmuted"))),lock:St(e.filter(t=>t.startsWith("lock"))),device:e.some(t=>t==="device"),screenshare:e.some(t=>t==="screenshare")}}var Cd=class extends P{constructor(...e){super(...e),this._state$=this.createBehaviorSubject(en)}updateFromRaw(e){const t=wd(e);this._state$.next(t)}get self$(){return this.cachedObservable("self$",()=>this._state$.pipe(f(e=>e.self),y()))}get self(){return this._state$.value.self}get member$(){return this.cachedObservable("member$",()=>this._state$.pipe(f(e=>e.member),y()))}get member(){return this._state$.value.member}get end$(){return this.cachedObservable("end$",()=>this._state$.pipe(f(e=>e.end),y()))}get end(){return this._state$.value.end}get setLayout$(){return this.cachedObservable("setLayout$",()=>this._state$.pipe(f(e=>e.setLayout),y()))}get setLayout(){return this._state$.value.setLayout}get sendDigit$(){return this.cachedObservable("sendDigit$",()=>this._state$.pipe(f(e=>e.sendDigit),y()))}get sendDigit(){return this._state$.value.sendDigit}get vmutedHide$(){return this.cachedObservable("vmutedHide$",()=>this._state$.pipe(f(e=>e.vmutedHide),y()))}get vmutedHide(){return this._state$.value.vmutedHide}get lock$(){return this.cachedObservable("lock$",()=>this._state$.pipe(f(e=>e.lock),y()))}get lock(){return this._state$.value.lock}get device$(){return this.cachedObservable("device$",()=>this._state$.pipe(f(e=>e.device),y()))}get device(){return this._state$.value.device}get screenshare$(){return this.cachedObservable("screenshare$",()=>this._state$.pipe(f(e=>e.screenshare),y()))}get screenshare(){return this._state$.value.screenshare}get state$(){return this._state$.asObservable()}get state(){return this._state$.value}};function Sd(e){return e?"call.undeaf":"call.deaf"}function $d(e){return e?"call.lowerhand":"call.raisehand"}const et=D(),Td={};var sn=class extends P{constructor(e,t,i){super(),this.executeMethod=t,this.deviceController=i,this._state$=this.createBehaviorSubject(Td),this.id=e}upnext(e){this._state$.next({...this._state$.value,...e})}get name$(){return this.cachedObservable("name$",()=>this._state$.pipe(f(e=>e.name),y()))}get type$(){return this.cachedObservable("type$",()=>this._state$.pipe(f(e=>e.type),y()))}get handraised$(){return this.cachedObservable("handraised$",()=>this._state$.pipe(f(e=>e.handraised),y()))}get visible$(){return this.cachedObservable("visible$",()=>this._state$.pipe(f(e=>e.visible),y()))}get audioMuted$(){return this.cachedObservable("audioMuted$",()=>this._state$.pipe(f(e=>e.audio_muted),y()))}get videoMuted$(){return this.cachedObservable("videoMuted$",()=>this._state$.pipe(f(e=>e.video_muted),y()))}get deaf$(){return this.cachedObservable("deaf$",()=>this._state$.pipe(f(e=>e.deaf),y()))}get inputVolume$(){return this.cachedObservable("inputVolume$",()=>this._state$.pipe(f(e=>e.input_volume),y()))}get outputVolume$(){return this.cachedObservable("outputVolume$",()=>this._state$.pipe(f(e=>e.output_volume),y()))}get inputSensitivity$(){return this.cachedObservable("inputSensitivity$",()=>this._state$.pipe(f(e=>e.input_sensitivity),y()))}get echoCancellation$(){return this.cachedObservable("echoCancellation$",()=>this._state$.pipe(f(e=>e.echo_cancellation),y()))}get autoGain$(){return this.cachedObservable("autoGain$",()=>this._state$.pipe(f(e=>e.auto_gain),y()))}get noiseSuppression$(){return this.cachedObservable("noiseSuppression$",()=>this._state$.pipe(f(e=>e.noise_suppression),y()))}get lowbitrate$(){return this.cachedObservable("lowbitrate$",()=>this._state$.pipe(f(e=>e.lowbitrate),y()))}get denoise$(){return this.cachedObservable("denoise$",()=>this._state$.pipe(f(e=>e.denoise),y()))}get meta$(){return this.cachedObservable("meta$",()=>this._state$.pipe(f(e=>e.meta),y()))}get subscriberId$(){return this.cachedObservable("subscriberId$",()=>this._state$.pipe(f(e=>e.subscriber_id),y()))}get addressId$(){return this.cachedObservable("addressId$",()=>this._state$.pipe(f(e=>e.address_id),y()))}get nodeId$(){return this.cachedObservable("nodeId$",()=>this._state$.pipe(f(e=>e.node_id),y()))}get isTalking$(){return this.cachedObservable("isTalking$",()=>this._state$.pipe(f(e=>e.talking),y()))}get isTalking(){return this._state$.value.talking??!1}get position$(){return this.cachedObservable("position$",()=>this._state$.pipe(f(e=>e.position),y()))}get position(){return this._state$.value.position}get isAudience(){return this._state$.value.isAudience??!1}get name(){return this._state$.value.name}get type(){return this._state$.value.type}get handraised(){return this._state$.value.handraised??!1}get visible(){return this._state$.value.visible??!1}get audioMuted(){return this._state$.value.audio_muted??!1}get videoMuted(){return this._state$.value.video_muted??!1}get deaf(){return this._state$.value.deaf??!1}get inputVolume(){return this._state$.value.input_volume}get outputVolume(){return this._state$.value.output_volume}get inputSensitivity(){return this._state$.value.input_sensitivity}get echoCancellation(){return this._state$.value.echo_cancellation??!1}get autoGain(){return this._state$.value.auto_gain??!1}get noiseSuppression(){return this._state$.value.noise_suppression??!1}get lowbitrate(){return this._state$.value.lowbitrate??!1}get denoise(){return this._state$.value.denoise??!1}get meta(){return this._state$.value.meta}get subscriberId(){return this._state$.value.subscriber_id}get addressId(){return this._state$.value.address_id}get nodeId(){return this._state$.value.node_id}get value(){return this._state$.value}async toggleDeaf(){const e=Sd(this.deaf);await this.executeMethod(this.id,e,{})}async toggleHandraise(){await this.executeMethod(this.id,$d(this.handraised),{})}async mute(){await this.executeMethod(this.id,"call.mute",{channels:["audio"]})}async unmute(){await this.executeMethod(this.id,"call.unmute",{channels:["audio"]})}async toggleMute(){return this.audioMuted?this.unmute():this.mute()}async muteVideo(){await this.executeMethod(this.id,"call.mute",{channels:["video"]})}async unmuteVideo(){await this.executeMethod(this.id,"call.unmute",{channels:["video"]})}async toggleMuteVideo(){return this.videoMuted?this.unmuteVideo():this.muteVideo()}async toggleEchoCancellation(){await this.executeMethod(this.id,"call.audioflags.set",{echo_cancellation:!this.echoCancellation,auto_gain:this.autoGain,noise_suppression:this.noiseSuppression})}async toggleAudioInputAutoGain(){await this.executeMethod(this.id,"call.audioflags.set",{echo_cancellation:this.echoCancellation,auto_gain:!this.autoGain,noise_suppression:this.noiseSuppression})}async toggleNoiseSuppression(){await this.executeMethod(this.id,"call.audioflags.set",{echo_cancellation:this.echoCancellation,auto_gain:this.autoGain,noise_suppression:!this.noiseSuppression})}async toggleLowbitrate(){throw new Se}async setAudioInputSensitivity(e){await this.executeMethod(this.id,"call.microphone.sensitivity.set",{sensitivity:e})}async setAudioInputVolume(e){await this.executeMethod(this.id,"call.microphone.volume.set",{volume:e})}async setAudioOutputVolume(e){await this.executeMethod(this.id,"call.speaker.volume.set",{volume:e})}async setPosition(e){await this.executeMethod(this.id,"call.member.position.set",{position:e})}async remove(){const e=this._state$.value,t={member_id:this.id,call_id:e.call_id??"",node_id:e.node_id??""};await this.executeMethod(t,"call.member.remove",{})}async end(){await this.executeMethod(this.id,"call.end",{})}async setMeta(e){throw new Se}async updateMeta(e){throw new Se}destroy(){this.executeMethod=void 0,super.destroy()}},nn=class extends sn{constructor(e,t,i,r){super(e,t,r),this.vertoManager=i,this._studioAudio$=this.createBehaviorSubject(!1),this.capabilities=new Cd}destroy(){this.capabilities.destroy(),super.destroy()}get studioAudio$(){return this._studioAudio$.asObservable()}get studioAudio(){return this._studioAudio$.value}async enableStudioAudio(){this._studioAudio$.value||(this._studioAudio$.next(!0),await this.executeMethod(this.id,"call.audioflags.set",{echo_cancellation:!1,auto_gain:!1,noise_suppression:!1}))}async disableStudioAudio(){this._studioAudio$.value&&(this._studioAudio$.next(!1),await this.executeMethod(this.id,"call.audioflags.set",{echo_cancellation:!0,auto_gain:!0,noise_suppression:!0}))}async startScreenShare(){try{await this.vertoManager.addScreenMedia()}catch(e){et.error("[Participant.startScreenShare] Screen share error:",e)}}get screenShareStatus$(){return this.vertoManager.screenShareStatus$}get screenShareStatus(){return this.vertoManager.screenShareStatus}async stopScreenShare(){return this.vertoManager.removeScreenMedia()}async addAdditionalDevice(e){try{await this.vertoManager.addInputDevice(e)}catch(t){et.error("[Participant.startScreenShare] Screen share error:",t)}}async removeAdditionalDevice(e){return this.vertoManager.removeInputDevices(e)}async addAudioInputDevice({constraints:e,stream:t}={}){const i=e??t?void 0:!0;return this.vertoManager.addMainInputDevices({audio:i,inputAudioDeviceConstraints:e,inputAudioStream:t})}async addVideoInputDevice({constraints:e,stream:t}={}){const i=e??t?void 0:!0;return this.vertoManager.addMainInputDevices({video:i,inputVideoDeviceConstraints:e,inputVideoStream:t})}async addInputDevices(e={}){await this.vertoManager.addMainInputDevices(e)}selectAudioInputDevice(e,t={}){this.deviceController.selectAudioInputDevice(e),t.savePreference&&(d.instance.preferredAudioInput=e)}async setAudioInputDeviceConstraints(e){await this.vertoManager.updateMediaConstraints({audio:e})}async setInputDevicesConstraints(e){await this.vertoManager.updateMediaConstraints(e)}selectVideoInputDevice(e,t={}){this.deviceController.selectVideoInputDevice(e),t.savePreference&&(d.instance.preferredVideoInput=e)}async setVideoInputDeviceConstraints(e){await this.vertoManager.updateMediaConstraints({video:e})}selectAudioOutputDevice(e,t={}){this.deviceController.selectAudioOutputDevice(e),t.savePreference&&(d.instance.preferredAudioOutput=e)}exitStudioModeIfActive(){this._studioAudio$.value&&(et.debug("[SelfParticipant] Exiting studio audio mode due to individual flag toggle"),this._studioAudio$.next(!1))}async toggleEchoCancellation(){this.exitStudioModeIfActive(),await super.toggleEchoCancellation()}async toggleAudioInputAutoGain(){this.exitStudioModeIfActive(),await super.toggleAudioInputAutoGain()}async toggleNoiseSuppression(){this.exitStudioModeIfActive(),await super.toggleNoiseSuppression()}async mute(){try{await super.mute()}catch(e){et.warn("[Participant.toggleAudioInput] Server Error while muting audio input, proceeding with local toggle anyway",e)}finally{this.vertoManager.muteMainAudioInputDevice()}}async unmute(){try{await super.unmute()}catch(e){et.warn("[Participant.toggleAudioInput] Server Error while unmuting audio input, proceeding with local toggle anyway",e)}finally{await this.vertoManager.unmuteMainAudioInputDevice()}}async muteVideo(){try{await super.muteVideo()}catch(e){et.warn("[Participant.toggleVideoInput] Server Error while muting video input, proceeding with local toggle anyway",e)}finally{this.vertoManager.muteMainVideoInputDevice()}}async unmuteVideo(){try{await super.unmuteVideo()}catch(e){et.warn("[Participant.toggleVideoInput] Server Error while unmuting video input, proceeding with local toggle anyway",e)}finally{await this.vertoManager.unmuteMainVideoInputDevice()}}};const on=e=>e instanceof nn;function K(e){return typeof e=="object"&&e!==null}function M(e,t){return t in e}function Yi(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"id")&&typeof e.id=="string"&&M(e,"method")&&typeof e.method=="string"}function Xi(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"id")&&typeof e.id=="string"&&(M(e,"result")||M(e,"error"))}function Ed(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"id")&&typeof e.id=="string"&&(M(e,"error")&&K(e.error)&&M(e.error,"code")&&M(e.error,"message")||M(e,"result")&&K(e.result)&&M(e.result,"code")&&e.result.code!=="200"&&M(e.result,"message"))}function ie(e){return t=>an(t)&&t.event_type===e}function Qi(e){return Yi(e)&&e.method==="signalwire.event"&&K(e.params)&&M(e.params,"event_type")}function an(e){return K(e)&&M(e,"event_type")&&typeof e.event_type=="string"&&M(e,"params")}function Md(e){return an(e)&&(Ad(e)||xd(e)||cn(e)||ln(e)||Dd(e)||Id(e)||Rd(e)||dn(e)||un(e)||hn(e)||pn(e)||Zi(e)||hi(e)||vn(e)||fn(e))}const kd=ie("signalwire.authorization.state"),hi=ie("webrtc.message"),Ad=ie("call.joined"),xd=ie("call.left"),cn=ie("call.updated"),ln=ie("call.state"),Dd=ie("call.play"),Id=ie("call.connect"),Rd=ie("room.updated"),dn=ie("member.updated"),un=ie("member.joined"),hn=ie("member.left"),pn=ie("member.talking"),Zi=ie("layout.changed"),vn=ie("conversation.message"),fn=ie("conversation.message.updated");function gn(e){return K(e)&&M(e,"room_session")&&M(e,"call_id")&&M(e,"member_id")&&M(e,"capabilities")}function Pd(e){return K(e)&&M(e,"room_id")&&M(e,"room_session_id")&&M(e,"layout")}const le=D(),Od={};var Vd=class extends P{constructor(e,t={}){super(),this.webRtcCallSession=e,this.options=t,this.callIds=new Set,this.roomSessionIds=new Set,this._participants$=this.createBehaviorSubject({}),this._self$=this.createBehaviorSubject(null),this._sessionState$=this.createBehaviorSubject(Od),this.initSubscriptions()}get participants$(){return this.cachedObservable("participants$",()=>this._participants$.asObservable().pipe(f(e=>Object.values(e))))}get participants(){return Object.values(this._participants$.value)}get self$(){return this.cachedObservable("self$",()=>this._self$.asObservable().pipe(B()))}isRoomSessionIdValid(e){return this.roomSessionIds.has(e)}addCallId(e){this.callIds.add(e)}isCallIdValid(e){return this.callIds.has(e)}get recording$(){return this.cachedObservable("recording$",()=>this._sessionState$.pipe(f(e=>e.recording),y(),B()))}get recordings$(){return this.cachedObservable("recordings$",()=>this._sessionState$.pipe(f(e=>e.recordings),y(),B()))}get streaming$(){return this.cachedObservable("streaming$",()=>this._sessionState$.pipe(f(e=>e.streaming),y(),B()))}get streams$(){return this.cachedObservable("streams$",()=>this._sessionState$.pipe(f(e=>e.streams),y(),B()))}get playbacks$(){return this.cachedObservable("playbacks$",()=>this._sessionState$.pipe(f(e=>e.playbacks),y(),B()))}get raiseHandPriority$(){return this.cachedObservable("raiseHandPriority$",()=>this._sessionState$.pipe(f(e=>e.prioritize_handraise),y(),B()))}get locked$(){return this.cachedObservable("locked$",()=>this._sessionState$.pipe(f(e=>e.locked),y(),B()))}get meta$(){return this.cachedObservable("meta$",()=>this._sessionState$.pipe(f(e=>e.meta),y(),B()))}get capabilities$(){return this.cachedObservable("capabilities$",()=>this._sessionState$.pipe(f(e=>e.capabilities),y(),B()))}get layout$(){return this.cachedObservable("layout$",()=>this._sessionState$.pipe(f(e=>e.layout_name),y(),B()))}get layouts$(){return this.cachedObservable("layouts$",()=>this._sessionState$.pipe(f(e=>e.layouts),y(),B()))}get layoutLayers$(){return this.cachedObservable("layoutLayers$",()=>this._sessionState$.pipe(f(e=>e.layout_layers),y(),B()))}get self(){return this._self$.value}get layoutLayers(){return this._sessionState$.value.layout_layers??[]}get recording(){return this._sessionState$.value.recording??!1}get streaming(){return this._sessionState$.value.streaming??!1}get raiseHandPriority(){return this._sessionState$.value.prioritize_handraise??!1}get locked(){return this._sessionState$.value.locked??!1}get meta(){return this._sessionState$.value.meta??{}}get layout(){return this._sessionState$.value.layout_name}get layouts(){return this._sessionState$.value.layouts??[]}get capabilities(){return this._sessionState$.value.capabilities??[]}isSessionEvent(e){return this.callIds.has(e)||this.roomSessionIds.has(e)}initSubscriptions(){this.subscribeTo(this.callJoinedEvent$,e=>{var r,s;le.debug("[CallEventsManager] Handling call.joined event for call/session IDs:",{callId:e.call_id,roomSessionId:e.room_session_id});const t=e.room_session,i=e.capabilities;this.selfId=this.selfId??e.member_id,this.originCallId=this.originCallId??e.origin_call_id,this.callIds.add(e.call_id),this.roomSessionIds.add(e.room_session_id),this._sessionState$.next({...this._sessionState$.value,recording:t.recording,recordings:t.recordings,streaming:t.streaming,streams:t.streams,playbacks:t.playbacks,prioritize_handraise:t.prioritize_handraise,locked:t.locked,meta:t.meta,capabilities:i}),this.updateParticipants(t.members),(r=this._self$.value)==null||r.capabilities.updateFromRaw(i),(s=this._self$.value)!=null&&s.capabilities.setLayout&&this.updateLayouts()}),this.subscribeTo(this.memberUpdates$,e=>{le.debug("[CallEventsManager] Handling member update event for member ID:",e),this.upsertParticipant(e)}),this.subscribeTo(this.webRtcCallSession.memberLeft$,e=>{le.debug("[CallEventsManager] Handling member.left event for member ID:",e.member.member_id);const t={...this._participants$.value};e.member.member_id in t?(delete t[e.member.member_id],this._participants$.next(t)):le.warn(`[CallEventsManager] Received member.left event for unknown member ID: ${e.member.member_id}`)}),this.subscribeTo(this.webRtcCallSession.callUpdated$,e=>{le.debug("[CallEventsManager] Handling call.updated event:",e);const t=e.room_session;this._sessionState$.next({...this._sessionState$.value,recording:t.recording,recordings:t.recordings,streaming:t.streaming,streams:t.streams,playbacks:t.playbacks,prioritize_handraise:t.prioritize_handraise,locked:t.locked,meta:t.meta})}),this.subscribeTo(this.layoutChangedEvent$,e=>{le.debug("[CallEventsManager] Handling layout.changed event:",e),this._sessionState$.next({...this._sessionState$.value,layout_name:e.id,layout_layers:e.layers}),this.updateParticipantPositions(e)})}updateParticipantPositions(e){Object.keys(this._participants$.value).length>0&&!e.layers.some(t=>!!t.member_id)&&le.warn("[CallEventsManager] No layers with member_id found in layout.changed event. Nothing to update."),e.layers.filter(t=>!!t.member_id).filter(t=>t.member_id in this._participants$.value?!0:(le.warn(`[CallEventsManager] Skipping layout layer for unknown member_id: ${t.member_id}`),!1)).map(t=>(this._participants$.value[t.member_id].upnext({position:t}),this._participants$.value[t.member_id])).forEach(t=>{on(t)&&this._self$.next(t),this._participants$.next({...this._participants$.value,[t.id]:t})})}updateLayouts(){this.selfId&&this.webRtcCallSession.executeMethod(this.selfId,"call.layout.list",{}).then(e=>{this._sessionState$.next({...this._sessionState$.value,layouts:e.result.layouts})}).catch(e=>{le.error("[CallEventsManager] Error fetching layouts:",e)})}updateParticipants(e){e.forEach(t=>this.upsertParticipant(t))}upsertParticipant(e){if(!(e.member_id in this._participants$.value)){const r=this.webRtcCallSession.createParticipant(e.member_id,this.selfId);this._participants$.next({...this._participants$.value,[e.member_id]:r})}const t=this._participants$.value[e.member_id],i=t.value;le.debug("[CallEventsManager] Updating participant:",e.member_id,{oldValue:i,newValue:e}),t.upnext({...i,...e}),on(t)&&this._self$.next(t),this._participants$.next(this._participants$.value)}get callJoinedEvent$(){return this.cachedObservable("callJoinedEvent$",()=>this.webRtcCallSession.callEvent$.pipe(C(gn),W(e=>{le.debug("[CallEventsManager] Call joined event:",e)})))}get layoutChangedEvent$(){return this.cachedObservable("layoutChangedEvent$",()=>this.webRtcCallSession.callEvent$.pipe(F(Pd,"layout"),W(e=>{le.debug("[CallEventsManager] Layout changed event:",e)})))}get memberUpdates$(){return this.cachedObservable("memberUpdates$",()=>vt(this.webRtcCallSession.memberJoined$,this.webRtcCallSession.memberUpdated$,this.webRtcCallSession.memberTalking$).pipe(f(e=>e.member),W(e=>{le.debug("[CallEventsManager] Member update event:",e)})))}destroy(){Object.values(this._participants$.value).forEach(e=>{e.destroy()}),this._participants$.next({}),this._self$.next(null),this.callIds.clear(),this.roomSessionIds.clear(),this.selfId=void 0,this.originCallId=void 0,this.webRtcCallSession=void 0,this.callSession=void 0,super.destroy()}};const Ld=new Set(["sendrecv","sendonly","recvonly","inactive"]);function Bd(e){const t={audio:"inactive",video:"inactive"};if(!e)return t;const i=e.split(/\r?\n/);let r=null,s=null;for(const n of i)if(n.startsWith("m="))r&&(t[r]=s??"sendrecv"),n.startsWith("m=audio")?r="audio":n.startsWith("m=video")?r="video":r=null,s=null;else if(r&&n.startsWith("a=")){const o=n.substring(2).trim();Ld.has(o)&&(s=o)}return r&&(t[r]=s??"sendrecv"),t}function bn(e){if(!e)return!1;const t=e.split(`\r
2469
+ `),i=[];let r=-1;for(const s of t)if(s.startsWith("m="))r+=1,i[r]=0;else if(s.startsWith("a=candidate:")){const n=/\styp\s+(host|srflx|prflx|relay)/.exec(s);n&&n[1]!=="host"&&(i[r]+=1)}return!i.length||i.every(s=>s>0)}function Nd(e,t=[],i=[]){if(!e||t.length===0&&i.length===0)return e;const r=Fd(e),s=[r[0]];for(let n=1;n<r.length;n++){const o=r[n],a=o.split(/\r?\n/)[0];a.startsWith("m=video")&&t.length>0?s.push(mn(o,t)):a.startsWith("m=audio")&&i.length>0?s.push(mn(o,i)):s.push(o)}return s.join("")}function Ud(e,t=Al){if(!e)return e;const i=jd(e);if(i===null)return e;const r=e.split(/\r?\n/),s=[],n=`a=fmtp:${i} `;let o=!1;for(const a of r)a.startsWith(n)?(o=!0,s.push(Hd(a,t))):s.push(a);if(!o){const a=`a=rtpmap:${i} `,c=[];for(const l of s)c.push(l),l.startsWith(a)&&c.push(`a=fmtp:${i} stereo=1;sprop-stereo=1;maxaveragebitrate=${t}`);return c.join(`\r
2470
+ `)}return s.join(`\r
2471
+ `)}function zd(e,t=[],i=[]){return Nd(e,i,t)}function Fd(e){return e.split(/(?=m=)/)}function mn(e,t){var h;const i=e.split(/\r?\n/),r=i[0].split(" ");if(r.length<4)return e;const s=r.slice(3),n=new Map;for(const p of i){const b=/^a=rtpmap:(\d+)\s+([^\s/]+)/.exec(p);b&&n.set(b[1],b[2])}const o=t.map(p=>p.toUpperCase()),a=[],c=[];for(const p of s){const b=((h=n.get(p))==null?void 0:h.toUpperCase())??"";o.indexOf(b)>=0?a.push(p):c.push(p)}a.sort((p,b)=>{var m,x;const _=((m=n.get(p))==null?void 0:m.toUpperCase())??"",T=((x=n.get(b))==null?void 0:x.toUpperCase())??"";return o.indexOf(_)-o.indexOf(T)});const l=[...a,...c];return[[...r.slice(0,3),...l].join(" "),...i.slice(1)].join(`\r
2472
+ `)}function jd(e){const t=/a=rtpmap:(\d+)\s+opus\/48000/i.exec(e);return t?t[1]:null}function Hd(e,t){let i=e;return i.includes("stereo=")||(i+=";stereo=1"),i.includes("sprop-stereo=")||(i+=";sprop-stereo=1"),i.includes("maxaveragebitrate=")||(i+=`;maxaveragebitrate=${t}`),i}const re=D();var Wd=class extends P{constructor(e,t,i={}){super(),this.peerConnection=e,this.peerConnectionControllerNegotiating$=t,this.onicegatheringstatechangeHandler=()=>{const{iceGatheringState:r}=this.peerConnection;re.debug(`[ICEGatheringController] ICE gathering state changed to: ${r}`),r==="gathering"&&this._iceCandidatesState.next({state:"gathering",validSDP:!1})},this.onicecandidateHandler=r=>{re.debug("[ICEGatheringController] ICE candidate event received:",r.candidate),this.removeTimer("iceCandidateTimer"),r.candidate?this.iceCandidateTimer=setTimeout(()=>{this.peerConnection.iceGatheringState!=="complete"&&(re.warn("[ICEGatheringController] ICE candidate timeout, using current SDP"),this.handleICECandidateTimeout())},this.iceCandidateTimeout):(re.debug("[ICEGatheringController] ICE gathering completed: null candidate received"),this.removeTimer("iceGatheringTimer"),this.handleICEGatheringComplete())},this._iceCandidatesState=this.createBehaviorSubject({state:"new",validSDP:!1}),this.iceCandidateTimeout=i.iceCandidateTimeout??Ms,this.iceGatheringTimeout=i.iceGatheringTimeout??ks,this.relayOnly=i.relayOnly??!1,this.setupEventListeners(),this.subscribeTo(this.peerConnectionControllerNegotiating$.pipe(C(r=>r)),r=>{r&&(this.setupEventListeners(),this.iceGatheringTimer=setTimeout(()=>{this.peerConnection.iceGatheringState!=="complete"&&(re.warn("[ICEGatheringController] ICE gathering timeout, using current SDP"),this.handleICEGatheringTimeout())},this.iceGatheringTimeout))})}setupEventListeners(){this.peerConnection.removeEventListener("icecandidate",this.onicecandidateHandler),this.peerConnection.addEventListener("icecandidate",this.onicecandidateHandler),this.peerConnection.removeEventListener("icegatheringstatechange",this.onicegatheringstatechangeHandler),this.peerConnection.addEventListener("icegatheringstatechange",this.onicegatheringstatechangeHandler)}get iceCandidatesState$(){return this._iceCandidatesState.pipe(ps(this.peerConnectionControllerNegotiating$),C(([e,t])=>t),f(([e,t])=>e.state))}get hasValidLocalDescriptionSDP(){var t;const e=(t=this.peerConnection.localDescription)==null?void 0:t.sdp;return bn(e??"")}get isRelayOnly(){return this.relayOnly}setRelayOnly(e){this.relayOnly=e}handleICEGatheringComplete(){re.debug("[ICEGatheringController] Handling ICE gathering complete"),re.debug(`[ICEGatheringController] Checking ICE gathering state: ${this.peerConnection.iceGatheringState}`),re.debug("[ICEGatheringController] ICE gathering complete"),this._iceCandidatesState.next({state:"complete",validSDP:this.hasValidLocalDescriptionSDP}),this.stopGathering()}stopGathering(){this.peerConnection.removeEventListener("icegatheringstatechange",this.onicegatheringstatechangeHandler),this.peerConnection.removeEventListener("icecandidate",this.onicecandidateHandler),this.clearAllTimers()}handleICEGatheringTimeout(){var t;this.removeTimer("iceGatheringTimer");const e=this.hasValidLocalDescriptionSDP;e?(re.debug("[ICEGatheringController] Local SDP is valid"),this._iceCandidatesState.next({state:"timeout",validSDP:e}),this.stopGathering()):re.debug(`### ICE gathering timeout
2473
+ `,(t=this.peerConnection.localDescription)==null?void 0:t.sdp)}handleICECandidateTimeout(){this.iceCandidateTimer&&this.removeTimer("iceCandidateTimer"),re.warn("[ICEGatheringController] ICE candidate timeout");const e=this.hasValidLocalDescriptionSDP;!e&&!this.relayOnly?this.restartICEGatheringWithRelayOnly():(re.debug("[ICEGatheringController] Using current SDP due to ICE candidate timeout"),this._iceCandidatesState.next({state:"timeout",validSDP:e}),this.stopGathering())}restartICEGatheringWithRelayOnly(){re.debug("[ICEGatheringController] Restarting ICE gathering with relay-only candidates"),this.relayOnly=!0,this.peerConnection.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:"relay"}),this.peerConnection.restartIce()}removeTimer(e){this[e]&&(clearTimeout(this[e]),this[e]=void 0)}clearAllTimers(){re.debug("[ICEGatheringController] Clearing all timers"),this.removeTimer("iceGatheringTimer"),this.removeTimer("iceCandidateTimer")}removeEventListeners(){this.peerConnection.removeEventListener("icegatheringstatechange",this.onicegatheringstatechangeHandler),this.peerConnection.removeEventListener("icecandidate",this.onicecandidateHandler)}destroy(){re.debug("[ICEGatheringController] Destroying ICEGatheringController"),this.clearAllTimers(),this.removeEventListeners(),super.destroy()}};const er=D();var Gd=class extends P{constructor(e={}){super(),this._inputSource=null,this._inputStream=null,this._lastSpokeAt=0,this._gain$=this.createBehaviorSubject(1),this._pttMultiplier=1,this._audioContext=(e.audioContextFactory??(()=>new AudioContext))(),this._gainNode=this._audioContext.createGain(),this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,this._analyser.smoothingTimeConstant=.3,this._analyserBuffer=new Uint8Array(new ArrayBuffer(this._analyser.fftSize)),this._destination=this._audioContext.createMediaStreamDestination(),this._gainNode.connect(this._analyser),this._analyser.connect(this._destination),this._speakingThreshold=e.speakingThreshold??hl,this._speakingHoldMs=e.speakingHoldMs??pl,this._pollIntervalMs=e.pollIntervalMs??Ls;const t=e.initialGain??1;this._gain$.next(t),this.applyEffectiveGain()}get gain$(){return this._gain$.asObservable()}get gain(){return this._gain$.value}get outputTrack(){const[e]=this._destination.stream.getAudioTracks();return e}get level$(){return this.deferEmission(Zt(this._pollIntervalMs,zr).pipe(f(()=>this.computeLevel())))}get speaking$(){return this.deferEmission(this.level$.pipe(f(e=>this.evaluateSpeaking(e)),y()))}setGain(e){const t=Math.max(0,Math.min(2,e));this._gain$.next(t),this.applyEffectiveGain()}setPTTActive(e){this._pttMultiplier=e?1:0,this.applyEffectiveGain()}applyEffectiveGain(){this._gainNode.gain.value=this._gain$.value*this._pttMultiplier}setInputTrack(e){if(this._inputSource){try{this._inputSource.disconnect()}catch(t){er.debug("[LocalAudioPipeline] input disconnect warning:",t)}this._inputSource=null}this._inputStream&&(this._inputStream=null),e&&(this._inputStream=new MediaStream([e]),this._inputSource=this._audioContext.createMediaStreamSource(this._inputStream),this._inputSource.connect(this._gainNode),this._audioContext.state==="suspended"&&this._audioContext.resume().catch(t=>{er.warn("[LocalAudioPipeline] AudioContext resume failed:",t)}))}destroy(){if(this._inputSource){try{this._inputSource.disconnect()}catch{}this._inputSource=null}try{this._gainNode.disconnect(),this._analyser.disconnect()}catch{}this._audioContext.close().catch(e=>{er.debug("[LocalAudioPipeline] audio context close warning:",e)}),super.destroy()}computeLevel(){if(!this._inputSource)return 0;this._analyser.getByteTimeDomainData(this._analyserBuffer);let e=0;for(const t of this._analyserBuffer){const i=(t-128)/128;e+=i*i}return Math.sqrt(e/this._analyserBuffer.length)}evaluateSpeaking(e){const t=Date.now();return e>=this._speakingThreshold?(this._lastSpokeAt=t,!0):t-this._lastSpokeAt<this._speakingHoldMs}};const De=D();var qd=class extends P{constructor(e){super(),this.options=e,this.mediaTrackEndedHandler=t=>{this._mediaTrackEnded$.next(t)},this._localStream$=this.createBehaviorSubject(null),this._localAudioTracks$=this.createBehaviorSubject([]),this._localVideoTracks$=this.createBehaviorSubject([]),this._mediaTrackEnded$=this.createSubject()}get localStream$(){return this._localStream$.asObservable().pipe(v(this.destroyed$))}get localAudioTracks$(){return this._localAudioTracks$.asObservable().pipe(v(this.destroyed$))}get localVideoTracks$(){return this._localVideoTracks$.asObservable().pipe(v(this.destroyed$))}get mediaTrackEnded$(){return this._mediaTrackEnded$.asObservable().pipe(v(this.destroyed$))}get localStream(){return this._localStream$.value}get localAudioTracks(){return this._localAudioTracks$.value}get localVideoTracks(){return this._localVideoTracks$.value}async buildLocalStream(){var t,i;De.debug("[LocalStreamController] Building local media stream.");let e;if(this.options.inputAudioStream??this.options.inputVideoStream){const r=[...((t=this.options.inputAudioStream)==null?void 0:t.getTracks())??[],...((i=this.options.inputVideoStream)==null?void 0:i.getTracks())??[]];e=new MediaStream(r)}else if(this.options.propose==="screenshare")De.debug("[LocalStreamController] Requesting display media for screen sharing with audio:",!!this.options.inputAudioDeviceConstraints),e=await this.options.getDisplayMedia({video:!0,audio:!!this.options.inputAudioDeviceConstraints}),De.debug("[LocalStreamController] Screen share media obtained:",e);else{const r={audio:this.options.inputAudioDeviceConstraints,video:this.options.inputVideoDeviceConstraints};De.debug("[LocalStreamController] Requesting user media with constraints:",r),e=await this.options.getUserMedia(r),De.debug("[LocalStreamController] User media obtained:",e)}return this._localStream$.next(e),e}addTrack(e){const t=this._localStream$.value??new MediaStream;return e.addEventListener("ended",this.mediaTrackEndedHandler),t.addTrack(e),this._localStream$.next(t),e.kind==="video"?this._localVideoTracks$.next(t.getVideoTracks()):this._localAudioTracks$.next(t.getAudioTracks()),De.debug(`[LocalStreamController] ${e.kind} track added:`,e.id),t}removeTrack(e){const t=this._localStream$.value,i=t==null?void 0:t.getTracks().find(r=>r.id===e);if(!i){De.debug(`[LocalStreamController] track not found: ${e}`);return}return i.removeEventListener("ended",this.mediaTrackEndedHandler),t==null||t.removeTrack(i),i.stop(),this._localStream$.next(t),i.kind==="video"?this._localVideoTracks$.next((t==null?void 0:t.getVideoTracks())??[]):this._localAudioTracks$.next((t==null?void 0:t.getAudioTracks())??[]),De.debug(`[LocalStreamController] ${i.kind} track removed:`,e),i}getOrCreateLocalStream(){return this._localStream$.value??new MediaStream}setLocalStream(e){this._localStream$.next(e)}addTrackEndedListener(e){e.addEventListener("ended",this.mediaTrackEndedHandler)}updateOptions(e){this.options={...this.options,...e}}stopAllTracks(){var e;(e=this._localStream$.value)==null||e.getTracks().forEach(t=>{De.debug(`[LocalStreamController] Stopping local track: ${t.kind}`),t.removeEventListener("ended",this.mediaTrackEndedHandler),t.stop()})}destroy(){this.stopAllTracks(),super.destroy()}};const se=D(),yn=(e,t)=>e&&t?"sendrecv":e&&!t?"sendonly":!e&&t?"recvonly":"inactive";var Kd=class extends P{constructor(e){super(),this.peerConnection=e.peerConnection,this.options=e}get useAddTransceivers(){return typeof this.peerConnection.addTransceiver=="function"}get useAddTrack(){return typeof this.peerConnection.addTrack=="function"}get useAddStream(){return typeof this.peerConnection.addStream=="function"&&!this.useAddTransceivers&&!this.useAddTrack}get propose(){return this.options.propose}get isAdditionalDevice(){return this.propose==="additional-device"}get isScreenShare(){return this.propose==="screenshare"}get isSimulcast(){return!!this.options.simulcast}get isSFU(){return!!this.options.sfu}get receiveVideo(){return!!this.options.receiveVideo}get receiveAudio(){return!!this.options.receiveAudio}get localStream(){return this.options.localStreamController.localStream}get inputAudioDeviceConstraints(){return this.options.getInputAudioDeviceConstraints()}get inputVideoDeviceConstraints(){return this.options.getInputVideoDeviceConstraints()}get audioDirection(){if(this.isAdditionalDevice)return"sendonly";const{localStream:e}=this,t=e==null?void 0:e.getAudioTracks().some(s=>s.enabled),i=!!this.inputAudioDeviceConstraints,r=!!this.receiveAudio;return yn(t||i,r)}get videoDirection(){if(this.isAdditionalDevice||this.isScreenShare)return"sendonly";if(this.isSFU)return"recvonly";const{localStream:e}=this,t=e==null?void 0:e.getVideoTracks().some(s=>s.enabled),i=!!this.inputVideoDeviceConstraints,r=!!this.receiveVideo;return yn(t||i,r)}get sendEncodings(){if(this.isSimulcast)return["0","1","2"].map(e=>({active:!0,rid:e,scaleResolutionDownBy:Number(e)*6||1}))}getConstraintsFor(e){const t=e==="audio"?this.inputAudioDeviceConstraints:this.inputVideoDeviceConstraints;return typeof t=="boolean"?{}:t}transceiverByKind(e){return this.peerConnection.getTransceivers().filter(t=>e==="both"||t.receiver.track.kind===e)}get audioTransceivers(){return this.transceiverByKind("audio")}get videoTransceivers(){return this.transceiverByKind("video")}async setupTransceiverSender(e,t,i){var o;const r=e.kind==="audio",s=r?this.audioDirection:this.videoDirection,n={direction:s,sendEncodings:r?void 0:this.sendEncodings,streams:s==="recvonly"?void 0:[t]};se.debug(`[TransceiverController] Setting up transceiver sender for local ${e.kind} track:`,{transceiver:i,transceiverParams:n}),n.direction&&["sendonly","sendrecv"].includes(n.direction)&&(i?(await i.sender.replaceTrack(e),i.direction=n.direction,(o=n.streams)!=null&&o.some(a=>!!a)&&(se.debug(`[TransceiverController] Setting streams for transceiver sender for local ${e.kind} track:`,n.streams),i.sender.setStreams(...n.streams))):(se.debug(`[TransceiverController] Adding new transceiver for local ${e.kind} track:`,e.id),this.peerConnection.addTransceiver(e,n)))}stopTrackSender(e,t={updateTransceiverDirection:!1}){var i,r,s;try{const n=this.transceiverByKind(e);for(const o of n)if(((i=o.sender.track)==null?void 0:i.readyState)==="live"){const a=o.sender.track.id;o.sender.track.stop(),this.options.localStreamController.removeTrack(a),t.updateTransceiverDirection&&(o.direction="inactive")}}catch(n){se.error("[TransceiverController] stopTrackSender error",e,n),(s=(r=this.options).onError)==null||s.call(r,new bt("stopTrackSender",e,n))}}async restoreTrackSender(e){var t,i;try{se.debug("[TransceiverController] restoreTrackSender called",e);const r={},s=this.transceiverByKind(e);for(const o of s){const{track:a}=o.sender;if(!a||a.readyState==="ended"){const c=(a==null?void 0:a.kind)??o.receiver.track.kind;(c==="audio"||c==="video")&&(r[c]=this.getConstraintsFor(c))}}if(se.debug("[TransceiverController] restoreTrackSender constraints:",r),Object.keys(r).length===0){se.warn("[TransceiverController] restoreTrackSender: no tracks need restoration",e);return}const n=(await this.options.getUserMedia(r)).getTracks();se.debug("[TransceiverController] restoreTrackSender new tracks:",n);for(const o of n){this.options.localStreamController.addTrack(o);const a=o.kind,c=this.transceiverByKind(a)[0];c.direction=a==="audio"?this.audioDirection:this.videoDirection,se.debug("[TransceiverController] restoreTrackSender setting direction for",a,c.direction),await c.sender.replaceTrack(o)}}catch(r){se.error("[TransceiverController] restoreTrackSender error",e,r),(i=(t=this.options).onError)==null||i.call(t,new bt("restoreTrackSender",e,r))}}async replaceSenderTrack(e,t){const i=e==="audio"?this.audioTransceivers:this.videoTransceivers;for(const r of i)await r.sender.replaceTrack(t)}async setupRemoteTransceivers(e){if(e!=="answer"){for(const t of["audio","video"]){const i=t==="audio"?this.audioTransceivers:this.videoTransceivers;for(const r of i){const s=t==="audio"?this.audioDirection:this.videoDirection;["inactive","recvonly"].includes(s)&&(r.direction=s,await r.sender.replaceTrack(null),r.sender.setStreams())}}if(this.videoDirection==="recvonly"&&this.isSFU&&this.useAddTransceivers){const{msStreamsNumber:t=5}=this.options;for(let i=0;i<Number(t);i++)this.peerConnection.addTransceiver("video",{direction:"recvonly"})}}}async updateSendersConstraints(e,t){var r,s;if(!t)return this.stopTrackSender(e),Promise.resolve();const i=this.peerConnection.getSenders().filter(n=>{var o;return((o=n.track)==null?void 0:o.kind)===e&&n.track.readyState==="live"});for(const n of i){const{track:o}=n;if(o){const a={...o.getConstraints(),...t};try{await o.applyConstraints(a),se.debug(`[TransceiverController] Updated ${e} sender constraints:`,a),se.debug(`[TransceiverController] Updated ${e} sender constraints:`,o.getConstraints())}catch(c){se.warn(`[TransceiverController] applyConstraints failed for ${e} track ${o.id}, attempting track replacement fallback:`,c);try{await this.replaceTrackFallback(n,o,e,a)}catch(l){se.warn(`[TransceiverController] Track replacement fallback also failed for ${e} track:`,l),(s=(r=this.options).onError)==null||s.call(r,new bt("updateSendersConstraints",e,l))}}}}}async replaceTrackFallback(e,t,i,r){const{deviceId:s}=t.getSettings(),n={...r,...s?{deviceId:{exact:s}}:{}},o=t.id;t.stop(),this.options.localStreamController.removeTrack(o);const a=(await this.options.getUserMedia({[i]:n})).getTracks().find(c=>c.kind===i);if(!a)throw new bt("replaceTrackFallback",i,new Error("getUserMedia returned no track of the requested kind"));await e.replaceTrack(a),this.options.localStreamController.addTrack(a),se.debug(`[TransceiverController] Track replacement fallback succeeded for ${i}. New track: ${a.id}`)}getMediaDirections(){return this.peerConnection.connectionState==="connected"?this.peerConnection.getTransceivers().reduce((e,t)=>({...e,[t.receiver.track.kind]:t.direction}),{audio:"inactive",video:"inactive"}):{audio:this.audioDirection,video:this.videoDirection}}updatePeerConnection(e){this.peerConnection=e}updateOptions(e){this.options={...this.options,...e}}};const S=D();var _n=class extends P{constructor(e={},t,i){super(),this.options=e,this.firstSDPExchangeCompleted=!1,this.negotiationNeeded$=this.createSubject(),this.localDescription$=We(()=>Q(this.init())).pipe(we(()=>this.iceGatheringController.iceCandidatesState$.pipe(C(s=>!["new","gathering"].includes(s)),W(()=>{this.negotiationEnded()}),C(()=>this.shouldEmitLocalDescription),f(()=>{var s;return(s=this.peerConnection)==null?void 0:s.localDescription}),B(),W(s=>{s.type==="answer"&&(this._type="offer")}))),pe(1),v(this.destroyed$)),this.connectionTimeout=3e3,this.oniceconnectionstatechangeHandler=()=>{if(this.peerConnection){const{iceConnectionState:s}=this.peerConnection;S.debug(`[RTCPeerConnectionController] ICE connection state changed to: ${s}`),this._iceConnectionState$.next(this.peerConnection.iceConnectionState)}},this.onconnectionstatechangeHandler=()=>{if(this.peerConnection){const{connectionState:s}=this.peerConnection;S.debug(`[RTCPeerConnectionController] Connection state changed to: ${s}`),s==="connected"&&this.removeConnectionTimer(),this._connectionState$.next(this.peerConnection.connectionState)}},this.onsignalingstatechangeHandler=()=>{var s;S.debug(`[RTCPeerConnectionController] Signaling state changed to: ${(s=this.peerConnection)==null?void 0:s.signalingState}`)},this.onicegatheringstatechangeHandler=()=>{this.peerConnection&&this._iceGatheringState$.next(this.peerConnection.iceGatheringState)},this.onnegotiationneededHandler=s=>{S.debug("[RTCPeerConnectionController] Negotiation needed event received.",s),this.negotiationNeeded$.next()},this.updateSelectedInputDevice=async(s,n)=>{var o,a,c;try{const{localStream:l}=this;if(!l){S.warn("[RTCPeerConnectionController] No local stream available to update input device.");return}S.debug(`[RTCPeerConnectionController] Updating selected ${s} input device:`,l.getTracks());const h=l.getTracks().find(p=>p.kind===s);if(h){if((o=this.transceiverController)==null||o.stopTrackSender(s),this.localStreamController.removeTrack(h.id),S.debug(`[RTCPeerConnectionController] Stopped existing ${s} track: ${h.id}`,l.getTracks()),!n){S.debug(`[RTCPeerConnectionController] ${s} input device selected: none`);return}const p=(await this.getUserMedia({[s]:{...h.getConstraints(),...this.deviceController.deviceInfoToConstraints(n)}})).getTracks().find(b=>b.kind===s);p&&(S.debug(`[RTCPeerConnectionController] Adding new ${s} track: ${p.id}`),this.localStreamController.addTrack(p),await((a=this.transceiverController)==null?void 0:a.replaceSenderTrack(s,p)),S.debug(`[RTCPeerConnectionController] Added new ${s} track: ${p.id}`,(c=this.localStream)==null?void 0:c.getTracks()))}S.debug(`[RTCPeerConnectionController] ${s} input device selected:`,n==null?void 0:n.label)}catch(l){throw S.error(`[RTCPeerConnectionController] Failed to select ${s} input device:`,l),this._errors$.next(ke(l)),l}},this._isNegotiating$=this.createBehaviorSubject(!1),this._memberId=null,this._iceConnectionState$=this.createReplaySubject(1),this._connectionState$=this.createReplaySubject(1),this._signalingState$=this.createReplaySubject(1),this._iceGatheringState$=this.createReplaySubject(1),this._errors$=this.createReplaySubject(1),this._iceCandidates$=this.createReplaySubject(1),this._initialized$=this.createReplaySubject(1),this._remoteDescription$=this.createReplaySubject(1),this._remoteStream$=this.createBehaviorSubject(null),this._remoteOfferMediaDirections=null,this._localAudioPipeline=null,this.deviceController=i??{},this.id=e.callId??oi(),this._type=t?"answer":"offer",this.sdpInit=t?{type:"offer",sdp:t}:void 0,this._remoteOfferMediaDirections=t?Bd(t):null;const r=this._remoteOfferMediaDirections?{audio:this._remoteOfferMediaDirections.audio.includes("recv"),video:this._remoteOfferMediaDirections.video.includes("recv"),receiveAudio:this._remoteOfferMediaDirections.audio.includes("send"),receiveVideo:this._remoteOfferMediaDirections.video.includes("send")}:{};this.options={...e,audio:e.audio??r.audio,video:e.video??r.video,receiveAudio:e.receiveAudio??r.receiveAudio??d.instance.receiveAudio,receiveVideo:e.receiveVideo??r.receiveVideo??d.instance.receiveVideo},this.localStreamController=new qd({propose:this.propose,inputAudioStream:this.options.inputAudioStream,inputVideoStream:this.options.inputVideoStream,inputAudioDeviceConstraints:this.inputAudioDeviceConstraints,inputVideoDeviceConstraints:this.inputVideoDeviceConstraints,getUserMedia:async s=>this.getUserMedia(s),getDisplayMedia:async s=>this.getDisplayMedia(s)})}get iceGatheringController(){if(!this._iceGatheringController)throw new R("ICEGatheringController is not initialized");return this._iceGatheringController}get shouldEmitLocalDescription(){if(!this.peerConnection)return!1;const{localDescription:e,signalingState:t}=this.peerConnection;return!e||!bn(e.sdp)?!1:e.type==="offer"&&t==="have-local-offer"||e.type==="answer"&&t==="stable"}removeConnectionTimer(){this.connectionTimer&&(clearTimeout(this.connectionTimer),this.connectionTimer=void 0)}setMemberId(e){this._memberId=e}get memberId(){return this._memberId}stopTrackSender(e,t={updateTransceiverDirection:!1}){var i;(i=this.transceiverController)==null||i.stopTrackSender(e,t)}get isNegotiating$(){return this._isNegotiating$.asObservable()}get isNegotiating(){return this._isNegotiating$.value}updateMediaDevicesOptions(e){this.options={...this.options,...e}}get iceGatheringState$(){return this.cachedObservable("iceGatheringState$",()=>this._iceGatheringState$.asObservable().pipe(v(this.destroyed$)))}get mediaTrackEnded$(){return this.cachedObservable("mediaTrackEnded$",()=>this.localStreamController.mediaTrackEnded$.pipe(v(this.destroyed$)))}get errors$(){return this.cachedObservable("errors$",()=>this._errors$.asObservable().pipe(v(this.destroyed$)))}get iceCandidates$(){return this.cachedObservable("iceCandidates$",()=>this._iceCandidates$.asObservable().pipe(v(this.destroyed$)))}get initialized$(){return this.cachedObservable("initialized$",()=>this._initialized$.asObservable().pipe(C(e=>e),v(this.destroyed$)))}get remoteDescription$(){return this.cachedObservable("remoteDescription$",()=>this._remoteDescription$.asObservable().pipe(v(this.destroyed$)))}get localStream$(){return this.cachedObservable("localStream$",()=>this.localStreamController.localStream$.pipe(v(this.destroyed$)))}get remoteStream$(){return this.cachedObservable("remoteStream$",()=>this._remoteStream$.asObservable().pipe(v(this.destroyed$)))}get localAudioTracks$(){return this.cachedObservable("localAudioTracks$",()=>this.localStreamController.localAudioTracks$.pipe(v(this.destroyed$)))}get localVideoTracks$(){return this.cachedObservable("localVideoTracks$",()=>this.localStreamController.localVideoTracks$.pipe(v(this.destroyed$)))}get iceConnectionState$(){return this.cachedObservable("iceConnectionState$",()=>this._iceConnectionState$.asObservable().pipe(v(this.destroyed$)))}get connectionState$(){return this.cachedObservable("connectionState$",()=>this._connectionState$.asObservable().pipe(v(this.destroyed$)))}get signalingState$(){return this.cachedObservable("signalingState$",()=>this._signalingState$.asObservable().pipe(v(this.destroyed$)))}get type(){return this._type}get propose(){return this.options.propose??"main"}get isAdditionalDevice(){return this.propose==="additional-device"}get isMainDevice(){return this.propose==="main"}get isScreenShare(){return this.propose==="screenshare"}get iceServers(){if(!this.options.disableUdpIceServers)return this.options.iceServers??[];const e="transport=tcp";return(this.options.iceServers??[]).map(t=>{const i=Array.isArray(t.urls)?t.urls:[t.urls];return{...t,urls:i.filter(r=>r.includes(e))}})}get rtcConfiguration(){const{iceServers:e,...t}=this.options;return{bundlePolicy:"max-compat",iceCandidatePoolSize:10,iceServers:this.iceServers,iceTransportPolicy:this.options.relayOnly?"relay":"all",sdpSemantics:"unified-plan",...t}}get receiveVideo(){return!!this.options.receiveVideo}get receiveAudio(){return!!this.options.receiveAudio}get localStream(){return this.localStreamController.localStream}get remoteStream(){return this._remoteStream$.value}get inputAudioDeviceConstraints(){if(this.options.audio===!1&&!this.options.inputAudioDeviceConstraints)return!1;const e=this.deviceController.selectedAudioInputDeviceConstraints;return e===!1?!1:{...typeof this.options.inputAudioDeviceConstraints=="object"?this.options.inputAudioDeviceConstraints:{},...typeof e=="object"?e:{}}}get inputVideoDeviceConstraints(){if(!this.options.video&&!this.options.inputVideoDeviceConstraints)return!1;const e=this.deviceController.selectedVideoInputDeviceConstraints;return e===!1?!1:{...typeof this.options.inputVideoDeviceConstraints=="object"?this.options.inputVideoDeviceConstraints:{},...typeof e=="object"?e:{}}}get WebRTCPeerConnectionConstructor(){var e;return((e=this.options.webRTCApiProvider)==null?void 0:e.RTCPeerConnection)??RTCPeerConnection}get offerOptions(){const e={iceRestart:this.firstSDPExchangeCompleted?!0:void 0};switch(this.propose){case"screenshare":case"additional-device":return{...e,offerToReceiveAudio:!1,offerToReceiveVideo:!1};case"main":default:return{...e,offerToReceiveAudio:!0,offerToReceiveVideo:this.options.receiveVideo??!!this.inputVideoDeviceConstraints}}}get answerOptions(){return{iceRestart:this.firstSDPExchangeCompleted?!0:void 0}}async init(){return this.initPromise??(this.initPromise=this.doInit()),this.initPromise}async doInit(){try{this.setupPeerConnection(),this.subscribeTo(this.negotiationNeeded$.pipe(Ta(0),Bi(async()=>this.startNegotiation())),{next:()=>{S.debug("[RTCPeerConnectionController] Start Negotiation completed successfully")},error:e=>{S.error("[RTCPeerConnectionController] Start Negotiation error:",e),this._errors$.next(ke(e))}}),this.subscribeTo(vt(this.deviceController.selectedAudioInputDevice$.pipe(f(e=>["audio",e])),this.deviceController.selectedVideoInputDevice$.pipe(f(e=>["video",e]))).pipe(xa(()=>!this.localStreamController.localStream)),async([e,t])=>{S.debug("[RTCPeerConnectionController] Selected input device changed for:",{kind:e,deviceInfo:t}),await this.updateSelectedInputDevice(e,t)}),this.type==="answer"&&this.sdpInit?(await this.setupRemoteTracks(),this._initialized$.next(!0),this.setupEventListeners(),this._isNegotiating$.next(!0),await this._setRemoteDescription(this.sdpInit)):(await this.setupTrackHandling(),this._initialized$.next(!0))}catch(e){S.error("[RTCPeerConnectionController] Initialization error:",e),this._errors$.next(ke(e)),this.destroy()}}setupPeerConnection(){this.peerConnection=new this.WebRTCPeerConnectionConstructor(this.rtcConfiguration),this.peerConnection.addEventListener("negotiationneeded",this.onnegotiationneededHandler),this._iceGatheringController=new Wd(this.peerConnection,this.isNegotiating$,{iceCandidateTimeout:this.options.iceCandidateTimeout,iceGatheringTimeout:this.options.iceGatheringTimeout,relayOnly:this.options.relayOnly}),this.transceiverController=new Kd({peerConnection:this.peerConnection,propose:this.propose,simulcast:this.options.simulcast,sfu:this.options.sfu,msStreamsNumber:this.options.msStreamsNumber,receiveAudio:this.receiveAudio,receiveVideo:this.receiveVideo,localStreamController:this.localStreamController,getInputAudioDeviceConstraints:()=>this.inputAudioDeviceConstraints,getInputVideoDeviceConstraints:()=>this.inputVideoDeviceConstraints,getUserMedia:async e=>this.getUserMedia(e),onError:e=>{this._errors$.next(e)}})}async startNegotiation(){if(this.isNegotiating){S.debug("[RTCPeerConnectionController] Negotiation already in progress, skipping.");return}if(this.setupEventListeners(),this.type==="answer"){S.debug("[RTCPeerConnectionController] This is an answer type still, skipping offer creation.");return}this._isNegotiating$.next(!0),S.debug("[RTCPeerConnectionController] Starting negotiation.");try{const{offerOptions:e}=this;S.debug("[RTCPeerConnectionController] Creating offer with options:",e),await this.createOffer(e)}catch(e){S.error("[RTCPeerConnectionController] Error during negotiation:",e),this._errors$.next(ke(e))}}async createOffer(e){if(!this.peerConnection)throw new R("RTCPeerConnection is not initialized");const t=await this.peerConnection.createOffer(e);await this.setLocalDescription(t)}async updateAnswerStatus({status:e,sdp:t}){let i=e!=="failed";try{e==="received"&&t&&(S.debug("[RTCPeerConnectionController] Received answer SDP:",t),await this._setRemoteDescription({type:"answer",sdp:t}))}catch(r){S.error("[RTCPeerConnectionController] Error updating answer status:",r),this._errors$.next(ke(r)),i=!1}finally{i?this.readyToConnect():this.iceGatheringController.restartICEGatheringWithRelayOnly()}}async updateOfferStatus({status:e,sdp:t}){switch(e){case"received":this._type="answer",this.sdpInit={type:"offer",sdp:t},await this.handleOfferReceived();break;case"failed":S.error("[RTCPeerConnectionController] Offer failed to be processed by remote.");break}}async acceptInbound(e){var i;if(e){const{audio:r,video:s,receiveAudio:n,receiveVideo:o}=e;this.options={...this.options,...r!==void 0?{audio:r}:{},...s!==void 0?{video:s}:{},...n!==void 0?{receiveAudio:n}:{},...o!==void 0?{receiveVideo:o}:{}},(i=this.transceiverController)==null||i.updateOptions({receiveAudio:this.receiveAudio,receiveVideo:this.receiveVideo}),this.localStreamController.updateOptions({inputAudioDeviceConstraints:this.inputAudioDeviceConstraints,inputVideoDeviceConstraints:this.inputVideoDeviceConstraints})}await this.setupLocalTracks();const{answerOptions:t}=this;S.debug("[RTCPeerConnectionController] Creating inbound answer with options:",t),await this.createAnswer(t)}async handleOfferReceived(){if(!this.sdpInit)throw new R("SDP initialization parameters are not set");this._isNegotiating$.next(!0),await this._setRemoteDescription(this.sdpInit);const{answerOptions:e}=this;S.debug("[RTCPeerConnectionController] Creating answer with options:",e),await this.createAnswer(e)}readyToConnect(){this.firstSDPExchangeCompleted=!0,this.connectionTimer=setTimeout(()=>{var e;this.removeConnectionTimer(),((e=this.peerConnection)==null?void 0:e.connectionState)!=="connected"&&(S.debug("[RTCPeerConnectionController] Connection timeout, restarting ICE gathering with relay only."),this.iceGatheringController.restartICEGatheringWithRelayOnly())},this.connectionTimeout)}async setRemoteDescriptionBefore(e=""){return Promise.resolve(e)}async setLocalDescription(e){var i;const t=await this.setLocalDescriptionBefore(e.sdp);return(i=this.peerConnection)==null?void 0:i.setLocalDescription({...e,sdp:t})}async setLocalDescriptionBefore(e=""){let t=e;const i=this.options.preferredAudioCodecs??d.instance.preferredAudioCodecs,r=this.options.preferredVideoCodecs??d.instance.preferredVideoCodecs,s=this.options.stereo??d.instance.stereoAudio;return(i.length>0||r.length>0)&&(t=zd(t,i,r),S.debug("[RTCPeerConnectionController] Applied codec preferences to SDP",{preferredAudioCodecs:i,preferredVideoCodecs:r})),s&&(t=Ud(t),S.debug("[RTCPeerConnectionController] Applied stereo Opus to SDP")),Promise.resolve(t)}async createAnswer(e){if(!this.peerConnection)throw new R("RTCPeerConnection is not initialized");const t=await this.peerConnection.createAnswer(e);await this.setLocalDescription(t)}setupEventListeners(){if(!this.peerConnection)throw new R("RTCPeerConnection is not initialized");this._iceConnectionState$.next(this.peerConnection.iceConnectionState),this._connectionState$.next(this.peerConnection.connectionState),this._signalingState$.next(this.peerConnection.signalingState),this._iceGatheringState$.next(this.peerConnection.iceGatheringState),this._remoteDescription$.next(this.peerConnection.remoteDescription),this.peerConnection.removeEventListener("icegatheringstatechange",this.onicegatheringstatechangeHandler),this.peerConnection.addEventListener("icegatheringstatechange",this.onicegatheringstatechangeHandler),this.peerConnection.removeEventListener("iceconnectionstatechange",this.oniceconnectionstatechangeHandler),this.peerConnection.addEventListener("iceconnectionstatechange",this.oniceconnectionstatechangeHandler),this.peerConnection.removeEventListener("connectionstatechange",this.onconnectionstatechangeHandler),this.peerConnection.addEventListener("connectionstatechange",this.onconnectionstatechangeHandler),this.peerConnection.removeEventListener("signalingstatechange",this.onsignalingstatechangeHandler),this.peerConnection.addEventListener("signalingstatechange",this.onsignalingstatechangeHandler)}negotiationEnded(){this._isNegotiating$.next(!1)}async triggerIceRestart(e){if(!this.peerConnection)throw new R("RTCPeerConnection is not initialized");const t=e&&!this.options.relayOnly;if(t)try{this.peerConnection.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:"relay"}),S.debug("[RTCPeerConnectionController] ICE transport policy set to relay-only")}catch(i){S.warn("[RTCPeerConnectionController] Failed to set relay-only policy:",i)}this.setupEventListeners(),this._isNegotiating$.next(!0),S.debug(`[RTCPeerConnectionController] Triggering ICE restart${e?" (relay-only)":""}.`);try{const i=await this.peerConnection.createOffer({iceRestart:!0});await this.setLocalDescription(i)}catch(i){throw S.error("[RTCPeerConnectionController] ICE restart offer failed:",i),this._errors$.next(ke(i)),this.negotiationEnded(),t&&this.restoreIceTransportPolicy(),i}t&&ae(Lt(this._iceGatheringState$.pipe(C(i=>i==="complete"),te(1)),pt(ll).pipe(f(()=>"timeout")))).then(()=>this.restoreIceTransportPolicy()).catch(i=>{S.warn("[RTCPeerConnectionController] Error waiting for ICE gathering to complete:",i),this.restoreIceTransportPolicy()})}restoreIceTransportPolicy(){var e;try{(e=this.peerConnection)==null||e.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:this.options.relayOnly?"relay":"all"}),S.debug("[RTCPeerConnectionController] ICE transport policy restored")}catch(t){S.warn("[RTCPeerConnectionController] Failed to restore ICE transport policy:",t)}}async setupTrackHandling(){if(!this.peerConnection)throw new R("RTCPeerConnection is not initialized");await this.setupLocalTracks(),await this.setupRemoteTracks()}async setupLocalTracks(){var t,i,r,s,n,o,a;S.debug("[RTCPeerConnectionController] Setting up local tracks/transceivers.");const e=this.localStream??await this.localStreamController.buildLocalStream();if(((t=this.transceiverController)==null?void 0:t.useAddStream)??!1){S.warn("[RTCPeerConnectionController] Using deprecated addStream API to add local stream."),(i=this.peerConnection)==null||i.addStream(e),this.isNegotiating||(S.debug("[RTCPeerConnectionController] Forcing negotiationneeded after local tracks setup."),this.negotiationNeeded$.next());return}for(const c of["audio","video"]){const l=(c==="audio"?e.getAudioTracks():e.getVideoTracks()).map((h,p)=>({index:p,track:h}));for(const{index:h,track:p}of l)if(this.localStreamController.addTrackEndedListener(p),((r=this.transceiverController)==null?void 0:r.useAddTransceivers)??!1){const b=(c==="audio"?(s=this.transceiverController)==null?void 0:s.audioTransceivers:(n=this.transceiverController)==null?void 0:n.videoTransceivers)??[];await((o=this.transceiverController)==null?void 0:o.setupTransceiverSender(p,e,b[h]))}else S.debug(`[RTCPeerConnectionController] Using addTrack for local ${c} track:`,p.id),(a=this.peerConnection)==null||a.addTrack(p,e)}}async getUserMedia(e){var t;return(((t=this.options.webRTCApiProvider)==null?void 0:t.mediaDevices)??navigator.mediaDevices).getUserMedia(e)}async getDisplayMedia(e){var i;const t=((i=this.options.webRTCApiProvider)==null?void 0:i.mediaDevices)??navigator.mediaDevices;if(!t.getDisplayMedia)throw new R("getDisplayMedia is not supported by the current WebRTC provider");return t.getDisplayMedia(e)}async setupRemoteTracks(){var e;if(!this.peerConnection)throw new R("RTCPeerConnection is not initialized");this.peerConnection.ontrack=t=>{var i;if(S.debug("[RTCPeerConnectionController] Remote track received:",t.track.kind),t.streams[0])this._remoteStream$.next(t.streams[0]);else{const r=((i=this._remoteStream$.value)==null?void 0:i.getTracks())??[],s=new MediaStream([...r,t.track]);this._remoteStream$.next(s)}},await((e=this.transceiverController)==null?void 0:e.setupRemoteTransceivers(this.type))}async restoreTrackSender(e){var t;await((t=this.transceiverController)==null?void 0:t.restoreTrackSender(e)),e!=="video"&&this._localAudioPipeline&&await this.applyLocalAudioPipelineToSender()}ensureLocalAudioPipeline(){if(this._localAudioPipeline)return this._localAudioPipeline;if(!this.peerConnection)return null;try{this._localAudioPipeline=new Gd}catch(e){return S.warn("[RTCPeerConnectionController] Failed to create LocalAudioPipeline:",e),null}return this.subscribeTo(this.localStreamController.localAudioTracks$,()=>{this.applyLocalAudioPipelineToSender()}),this.applyLocalAudioPipelineToSender(),this._localAudioPipeline}get localAudioPipeline(){return this._localAudioPipeline}async applyLocalAudioPipelineToSender(){var r;if(!this._localAudioPipeline||!this.peerConnection)return;const[e]=this.localStreamController.localAudioTracks;this._localAudioPipeline.setInputTrack(e??null);const[t]=((r=this.transceiverController)==null?void 0:r.audioTransceivers)??[],i=(t==null?void 0:t.sender)??this.peerConnection.getSenders().find(s=>{var n;return((n=s.track)==null?void 0:n.kind)==="audio"});if(!(!i||!e))try{await i.replaceTrack(this._localAudioPipeline.outputTrack)}catch(s){S.warn("[RTCPeerConnectionController] Failed to route audio sender through pipeline:",s)}}addLocalTrack(e){if(!this.peerConnection){const t=new R("RTCPeerConnection is not initialized");throw this._errors$.next(t),t}try{const t=this.localStreamController.addTrack(e);this.peerConnection.addTrack(e,t),S.debug(`[RTCPeerConnectionController] ${e.kind} track added:`,e.id)}catch(t){throw S.error(`[RTCPeerConnectionController] Failed to add ${e.kind} track:`,t),this._errors$.next(ke(t)),t}}removeLocalTrack(e){var i,r;if(!this.peerConnection){const s=new R("RTCPeerConnection is not initialized");throw this._errors$.next(s),s}const t=this.peerConnection.getSenders().find(s=>{var n;return((n=s.track)==null?void 0:n.id)===e});if(!t){S.debug(`[RTCPeerConnectionController] track not found: ${e}`);return}try{this.peerConnection.removeTrack(t),this.localStreamController.removeTrack(e),S.debug(`[RTCPeerConnectionController] ${(i=t.track)==null?void 0:i.kind} track removed:`,e)}catch(s){throw S.error(`[RTCPeerConnectionController] Failed to remove ${(r=t.track)==null?void 0:r.kind} track:`,s),this._errors$.next(ke(s)),s}}setLocalTrack(e){const t=[...e.kind==="audio"?this.localStreamController.localAudioTracks:this.localStreamController.localVideoTracks];for(const i of t)this.removeLocalTrack(i.id);this.addLocalTrack(e)}async updateSendersConstraints(e,t){var i;await((i=this.transceiverController)==null?void 0:i.updateSendersConstraints(e,t))}async replaceAudioTrackWithConstraints(e){var i;const t=(i=this.peerConnection)==null?void 0:i.getSenders().filter(r=>{var s;return((s=r.track)==null?void 0:s.kind)==="audio"&&r.track.readyState==="live"});if(!t||t.length===0){S.warn("[RTCPeerConnectionController] No live audio sender to replace");return}for(const r of t){const s=r.track;if(!s)continue;const{deviceId:n}=s.getSettings(),o={...s.getConstraints(),...e,...n?{deviceId:{exact:n}}:{}},a=s.id;s.stop(),this.localStreamController.removeTrack(a);const c=(await this.getUserMedia({audio:o})).getAudioTracks()[0];await r.replaceTrack(c),this.localStreamController.addTrack(c),S.debug(`[RTCPeerConnectionController] Audio track replaced for server-pushed params. New track: ${c.id}`)}}destroy(){var e,t,i;S.debug(`[RTCPeerConnectionController] Destroying RTCPeerConnectionController. ${this.propose}`),this.removeConnectionTimer(),(e=this._iceGatheringController)==null||e.destroy(),(t=this._localAudioPipeline)==null||t.destroy(),this._localAudioPipeline=null,this.localStreamController.destroy(),(i=this.transceiverController)==null||i.destroy(),this.peerConnection&&(this.stopRemoteTracks(),this.removeAllListeners(),this.peerConnection.close(),this.peerConnection=void 0),super.destroy()}removeAllListeners(){this.peerConnection&&(this.peerConnection.removeEventListener("icegatheringstatechange",this.onicegatheringstatechangeHandler),this.peerConnection.removeEventListener("iceconnectionstatechange",this.oniceconnectionstatechangeHandler),this.peerConnection.removeEventListener("connectionstatechange",this.onconnectionstatechangeHandler),this.peerConnection.removeEventListener("signalingstatechange",this.onsignalingstatechangeHandler),this.peerConnection.removeEventListener("negotiationneeded",this.onnegotiationneededHandler))}stopRemoteTracks(){var e;(e=this._remoteStream$.value)==null||e.getTracks().forEach(t=>{S.debug(`[RTCPeerConnectionController] Stopping remote track: ${t.kind}`),t.stop()})}get mediaDirections(){var e;return((e=this.transceiverController)==null?void 0:e.getMediaDirections())??this._remoteOfferMediaDirections??{audio:"inactive",video:"inactive"}}async _setRemoteDescription(e){if(!this.peerConnection)throw new R("RTCPeerConnection is not initialized");const t=await this.setRemoteDescriptionBefore(e.sdp),i={...e,sdp:t};return S.debug("[RTCPeerConnectionController] Setting remote description:",i),this.peerConnection.setRemoteDescription(i)}};function tr(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"id")}function wn(e){if(!tr(e))return!1;const t=e;return t.method==="verto.invite"&&K(t.params)&&M(t.params,"sdp")&&M(t.params,"callID")}function ir(e){return tr(e)?e.method==="verto.bye":!1}function Cn(e){return tr(e)?e.method==="verto.attach":!1}function Jd(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"method")&&e.method==="verto.answer"&&K(e.params)&&M(e.params,"callID")}function Yd(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"method")&&e.method==="verto.media"&&K(e.params)&&M(e.params,"callID")&&M(e.params,"sdp")}function Xd(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"method")&&e.method==="verto.mediaParams"&&K(e.params)&&M(e.params,"mediaParams")}function Qd(e){return K(e)&&M(e,"jsonrpc")&&e.jsonrpc==="2.0"&&M(e,"method")&&e.method==="verto.ping"}const $=D();function Zd(e){return e.isInvite&&!e.reattach&&!e.explicitNodeId?"":e.currentNodeId??""}var eu=class extends P{constructor(e){super(),this.callSession=e}destroy(){this.callSession=void 0,super.destroy()}},tu=class extends eu{constructor(e,t,i,r,s={}){super(e),this.webRtcCallSession=e,this.attachManager=t,this.deviceController=i,this.webRTCApiProvider=r,this._rtcPeerConnections$=this.createBehaviorSubject([]),this._selfId$=this.createBehaviorSubject(null),this._signalingStatus$=this.createReplaySubject(1),this._screenShareStatus$=this.createBehaviorSubject("none"),this._rtcPeerConnectionsMap=new Map,this._screenShareTimeoutMs=5e4,this._nodeId$=this.createBehaviorSubject(s.nodeId??null),this.onError=s.onError,this.onModifyFailed=s.onModifyFailed,this.initSubscriptions(),this.initMainPeerConnection()}async hold(){const e=ui({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},action:"hold"});try{await this.executeVerto(e)}catch(t){throw $.warn("[WebRTCManager] Call might already be disconnected, error sending Verto hold:",t),t}}async unhold(){const e=ui({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},action:"unhold"});try{await this.executeVerto(e)}catch(t){throw $.warn("[WebRTCManager] Call might already be disconnected, error sending Verto unhold:",t),t}}get mediaDirections(){return this.mainPeerConnection.mediaDirections}get rtcPeerConnections$(){return this._rtcPeerConnections$.asObservable()}get rtcPeerConnections(){return this._rtcPeerConnections$.value}get nodeId$(){return this._nodeId$.asObservable()}get selfId$(){return this._selfId$.asObservable()}get localStream(){var e;return((e=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id))==null?void 0:e.localStream)??null}get remoteStream(){var e;return((e=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id))==null?void 0:e.remoteStream)??null}get nodeId(){return this._nodeId$.value}get screenShareStatus(){return this._screenShareStatus$.value}get screenShareStatus$(){return this._screenShareStatus$.asObservable()}get mainPeerConnection(){const e=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id);if(!e)throw new R("Main peer connection not found");return e}get signalingStatus$(){return this.cachedObservable("signalingStatus$",()=>vt(this._signalingStatus$.asObservable(),this.mainPeerConnection.connectionState$.pipe(C(e=>["connected","disconnected","failed"].includes(e)))))}initSubscriptions(){this.subscribeTo(this.callJoinedEvent$,e=>{var i;const t=(i=e.room_session.members.find(r=>r.call_id===e.call_id))==null?void 0:i.node_id;t&&this.setNodeIdIfNull(t),e.member_id&&this.setSelfIdIfNull(e.member_id)}),this.subscribeTo(this.vertoMedia$,e=>{var r;$.debug("[WebRTCManager] Received Verto media event (early media SDP):",e),this._signalingStatus$.next("ringing");const{sdp:t,callID:i}=e;(r=this._rtcPeerConnectionsMap.get(i))==null||r.updateAnswerStatus({status:"received",sdp:t})}),this.subscribeTo(this.vertoAnswer$,e=>{var r;$.debug("[WebRTCManager] Received Verto answer event:",e),this._signalingStatus$.next("connecting");const{sdp:t,callID:i}=e;(r=this._rtcPeerConnectionsMap.get(i))==null||r.updateAnswerStatus({status:"received",sdp:t})}),this.subscribeTo(this.vertoMediaParams$,e=>{$.debug("[WebRTCManager] Received Verto mediaParams event:",e);const{mediaParams:t,callID:i}=e,r=this._rtcPeerConnectionsMap.get(i),{audio:s,video:n}=t;(async()=>{var o;try{s&&r&&await r.replaceAudioTrackWithConstraints(s),n&&await(r==null?void 0:r.updateSendersConstraints("video",n)),this.webRtcCallSession.emitMediaParamsUpdated({audio:s,video:n,timestamp:Date.now()})}catch(a){$.warn("[WebRTCManager] Error applying server-pushed media params:",a),(o=this.onError)==null||o.call(this,a instanceof Error?a:new Error(String(a),{cause:a}))}})()}),this.subscribeTo(this.vertoPing$,e=>{this.attachManager.attach(this.buildAttachableCall()),this.sendVertoPong(e)})}setNodeIdIfNull(e){!this._nodeId$.value&&e&&($.debug(`[WebRTCManager] Early node_id set: ${e}`),this._nodeId$.next(e))}setSelfIdIfNull(e){!this._selfId$.value&&e&&($.debug(`[WebRTCManager] Early selfId set: ${e}`),this._selfId$.next(e))}async sendVertoPong(e){var t;try{const i=bd({...e});await this.executeVerto(i)}catch(i){$.warn("[WebRTCManager] Call might disconnect, error sending Verto pong:",i),(t=this.onError)==null||t.call(this,new _s(i))}}async updateMediaConstraints(e={}){var r;const{audio:t,video:i}=e;try{t&&await this.mainPeerConnection.updateSendersConstraints("audio",t),i&&await this.mainPeerConnection.updateSendersConstraints("video",i)}catch(s){throw $.warn("[WebRTCManager] Error updating media constraints:",s),(r=this.onError)==null||r.call(this,s instanceof Error?s:new Error(String(s),{cause:s})),s}}get selfId(){return this._selfId$.value}buildAttachableCall(e){return{nodeId:this.nodeId??void 0,id:e??this.webRtcCallSession.id,to:this.webRtcCallSession.to,mediaDirections:this.webRtcCallSession.mediaDirections}}requestKeyframe(){try{const e=this.mainPeerConnection.peerConnection;if(!e){$.warn("[WebRTCManager] No peer connection for keyframe request");return}const t=e.getReceivers().find(i=>i.track.kind==="video");if(!t){$.warn("[WebRTCManager] No video receiver for keyframe request");return}typeof t.requestKeyFrame=="function"?(t.requestKeyFrame(),$.debug("[WebRTCManager] Keyframe requested via RTCRtpReceiver.requestKeyFrame()")):$.debug("[WebRTCManager] requestKeyFrame() not supported, skipping")}catch(e){$.warn("[WebRTCManager] Keyframe request failed (non-fatal):",e)}}async requestIceRestart(e){try{const t=this.mainPeerConnection;if(!t.peerConnection){$.warn("[WebRTCManager] No peer connection for ICE restart");return}await t.triggerIceRestart(e),$.info(`[WebRTCManager] ICE restart initiated${e?" (relay-only)":""}`)}catch(t){throw $.error("[WebRTCManager] ICE restart failed:",t),t}}async requestIceRestartAll(e){const t=Array.from(this._rtcPeerConnectionsMap.entries());for(const[i,r]of t)try{if(!r.peerConnection){$.debug(`[WebRTCManager] No peer connection for leg ${i}, skipping ICE restart`);continue}await r.triggerIceRestart(e),$.info(`[WebRTCManager] ICE restart initiated for leg ${i}${e?" (relay-only)":""}`)}catch(s){$.warn(`[WebRTCManager] ICE restart failed for leg ${i}:`,s)}}requestKeyframeAll(){for(const[e,t]of this._rtcPeerConnectionsMap){if(t.isScreenShare){$.debug(`[WebRTCManager] Skipping keyframe for send-only screen share leg ${e}`);continue}try{const i=t.peerConnection;if(!i)continue;const r=i.getReceivers().find(s=>s.track.kind==="video");if(!r)continue;typeof r.requestKeyFrame=="function"&&(r.requestKeyFrame(),$.debug(`[WebRTCManager] Keyframe requested for leg ${e}`))}catch(i){$.warn(`[WebRTCManager] Keyframe request failed for leg ${e} (non-fatal):`,i)}}}get callJoinedEvent$(){return this.webRtcCallSession.callEvent$.pipe(C(gn),v(this.destroyed$))}get vertoMedia$(){return this.webRtcCallSession.webrtcMessages$.pipe(F(Yd,"params"),v(this.destroyed$))}get vertoAnswer$(){return this.cachedObservable("vertoAnswer$",()=>this.webRtcCallSession.webrtcMessages$.pipe(F(Jd,"params"),v(this.destroyed$)))}get vertoMediaParams$(){return this.cachedObservable("vertoMediaParams$",()=>this.webRtcCallSession.webrtcMessages$.pipe(F(Xd,"params"),v(this.destroyed$)))}get vertoBye$(){return this.cachedObservable("vertoBye$",()=>this.webRtcCallSession.webrtcMessages$.pipe(F(ir,"params"),v(this.destroyed$)))}get vertoAttach$(){return this.cachedObservable("vertoAttach$",()=>this.webRtcCallSession.webrtcMessages$.pipe(F(Cn,"params"),v(this.destroyed$)))}get vertoPing$(){return this.cachedObservable("vertoPing$",()=>this.webRtcCallSession.webrtcMessages$.pipe(F(Qd,"params"),v(this.destroyed$)))}async executeVerto(e,t={}){var n,o;const i=Zs({callID:t.callID??this.webRtcCallSession.id,node_id:t.node_id??this._nodeId$.value??"",message:e,subscribe:t.subscribe}),r=await this.webRtcCallSession.execute(i);if(r.error){const a=new xe(r.error.code,r.error.message,r.error.data);return(n=this.onError)==null||n.call(this,a),r}const s=ve(r,"result.result");if(s!=null&&s.error){const a=new xe(s.error.code,s.error.message,s.error.data);return(o=this.onError)==null||o.call(this,a),r}return r}async sendLocalDescription(e,t){var s,n;const i=e.method,r=this.getSendLocalSDPOptionalParams(t,e);try{const o=await this.executeVerto(e,r);switch(i){case"verto.invite":this.processInviteResponse(o,t);break;case"verto.modify":await this.processModifyResponse(o,t);break;default:}}catch(o){$.error(`[WebRTCManager] Error sending Verto ${i}:`,o),(s=this.onError)==null||s.call(this,o instanceof Error?o:new Error(String(o),{cause:o})),i==="verto.modify"&&((n=this.onModifyFailed)==null||n.call(this))}}async processModifyResponse(e,t){var i;if(!e.error){const r=ve(e,"result.result.result.action"),s=ve(e,"result.result.result.sdp");if(r==="updateMedia"&&s)try{await t.updateAnswerStatus({status:"received",sdp:s})}catch(n){$.warn("[WebRTCManager] Error processing modify response:",n);const o=n instanceof Error?n:new Error(String(n),{cause:n});(i=this.onError)==null||i.call(this,o)}}}processInviteResponse(e,t){var i;if(!e.error&&ve(e,"result.result.result.message")==="CALL CREATED"){this._signalingStatus$.next("trying"),this._nodeId$.next(ve(e,"result.node_id")??null);const r=ve(e,"result.result.result.memberID")??null,s=ve(e,"result.result.result.callID")??null;$.debug("[WebRTCManager] Verto invite response:",{callId:s,memberId:r,response:e}),this._selfId$.next(r),t.setMemberId(r),s?(this.webRtcCallSession.addCallId(s),this.attachManager.attach(this.buildAttachableCall(s))):$.warn("[WebRTCManager] Cannot attach call, missing callId:",{nodeId:this.nodeId,callId:s}),$.info("[WebRTCManager] Verto invite successful"),$.debug(`[WebRTCManager] nodeid: ${this._nodeId$.value}, selfId: ${this._selfId$.value}`)}else{$.error("[WebRTCManager] Verto invite failed:",e);const r=e.error?new xe(e.error.code,e.error.message,e.error.data):new Error("Verto invite failed: unexpected response");(i=this.onError)==null||i.call(this,r)}}get RTCPeerConnectionConfig(){return{iceServers:this.webRtcCallSession.clientSession.iceServers??d.instance.iceServers,relayOnly:d.instance.relayOnly||d.instance.disableUdpIceServers,disableUdpIceServers:d.instance.disableUdpIceServers,iceCandidateTimeout:d.instance.iceCandidateTimeout,iceGatheringTimeout:d.instance.iceGatheringTimeout}}initMainPeerConnection(){const{options:e}=this.webRtcCallSession,t=new _n({propose:"main",callId:this.webRtcCallSession.id,audio:e.audio,video:e.video,inputAudioDeviceConstraints:e.inputAudioDeviceConstraints,inputVideoDeviceConstraints:e.inputVideoDeviceConstraints,inputAudioStream:e.inputAudioStream,inputVideoStream:e.inputVideoStream,receiveAudio:e.receiveAudio,receiveVideo:e.receiveVideo,webRTCApiProvider:this.webRTCApiProvider,preferredVideoCodecs:e.preferredVideoCodecs,preferredAudioCodecs:e.preferredAudioCodecs,stereo:e.stereo,...this.RTCPeerConnectionConfig},e.initOffer,this.deviceController);this.setupLocalDescriptionHandler(t),this.setupVertoByeHandler(),this.setupVertoAttachHandler(),this.initObservables(t),this._rtcPeerConnectionsMap.set(t.id,t),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values())),this.subscribeTo(t.errors$,i=>{var r;(r=this.onError)==null||r.call(this,i)}),e.initOffer&&this.handleInboundAnswer(t)}async handleInboundAnswer(e){var i,r,s;$.debug("[WebRTCManager] Waiting for inbound call to be accepted or rejected");const t=await ae(Lt(this.vertoBye$,this.webRtcCallSession.answered$).pipe(v(this.destroyed$))).catch(()=>null);if(t===null){$.debug("[WebRTCManager] Inbound answer handler aborted (destroyed).");return}if(ir(t))$.info("[WebRTCManager] Inbound call ended by remote before answer."),(i=this.callSession)==null||i.destroy();else if(t){$.debug("[WebRTCManager] Inbound call accepted, creating SDP answer");const n=this.webRtcCallSession.answerMediaOptions;try{await e.acceptInbound(n)}catch(o){$.error("[WebRTCManager] Error creating inbound answer:",o),(s=this.onError)==null||s.call(this,o instanceof Error?o:new Error(String(o),{cause:o}))}}else{$.info("[WebRTCManager] Inbound call rejected by user.");try{await this.bye("USER_BUSY")}finally{this._signalingStatus$.next("disconnected"),(r=this.callSession)==null||r.destroy()}}}setupVertoAttachHandler(){this.subscribeTo(this.vertoAttach$,async e=>{$.debug("[WebRTCManager] Received Verto attach event for existing call:",e);const{callID:t}=e;await this.attachManager.attach({nodeId:this.nodeId??void 0,id:t,to:e.callee_id_number,mediaDirections:{audio:"sendrecv",video:"inactive"}})})}initObservables(e){this.mediaDirections$=e.connectionState$.pipe(C(t=>t==="connected"),f(()=>e.mediaDirections),Da(e.mediaDirections),v(this.destroyed$)),this.localStream$=e.localStream$.pipe(B(),v(this.destroyed$)),this.remoteStream$=e.remoteStream$.pipe(B(),v(this.destroyed$))}setupLocalDescriptionHandler(e){this.subscribeTo(e.localDescription$.pipe(C(t=>t!==null),v(this.destroyed$)),t=>{const{type:i,sdp:r}=t,s=this.dialogParams(e),n=!e.firstSDPExchangeCompleted;if(i==="answer"){const o=fd({dialogParams:s,sdp:r});this.sendLocalDescriptionOnceAccepted(o,e)}else if(n){const o=hd({dialogParams:s,sdp:r});this.sendLocalDescription(o,e)}else{const o=ui({dialogParams:s,sdp:r,action:"updateMedia"});this.sendLocalDescription(o,e)}})}setupVertoByeHandler(){this.subscribeTo(this.vertoBye$,()=>{var e;this._signalingStatus$.next("disconnected"),this.attachManager.detach(this.buildAttachableCall()),(e=this.callSession)==null||e.destroy()})}getSendLocalSDPOptionalParams(e,t){let i;return e.firstSDPExchangeCompleted||(i=[],e.isMainDevice?i.push(...d.instance.inviteSubscribeMainDevice):e.isAdditionalDevice?i.push(...d.instance.inviteSubscribeAdditionalDevice):e.isScreenShare&&i.push(...d.instance.inviteSubscribeScreenshare)),{callID:e.id,node_id:Zd({isInvite:wn(t),reattach:this.webRtcCallSession.options.reattach===!0,explicitNodeId:this.webRtcCallSession.options.nodeId,currentNodeId:this._nodeId$.value}),subscribe:i}}async sendLocalDescriptionOnceAccepted(e,t){var r,s,n;$.debug("[WebRTCManager] Waiting for call to be accepted or ended before sending answer");const i=await ae(Lt(this.vertoBye$,this.webRtcCallSession.answered$).pipe(v(this.destroyed$))).catch(()=>null);if(i===null){$.debug("[WebRTCManager] Destroyed while waiting for call acceptance");return}if(ir(i))$.info("[WebRTCManager] Call ended before answer was sent."),(r=this.callSession)==null||r.destroy();else if(i){$.debug("[WebRTCManager] Call accepted, sending answer");try{this._signalingStatus$.next("connecting"),await this.sendLocalDescription(e,t),await t.updateAnswerStatus({status:"sent"}),await this.attachManager.attach(this.buildAttachableCall())}catch(o){$.error("[WebRTCManager] Error sending Verto answer:",o),(n=this.onError)==null||n.call(this,o instanceof Error?o:new Error(String(o),{cause:o})),await t.updateAnswerStatus({status:"failed"})}}else{$.info("[WebRTCManager] Call was not accepted, sending verto.bye.");try{await this.bye("USER_BUSY")}finally{this._signalingStatus$.next("disconnected"),(s=this.callSession)==null||s.destroy()}}}dialogParams(e){const t=e.memberId??this._selfId$.value??void 0,i=e.propose==="main"&&!e.firstSDPExchangeCompleted&&this.webRtcCallSession.options.reattach;return{id:e.isMainDevice?this.webRtcCallSession.id:e.id,destinationNumber:this.webRtcCallSession.to??this.webRtcCallSession.from,attach:i,reattaching:i,callerName:this.webRtcCallSession.fromName,callerNumber:this.webRtcCallSession.from,remoteCallerName:this.webRtcCallSession.toName,remoteCallerNumber:this.webRtcCallSession.to,userVariables:{memberCallId:this.webRtcCallSession.id,memberId:t,...this.webRtcCallSession.userVariables},screenShare:e.isScreenShare,additionalDevice:e.isAdditionalDevice,pingSupported:!0,version:Ic}}muteMainAudioInputDevice(){return this.mainPeerConnection.stopTrackSender("audio")}muteMainVideoInputDevice(){return this.mainPeerConnection.stopTrackSender("video")}async unmuteMainAudioInputDevice(){return this.mainPeerConnection.restoreTrackSender("audio")}async unmuteMainVideoInputDevice(){return this.mainPeerConnection.restoreTrackSender("video")}ensureLocalAudioPipeline(){return this.mainPeerConnection.ensureLocalAudioPipeline()}get localAudioPipeline(){return this.mainPeerConnection.localAudioPipeline}async addInputDevice(e={audio:!1,video:!0}){return this.initAdditionalPeerConnection("additional-device",e)}async addMainInputDevices(e={audio:!0}){var r;let t;const{mediaDirections:i}=this.mainPeerConnection;if((e.audio??e.inputAudioDeviceConstraints??(e.inputAudioStream&&i.audio.startsWith("send")))&&(t="audio"),(e.video??e.inputVideoDeviceConstraints??(e.inputVideoStream&&!i.video.startsWith("send")))&&(t=t==="audio"?"both":"video"),t)this.mainPeerConnection.updateMediaDevicesOptions(e),await this.mainPeerConnection.restoreTrackSender(t);else{const s=new ms("No valid device to be added");throw(r=this.onError)==null||r.call(this,s),s}}async addScreenMedia(e={audio:!1}){await this.initAdditionalPeerConnection("screenshare",e)}async initAdditionalPeerConnection(e,t){var r;let i=null;try{return this._screenShareStatus$.next("starting"),i=new _n({...t,...this.RTCPeerConnectionConfig,propose:e,webRTCApiProvider:this.webRTCApiProvider},void 0,this.deviceController),this.setupLocalDescriptionHandler(i),e==="screenshare"&&(this._screenShareId=i.id),this._rtcPeerConnectionsMap.set(i.id,i),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values())),this.subscribeTo(i.errors$,s=>{var n;(n=this.onError)==null||n.call(this,s)}),await ae(i.connectionState$.pipe(C(s=>s==="connected"),te(1),Vt(this._screenShareTimeoutMs),v(this.destroyed$))),this._screenShareStatus$.next("started"),$.info("[WebRTCManager] Screen share started successfully."),i.id}catch(s){$.warn("[WebRTCManager] Error initializing additional peer connection:",s),(r=this.onError)==null||r.call(this,s instanceof Error?s:new Error(String(s),{cause:s})),i&&i.destroy(),this._screenShareStatus$.next("none")}}async removeInputDevices(e){return this.removeAdditionalPeerConnection(e)}removeMainInputDevice(e={removeAudio:!1,removeVideo:!0}){let t;if(e.removeAudio&&(t="audio"),e.removeVideo&&(t=t==="audio"?"both":"video"),t)return this.mainPeerConnection.stopTrackSender(t,{updateTransceiverDirection:!0})}async removeScreenMedia(){if(["starting","started"].includes(this._screenShareStatus$.value)||$.warn("[WebRTCManager] No active screen share to stop."),!this._screenShareId){$.debug("[WebRTCManager] No screen share peer connection found.");return}this._screenShareStatus$.next("stopping"),await this.removeAdditionalPeerConnection(this._screenShareId),this._screenShareId=void 0,this._screenShareStatus$.next("none")}async removeAdditionalPeerConnection(e){const t=this._rtcPeerConnectionsMap.get(e);try{t&&await this.executeVertoBye(t)}finally{t==null||t.destroy(),this._rtcPeerConnectionsMap.delete(e),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values()))}}async executeVertoBye(e,t){try{const i=t?{cause:t,causeCode:md[t]}:{};await this.executeVerto(pd({...i,dialogParams:this.dialogParams(e)}))}catch(i){throw $.warn("[WebRTCManager] Call might already be disconnected, error sending Verto bye:",i),i}}async bye(e){this.attachManager.detach(this.buildAttachableCall());const t=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id);t&&await this.executeVertoBye(t,e)}async sendDigits(e){const t=vd({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},dtmf:e});try{await this.executeVerto(t)}catch(i){throw $.warn("[WebRTCManager] Error sending DTMF digits:",i),i}}async transfer(e){const t=ui({...e,dialogParams:this.dialogParams(this.mainPeerConnection),action:"transfer"});try{$.debug("[WebRTCManager] Transferring call with options:",e),await this.executeVerto(t)}catch(i){throw $.error("[WebRTCManager] Error transferring call:",i),i}}destroy(){this._rtcPeerConnectionsMap.forEach(e=>{e.destroy()}),this._rtcPeerConnectionsMap.clear(),this._rtcPeerConnections$.complete(),super.destroy()}};const Sn=D();var iu=class extends P{constructor(e={}){super(),this._source=null,this._stream=null,this._audioContext=(e.audioContextFactory??(()=>new AudioContext))(),this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,this._analyser.smoothingTimeConstant=.3,this._analyserBuffer=new Uint8Array(new ArrayBuffer(this._analyser.fftSize)),this._pollIntervalMs=e.pollIntervalMs??Ls}get level$(){return this.deferEmission(Zt(this._pollIntervalMs,zr).pipe(f(()=>this.computeLevel())))}setStream(e){if(this._source){try{this._source.disconnect()}catch(t){Sn.debug("[RemoteAudioMeter] source disconnect warning:",t)}this._source=null,this._stream=null}!e||e.getAudioTracks().length===0||(this._stream=new MediaStream(e.getAudioTracks()),this._source=this._audioContext.createMediaStreamSource(this._stream))}destroy(){if(this._source){try{this._source.disconnect()}catch{}this._source=null}this._audioContext.close().catch(e=>{Sn.debug("[RemoteAudioMeter] audio context close warning:",e)}),super.destroy()}computeLevel(){if(!this._source)return 0;this._analyser.getByteTimeDomainData(this._analyserBuffer);let e=0;for(const t of this._analyserBuffer){const i=(t-128)/128;e+=i*i}return Math.sqrt(e/this._analyserBuffer.length)}};const Ut=D(),ru=1e3,su=10,nu=2e3,ou=3e3,au=3,cu=5,lu=5,du=10,uu=4,hu=30;function pu(e,t){const i=e+t;return i===0?0:e/i*100}function vu(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="inbound-rtp"}function fu(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="candidate-pair"}var gu=class extends P{constructor(e,t={}){super(),this.peerConnection=e,this.running=!1,this.lastAudioPacketsReceived=0,this.lastAudioPacketChangeTime=0,this.lastVideoPacketsReceived=0,this.lastVideoPacketChangeTime=0,this.lastRoundTripTime=0,this.lastAvailableOutgoingBitrate=void 0,this._sample$=this.createReplaySubject(1),this._baseline$=this.createBehaviorSubject({rtt:0,jitter:0,ready:!1}),this._networkIssues$=this.createBehaviorSubject([]),this._networkMetrics$=this.createBehaviorSubject([]),this.pollingIntervalMs=t.pollingIntervalMs??ru,this.baselineSampleCount=t.baselineSamples??su,this.noAudioPacketThresholdMs=t.noAudioPacketThresholdMs??nu,this.noVideoPacketThresholdMs=t.noVideoPacketThresholdMs??ou,this.rttSpikeWarningMultiplier=t.rttSpikeWarningMultiplier??au,this.rttSpikeCriticalMultiplier=t.rttSpikeCriticalMultiplier??cu,this.packetLossWarningPercent=t.packetLossWarningPercent??lu,this.packetLossCriticalPercent=t.packetLossCriticalPercent??du,this.jitterSpikeMultiplier=t.jitterSpikeMultiplier??uu,this.historyWindowSeconds=t.historyWindowSeconds??hu}get networkIssues$(){return this._networkIssues$.asObservable()}get networkIssues(){return[...this._networkIssues$.value]}get isNetworkHealthy$(){return this.cachedObservable("isNetworkHealthy$",()=>this._networkIssues$.pipe(f(e=>e.length===0),y(),v(this.destroyed$)))}get isNetworkHealthy(){return this._networkIssues$.value.length===0}get networkMetrics$(){return this._networkMetrics$.asObservable()}get networkMetrics(){return[...this._networkMetrics$.value]}get criticalIssue$(){return this.cachedObservable("criticalIssue$",()=>this._networkIssues$.pipe(Li(e=>Q(e.filter(t=>t.severity==="critical"))),v(this.destroyed$)))}get sample$(){return this._sample$.asObservable()}start(){if(this.running)return;this.running=!0;const e=Date.now();this.lastAudioPacketChangeTime=e,this.lastVideoPacketChangeTime=e,Ut.debug("[RTCStatsMonitor] Starting stats monitoring"),this.subscribeTo(Zt(this.pollingIntervalMs).pipe(C(()=>this.running),we(()=>Q(this.peerConnection.getStats()).pipe(Ge(t=>(Ut.warn("[RTCStatsMonitor] Failed to get stats:",t),He)))),C(()=>this.running),f(t=>this.extractSample(t))),t=>this._sample$.next(t)),this.subscribeTo(this._sample$.pipe(te(this.baselineSampleCount),ka(),f(t=>({rtt:t.reduce((i,r)=>i+r.roundTripTime,0)/t.length,jitter:t.reduce((i,r)=>i+r.audioJitter,0)/t.length,ready:!0}))),t=>{Ut.debug(`[RTCStatsMonitor] Baseline established: rtt=${t.rtt.toFixed(1)}ms, jitter=${t.jitter.toFixed(1)}ms`),this._baseline$.next(t)}),this.subscribeTo(this._sample$.pipe(hs((t,i)=>({prev:t.current,current:i}),{prev:null,current:null}),C(t=>t.current!==null)),({prev:t,current:i})=>{const r=i.timestamp;this.updatePacketTracking(i,r);const s=this.detectIssues(i,t,r);this._networkIssues$.next(s)}),this.subscribeTo(this._sample$.pipe(hs((t,i)=>{const r=i.timestamp-this.historyWindowSeconds*1e3,s={timestamp:i.timestamp,audio:{packetsReceived:i.audioPacketsReceived,packetsLost:i.audioPacketsLost,jitter:i.audioJitter},video:{packetsReceived:i.videoPacketsReceived,packetsLost:i.videoPacketsLost},roundTripTime:i.roundTripTime,availableOutgoingBitrate:i.availableOutgoingBitrate};return[...t.filter(n=>n.timestamp>r),s]},[])),t=>this._networkMetrics$.next(t))}stop(){this.running&&(this.running=!1,Ut.debug("[RTCStatsMonitor] Stopping stats monitoring"))}destroy(){Ut.debug("[RTCStatsMonitor] Destroying RTCStatsMonitor"),this.stop(),super.destroy()}extractSample(e){let t=0,i=0,r=0,s=0,n=0,o=0,a;return e.forEach(c=>{vu(c)&&(c.kind==="audio"?(t+=c.packetsReceived??0,i+=c.packetsLost??0,r=Math.max(r,(c.jitter??0)*1e3)):(s+=c.packetsReceived??0,n+=c.packetsLost??0)),fu(c)&&c.state==="succeeded"&&c.nominated&&(o=c.currentRoundTripTime?c.currentRoundTripTime*1e3:this.lastRoundTripTime,a=c.availableOutgoingBitrate??this.lastAvailableOutgoingBitrate)}),{audioPacketsReceived:t,audioPacketsLost:i,audioJitter:r,videoPacketsReceived:s,videoPacketsLost:n,roundTripTime:o,availableOutgoingBitrate:a,timestamp:Date.now()}}updatePacketTracking(e,t){e.audioPacketsReceived!==this.lastAudioPacketsReceived&&(this.lastAudioPacketsReceived=e.audioPacketsReceived,this.lastAudioPacketChangeTime=t),e.videoPacketsReceived!==this.lastVideoPacketsReceived&&(this.lastVideoPacketsReceived=e.videoPacketsReceived,this.lastVideoPacketChangeTime=t),e.roundTripTime>0&&(this.lastRoundTripTime=e.roundTripTime),e.availableOutgoingBitrate!==void 0&&(this.lastAvailableOutgoingBitrate=e.availableOutgoingBitrate)}detectIssues(e,t,i){const r=[],s=this._baseline$.value,n=i-this.lastAudioPacketChangeTime;n>this.noAudioPacketThresholdMs&&r.push({type:"no_inbound_audio",severity:"critical",timestamp:i,value:n,threshold:this.noAudioPacketThresholdMs});const o=i-this.lastVideoPacketChangeTime;if(o>this.noVideoPacketThresholdMs&&r.push({type:"no_inbound_video",severity:"warning",timestamp:i,value:o,threshold:this.noVideoPacketThresholdMs}),s.ready){const a=e.roundTripTime,c=s.rtt;if(c>0){const p=a/c;p>this.rttSpikeCriticalMultiplier?r.push({type:"high_rtt",severity:"critical",timestamp:i,value:a,threshold:c*this.rttSpikeCriticalMultiplier}):p>this.rttSpikeWarningMultiplier&&r.push({type:"high_rtt",severity:"warning",timestamp:i,value:a,threshold:c*this.rttSpikeWarningMultiplier})}const l=e.audioJitter,h=s.jitter;h>0&&l/h>this.jitterSpikeMultiplier&&r.push({type:"high_jitter",severity:"warning",timestamp:i,value:l,threshold:h*this.jitterSpikeMultiplier})}if(t){const a=Math.max(0,e.audioPacketsReceived-t.audioPacketsReceived),c=Math.max(0,e.audioPacketsLost-t.audioPacketsLost),l=Math.max(0,e.videoPacketsReceived-t.videoPacketsReceived),h=Math.max(0,e.videoPacketsLost-t.videoPacketsLost),p=a+l,b=pu(c+h,p);b>this.packetLossCriticalPercent?r.push({type:"high_packet_loss",severity:"critical",timestamp:i,value:b,threshold:this.packetLossCriticalPercent}):b>this.packetLossWarningPercent&&r.push({type:"high_packet_loss",severity:"warning",timestamp:i,value:b,threshold:this.packetLossWarningPercent})}return r}};const O=D(),bu=2e3,mu=1e4,yu=3e3,_u=5e3,wu=3,Cu=3,Su=3e3,$u=1e4,Tu=150,Eu=300,Mu=5,ku=new Set(["high_rtt","high_jitter","high_packet_loss"]);var Au=class extends P{constructor(e,t,i={}){super(),this._recoveryState$=this.createBehaviorSubject("idle"),this._recoveryEvent$=this.createSubject(),this._bandwidthConstrained$=this.createBehaviorSubject(!1),this._hasPacketLoss$=this.createBehaviorSubject(!1),this._trigger$=this.createSubject(),this._attemptCount=0,this._keyframeBurstCount=0,this._keyframeBurstStart=0,this._keyframeCooldownUntil=0,this._cooldownUntil=0,this._pipelineStop$=this.createSubject(),this._callbacks=e,this._inputs=t,this._config={debounceTimeMs:i.debounceTimeMs??bu,cooldownMs:i.cooldownMs??mu,iceGracePeriodMs:i.iceGracePeriodMs??yu,iceRestartTimeoutMs:i.iceRestartTimeoutMs??_u,maxAttempts:i.maxAttempts??wu,enableRelayFallback:i.enableRelayFallback??!0,keyframeMaxBurst:i.keyframeMaxBurst??Cu,keyframeBurstWindowMs:i.keyframeBurstWindowMs??Su,keyframeCooldownMs:i.keyframeCooldownMs??$u,degradationBitrateThreshold:i.degradationBitrateThreshold??Tu,degradationRecoveryThreshold:i.degradationRecoveryThreshold??Eu,enableAutoDegradation:i.enableAutoDegradation??!0,packetLossRecoveryDelaySec:i.packetLossRecoveryDelaySec??Mu},this.initPipeline(),this.initDegradationRecoveryPipeline()}get recoveryState$(){return this._recoveryState$.asObservable().pipe(v(this._destroyed$))}get recoveryState(){return this._recoveryState$.value}get recoveryEvent$(){return this._recoveryEvent$.asObservable().pipe(v(this._destroyed$))}get bandwidthConstrained$(){return this._bandwidthConstrained$.asObservable().pipe(v(this._destroyed$))}get bandwidthConstrained(){return this._bandwidthConstrained$.value}pushTrigger(e){this._trigger$.next(e)}async requestIceRestart(){if(this._recoveryState$.value==="recovering"){O.info("CallRecoveryManager: manual ICE restart skipped — recovery already in progress");return}O.info("CallRecoveryManager: manual ICE restart requested"),this.transitionTo("recovering"),await this.executeIceRestart(!1),this.startCooldown()}requestKeyframe(){this.executeKeyframe("manual request")}reset(){O.info("CallRecoveryManager: resetting counters"),this._attemptCount=0,this._keyframeBurstCount=0,this._keyframeBurstStart=0,this._keyframeCooldownUntil=0,this._cooldownUntil=0,this.transitionTo("idle")}notifyModifyFailed(){(this._recoveryState$.value==="cooldown"||this._recoveryState$.value==="idle")&&(O.info("CallRecoveryManager: verto.modify failed — re-entering recovery"),this._cooldownUntil=0,this.transitionTo("idle"),this.pushTrigger({source:"network",detail:"modify_failed_during_recovery"}))}reportBandwidth(e){if(!this._config.enableAutoDegradation)return;const t=this._bandwidthConstrained$.value;!t&&e<this._config.degradationBitrateThreshold?(this._bandwidthConstrained$.next(!0),this._callbacks.disableVideo(),this.emitEvent({action:"video_disabled",reason:`bandwidth ${e}kbps below threshold ${this._config.degradationBitrateThreshold}kbps`,timestamp:Date.now()}),O.warn(`CallRecoveryManager: disabling video — bandwidth ${e}kbps < ${this._config.degradationBitrateThreshold}kbps`)):t&&e>=this._config.degradationRecoveryThreshold&&(this._bandwidthConstrained$.next(!1),this._callbacks.enableVideo(),this.emitEvent({action:"video_restored",reason:`bandwidth ${e}kbps recovered above ${this._config.degradationRecoveryThreshold}kbps`,timestamp:Date.now()}),O.info(`CallRecoveryManager: restoring video — bandwidth ${e}kbps >= ${this._config.degradationRecoveryThreshold}kbps`))}reportNetworkIssues(e){const t=e.some(i=>i.type==="high_packet_loss");t!==this._hasPacketLoss$.value&&this._hasPacketLoss$.next(t)}handleWebSocketReconnect(){const e=this._callbacks.getPeerConnectionState();e==="connected"||e==="completed"?(O.info("CallRecoveryManager: signal-only reconnect — peer connection still alive"),this.emitEvent({action:"signal_reconnect",reason:"WebSocket reconnected, peer connection still connected",timestamp:Date.now()})):(O.info("CallRecoveryManager: full reconnect — peer connection also down"),this.emitEvent({action:"full_reconnect",reason:"WebSocket reconnected, peer connection not connected — ICE restart needed",timestamp:Date.now()}),this.pushTrigger({source:"network",detail:"full_reconnect_after_ws"})),this.reset()}destroy(){this._pipelineStop$.next(),this._pipelineStop$.complete(),super.destroy()}initPipeline(){this.subscribeTo(this._trigger$.pipe(W(()=>{this._recoveryState$.value==="idle"&&this.transitionTo("debouncing")}),us(this._config.debounceTimeMs),ps(this._inputs.signalingReady$),C(([,e])=>this.passGateChecks(e)),f(([e])=>e),Bi(e=>this.executeTieredRecovery(e)),v(vt(this._destroyed$,this._pipelineStop$))),{next:()=>{},error:e=>{O.error("CallRecoveryManager: pipeline error",e),this.transitionTo("idle")}})}initDegradationRecoveryPipeline(){if(!this._config.enableAutoDegradation)return;const e=this._config.packetLossRecoveryDelaySec*1e3;this.subscribeTo(os([this._bandwidthConstrained$,this._hasPacketLoss$]).pipe(we(([t,i])=>t&&!i?pt(e):He),v(this._destroyed$)),()=>{this._bandwidthConstrained$.next(!1),this._callbacks.enableVideo(),this.emitEvent({action:"video_restored",reason:`no packet loss for ${this._config.packetLossRecoveryDelaySec}s — restoring video`,timestamp:Date.now()}),O.info(`CallRecoveryManager: restoring video — no packet loss for ${this._config.packetLossRecoveryDelaySec}s`)})}passGateChecks(e){return this._callbacks.isNegotiating()?(O.debug("CallRecoveryManager: gate blocked — negotiation in progress"),this.transitionTo("idle"),!1):e?this._callbacks.isCallConnected()?this.isCooldownActive()?(O.debug("CallRecoveryManager: gate blocked — cooldown active"),this.transitionTo("cooldown"),!1):!0:(O.debug("CallRecoveryManager: gate blocked — call not connected"),this.transitionTo("idle"),!1):(O.debug("CallRecoveryManager: gate blocked — signaling not ready"),this.transitionTo("idle"),!1)}isCooldownActive(){return Date.now()<this._cooldownUntil}executeTieredRecovery(e){return this.transitionTo("recovering"),O.info(`CallRecoveryManager: starting tiered recovery — source=${e.source} detail=${e.detail}`),Q(this.runTiers(e)).pipe(W(()=>this.startCooldown()),Ge(t=>(O.error("CallRecoveryManager: tiered recovery failed",t),this.startCooldown(),He)))}async runTiers(e){if(this.executeKeyframe(e.detail),e.issueType&&ku.has(e.issueType)){O.debug(`CallRecoveryManager: degradation-only issue (${e.issueType}) — Tier 1 only, skipping ICE restart`);return}this._attemptCount<this._config.maxAttempts&&await this.executeIceRestart(!1)||this._config.enableRelayFallback&&this._attemptCount<this._config.maxAttempts&&await this.executeIceRestart(!0)||this._attemptCount>=this._config.maxAttempts&&(this.emitEvent({action:"max_attempts_reached",reason:`all ${this._config.maxAttempts} recovery attempts exhausted`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),O.warn("CallRecoveryManager: max recovery attempts reached"))}executeKeyframe(e){const t=Date.now();if(t<this._keyframeCooldownUntil){O.debug("CallRecoveryManager: keyframe request skipped — cooldown active");return}if(t-this._keyframeBurstStart>this._config.keyframeBurstWindowMs&&(this._keyframeBurstCount=0,this._keyframeBurstStart=t),this._keyframeBurstCount>=this._config.keyframeMaxBurst){this._keyframeCooldownUntil=t+this._config.keyframeCooldownMs,O.debug(`CallRecoveryManager: keyframe burst limit reached (${this._config.keyframeMaxBurst}), cooldown until ${this._keyframeCooldownUntil}`);return}this._keyframeBurstCount+=1,this._callbacks.requestKeyframe(),this.emitEvent({action:"keyframe_requested",reason:e,timestamp:t}),O.debug(`CallRecoveryManager: keyframe requested (burst ${this._keyframeBurstCount}/${this._config.keyframeMaxBurst})`)}async executeIceRestart(e){this._attemptCount+=1;const t=e?"Tier 3 (relay-only)":"Tier 2 (standard)";O.info(`CallRecoveryManager: ${t} ICE restart — attempt ${this._attemptCount}/${this._config.maxAttempts}`),this.emitEvent({action:"reinvite_started",reason:`${t} ICE restart`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()});try{return await this.withTimeout(this._callbacks.requestIceRestart(e),this._config.iceRestartTimeoutMs)?(this.emitEvent({action:"reinvite_succeeded",reason:`${t} ICE restart succeeded`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),O.info(`CallRecoveryManager: ${t} ICE restart succeeded`),this._attemptCount=0,!0):(this.emitEvent({action:"reinvite_failed",reason:`${t} ICE restart returned false`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),O.warn(`CallRecoveryManager: ${t} ICE restart failed`),!1)}catch{return this.emitEvent({action:"reinvite_timeout",reason:`${t} ICE restart timed out after ${this._config.iceRestartTimeoutMs}ms`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),O.warn(`CallRecoveryManager: ${t} ICE restart timed out`),!1}}async withTimeout(e,t){return new Promise((i,r)=>{const s=setTimeout(()=>{r(new Error(`Timeout after ${t}ms`))},t);e.then(n=>{clearTimeout(s),i(n)},n=>{clearTimeout(s),r(n instanceof Error?n:new Error(String(n)))})})}transitionTo(e){const t=this._recoveryState$.value;t!==e&&(O.debug(`CallRecoveryManager: state ${t} -> ${e}`),this._recoveryState$.next(e))}startCooldown(){this._cooldownUntil=Date.now()+this._config.cooldownMs,this.transitionTo("cooldown"),this._cooldownSubscription&&this._cooldownSubscription.unsubscribe(),this._cooldownSubscription=pt(this._config.cooldownMs).pipe(te(1),v(this._destroyed$),C(()=>this._recoveryState$.value==="cooldown")).subscribe(()=>this.transitionTo("idle"))}emitEvent(e){this._recoveryEvent$.next(e)}},xu=class{constructor(e,t,i){this.executeMethod=e,this.vertoManager=t,this.deviceController=i}createSelfParticipant(e){return new nn(e,this.executeMethod,this.vertoManager,this.deviceController)}createParticipant(e){return new sn(e,this.executeMethod,this.deviceController)}};const Du=93.2,Iu=.024,Ru=2.5,Pu=0,Ou=100,Vu=1,Lu=5,Bu=4,Nu=3.5,Uu=3,zu=2;function Fu(e,t,i){const r=Du-(e/2+t)*Iu-i*Ru,s=Math.min(Ou,Math.max(Pu,r)),n=1+.035*s+s*(s-60)*(100-s)*7e-6;return Math.min(Lu,Math.max(Vu,n))}function ju(e){return e>=Bu?"excellent":e>=Nu?"good":e>=Uu?"fair":e>=zu?"poor":"critical"}const H=D(),Hu=5/3,Wu=e=>{if(!e)return{};try{const t=new URL(`destination:${e}`),i={};return t.searchParams.forEach((r,s)=>{i[s]=r}),i}catch(t){return H.warn(`Failed to parse destination URI: ${e}`,t),{}}};var Gu=class extends P{constructor(e,t,i,r){super(),this.clientSession=e,this.options=t,this.address=r,this._errors$=this.createReplaySubject(1),this._lastMergedStatus="new",this._answered$=this.createReplaySubject(),this._holdState=!1,this._userVariables$=this.createBehaviorSubject({...d.instance.userVariables}),this._networkIssues$=this.createBehaviorSubject([]),this._networkMetrics$=this.createBehaviorSubject([]),this._isNetworkHealthy$=this.createBehaviorSubject(!0),this._qualityScore$=this.createBehaviorSubject(5),this._qualityLevel$=this.createBehaviorSubject("excellent"),this._recoveryState$=this.createBehaviorSubject("idle"),this._recoveryEvent$=this.createSubject(),this._bandwidthConstrained$=this.createBehaviorSubject(!1),this._mediaParamsUpdated$=this.createSubject(),this._customSubscriptions=new Map,this._pushToTalkEnabled=!1,this._remoteAudioMeter=null,this.id=t.callId??oi(),this.to=t.to,this._userVariables$.next({...this._userVariables$.value,...Wu(t.to),...t.userVariables}),this.subscribeTo(this.webrtcMessages$,a=>{const c=ve(a,"params.userVariables");c&&this._userVariables$.next({...this._userVariables$.value,...c})});const s=i.initializeManagers(this);this.vertoManager=s.vertoManager,this.callEventsManager=s.callEventsManager,t.initOffer?(this._status$=this.createBehaviorSubject("ringing"),this._lastMergedStatus="ringing"):this._status$=this.createBehaviorSubject("new");const{deviceController:n,networkChange$:o}=i;this._networkChange$=o,this.participantFactory=new xu(this.executeMethod.bind(this),this.vertoManager,n),this.subscribeTo(vt(this._status$.asObservable(),this.vertoManager.signalingStatus$).pipe(y(),v(this._destroyed$)),a=>{var c;this._lastMergedStatus=a,a==="connected"&&!this._statsMonitor?this.initResilienceSubsystems():a==="disconnected"?((c=this._statsMonitor)==null||c.destroy(),this._statsMonitor=void 0):(a==="destroyed"||a==="failed")&&this.stopResilienceSubsystems()})}get errors$(){return this.deferEmission(this._errors$.asObservable())}emitError(e){this._status$.value==="destroyed"||this._status$.value==="failed"||(this._errors$.next(e),e.fatal&&(this._status$.next("failed"),this.destroy()))}notifyModifyFailed(){var e;(e=this._recoveryManager)==null||e.notifyModifyFailed()}get direction(){return this.options.initOffer?"inbound":"outbound"}get address$(){return this.deferEmission(Q([this.address])).pipe(v(this._destroyed$))}get fromName(){return this.options.fromName}get from(){return this.options.from}get toName(){return this.options.toName}async toggleIncomingVideo(){throw new Se}async toggleIncomingAudio(){throw new Se}addCallId(e){this.callEventsManager.addCallId(e)}get capabilities(){return this.callEventsManager.capabilities}get participants(){return this.callEventsManager.participants}get self(){return this.callEventsManager.self}async toggleLock(){const e=this.locked?"call.unlock":"call.lock";await this.executeMethod(this.selfId??"",e,{})}async toggleHold(){this._holdState?await this.vertoManager.unhold():await this.vertoManager.hold(),this._holdState=!this._holdState}async startRecording(){throw new Se}async startStreaming(){throw new Se}async setMeta(e){throw new Se}async updateMeta(e){throw new Se}get layoutLayers$(){return this.deferEmission(this.callEventsManager.layoutLayers$).pipe(v(this._destroyed$))}get layoutLayers(){return this.callEventsManager.layoutLayers}async executeMethod(e,t,i){var n,o,a;const r=this.buildMethodParams(e,i),s=wt({method:t,params:r});try{const c=await this.clientSession.execute(s);if(Ed(c))throw new xe(parseInt(((n=c.result)==null?void 0:n.code)??"0"),`Error response from method ${t}: ${(o=c.result)==null?void 0:o.code} ${(a=c.result)==null?void 0:a.message}`,void 0,void 0,s.id);return c}catch(c){throw H.error(`[Call] Error executing method ${t} with params`,r,c),c}}buildMethodParams(e,t){const i={node_id:this.nodeId??"",call_id:this.id,member_id:this.vertoManager.selfId??""};return typeof e=="object"?{...t,self:i,targets:[e]}:{...t,self:i,target:{node_id:this.nodeId??"",call_id:this.id,member_id:e}}}get status$(){return this.publicCachedObservable("status$",()=>vt(this._status$.asObservable(),this.vertoManager.signalingStatus$).pipe(y(),W(e=>{this._lastMergedStatus=e})))}get participants$(){return this.deferEmission(this.callEventsManager.participants$).pipe(v(this._destroyed$))}get self$(){return this.deferEmission(this.callEventsManager.self$).pipe(v(this._destroyed$))}get recording$(){return this.deferEmission(this.callEventsManager.recording$).pipe(v(this._destroyed$))}get streaming$(){return this.deferEmission(this.callEventsManager.streaming$).pipe(v(this._destroyed$))}get raiseHandPriority$(){return this.deferEmission(this.callEventsManager.raiseHandPriority$).pipe(v(this._destroyed$))}get locked$(){return this.deferEmission(this.callEventsManager.locked$).pipe(v(this._destroyed$))}get meta$(){return this.deferEmission(this.callEventsManager.meta$).pipe(v(this._destroyed$))}get capabilities$(){return this.deferEmission(this.callEventsManager.capabilities$).pipe(v(this._destroyed$))}get layout$(){return this.deferEmission(this.callEventsManager.layout$).pipe(v(this._destroyed$))}get status(){return this._lastMergedStatus}get recording(){return this.callEventsManager.recording}get streaming(){return this.callEventsManager.streaming}get raiseHandPriority(){return this.callEventsManager.raiseHandPriority}get locked(){return this.callEventsManager.locked}get meta(){return this.callEventsManager.meta}get layout(){return this.callEventsManager.layout}get layouts$(){return this.deferEmission(this.callEventsManager.layouts$).pipe(v(this._destroyed$))}get layouts(){return this.callEventsManager.layouts}get localStream$(){return this.deferEmission(this.vertoManager.localStream$).pipe(v(this._destroyed$))}get localStream(){return this.vertoManager.localStream}get remoteStream$(){return this.deferEmission(this.vertoManager.remoteStream$).pipe(v(this._destroyed$))}get remoteStream(){return this.vertoManager.remoteStream}get userVariables$(){return this.deferEmission(this._userVariables$.asObservable())}get userVariables(){return{...this._userVariables$.value}}set userVariables(e){this._userVariables$.next({...this._userVariables$.value,...e})}get networkIssues$(){return this.deferEmission(this._networkIssues$.asObservable())}get networkIssues(){return this._networkIssues$.value}get isNetworkHealthy$(){return this.deferEmission(this._isNetworkHealthy$.asObservable())}get isNetworkHealthy(){return this._isNetworkHealthy$.value}get networkMetrics$(){return this.deferEmission(this._networkMetrics$.asObservable())}get networkMetrics(){return this._networkMetrics$.value}get qualityScore$(){return this.deferEmission(this._qualityScore$.asObservable())}get qualityLevel$(){return this.deferEmission(this._qualityLevel$.asObservable())}get recoveryState$(){return this.deferEmission(this._recoveryState$.asObservable())}get recoveryEvent$(){return this.deferEmission(this._recoveryEvent$.asObservable())}get bandwidthConstrained$(){return this.deferEmission(this._bandwidthConstrained$.asObservable())}get mediaParamsUpdated$(){return this.deferEmission(this._mediaParamsUpdated$.asObservable())}emitMediaParamsUpdated(e){this._mediaParamsUpdated$.next(e)}requestKeyframe(){var e,t;(t=(e=this.vertoManager).requestKeyframe)==null||t.call(e)}async requestIceRestart(){var e,t;await((t=(e=this.vertoManager).requestIceRestart)==null?void 0:t.call(e))}initResilienceSubsystems(){const e=this.rtcPeerConnection;if(H.debug(`[Call] initResilienceSubsystems: pc=${e?"exists":"undefined"}, connectionState=${e==null?void 0:e.connectionState}`),!e){H.warn("[Call] No peer connection available, skipping resilience init");return}try{const t=d.instance;this._statsMonitor=new gu(e,{pollingIntervalMs:t.statsPollingInterval,baselineSamples:t.statsBaselineSamples,noAudioPacketThresholdMs:t.statsNoPacketThreshold,rttSpikeWarningMultiplier:t.statsRttSpikeMultiplier,rttSpikeCriticalMultiplier:t.statsRttSpikeMultiplier*Hu,packetLossWarningPercent:t.statsPacketLossThreshold*100,packetLossCriticalPercent:t.statsPacketLossThreshold*200,jitterSpikeMultiplier:t.statsJitterSpikeMultiplier,historyWindowSeconds:t.statsHistorySize}),this._recoveryManager=new Au({requestKeyframe:()=>{var i,r;try{this.vertoManager.requestKeyframeAll?this.vertoManager.requestKeyframeAll():(r=(i=this.vertoManager).requestKeyframe)==null||r.call(i)}catch{}},requestIceRestart:async i=>{var r,s;try{this.vertoManager.requestIceRestartAll?await this.vertoManager.requestIceRestartAll(i):await((s=(r=this.vertoManager).requestIceRestart)==null?void 0:s.call(r,i))}catch{return!1}return this.waitForPeerConnectionConnected()},disableVideo:()=>{try{this.vertoManager.muteMainVideoInputDevice(),H.debug("[Call] Recovery manager disabled video")}catch{H.debug("[Call] Recovery manager failed to disable video")}},enableVideo:()=>{this.vertoManager.unmuteMainVideoInputDevice().catch(()=>{H.debug("[Call] Recovery manager failed to enable video")})},isNegotiating:()=>this.vertoManager.mainPeerConnection.isNegotiating,isCallConnected:()=>this._lastMergedStatus==="connected",getPeerConnectionState:()=>e.connectionState},{signalingReady$:this.clientSession.authenticated$},{debounceTimeMs:t.recoveryDebounceTime,cooldownMs:t.recoveryCooldown,iceGracePeriodMs:t.iceDisconnectedGracePeriod,iceRestartTimeoutMs:t.iceRestartTimeout,maxAttempts:t.maxRecoveryAttempts,enableRelayFallback:t.enableRelayFallback,keyframeMaxBurst:t.keyframeMaxBurst,keyframeBurstWindowMs:t.keyframeBurstWindow,keyframeCooldownMs:t.keyframeCooldown}),this.subscribeTo(this._statsMonitor.networkIssues$,i=>{var r;this._networkIssues$.next(i),(r=this._recoveryManager)==null||r.reportNetworkIssues(i)}),this.subscribeTo(this._statsMonitor.isNetworkHealthy$,i=>{this._isNetworkHealthy$.next(i)}),this.subscribeTo(this._statsMonitor.networkMetrics$,i=>{var r;if(this._networkMetrics$.next(i),i.length>0){const s=i[i.length-1],n=s.audio.packetsReceived+s.video.packetsReceived,o=s.audio.packetsLost+s.video.packetsLost,a=n+o>0?o/(n+o)*100:0,c=Fu(s.roundTripTime,s.audio.jitter,a);this._qualityScore$.next(c),this._qualityLevel$.next(ju(c)),s.availableOutgoingBitrate!==void 0&&((r=this._recoveryManager)==null||r.reportBandwidth(s.availableOutgoingBitrate/1e3))}}),this.subscribeTo(this._statsMonitor.criticalIssue$,i=>{var r;(r=this._recoveryManager)==null||r.pushTrigger({source:"stats",detail:`${i.type}: ${i.severity}`,issueType:i.type})}),this.subscribeTo(this._recoveryManager.recoveryState$,i=>{this._recoveryState$.next(i)}),this.subscribeTo(this._recoveryManager.recoveryEvent$,i=>{this._recoveryEvent$.next(i),i.action==="max_attempts_reached"&&(H.warn("[Call] All recovery attempts exhausted, terminating call"),this.emitError({kind:"network",fatal:!0,error:new Error("Call recovery failed: all attempts exhausted"),callId:this.id}))}),this.subscribeTo(this._recoveryManager.bandwidthConstrained$,i=>{this._bandwidthConstrained$.next(i)}),this._networkChange$&&this.subscribeTo(this._networkChange$,i=>{var r,s;i.type==="offline"?(r=this._recoveryManager)==null||r.pushTrigger({source:"network",detail:"browser went offline"}):i.type==="online"&&((s=this._recoveryManager)==null||s.handleWebSocketReconnect())}),this.subscribeTo(this.clientSession.authenticated$.pipe(ei(1),C(Boolean)),()=>{var i;H.debug("[Call] WebSocket reconnected — notifying recovery manager"),(i=this._recoveryManager)==null||i.handleWebSocketReconnect()}),this._statsMonitor.start(),H.debug("[Call] Resilience subsystems initialized for call",this.id)}catch(t){H.warn("[Call] Failed to initialize resilience subsystems:",t)}}async waitForPeerConnectionConnected(){const e=this.rtcPeerConnection;if(!e)return!1;const t=Date.now()+dl;for(;;){const i=e.connectionState;if(i==="connected")return!0;if(i==="failed"||i==="closed"||Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,ul))}}stopResilienceSubsystems(){var e,t;try{(e=this._statsMonitor)==null||e.destroy(),(t=this._recoveryManager)==null||t.destroy()}catch{}this._statsMonitor=void 0,this._recoveryManager=void 0}createParticipant(e,t){return e===(t??this.vertoManager.selfId)?this.participantFactory.createSelfParticipant(e):this.participantFactory.createParticipant(e)}get mediaDirections$(){return this.deferEmission(this.vertoManager.mediaDirections$).pipe(v(this._destroyed$))}get mediaDirections(){return this.vertoManager.mediaDirections}get participantsId$(){return this.cachedObservable("participantsId$",()=>this.participants$.pipe(f(e=>e.map(t=>t.id))))}async execute(e,t){return this.clientSession.execute(e,t)}get selfId$(){return this.vertoManager.selfId$}get selfId(){return this.vertoManager.selfId}get nodeId$(){return this.vertoManager.nodeId$}get nodeId(){return this.vertoManager.nodeId}isCallSessionEvent(e){try{H.debug("[Call] Checking if event is for this call session:",e);const t=ve(e,"params.params.callID")??ve(e,"params.call_id"),i=ve(e,"params.room_session_id");return H.debug(`[Call] Extracted session identifiers callID: ${t} and roomSessionID: ${i} from event:`),t===this.id||!!t&&this.callEventsManager.isCallIdValid(t)||!!i&&this.callEventsManager.isRoomSessionIdValid(i)}catch(t){return H.error("[Call] Error checking if event is for this call session:",t),!1}}get callSessionEvents$(){return this.cachedObservable("callSessionEvents$",()=>this.clientSession.signalingEvent$.pipe(C(e=>this.isCallSessionEvent(e)),W(e=>{H.debug("[Call] Received call session event:",e)}),v(this.destroyed$),qe()))}get callUpdated$(){return this.publicCachedObservable("callUpdated$",()=>this.callSessionEvents$.pipe(F(cn,"params"),v(this.destroyed$)))}get memberJoined$(){return this.publicCachedObservable("memberJoined$",()=>this.callSessionEvents$.pipe(F(un,"params"),v(this.destroyed$)))}get memberLeft$(){return this.publicCachedObservable("memberLeft$",()=>this.callSessionEvents$.pipe(F(hn,"params"),v(this.destroyed$)))}get memberUpdated$(){return this.publicCachedObservable("memberUpdated$",()=>this.callSessionEvents$.pipe(F(dn,"params"),v(this.destroyed$)))}get memberTalking$(){return this.publicCachedObservable("memberTalking$",()=>this.callSessionEvents$.pipe(F(pn,"params"),v(this.destroyed$)))}get callStates$(){return this.publicCachedObservable("callStates$",()=>this.callSessionEvents$.pipe(F(ln,"params"),v(this.destroyed$)))}get layoutUpdates$(){return this.publicCachedObservable("layoutUpdates$",()=>this.callSessionEvents$.pipe(F(Zi,"params"),v(this.destroyed$)))}get rtcPeerConnection(){return this.vertoManager.mainPeerConnection.peerConnection}get signalingEvent$(){return this.publicCachedObservable("signalingEvent$",()=>this.callEvent$.pipe(f(e=>JSON.parse(JSON.stringify(e)))))}subscribe(e){const t=this._customSubscriptions.get(e);if(t)return t;const i=this.callSessionEvents$.pipe(C(r=>r.event_type===e),f(r=>JSON.parse(JSON.stringify(r))),v(this._destroyed$));return this._sendVertoSubscribe(e).then(()=>{this._customSubscriptions.set(e,i)},r=>{this._customSubscriptions.delete(e),H.warn(`[Call] verto.subscribe for '${e}' failed, not caching:`,r)}),this._customSubscriptions.set(e,i),i}get webrtcMessages$(){return this.cachedObservable("webrtcMessages$",()=>this.callSessionEvents$.pipe(F(hi,"params"),W(e=>H.debug("[Call] Event is a WebRTC message event:",e)),v(this.destroyed$),qe()))}get callEvent$(){return this.cachedObservable("callEvent$",()=>this.callSessionEvents$.pipe(F(Md,"params"),W(e=>H.debug("[Call] Event is a call event:",e)),v(this.destroyed$),qe()))}get layoutEvent$(){return this.cachedObservable("layoutEvent$",()=>this.callEvent$.pipe(F(Zi,"params")))}async hangup(){this._status$.next("disconnecting");try{await this.vertoManager.bye()}finally{this.destroy()}}async sendDigits(e){return this.vertoManager.sendDigits(e)}answer(e){this._answerMediaOptions=e,this._answered$.next(!0)}get answerMediaOptions(){return this._answerMediaOptions}reject(){this._answered$.next(!1)}get answered$(){return this.deferEmission(this._answered$.asObservable())}async setLayout(e,t){if(!this.layouts.includes(e))throw new ms(`Layout ${e} is not available in the current call layouts: ${this.layouts.join(", ")}`);const i=await ae(this.selfId$.pipe(C(r=>r!==null)));await this.executeMethod(i,"call.layout.set",{layout:e,positions:t})}async transfer(e){return this.vertoManager.transfer(e)}setLocalMicrophoneGain(e){const t=this.vertoManager.ensureLocalAudioPipeline();if(!t){H.warn("[Call] setLocalMicrophoneGain: audio pipeline unavailable");return}const i=Math.max(0,Math.min(200,e));t.setGain(i/100)}get localMicrophoneGain$(){const e=this.vertoManager.ensureLocalAudioPipeline();return e?e.gain$.pipe(f(t=>t*100),v(this._destroyed$)):Ot(100).pipe(v(this._destroyed$))}get localAudioLevel$(){var e;return((e=this.vertoManager.ensureLocalAudioPipeline())==null?void 0:e.level$)??Ot(0).pipe(v(this._destroyed$))}get localSpeaking$(){var e;return((e=this.vertoManager.ensureLocalAudioPipeline())==null?void 0:e.speaking$)??Ot(!1).pipe(v(this._destroyed$))}enablePushToTalk(){const e=this.vertoManager.ensureLocalAudioPipeline();if(!e){H.warn("[Call] enablePushToTalk: audio pipeline unavailable");return}e.setPTTActive(!1),this._pushToTalkEnabled=!0}disablePushToTalk(){var e;(e=this.vertoManager.localAudioPipeline)==null||e.setPTTActive(!0),this._pushToTalkEnabled=!1}setPushToTalkActive(e){var t;this._pushToTalkEnabled&&((t=this.vertoManager.localAudioPipeline)==null||t.setPTTActive(e))}async setEchoCancellation(e){await this.vertoManager.updateMediaConstraints({audio:{echoCancellation:e}})}async setNoiseSuppression(e){await this.vertoManager.updateMediaConstraints({audio:{noiseSuppression:e}})}async setAutoGainControl(e){await this.vertoManager.updateMediaConstraints({audio:{autoGainControl:e}})}get remoteAudioLevel$(){this._remoteAudioMeter??(this._remoteAudioMeter=new iu);const e=this._remoteAudioMeter;return this.subscribeTo(this.vertoManager.remoteStream$,t=>{e.setStream(t)}),e.level$.pipe(v(this._destroyed$))}destroy(){var e;this._status$.value!=="destroyed"&&(this._status$.next("destroyed"),this.stopResilienceSubsystems(),(e=this._remoteAudioMeter)==null||e.destroy(),this._remoteAudioMeter=null,this.vertoManager.destroy(),this.callEventsManager.destroy(),super.destroy())}async _sendVertoSubscribe(e){const t=gd({sessid:this.id,eventChannel:[e]}),i={callID:this.id,node_id:this.vertoManager.nodeId??"",message:t};await this.clientSession.execute(Zs(i))}};function qu(e){return e instanceof ii?"timeout":e instanceof xe?"signaling":e instanceof bt?"media":e instanceof fs||e instanceof gs?"network":"internal"}const Ku=new Set([Ps,Vs,Os]);function Ju(e){return!(e instanceof _s||e instanceof bt||e instanceof ii||e instanceof xe&&Ku.has(e.code))}var Yu=class{constructor(e,t,i,r,s){this.sessionManager=e,this.deviceController=t,this.attachManager=i,this.webRTCApiProvider=r,this.networkChange$=s}createCall(e,t){return new Gu(this.sessionManager,t,{initializeManagers:i=>({vertoManager:new tu(i,this.attachManager,this.deviceController,this.webRTCApiProvider,{nodeId:t.nodeId,onError:r=>{const s={kind:qu(r),fatal:Ju(r),error:r,callId:i.id};i.emitError(s)},onModifyFailed:()=>{i.notifyModifyFailed()}}),callEventsManager:new Vd(i)}),deviceController:this.deviceController,networkChange$:this.networkChange$},e)}};const rr=D();var $n=class{constructor(e,t,i){this.endpoint=e,this.http=i,this.filter=r=>!0,this.mapper=r=>r,this.nextUrl=`${this.endpoint}?${t}`}async next(){if(!this.nextUrl)return this.hasMore=!1,[];const e=await this.http.request({...Wi,url:this.nextUrl});if(e.ok&&e.body){const t=JSON.parse(e.body);return this.nextUrl=t.links.next,this.hasMore=!!this.nextUrl,t.data.filter(this.filter).map(this.mapper)}return rr.error("Failed to fetch entity"),[]}async id(e){const t=await this.http.request({...Wi,url:`${this.endpoint}/${String(e)}`});if(t.ok&&t.body)return JSON.parse(t.body)}},Tn=class extends P{constructor(e,t,i){super(),this.fetchController=e,this.update$=t,this.onError=i,this.collectionData=new Map,this.observablesRegistry=new Map,this.upsertData=r=>{var a;if(!r.id)return;const s=this.collectionData.get(r.id)??{},n={},o=new Set([...Object.keys(s),...Object.keys(r)]);for(const c of o){const l=s[c],h=r[c];h!==void 0&&l!==void 0&&typeof l=="object"&&l!==null&&!Array.isArray(l)&&typeof h=="object"&&h!==null&&!Array.isArray(h)?n[c]={...l,...h}:h!==void 0?n[c]=h:n[c]=l}this.collectionData.set(r.id,n),(a=this.observablesRegistry.get(r.id))==null||a.next(n),this._values$.next(Array.from(this.collectionData.values()))},this._loading$=this.createBehaviorSubject(!1),this._values$=this.createReplaySubject(1),this._hasMore$=this.createBehaviorSubject(!0),this.subscribeTo(this.update$,this.upsertData),this.hasMore$=We(()=>Q(this.init())).pipe(we(()=>this._hasMore$),y(),pe(1),v(this.destroyed$))}get loading$(){return this._loading$.asObservable()}get loading(){return this._loading$.value}get values$(){return this._values$.asObservable()}get hasMore(){return this.fetchController.hasMore??!0}get updated$(){return this.cachedObservable("updated$",()=>this._loading$.pipe(y(),ei(1),C(e=>!e),f(()=>{}),v(this.destroyed$)))}get values(){return Array.from(this.collectionData.values())}async init(){if(this.fetchController.hasMore===!1){this._hasMore$.next(!1);return}await this.fetchMore()}async fetchMore(){var e;try{this._loading$.next(!0),(await this.fetchController.next()).forEach(this.upsertData),this._hasMore$.next(this.fetchController.hasMore??!1),this._loading$.next(!1)}catch(t){rr.error("Failed to fetch initial collection data",t),this._hasMore$.next(this.fetchController.hasMore??!1),this._loading$.next(!1),(e=this.onError)==null||e.call(this,new ws("fetchMore",t))}}async tryFetch(e,t){var i,r,s;try{this._loading$.next(!0);const n=await((r=(i=this.fetchController)[e])==null?void 0:r.call(i,t));return this._loading$.next(!1),n&&this.upsertData(n),n}catch(n){rr.error(`Failed to fetch data for (${String(e)}:${String(t)}) :`,n),this._loading$.next(!1),(s=this.onError)==null||s.call(this,new ws(`tryFetch(${String(e)})`,n))}}get$(e){var t,i;if(!this.observablesRegistry.has(e)){this.observablesRegistry.set(e,new Di(1));const r=this.collectionData.get(e);r?(t=this.observablesRegistry.get(e))==null||t.next(r):this.tryFetch("id",e)}return(i=this.observablesRegistry.get(e))==null?void 0:i.asObservable()}async find$(e,t){const i=Array.from(this.collectionData.values()).find(r=>r[e]===t)??await this.tryFetch(e,t);return i?this.get$(i.id):void 0}loadMore(){this.fetchController.hasMore!==!1&&this.fetchMore()}destroy(){this.observablesRegistry.forEach(e=>e.complete()),this.observablesRegistry.clear(),super.destroy()}},En=class{constructor(e,t=r=>!!r,i=r=>r){this.originalCollection=e,this.filter=t,this.mapper=i}get loading$(){return this.originalCollection.loading$}get loading(){return this.originalCollection.loading}get hasMore$(){return this.originalCollection.hasMore$}get hasMore(){return this.originalCollection.hasMore}get values(){return this.originalCollection.values.filter(this.filter).map(this.mapper)}get values$(){return this._values$??(this._values$=this.originalCollection.values$.pipe(f(e=>e.filter(this.filter).map(this.mapper))))}get$(e){const t=this.originalCollection.get$(e);return t&&t.pipe(Xt(C(this.filter),f(this.mapper)))}async find$(e,t){const i=await this.originalCollection.find$(e,t);return i&&i.pipe(Xt(C(this.filter),f(this.mapper)))}loadMore(){this.originalCollection.loadMore()}destroy(){this.originalCollection.destroy()}},Mn=class extends P{constructor(e,t,i){super(),this.addressId=e,this.conversationManager=t,this.addressProvider=i,this.initConversationMessages=async()=>(this._conversationMessages=this._conversationMessages??await this.conversationManager.getConversationMessageCollection(this.id),this._conversationMessages.hasMore&&this._conversationMessages.loadMore(),this._conversationMessages),this.textMessages$=We(this.initConversationMessages).pipe(f(()=>this.textMessage),pe(1),v(this.destroyed$)),this.history$=We(this.initConversationMessages).pipe(f(()=>this.history),pe(1),v(this.destroyed$)),this._state$=this.createBehaviorSubject(null)}upnext(e){const t={...this._state$.value,...e};this._state$.next(t)}get state(){return this._state$.value}get id(){return this.addressId}get name(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.name}get createdAt(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.created_at}get defaultChannel(){return this.type==="room"?this.channels.video:this.channels.audio}get displayName$(){return this.cachedObservable("displayName$",()=>this._state$.pipe(B(),f(e=>e.display_name),v(this.destroyed$)))}get displayName(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.display_name}get previewUrl$(){return this.cachedObservable("previewUrl$",()=>this._state$.pipe(B(),f(e=>e.preview_url),v(this.destroyed$)))}get previewUrl(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.preview_url}get coverUrl$(){return this.cachedObservable("coverUrl$",()=>this._state$.pipe(B(),pe(1),f(e=>e.cover_url),v(this.destroyed$)))}get coverUrl(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.cover_url}get resourceId$(){return this.cachedObservable("resourceId$",()=>this._state$.pipe(B(),pe(1),f(e=>e.resource_id),v(this.destroyed$)))}get resourceId(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.resource_id}get type$(){return this.cachedObservable("type$",()=>this._state$.pipe(B(),pe(1),f(e=>e.type),v(this.destroyed$)))}get type(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.type}get channels$(){return this.cachedObservable("channels$",()=>this._state$.pipe(B(),pe(1),f(e=>e.channels),v(this.destroyed$)))}get channels(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.channels}get locked(){if(!this._state$.value)throw new R("state not initialized");return this._state$.value.locked}get locked$(){return this.cachedObservable("locked$",()=>this._state$.pipe(B(),pe(1),f(e=>e.locked),v(this.destroyed$)))}async sendText(e){return this.conversationManager.sendText(e,this.id)}get textMessage(){if(this._conversationMessages)return this._textMessages$=this._textMessages$??new En(this._conversationMessages,e=>e.subtype==="chat",e=>({id:e.id,text:e.text,created:e.ts,fromAddress$:this.addressProvider.get$(e.from_fabric_address_id)})),this._textMessages$}get history(){if(this._conversationMessages)return this._history$=this._history$??new En(this._conversationMessages,e=>e.subtype==="log",e=>({id:e.id,kind:e.kind,status:e.details.status,started:e.details.start_time,ended:e.details.end_time,fromAddress$:this.addressProvider.get$(e.from_fabric_address_id)})),this._history$}get activity$(){throw new Se}get activity(){throw new Se}};const tt=D(),Xu=e=>{if(tt.debug("isRPCConnectResult check:",e),!e||typeof e!="object")return!1;const t=e,i=typeof t.identity=="string"&&typeof t.protocol=="string"&&typeof t.authorization=="object"&&typeof t.authorization.jti=="string"&&typeof t.authorization.project_id=="string"&&typeof t.authorization.fabric_subscriber=="object";return tt.debug("isRPCConnectResult check result:",i),i};var Qu=(it=class{constructor(t,i,r){this.id=oi(),tt.debug(`[PendingRPC(${this.id}) request:${t.id}: method:${t.method}] Creating PendingRPC`),this.request=t;const s=(r==null?void 0:r.timeoutMs)??it.defaultTimeoutMs,n=r==null?void 0:r.signal;this.promise=new Promise((o,a)=>{if(n!=null&&n.aborted){a(new DOMException("The operation was aborted","AbortError"));return}let c=!1;const l=Lt(i.pipe(C(h=>h.id===t.id),te(1)),new j(h=>{const p=setTimeout(()=>{h.error(new ii(t.id,s))},s);return()=>clearTimeout(p)}),n?new j(h=>{const p=()=>{h.error(new DOMException("The operation was aborted","AbortError"))};return n.addEventListener("abort",p),()=>n.removeEventListener("abort",p)}):_a).subscribe({next:h=>{if(c=!0,h.error){const p=new xe(h.error.code,h.error.message,h.error.data,void 0,t.id);tt.debug(`[PendingRPC(${this.id}) request:${t.id}] Rejecting promise with RPC error:`,p),a(p)}else tt.debug(`[PendingRPC(${this.id}) request:${t.id}] Resolving promise with response:`,h),o(h);l.unsubscribe()},error:h=>{tt.debug(`[PendingRPC(${this.id}) request:${t.id}] Rejecting promise with error:`,h),c=!0,a(h),l.unsubscribe()},complete:()=>{tt.debug(`[PendingRPC(${this.id}) request:${t.id}] Observable completed`),c||a(new ii(t.id,s)),l.unsubscribe()}})})}async then(t,i){return this.promise.then(t,i)}async catch(t){return this.promise.catch(t)}async finally(t){return this.promise.finally(t)}},it.defaultTimeoutMs=5e3,it);const k=D(),Zu=e=>{var s,n;const t=(s=e.to)==null?void 0:s.split("?")[0],i=(n=e.from)!=null&&n.startsWith("subscriber://")?e.from.replace("subscriber://",""):e.from,r=t??i;if(!r)throw new gt("Error building Address name");return r};var eh=class extends P{constructor(e,t,i,r,s,n,o,a,c){super(),this.getCredential=e,this.transport=t,this.storage=i,this.authorizationStateKey=r,this.attachManager=n,this.dpopManager=a,this.callCreateTimeout=6e3,this.agent="signalwire-js/4.0.0",this.eventAcks=!0,this.authorizationState$=this.createReplaySubject(1),this.connectVersion={major:4,minor:0,revision:0},this._authorization$=this.createBehaviorSubject(void 0),this._errors$=this.createReplaySubject(1),this._authState$=this.createBehaviorSubject({kind:"unauthenticated"}),this._wasClientBound=!1,this._subscriberInfo$=this.createBehaviorSubject(null),this._calls$=this.createBehaviorSubject({}),this._iceServers$=this.createBehaviorSubject([]),n.setSession(this),this.callFactory=new Yu(this,s,n,o,c),this.initialized$=We(()=>Q(this.init())).pipe(pe(1),v(this.destroyed$))}get incomingCalls$(){return this.cachedObservable("incomingCalls$",()=>this.calls$.pipe(f(e=>e.filter(t=>t.direction==="inbound"))))}get incomingCalls(){return Object.values(this._calls$.value).filter(e=>e.direction==="inbound")}get subscriberInfo$(){return this._subscriberInfo$.asObservable()}get subscriberInfo(){return this._subscriberInfo$.value}get calls$(){return this.cachedObservable("calls$",()=>this._calls$.pipe(f(e=>Object.values(e))))}get calls(){return Object.values(this._calls$.value)}get iceServers(){return this._iceServers$.value}get authorization$(){return this._authorization$.asObservable()}get authorization(){return this._authorization$.value}get errors$(){return this._errors$.asObservable()}get authenticated$(){return this._authState$.pipe(f(e=>e.kind==="authenticated"),y())}get authenticated(){return this._authState$.value.kind==="authenticated"}get clientBound(){return this._wasClientBound}get authState(){return this._authState$.value}setDirectory(e){this._directory=e}async execute(e,t){try{return await this.transport.execute(e,t)}catch(i){throw k.debug("[Session] Execute Error",i),this._errors$.next(i instanceof Error?i:new Error(String(i),{cause:i})),i}}send(e){this.transport.send(e)}async init(){return await this.loadAuthorizationStateFromStorage(),this.setupMessageHandlers(),!0}setupMessageHandlers(){k.debug("[Session] Setting up message handlers"),this.subscribeTo(this.authStateEvent$,async e=>{k.debug("[Session] Authorization state event received:",e);try{await this.updateAuthorizationStateInStorage(e.authorization_state)}catch(t){k.error("[Session] Failed to handle authorization state update:",t),this._errors$.next(new Ui(t))}}),this.subscribeTo(this.transport.connectionStatus$.pipe(C(e=>e==="disconnected"||e==="reconnecting")),()=>{this._authState$.value.kind==="authenticated"&&this._authState$.next({kind:"unauthenticated"})}),this.subscribeTo(this.transport.connectionStatus$.pipe(C(e=>e==="connected"),Bi(()=>(k.debug("[Session] Connection established, initiating authentication"),Q(this.authenticate()).pipe(Ge(e=>(this.handleAuthenticationError(e).catch(t=>{k.error("[Session] Error handling authentication failure:",t)}),He)))))),void 0),this.subscribeTo(this.vertoInvite$,async e=>{k.debug("[Session] Verto invite received:",e);try{await this.createInboundCall(e)}catch(t){k.error("[Session] Error handling Verto invite:",t),this._errors$.next(new rc(t))}}),this.subscribeTo(this.vertoAttach$,async e=>{k.debug("[Session] Verto attach received:",e);try{await this.handleVertoAttach(e)}catch(t){k.error("[Session] Error handling Verto attach:",t),this._errors$.next(new sc(t))}})}async loadAuthorizationStateFromStorage(){try{const e=await this.storage.getItem(this.authorizationStateKey);this.authorizationState$.next(e??void 0)}catch(e){k.error("Failed to retrieve authorization state from storage:",e),this.authorizationState$.next(void 0)}}async updateAuthorizationStateInStorage(e){if(!e){k.debug("[Session] Removing authorization state from storage");try{await this.storage.removeItem(this.authorizationStateKey),this.authorizationState$.next(void 0)}catch(t){throw k.error("Failed to remove authorization state from storage:",t),t}return}try{k.debug("[Session] Updating authorization state in storage"),await this.storage.setItem(this.authorizationStateKey,e),this.authorizationState$.next(e)}catch(t){throw k.error("Failed to retrieve authorization state from storage:",t),t}}get authStateEvent$(){return this.cachedObservable("authStateEvent$",()=>this.signalingEvent$.pipe(W(e=>{k.debug("[Session] Received incoming message:",e)}),F(kd,"params"),W(e=>{k.debug("[Session] Authorization state event received:",e.authorization_state)})))}get signalingEvent$(){return this.cachedObservable("signalingEvent$",()=>this.transport.incomingEvent$.pipe(F(Qi,"params"),qe()))}get vertoInvite$(){return this.cachedObservable("vertoInvite$",()=>this.signalingEvent$.pipe(C(hi),C(e=>wn(e.params)),f(e=>({node_id:e.node_id,...e.params.params}))))}get vertoAttach$(){return this.cachedObservable("vertoAttach$",()=>this.signalingEvent$.pipe(C(hi),C(e=>Cn(e.params)),f(e=>({node_id:e.node_id,...e.params.params}))))}get contexts(){return[]}get eventing(){return[]}get topics(){return[]}get authentication(){const e=this.getCredential();if(!e.token)throw new R("Credential token is undefined");return{jwt_token:e.token}}async connect(){await ae(this.initialized$),await this.transport.connect(),await ae(this.authenticated$.pipe(v(this.destroyed$),C(Boolean),te(1),Vt({first:15e3})))}async handleAuthenticationError(e){k.error("Authentication error:",e);const t=e instanceof xe&&(e.code===Ps||e.code===Os||e.code===Vs),i=await ae(this.authorizationState$.pipe(te(1)))!==void 0;if(t&&i){k.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");try{await this.cleanupStoredConnectionParams()}catch(r){k.error("Failed to cleanup stored connection params:",r)}finally{this.transport.reconnect()}}else this._errors$.next(e)}async cleanupStoredConnectionParams(){await this.transport.setProtocol(void 0),await this.updateAuthorizationStateInStorage(void 0),this._authorization$.next(void 0)}async updateAuthState(e){try{await this.storage.setItem(this.authorizationStateKey,e)}catch(t){k.error("Failed to update authorization state in storage:",t),this._errors$.next(new Ui(t))}}async reauthenticate(e,t,i){var r,s;k.debug("[Session] Re-authenticating session");try{let n=t;if(!n&&((r=this.dpopManager)!=null&&r.initialized))try{n=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"})}catch(a){if(this.clientBound)throw a;k.warn("[Session] Failed to create DPoP proof for reauthenticate:",a)}const o=ad({project:((s=this._authorization$.value)==null?void 0:s.project_id)??"",jwt_token:e,...n?{dpop_token:n}:{}});await rs(Q(this.transport.execute(o)).pipe(Ts(),te(1),Ge(a=>{throw k.error("[Session] Re-authentication RPC failed:",a),a}))),i!=null&&i.clientBound&&(this._wasClientBound=!0),k.debug("[Session] Re-authentication successful, updating stored auth state")}catch(n){throw k.error("[Session] Re-authentication failed:",n),this._errors$.next(new Ui(n)),n}}async authenticate(){var a,c;k.debug("[Session] Starting authentication process");const e=await ae(os({protocol:this.transport.protocol$,authorization_state:this.authorizationState$}).pipe(te(1)));k.debug(`[Session] Persisted params:
2474
+ `,{protocol:e.protocol,authStateLength:(a=e.authorization_state)==null?void 0:a.length});const t=e.authorization_state&&e.protocol,i=this.getCredential().token,r=t&&i;let s;if(r?k.debug("[Session] Reconnecting with stored jwt_token + authorization_state"):this.onBeforeReconnect&&this.clientBound&&(k.debug("[Session] Refreshing credentials before fresh connect"),await this.onBeforeReconnect()),(!r||this.clientBound)&&((c=this.dpopManager)!=null&&c.initialized))try{s=await this.dpopManager.createRpcProof({method:"signalwire.connect"})}catch(l){if(this.clientBound)throw l;k.warn("[Session] Failed to create DPoP proof for connect, proceeding without:",l)}const n=od({authentication:r?{jwt_token:i}:this.authentication,version:this.connectVersion,agent:this.agent,contexts:this.contexts,eventing:this.eventing,topics:this.topics,event_acks:this.eventAcks,...s?{dpop_token:s}:{},...r?{authorization_state:e.authorization_state,protocol:e.protocol}:{}}),o=await rs(Q(this.transport.execute(n)).pipe(Ts(),f(l=>l.result),C(Xu),W(()=>{k.debug("[Session] Response passed filter, processing authentication result")}),te(1),Ge(l=>{throw k.error("[Session] Authentication RPC failed:",l),l})));k.debug("[Session] Processing authentication result:",{hasProtocol:!!o.protocol,hasAuthorization:!!o.authorization,hasIceServers:!!o.ice_servers}),o.protocol&&await this.transport.setProtocol(o.protocol),this._authorization$.next(o.authorization),this._iceServers$.next(o.ice_servers??[]),this._authState$.next({kind:"authenticated"}),k.debug("[Session] Authentication completed successfully")}async disconnect(){this.transport.disconnect(),this._authState$.next({kind:"unauthenticated"}),await this.cleanupStoredConnectionParams()}async createInboundCall(e){const t=await this.createCall({nodeId:e.node_id,callId:e.callID,initOffer:e.sdp,toName:e.callee_id_name,to:e.callee_id_number,fromName:e.caller_id_name,from:e.caller_id_number,displayDirection:e.display_direction,userVariables:e.userVariables});this._calls$.next({[`${t.id}`]:t,...this._calls$.value})}async handleVertoAttach(e){const{callID:t}=e;if(t in this._calls$.value){k.debug(`[Session] Verto attach for existing call ${t}, deferring to per-call handler`);return}const i=await this.attachManager.consumePendingAttachment(t);k.debug(`[Session] Creating reattached call for callID: ${t}`);const r=await this.createCall({nodeId:e.node_id,callId:t,toName:e.callee_id_name,to:e.callee_id_number,fromName:e.caller_id_name,from:e.caller_id_number,reattach:!0,...i});this._calls$.next({[`${r.id}`]:r,...this._calls$.value})}async createOutboundCall(e,t={}){const i=e instanceof Mn?e.defaultChannel:e;let r;try{return r=await this.createCall({to:i,...t}),await ae(Lt(r.selfId$.pipe(C(s=>!!s),te(1),Vt(this.callCreateTimeout)),r.errors$.pipe(te(1),we(s=>na(()=>s.error))))),this._calls$.next({[`${r.id}`]:r,...this._calls$.value}),r}catch(s){k.error("[Session] Error creating outbound call:",s),r==null||r.destroy();const n=new bs(s instanceof ns?"Call create timeout":"Call creation failed",s,"outbound");throw this._errors$.next(n),n}}async createCall(e={}){try{const t=Zu(e);let i;try{if(!this._directory)throw new R("Directory not initialized");const s=await this._directory.findAddressIdByURI(t);if(!s)throw new R(`Address name: ${t} not found`);if(i=this._directory.get(s),!i)throw new R(`Address ID: ${s} not found`)}catch{k.warn(`[Session] Directory lookup failed for ${t}, proceeding with raw URI`)}const r=this.callFactory.createCall(i,{...e});return this.subscribeTo(r.status$.pipe(C(s=>s==="destroyed"),te(1)),()=>{const{[`${r.id}`]:s,...n}=this._calls$.value;this._calls$.next(n)}),r}catch(t){throw k.error("[Session] Error creating call session:",t),new bs("Call create error",t,e.initOffer?"inbound":"outbound")}}destroy(){for(const e of Object.values(this._calls$.value))e.hangup();super.destroy()}},th=class{constructor(e){this.clientSessionManager=e}get authenticated$(){return this.clientSessionManager.authenticated$}get authenticated(){return this.clientSessionManager.authenticated}get signalingEvent$(){return this.clientSessionManager.signalingEvent$}get iceServers(){return this.clientSessionManager.iceServers}async execute(e,t){return this.clientSessionManager.execute(e,t)}get incomingCalls$(){return this.clientSessionManager.incomingCalls$}get incomingCalls(){return this.clientSessionManager.incomingCalls}get calls$(){return this.clientSessionManager.calls$}get calls(){return this.clientSessionManager.calls}};const ih=e=>typeof e=="string",sr=D();var rh=class extends $n{constructor(e,t){super(`/api/fabric/conversations/${e}/messages`,"page_size=100",t),this.groupId=e}},sh=class extends Tn{constructor(e,t,i,r){super(new rh(e,i),t,r)}},nh=class{constructor(e,t,i,r){this.clientSession=e,this.http=t,this.getSubscriberAddressId=i,this.onError=r,this.groupIds=new Map}async join(e){const t=this.getSubscriberAddressId();try{const i=await this.http.request({...ai,url:"/api/fabric/conversations/join",body:JSON.stringify({from_fabric_address_id:t,fabric_address_ids:[e,t]})});if(i.ok&&i.body){const r=JSON.parse(i.body);if(ih(r.group_id))return this.groupIds.set(e,r.group_id),r.group_id}throw new ys("Join Failed - Unexpected response")}catch(i){throw sr.error("[ConversationsManager] Failed to join conversation:",i),i}}async getConversationMessageCollection(e){const t=this.groupIds.get(e)??await this.join(e);return Promise.resolve(new sh(t,this.clientSession.signalingEvent$.pipe(F(vn,"params"),W(i=>sr.debug("[ConversationsManager ] Conversation Event:",i)),f(i=>({...i}))),this.http,this.onError))}async sendText(e,t){const i=this.groupIds.get(t)??await this.join(t),r=this.getSubscriberAddressId();try{if((await this.http.request({...ai,url:"/api/fabric/messages",body:JSON.stringify({group_id:i,from_fabric_address_id:r,text:e})})).ok)return;throw new ys("Send Text Failed - Unexpected response")}catch(s){throw sr.error("[ConversationsManager] Failed to send text message:",s),s}}};const me=D();function oh(e){return e.expires_at?e.expires_at:e.expires_in?Math.floor(Date.now()/1e3)+e.expires_in:(me.warn("[DeviceToken] Could not determine token expiry, using default"),Math.floor(Date.now()/1e3)+Nt)}function kn(e){return e.expires_in?e.expires_in:e.expires_at?Math.max(e.expires_at-Math.floor(Date.now()/1e3),1):Nt}var ah=class extends P{constructor(e,t,i,r){super(),this.dpopManager=e,this.http=t,this.errorHandler=i,this.getCredential=r,this._currentToken$=this.createBehaviorSubject(null),this._refreshInProgress=!1,this._effectiveExpireIn=Nt,this.subscribeTo(this._currentToken$.pipe(C(Boolean),we(s=>{const n=oh(s),o=Math.max(n*1e3-Date.now()-Uc,1e3);return me.debug(`[DeviceToken] Scheduling Client Bound SAT refresh in ${o}ms`),pt(o)})),()=>{this.executeRefresh()})}get effectiveExpireIn(){return this._effectiveExpireIn}async activate(e,t,i){var s;const{satClaims:r}=e;if(!((s=r==null?void 0:r.scope)!=null&&s.includes(Nc))){me.debug("[DeviceToken] No sat:refresh scope, skipping Client Bound SAT activation");return}this._session=t,this._updateCredential=i;try{const n=await this.obtainToken();!n.expires_at&&!n.expires_in&&r.expires_at&&(n.expires_at=r.expires_at),this._effectiveExpireIn=kn(n);const o=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"});await t.reauthenticate(n.token,o,{clientBound:!0}),i({token:n.token}),me.info("[DeviceToken] Client Bound SAT activated successfully"),this._currentToken$.next(n)}catch(n){me.error("[DeviceToken] Failed to activate Client Bound SAT:",n),this.errorHandler(new si(n,"Failed to activate Client Bound SAT"));const o=this.getCredential(),a=r.expires_at??(o.expiry_at?o.expiry_at/1e3:Date.now()/1e3+Nt/1e3);this._currentToken$.next({token:o.token??"",expires_at:a})}}async obtainToken(){const e=await this.dpopManager.createHttpProof({method:"POST",uri:xs}),t=await this.http.request({url:xs,...ai,body:JSON.stringify({dpop_token:e,expire_in:Nt})});if(!t.ok||!t.body)throw new Cs(`Failed to obtain device token: ${t.status} ${t.statusText}`);const i=JSON.parse(t.body);if(!i.token)throw new Cs("Device token response missing token field");return i}async refreshToken(e,t,i){me.debug("[DeviceToken] Refreshing Client Bound SAT");const r=await this.dpopManager.createHttpProof({method:"POST",uri:Ds,accessToken:t}),s=await this.http.request({url:Ds,...ai,body:JSON.stringify({dpop_token:r,expire_in:this._effectiveExpireIn})});if(!s.ok||!s.body)throw new Ye(`Failed to refresh device token: ${s.status} ${s.statusText}`);const n=JSON.parse(s.body);if(!n.token)throw new Ye("Device token refresh response missing token field");!n.expires_at&&!n.expires_in&&(n.expires_in=this._effectiveExpireIn),this._effectiveExpireIn=kn(n);const o=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"});return await e.reauthenticate(n.token,o),i({token:n.token}),me.info("[DeviceToken] Client Bound SAT refreshed successfully"),n}async executeRefresh(){if(this._refreshInProgress){me.debug("[DeviceToken] Refresh already in progress, skipping");return}const e=this._session,t=this._updateCredential;if(!e||!t){me.warn("[DeviceToken] Cannot refresh: session or updateCredential not set");return}if(!e.authenticated){me.debug("[DeviceToken] Session not authenticated, deferring refresh");return}this._refreshInProgress=!0;try{const i=this.getCredential().token;if(!i)throw new Ye("No current token available for refresh");const r=await this.retryRefresh(e,i,t);this._currentToken$.next(r)}catch(i){me.error("[DeviceToken] Automatic Client Bound SAT refresh failed:",i),this.errorHandler(i instanceof Ye?i:new Ye("Automatic token refresh failed",i))}finally{this._refreshInProgress=!1}}async retryRefresh(e,t,i){let r;for(let s=0;s<Is;s++)try{return await this.refreshToken(e,t,i)}catch(n){if(r=n,s<Is-1){const o=zc*Math.pow(2,s);me.warn(`[DeviceToken] Refresh attempt ${s+1} failed, retrying in ${o}ms`),await new Promise(a=>setTimeout(a,o))}}throw r instanceof Error?r:new Ye("All refresh retries exhausted",r)}destroy(){super.destroy()}};const nr=D(),ch=1e3;function lh(){try{if(typeof navigator<"u"&&navigator.userAgent)return navigator.userAgent}catch{}return"unknown"}var dh=class extends P{constructor(e){super(),this._events=[],this._calls=[],this._deviceChanges=[],this._eventRecorded$=this.createSubject(),this._sdkVersion=e.sdkVersion,this._maxEvents=e.maxEvents??ch,nr.debug("DiagnosticsCollector initialized",{sdkVersion:this._sdkVersion,maxEvents:this._maxEvents})}get eventRecorded$(){return this._eventRecorded$.asObservable()}record(e,t,i){const r={timestamp:Date.now(),category:e,event:t,...i!==void 0?{details:i}:{}};this._events=this._appendToBuffer(this._events,r),this._eventRecorded$.next(r)}recordDeviceChange(e,t){const i={timestamp:Date.now(),category:"device",event:e,...t!==void 0?{details:t}:{}};this._deviceChanges=this._appendToBuffer(this._deviceChanges,i),this._events=this._appendToBuffer(this._events,i),this._eventRecorded$.next(i)}recordCallSummary(e){this._calls=this._appendCallToBuffer(this._calls,e),this.record("call","call_summary",{callId:e.callId,direction:e.direction,duration:e.duration,finalStatus:e.finalStatus})}export(){return{sdkVersion:this._sdkVersion,userAgent:lh(),exportedAt:Date.now(),events:[...this._events],calls:[...this._calls],deviceChanges:[...this._deviceChanges]}}clear(){this._events=[],this._calls=[],this._deviceChanges=[],nr.debug("DiagnosticsCollector buffers cleared")}destroy(){nr.debug("DiagnosticsCollector destroyed"),super.destroy()}_appendToBuffer(e,t){const i=[...e,t];return i.length>this._maxEvents?i.slice(i.length-this._maxEvents):i}_appendCallToBuffer(e,t){const i=[...e,t];return i.length>this._maxEvents?i.slice(i.length-this._maxEvents):i}};const An=e=>((e==null?void 0:e.length)??0)===0,uh=e=>{e.pipe(te(1)).subscribe()},hh=D();var ph=class extends $n{constructor(e){super("/api/fabric/addresses","sort_by=name&sort_order=asc",e)}async name(e){const t=await this.http.request({...Wi,url:`${this.endpoint}?name=${encodeURIComponent(e)}`});if(t.ok&&t.body){const i=JSON.parse(t.body);if(!An(i.data))return i.data[0]}hh.error("Failed to fetch addresses")}},vh=class extends Tn{constructor(e,t,i){super(new ph(t),e,i)}},fh=class extends P{constructor(e,t,i,r){super(),this.http=e,this.conversationManager=i,this.onError=r,this.addNewAddress=s=>{var a;const n=new Mn(s,this.conversationManager,this),o=(a=this._statesCollection.get$(s))==null?void 0:a.pipe(B(),f(c=>(n.upnext(c),n)));o&&(uh(o),this._observableRegistry.set(s,o)),this._addressesInstances.set(s,n)},this._addresses$=this.createBehaviorSubject([]),this._addressesInstances=new Map,this._observableRegistry=new Map,this._statesCollection=new vh(t.signalingEvent$.pipe(F(fn,"params"),f(s=>({}))),this.http,this.onError),this.initSubscriptions()}get loading(){return this._statesCollection.loading}initSubscriptions(){this.subscribeTo(this._statesCollection.updated$,()=>{const e=Array.from(this._addressesInstances.values().map(i=>i.id)),t=this._statesCollection.values.filter(i=>!e.includes(i.id));An(t)||(t.forEach(i=>this.addNewAddress(i.id)),this._addresses$.next(Array.from(this._addressesInstances.values())))})}get addresses$(){return this._addresses$.asObservable()}get addresses(){return this._addresses$.value}get hasMore$(){return this._statesCollection.hasMore$}get loading$(){return this._statesCollection.loading$}loadMore(){this._statesCollection.hasMore&&this._statesCollection.loadMore()}get$(e){return this._observableRegistry.has(e)||this.addNewAddress(e),this._observableRegistry.get(e)}get(e){return this._addressesInstances.get(e)}async findAddressIdByURI(e){var i;let t=(i=this._addressesInstances.values().find(r=>r.name===e))==null?void 0:i.id;if(!t){const r=await this._statesCollection.find$("name",e);if(r){const s=await ae(r);this.addNewAddress(s.id),t=s.id}}return t}};const xn=D();var gh=($e=class extends P{constructor(t,i,r,s={}){super(),this.WebSocketConstructor=t,this.endpoint=i,this.outgoingMessages$=r,this.messageQueue=[],this.shouldReconnect=!1,this.boundHandleOpen=()=>this.handleOpen(),this.boundHandleClose=n=>this.handleClose(n),this.boundHandleError=()=>this.handleError(),this.boundHandleMessage=n=>this.handleMessage(n),this._status$=this.createBehaviorSubject("disconnected"),this._incomingMessages$=this.createSubject(),this._errors$=this.createReplaySubject(1),this.reconnectDelayMin=s.reconnectDelayMin??$e.DEFAULT_RECONNECT_DELAY_MIN_MS,this.reconnectDelayMax=s.reconnectDelayMax??$e.DEFAULT_RECONNECT_DELAY_MAX_MS,this.connectionTimeout=s.connectionTimeout??$e.DEFAULT_CONNECTION_TIMEOUT_MS,this.currentReconnectDelay=this.reconnectDelayMin,this.subscriptions.push(this.outgoingMessages$.subscribe(n=>{this.send(n)}))}get status$(){return this._status$.asObservable()}get incomingMessages$(){return this._incomingMessages$.asObservable()}get errors$(){return this._errors$.asObservable()}connect(){this._status$.value==="connecting"||this._status$.value==="connected"||(this.shouldReconnect=!0,this._status$.next("connecting"),this.createWebSocket())}disconnect(){this.shouldReconnect=!1,this.clearReconnectTimer(),this.clearConnectionTimeout();const t=this._status$.value;t==="connected"||t==="connecting"||t==="reconnecting"?this.socket?(this._status$.next("disconnecting"),this.socket.close()):this._status$.next("disconnected"):this._status$.next("disconnected")}reconnect(){this.shouldReconnect=!0,this._status$.next("reconnecting"),this.scheduleReconnection()}send(t){var i;this._status$.value==="connected"&&((i=this.socket)==null?void 0:i.readyState)===1?(xn.wsTraffic({type:"send",raw:t}),this.socket.send(t)):this.messageQueue.push(t)}createWebSocket(){try{this.closeExistingSocket(),this.socket=new this.WebSocketConstructor(this.endpoint),this.setupWebSocketListeners(),this.startConnectionTimeout()}catch(t){const i=t instanceof Error?t:new gt("Failed to create WebSocket");this._errors$.next(i),this.handleConnectionError()}}closeExistingSocket(){if(!this.socket)return;const t=this.socket;this.socket=void 0,this.removeWebSocketListeners(t);try{t.close()}catch{}}setupWebSocketListeners(){this.socket&&(this.socket.addEventListener("open",this.boundHandleOpen),this.socket.addEventListener("close",this.boundHandleClose),this.socket.addEventListener("error",this.boundHandleError),this.socket.addEventListener("message",this.boundHandleMessage))}removeWebSocketListeners(t){try{t.removeEventListener("open",this.boundHandleOpen),t.removeEventListener("close",this.boundHandleClose),t.removeEventListener("error",this.boundHandleError),t.removeEventListener("message",this.boundHandleMessage)}catch{}}handleOpen(){this.clearConnectionTimeout(),this._status$.next("connected"),this.currentReconnectDelay=this.reconnectDelayMin,this.flushMessageQueue()}handleClose(t){this.clearConnectionTimeout(),this.shouldReconnect?(this._status$.next("reconnecting"),this.scheduleReconnection()):this._status$.next("disconnected")}handleError(){const t=new fs("WebSocket connection error");this._errors$.next(t),this.handleConnectionError()}handleMessage(t){xn.wsTraffic({type:"recv",raw:t.data}),this._incomingMessages$.next(t)}handleConnectionError(){this.reconnect()}scheduleReconnection(){this.clearReconnectTimer();const t=this.currentReconnectDelay*(.5+Math.random()*.5);this.reconnectTimer=setTimeout(()=>{this.shouldReconnect&&(this._status$.next("connecting"),this.createWebSocket(),this.increaseReconnectDelay())},t)}increaseReconnectDelay(){this.currentReconnectDelay=Math.min(this.currentReconnectDelay*2,this.reconnectDelayMax)}startConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeoutTimer=setTimeout(()=>{if(this._status$.value==="connecting"){const t=new Qa("WebSocket connection timeout");this._errors$.next(t),this.socket&&this.socket.close()}},this.connectionTimeout)}clearConnectionTimeout(){this.connectionTimeoutTimer&&(clearTimeout(this.connectionTimeoutTimer),this.connectionTimeoutTimer=void 0)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0)}flushMessageQueue(){var t;for(;this.messageQueue.length>0&&((t=this.socket)==null?void 0:t.readyState)===1;){const i=this.messageQueue.shift();i!==void 0&&this.socket.send(i)}}},$e.DEFAULT_RECONNECT_DELAY_MIN_MS=1e3,$e.DEFAULT_RECONNECT_DELAY_MAX_MS=3e4,$e.DEFAULT_CONNECTION_TIMEOUT_MS=1e4,$e);function bh(e){return Yi(e)&&e.method==="signalwire.ping"}const ee=D();var mh=class extends P{constructor(e,t,i,r,s){super(),this.storage=e,this.protocolKey=t,this.onError=s,this.protocol$=this.createReplaySubject(1),this.isConnecting=!1,this.isConnected=!1,this.ackEvent=()=>W(n=>{if(Qi(n))try{ee.debug("[Transport] Sending event ack",{eventId:n.id}),this.send(yd(n.id))}catch(o){ee.error("[Transport] Failed to send event acknowledgment:",o)}}),this.replySignalwirePing=()=>C(n=>{if(bh(n)){try{ee.debug("[Transport] Received ping, sending pong",{pingId:n.id}),this.send(cd(n.id))}catch(o){ee.error("[Transport] Failed to send ping response:",o)}return!1}return!0}),this.discardStaleEvents=()=>C(n=>{if(!Qi(n))return!0;const o=n.params.event_channel;if(!o)return!0;const a=this._currentProtocol;if(!a)return!0;if(!o.includes(a)){const c=n.params.event_type;return ee.warn(`[Transport] Discarding stale event: ${c} (event_channel does not match current protocol)`),!1}return!0}),this._outgoingMessages$=this.createSubject(),this._webSocketConnections=new gh(i,r,this._outgoingMessages$.asObservable(),{connectionTimeout:d.instance.connectionTimeout,reconnectDelayMin:d.instance.reconnectDelayMin,reconnectDelayMax:d.instance.reconnectDelayMax}),this.subscribeTo(this._webSocketConnections.errors$,n=>{var o;(o=this.onError)==null||o.call(this,n)}),this.initialized$=We(()=>Q(this._init())).pipe(pe(1),v(this.destroyed$)),this._jsonRPCMessage$=this._webSocketConnections.incomingMessages$.pipe(f(n=>{var o;try{return JSON.parse(n.data)}catch(a){return ee.error("[Transport] Failed to parse incoming message:",a),(o=this.onError)==null||o.call(this,new nc(a)),null}}),C(n=>n!==null&&(Xi(n)||Yi(n))),Ge(n=>{var o;return ee.error("[Transport] Message processing error:",n),(o=this.onError)==null||o.call(this,n instanceof Error?n:new Error(String(n),{cause:n})),He}),qe(),v(this.destroyed$)),this._jsonRPCResponse$=this._jsonRPCMessage$.pipe(C(Xi)),this._incomingEvent$=this._jsonRPCMessage$.pipe(this.ackEvent(),this.replySignalwirePing(),C(n=>!Xi(n)),this.discardStaleEvents(),qe(),v(this.destroyed$))}async setProtocol(e){this._currentProtocol=e,this.protocol$.next(e),await this._updateProtocolInStorage(e)}get incomingEvent$(){return this._incomingEvent$}get connectionStatus$(){return this._webSocketConnections.status$}async connect(){return this.isConnecting||this.isConnected?(ee.warn("[Transport] Already connecting or connected"),Promise.resolve()):new Promise((e,t)=>{this.isConnecting=!0,this.subscribeTo(this.initialized$,()=>{this._webSocketConnections.connect();const i=this._webSocketConnections.status$.pipe(C(r=>r==="connected"||r==="disconnected"),te(1),Vt(1e4)).subscribe({next:r=>{var s;if(r==="connected")this.isConnecting=!1,this.isConnected=!0,ee.debug("[Transport] Connection established"),e();else{this.isConnecting=!1;const n=new gs("Failed to connect");ee.error("[Transport] Connection failed"),(s=this.onError)==null||s.call(this,n),t(n)}},error:r=>{var s;this.isConnecting=!1,ee.error("[Transport] Connection error:",r),(s=this.onError)==null||s.call(this,r instanceof Error?r:new Error(String(r),{cause:r})),t(r)}});this.subscriptions.push(i),this.subscribeTo(this._webSocketConnections.status$.pipe(C(r=>r==="disconnected")),()=>{ee.debug("[Transport] Disconnected"),this.isConnected=!1})})})}reconnect(){this._webSocketConnections.reconnect()}async execute(e,t){return this.send(e),new Qu(e,this._jsonRPCResponse$,t).promise}send(e){const t=JSON.stringify(e);this._outgoingMessages$.next(t)}disconnect(){ee.debug("[Transport] Disconnecting"),this.isConnected=!1,this.isConnecting=!1,this._webSocketConnections.disconnect()}destroy(){ee.debug("[Transport] Destroying"),this.disconnect(),super.destroy(),this._webSocketConnections.destroy()}async _loadProtocolFromStorage(){try{const e=await this.storage.getItem(this.protocolKey);this._currentProtocol=e??void 0,this.protocol$.next(e??void 0)}catch(e){throw ee.error("Failed to retrieve protocol from storage:",e),e}}async _updateProtocolInStorage(e){if(!e){try{await this.storage.removeItem(this.protocolKey)}catch(t){throw ee.error("Failed to remove protocol from storage:",t),t}return}try{const t=await this.storage.getItem(this.protocolKey);(!t||t!==e)&&await this.storage.setItem(this.protocolKey,e)}catch(t){throw ee.error("Failed to update protocol in storage:",t),t}}async _init(){return await this._loadProtocolFromStorage(),!0}};const A=D(),yh=e=>{if(typeof e=="string"){const t=e.indexOf("?");if(t!==-1){const i=e.substring(t+1),r=new URLSearchParams(i).get("channel");if(r==="video")return{audio:!0,video:!0,receiveVideo:!0};if(r==="audio")return{audio:!0,video:!1}}}return{}};var _h=class extends P{constructor(e,t={}){super(),this.preferences=new Pl,this._subscriber$=this.createBehaviorSubject(void 0),this._directory$=this.createBehaviorSubject(void 0),this._isConnected$=this.createBehaviorSubject(!1),this._isRegistered$=this.createBehaviorSubject(!1),this._errors$=this.createReplaySubject(1),this._options={},this._deps=new Bl,this._credentialProvider=e,this._options={...d.instance.defaultSignalWireOptions,...t},this._options.storageImplementation&&(this._deps.storageImpl=this._options.storageImplementation),this._options.persistSession&&(this._deps.persistSession=!0),this._options.webSocketConstructor&&(this._deps.WebSocket=this._options.webSocketConstructor),this._options.savePreferences&&this.preferences.enableSavePreferences(this._deps.storage),this._options.webRTCApiProvider&&(this._deps.webRTCApiProvider=this._options.webRTCApiProvider),this._options.logger!==void 0&&dc(this._options.logger),this._options.logLevel&&hc(this._options.logLevel),this._options.debug&&uc(this._options.debug),this._deviceController=this._deps.deviceController,this._options.skipDeviceMonitoring||this._deviceController.enableDeviceMonitoring(),this.subscribeTo(this._deviceController.errors$,i=>{this._errors$.next(i)}),this.initResilienceSubsystems(),this.resolveCredentials().then(()=>{this.init().catch(i=>{A.error("[SignalWire] Initialization error:",i),this._deps.storage.removeItem("sw:cached_credential"),this._deps.storage.removeItem("sw:cached_credential","local"),this._errors$.next(i instanceof Error?i:new Error(String(i),{cause:i}))})}).catch(i=>{A.error("[SignalWire] Initialization error:",i),this._errors$.next(i instanceof Error?i:new Error(String(i),{cause:i}))})}async initDPoP(){var e;if((e=this._dpopManager)!=null&&e.initialized)return this._dpopManager.fingerprint;try{this._dpopManager=new jl;const t=await this._dpopManager.init();return A.debug("[SignalWire] DPoP initialized, fingerprint available"),t}catch(t){A.warn("[SignalWire] DPoP initialization failed, proceeding without DPoP:",t),this._dpopManager=void 0;return}}async resolveCredentials(){const e=await this.initDPoP();if(this._credentialProvider)return this.validateCredentials(this._credentialProvider,void 0,e);for(const t of this._deps.persistSession?["local","session"]:["session"])try{const i=await this._deps.storage.getItem("sw:cached_credential",t);if(i!=null&&i.token)return A.debug(`[SignalWire] Using cached credential from ${t}Storage`),await this.validateCredentials(void 0,i)}catch{}throw new Je("No credential provider and no cached session. Provide a CredentialProvider or enable persistSession with a prior login.")}async validateCredentials(e,t,i){var n;const r=i??((n=this._dpopManager)!=null&&n.initialized?this._dpopManager.fingerprint:void 0),s=t??(e?await e.authenticate(r?{fingerprint:r}:void 0):void 0);if(!s)throw new Je("No credentials available.");if(s.token)try{const o=mc(s.token,{header:!0});this._deps.ch=o.ch}catch(o){throw A.error("[SignalWire] Invalid JWT token provided in credentials:",o),new Je("Invalid JWT token provided in credentials.",{cause:o})}if(!s.token&&!s.authorizationState)throw A.error("[SignalWire] No valid authentication credentials provided."),new Je("No valid authentication credentials provided.");if(!this._deps.persistSession&&s.expiry_at&&s.expiry_at<Date.now())throw A.error("[SignalWire] Provided credentials have expired."),new Je("Provided credentials have expired.");if(s.expiry_at&&(e!=null&&e.refresh)&&this.scheduleCredentialRefresh(e,s.expiry_at),this._deps.credential=s,this.persistCredential(s),this.isConnected&&this._clientSession.authenticated&&s.token)try{await this._clientSession.reauthenticate(s.token),A.info("[SignalWire] Session refreshed with new credentials.")}catch(o){A.error("[SignalWire] Failed to refresh session with new credentials:",o),this._errors$.next(o instanceof Error?o:new Error(String(o),{cause:o}))}}scheduleCredentialRefresh(e,t,i=0){this._refreshTimerId!==void 0&&clearTimeout(this._refreshTimerId);const r=i===0?Math.max(t-Date.now()-Hc,1e3):Math.min(Fc*Math.pow(2,i)*(.5+Math.random()*.5),jc);this._refreshTimerId=setTimeout(async()=>{try{if(!e.refresh)throw new Je("Credential provider does not support refresh");const s=await e.refresh();this._deps.credential=s,this.persistCredential(s),A.info("[SignalWire] Credentials refreshed successfully."),s.expiry_at&&this.scheduleCredentialRefresh(e,s.expiry_at,0)}catch(s){const n=i+1;A.error(`[SignalWire] Credential refresh failed (attempt ${n}/${Rs}):`,s),this._errors$.next(s instanceof Error?s:new Error(String(s),{cause:s})),n<Rs?this.scheduleCredentialRefresh(e,t,n):(A.error("[SignalWire] Credential refresh exhausted all retries. Disconnecting."),this._errors$.next(new Ye("Credential refresh failed after max retries")),this.disconnect())}},r)}persistCredential(e){e.token&&(this._deps.storage.setItem("sw:cached_credential",e),this._deps.persistSession&&this._deps.storage.setItem("sw:cached_credential",e,"local"))}async init(){if(this._subscriber$.next(new sd(this._deps.http)),this._options.skipConnection||await this.connect(),!this._options.reconnectAttachedCalls&&this._attachManager&&await this._attachManager.flush(),!this._options.skipRegister)try{await this.register()}catch(e){A.error("[SignalWire] Registration failed:",e),this._errors$.next(e instanceof Error?e:new Error(String(e),{cause:e}))}this.handleAttachments()}async handleAttachments(){if(!this._attachManager){A.error("[SignalWire] AttachManager not initialized");return}if(this._options.reconnectAttachedCalls)try{await this._attachManager.reattachCalls()}catch(e){A.error("[SignalWire] Failed to reattach calls:",e),this._errors$.next(e instanceof Error?e:new Error(String(e),{cause:e}))}}async connect(){var r,s,n;await this.teardownTransportAndSession();try{const o=this._subscriber$.value;if(!o)throw new gt("Subscriber not initialized before connect");if(!await ae(o.fetched$))throw new gt("Failed to fetch subscriber information - fetched$ emitted false");this._deps.subscriber=o}catch(o){throw A.error(`[SignalWire] Failed to fetch subscriber information: ${o instanceof Error?o.message:"Unknown error"}. This usually means the subscriber token is invalid or expired.`),new gt("Error fetching subscriber information",{cause:o})}const e=o=>{this._errors$.next(o)};this._transport=new mh(this._deps.storage,this._deps.protocolKey,this._deps.WebSocket,d.instance.relayHost??this._deps.relayHost,e),this._attachManager=new _d(this._deps.storage,this._deps.deviceController,d.instance.reconnectCallsTimeout,this._deps.attachedCallsKey),this._clientSession=new eh(()=>this._deps.credential,this._transport,this._deps.storage,this._deps.authorizationStateKey,this._deps.deviceController,this._attachManager,this._deps.webRTCApiProvider,this._dpopManager,(r=this._networkMonitor)==null?void 0:r.networkChange$),this._publicSession=new th(this._clientSession),this._clientSession.onBeforeReconnect=async()=>{var o;if(this._credentialProvider)try{const a=(o=this._dpopManager)!=null&&o.initialized?this._dpopManager.fingerprint:void 0;A.debug("[SignalWire] Credential expired, refreshing before reconnect");const c=await this._credentialProvider.authenticate(a?{fingerprint:a}:void 0);this._deps.credential=c,A.debug("[SignalWire] Credential refreshed successfully for reconnect")}catch(a){throw A.error("[SignalWire] Failed to refresh credentials for reconnect:",a),this._errors$.next(a instanceof Error?a:new Error(String(a),{cause:a})),a}},this.subscribeTo(this._clientSession.errors$,o=>{this._errors$.next(o)}),await this._clientSession.connect(),(s=this._dpopManager)!=null&&s.initialized&&(this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0,A.debug("[SignalWire] Developer refresh disabled — Client Bound SAT activation starting")),this._deviceTokenManager=new ah(this._dpopManager,this._deps.http,o=>this._errors$.next(o),()=>this._deps.credential),await this._deviceTokenManager.activate(this._deps.subscriber,this._clientSession,o=>{this._deps.credential={...this._deps.credential,...o}})),this.subscribeTo(this._clientSession.authenticated$.pipe(ei(1),C(Boolean)),async()=>{try{this._deviceTokenManager&&(await this._deviceTokenManager.activate(this._deps.subscriber,this._clientSession,o=>{this._deps.credential={...this._deps.credential,...o}}),A.debug("[SignalWire] Client Bound SAT re-activated after reconnect"))}catch(o){A.error("[SignalWire] Client Bound SAT re-activation failed (non-fatal):",o),this._errors$.next(o instanceof Error?o:new Error(String(o),{cause:o}))}try{A.debug("[SignalWire] Re-registering subscriber after reconnect"),await this.register(),A.debug("[SignalWire] Subscriber re-registered successfully after reconnect")}catch(o){A.error("[SignalWire] Re-registration failed after reconnect:",o),this._errors$.next(o instanceof Error?o:new Error(String(o),{cause:o}))}});const t=new nh(this._clientSession,this._deps.http,()=>this._deps.getSubscriberFromAddressId(),e),i=new fh(this._deps.http,this._clientSession,t,e);this._directory$.next(i),this._clientSession.setDirectory(i),this._isConnected$.next(!0),(n=this._diagnosticsCollector)==null||n.record("connection","connected"),this.subscribeTo(this._clientSession.authenticated$.pipe(ei(2),C(Boolean)),()=>{var o;(o=this._diagnosticsCollector)==null||o.record("connection","reconnected")})}get subscriber$(){return this.deferEmission(this._subscriber$.asObservable())}get subscriber(){return this._subscriber$.value}get directory$(){return this.deferEmission(this._directory$.asObservable())}get directory(){return this._directory$.value}get isRegistered$(){return this.deferEmission(this._isRegistered$.asObservable())}get isRegistered(){return this._isRegistered$.value}get isConnected(){return this._isConnected$.value}get isConnected$(){return this.deferEmission(this._isConnected$.asObservable())}get ready$(){return this.publicCachedObservable("ready$",()=>this._isConnected$.pipe(we(e=>e?this._clientSession.authenticated$:Ot(!1))))}get errors$(){return this.deferEmission(this._errors$.asObservable())}get platformCapabilities(){return this._platformCapabilities??(this._platformCapabilities=Js(this._options.webRTCApiProvider)),this._platformCapabilities}get deviceRecovered$(){return this.deferEmission(this._deviceController.deviceRecovered$)}exportDiagnostics(){const e={audioInput:this.audioInputDevices,audioOutput:this.audioOutputDevices,videoInput:this.videoInputDevices},t={sdkVersion:"unknown",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown",capabilities:this.platformCapabilities,events:[],calls:[],deviceChanges:[],devices:e};if(!this._diagnosticsCollector)return t;const i=this._diagnosticsCollector.export();return{...t,sdkVersion:i.sdkVersion,userAgent:i.userAgent,events:i.events,calls:i.calls,deviceChanges:i.deviceChanges,devices:e}}initResilienceSubsystems(){try{this._platformCapabilities=Js(this._options.webRTCApiProvider)}catch(e){A.warn("[SignalWire] Failed to detect platform capabilities:",e)}try{this._networkMonitor=new Hl}catch(e){A.warn("[SignalWire] Failed to initialize NetworkMonitor:",e)}try{this._visibilityController=new id,this.subscribeTo(this._visibilityController.visibilityChange$.pipe(C(e=>e.to==="visible"&&d.instance.refreshDevicesOnVisible)),()=>{A.debug("[SignalWire] Page visible, re-enumerating devices");try{this._deviceController.disableDeviceMonitoring(),this._deviceController.enableDeviceMonitoring()}catch{}})}catch(e){A.warn("[SignalWire] Failed to initialize VisibilityController:",e)}try{this._diagnosticsCollector=new dh({sdkVersion:"3.30.0"})}catch(e){A.warn("[SignalWire] Failed to initialize DiagnosticsCollector:",e)}}async disconnect(){var e;this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0),(e=this._diagnosticsCollector)==null||e.record("connection","disconnected"),await this.teardownTransportAndSession(),this._isConnected$.next(!1)}async teardownTransportAndSession(){const e=this._clientSession,t=this._transport;if(e){try{await e.disconnect()}catch(i){A.warn("[SignalWire] Error disconnecting previous session:",i)}e.destroy()}t&&t.destroy(),this._clientSession=void 0,this._publicSession=void 0,this._transport=void 0,this._attachManager=void 0}async waitAuthentication(){await ae(this.ready$.pipe(C(e=>e===!0)))}async register(){try{await this.waitAuthentication(),await this._transport.execute(Ki({method:"subscriber.online",params:{}})),this._isRegistered$.next(!0);return}catch(e){if(!this._deps.credential.token)throw this._errors$.next(e instanceof Error?e:new Error(String(e),{cause:e})),e;A.debug("[SignalWire] Failed to register subscriber, trying reauthentication...");try{await this._clientSession.reauthenticate(this._deps.credential.token),A.debug("[SignalWire] Reauthentication successful, retrying register()"),await this._transport.execute(Ki({method:"subscriber.online",params:{}})),this._isRegistered$.next(!0)}catch(t){A.error("[SignalWire] Reauthentication failed during register():",t);const i=new Je("Failed to register subscriber, and reauthentication attempt also failed. Please check your credentials.",{cause:t instanceof Error?t:new Error(String(t),{cause:t})});throw this._errors$.next(i),i}}}async unregister(){try{await this._transport.execute(Ki({method:"subscriber.offline",params:{}})),this._isRegistered$.next(!1)}catch(e){throw A.error("[SignalWire] Failed to unregister subscriber:",e),this._errors$.next(e instanceof Error?e:new Error(String(e),{cause:e})),e}}async dial(e,t={}){const i={...d.instance.preferredMediaOptions,...yh(e),...t};return await this.waitAuthentication(),A.debug("[SignalWire] Dialing with options:",i),this._clientSession.createOutboundCall(e,i)}async preflight(e,t){const i=this._clientSession.iceServers??d.instance.iceServers??[],r=this._isConnected$.value;return new ed(this._deviceController,i,r,0,async(s,n)=>this.dial(s,n),t).run(e)}get session(){return this._publicSession}get audioInputDevices$(){return this.deferEmission(this._deviceController.audioInputDevices$)}get audioInputDevices(){return this._deviceController.audioInputDevices}get audioOutputDevices$(){return this.deferEmission(this._deviceController.audioOutputDevices$)}get audioOutputDevices(){return this._deviceController.audioOutputDevices}get videoInputDevices$(){return this.deferEmission(this._deviceController.videoInputDevices$)}get videoInputDevices(){return this._deviceController.videoInputDevices}get selectedAudioInputDevice$(){return this.deferEmission(this._deviceController.selectedAudioInputDevice$)}get selectedAudioOutputDevice$(){return this.deferEmission(this._deviceController.selectedAudioOutputDevice$)}get selectedVideoInputDevice$(){return this.deferEmission(this._deviceController.selectedVideoInputDevice$)}get selectedAudioInputDevice(){return this._deviceController.selectedAudioInputDevice}get selectedAudioOutputDevice(){return this._deviceController.selectedAudioOutputDevice}get selectedVideoInputDevice(){return this._deviceController.selectedVideoInputDevice}get selectedAudioInputDeviceConstraints(){return this._deviceController.selectedAudioInputDeviceConstraints}get selectedVideoInputDeviceConstraints(){return this._deviceController.selectedVideoInputDeviceConstraints}deviceInfoToConstraints(e){return this._deviceController.deviceInfoToConstraints(e)}selectAudioInputDevice(e){this._deviceController.selectAudioInputDevice(e)}selectVideoInputDevice(e){this._deviceController.selectVideoInputDevice(e)}selectAudioOutputDevice(e){this._deviceController.selectAudioOutputDevice(e)}async applySelectedAudioOutputDevice(e){const t=this._deviceController.selectedAudioOutputDevice;if(!(t!=null&&t.deviceId))return!1;const i=e;if(typeof i.setSinkId!="function")return A.warn("[SignalWire] setSinkId not supported on this element / browser"),!1;try{return await i.setSinkId(t.deviceId),!0}catch(r){return A.warn("[SignalWire] Failed to apply audio output device:",r),!1}}enableDeviceMonitoring(){this._deviceController.enableDeviceMonitoring()}disableDeviceMonitoring(){this._deviceController.disableDeviceMonitoring()}async getDeviceCapabilities(e){return this._deviceController.getDeviceCapabilities(e)}async isValidDevice(e){return this._deviceController.isValidDevice(e)}setStorageManager(e){this._deviceController.setStorageManager(e)}async clearDeviceState(){return this._deviceController.clearDeviceState()}async enumerateDevices(){return this._deviceController.enumerateDevices()}disableAudioInput(){this._deviceController.disableAudioInput()}enableAudioInput(){this._deviceController.enableAudioInput()}disableVideoInput(){this._deviceController.disableVideoInput()}enableVideoInput(){this._deviceController.enableVideoInput()}get videoInputDisabled$(){return this.deferEmission(this._deviceController.videoInputDisabled$)}get audioInputDisabled$(){return this.deferEmission(this._deviceController.audioInputDisabled$)}get videoInputDisabled(){return this._deviceController.videoInputDisabled}get audioInputDisabled(){return this._deviceController.audioInputDisabled}async requestMediaPermissions(e={audio:!0,video:!0}){const t={audio:e.audio??!1,video:e.video??!1};let i=!1,r=!1,s,n;try{const o=(await this._deps.webRTCApiProvider.mediaDevices.getUserMedia(t)).getTracks();for(const a of o){const c=a.getSettings();a.kind==="audio"?(i=!0,c.deviceId&&(s=this.audioInputDevices.find(l=>l.deviceId===c.deviceId))):a.kind==="video"&&(r=!0,c.deviceId&&(n=this.videoInputDevices.find(l=>l.deviceId===c.deviceId))),a.stop()}}catch(o){A.warn("[SignalWire] Media permission request failed:",o)}if(await this._deviceController.enumerateDevices(),i&&s){const o=s.deviceId;s=this.audioInputDevices.find(a=>a.deviceId===o)??s}if(r&&n){const o=n.deviceId;n=this.videoInputDevices.find(a=>a.deviceId===o)??n}return i&&s&&!this.selectedAudioInputDevice&&this.selectAudioInputDevice(s),r&&n&&!this.selectedVideoInputDevice&&this.selectVideoInputDevice(n),{audio:i,video:r,selectedAudioDevice:s,selectedVideoDevice:n}}async resetToDefaults(){await this._deps.storage.clearAll();const e=d.instance;e.preferredAudioInput=null,e.preferredAudioOutput=null,e.preferredVideoInput=null,await this._deviceController.clearDeviceState()}destroy(){var e,t,i,r,s;this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0),(e=this._deviceTokenManager)==null||e.destroy(),(t=this._dpopManager)==null||t.destroy(),this._attachManager&&this._attachManager.detachAll(),this._transport.destroy(),this._clientSession.destroy();try{(i=this._networkMonitor)==null||i.destroy()}catch{}try{(r=this._visibilityController)==null||r.destroy()}catch{}try{(s=this._diagnosticsCollector)==null||s.destroy()}catch{}this._networkMonitor=void 0,this._visibilityController=void 0,this._diagnosticsCollector=void 0,super.destroy()}};D();var wh=class{constructor(e){this.credentials=e}async authenticate(){return Promise.resolve(this.credentials)}};return(()=>{if(typeof window<"u"){const e=new CustomEvent("signalwire:js:ready",{detail:{version:"3.30.0"}});window.dispatchEvent(e)}})(),u.LitElement=X,u.SignalWire=_h,u.StaticCredentialProvider=wh,u.callContext=Fe,u.css=ce,u.html=g,u.ready=Ga,u.version=Wa,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),u})({});
2475
+ //# sourceMappingURL=signalwire-web-components-embed.iife.js.map