@signalwire/web-components 1.0.0-dev-20260429174756 → 1.0.0-dev-20260430003639
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var SignalWireUI=(function(l){"use strict";var Km=Object.defineProperty;var Vl=l=>{throw TypeError(l)};var Zm=(l,ve,Ue)=>ve in l?Km(l,ve,{enumerable:!0,configurable:!0,writable:!0,value:Ue}):l[ve]=Ue;var ce=(l,ve,Ue)=>Zm(l,typeof ve!="symbol"?ve+"":ve,Ue),Qm=(l,ve,Ue)=>ve.has(l)||Vl("Cannot "+Ue);var Hl=(l,ve,Ue)=>ve.has(l)?Vl("Cannot add the same private member more than once"):ve instanceof WeakSet?ve.add(l):ve.set(l,Ue);var Tn=(l,ve,Ue)=>(Qm(l,ve,"access private method"),Ue);var Cl,je,pi,
|
|
1
|
+
var SignalWireUI=(function(l){"use strict";var Km=Object.defineProperty;var Vl=l=>{throw TypeError(l)};var Zm=(l,ve,Ue)=>ve in l?Km(l,ve,{enumerable:!0,configurable:!0,writable:!0,value:Ue}):l[ve]=Ue;var ce=(l,ve,Ue)=>Zm(l,typeof ve!="symbol"?ve+"":ve,Ue),Qm=(l,ve,Ue)=>ve.has(l)||Vl("Cannot "+Ue);var Hl=(l,ve,Ue)=>ve.has(l)?Vl("Cannot add the same private member more than once"):ve instanceof WeakSet?ve.add(l):ve.set(l,Ue);var Tn=(l,ve,Ue)=>(Qm(l,ve,"access private method"),Ue);var Cl,je,pi,yt,gi,js,Wl;function ve(t,e){for(var i=0;i<e.length;i++){const r=e[i];if(typeof r!="string"&&!Array.isArray(r)){for(const n in r)if(n!=="default"&&!(n in t)){const s=Object.getOwnPropertyDescriptor(r,n);s&&Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>r[n]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}/**
|
|
2
2
|
* @license
|
|
3
3
|
* Copyright 2019 Google LLC
|
|
4
4
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -62,15 +62,15 @@ var SignalWireUI=(function(l){"use strict";var Km=Object.defineProperty;var Vl=l
|
|
|
62
62
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
63
63
|
*/function $e({context:t,subscribe:e}){return(i,r)=>{typeof r=="object"?r.addInitializer((function(){new aa(this,{context:t,callback:n=>{i.set.call(this,n)},subscribe:e})})):i.constructor.addInitializer((n=>{new aa(n,{context:t,callback:s=>{n[r]=s},subscribe:e})}))}}const ht="sw-call-state";class oa{constructor(e){this._subscription=null,this._seenCallIds=new Set,this._callback=null,e.addController(this)}hostConnected(){}hostDisconnected(){this.disconnect()}set onIncomingCall(e){this._callback=e}connect(e){this.disconnect(),this._subscription=e.subscribe(i=>{var r;for(const n of i)this._seenCallIds.has(n.id)||(this._seenCallIds.add(n.id),(r=this._callback)==null||r.call(this,{call:n,callerName:n.fromName,callerNumber:n.from}))})}disconnect(){var e;(e=this._subscription)==null||e.unsubscribe(),this._subscription=null,this._seenCallIds.clear()}}const ir="sw-devices";function fu(t,e){let i=null;return function(...n){const s=()=>{i=null,t(...n)};i!==null&&clearTimeout(i),i=setTimeout(s,e)}}const vu=2e3;function bu(t){return new Promise(e=>{if(t.readyState>=HTMLMediaElement.HAVE_METADATA){e();return}let i=!1;const r=()=>{i||(i=!0,clearTimeout(n),t.removeEventListener("canplay",r),t.removeEventListener("resize",r),e())},n=setTimeout(r,vu);t.addEventListener("canplay",r),t.addEventListener("resize",r)})}function Lr(t,e){t.srcObject=e}function ca(t){t.srcObject&&(t.srcObject=null)}var _n=function(t,e){return _n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,r){i.__proto__=r}||function(i,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(i[n]=r[n])},_n(t,e)};function We(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");_n(t,e);function i(){this.constructor=t}t.prototype=e===null?Object.create(e):(i.prototype=e.prototype,new i)}function mu(t,e,i,r){function n(s){return s instanceof i?s:new i(function(a){a(s)})}return new(i||(i=Promise))(function(s,a){function o(h){try{u(r.next(h))}catch(p){a(p)}}function c(h){try{u(r.throw(h))}catch(p){a(p)}}function u(h){h.done?s(h.value):n(h.value).then(o,c)}u((r=r.apply(t,e||[])).next())})}function la(t,e){var i={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,n,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(u){return function(h){return c([u,h])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(i=0)),i;)try{if(r=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return i.label++,{value:u[1],done:!1};case 5:i.label++,n=u[1],u=[0];continue;case 7:u=i.ops.pop(),i.trys.pop();continue;default:if(s=i.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){i=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){i.label=u[1];break}if(u[0]===6&&i.label<s[1]){i.label=s[1],s=u;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(u);break}s[2]&&i.ops.pop(),i.trys.pop();continue}u=e.call(t,i)}catch(h){u=[6,h],n=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Si(t){var e=typeof Symbol=="function"&&Symbol.iterator,i=e&&t[e],r=0;if(i)return i.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function pt(t,e){var i=typeof Symbol=="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=r.next()).done;)s.push(n.value)}catch(o){a={error:o}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(a)throw a.error}}return s}function gt(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}function Ci(t){return this instanceof Ci?(this.v=t,this):new Ci(t)}function yu(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=i.apply(t,e||[]),n,s=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),n[Symbol.asyncIterator]=function(){return this},n;function a(m){return function(R){return Promise.resolve(R).then(m,p)}}function o(m,R){r[m]&&(n[m]=function(y){return new Promise(function(I,x){s.push([m,y,I,x])>1||c(m,y)})},R&&(n[m]=R(n[m])))}function c(m,R){try{u(r[m](R))}catch(y){f(s[0][3],y)}}function u(m){m.value instanceof Ci?Promise.resolve(m.value.v).then(h,p):f(s[0][2],m)}function h(m){c("next",m)}function p(m){c("throw",m)}function f(m,R){m(R),s.shift(),s.length&&c(s[0][0],s[0][1])}}function wu(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],i;return e?e.call(t):(t=typeof Si=="function"?Si(t):t[Symbol.iterator](),i={},r("next"),r("throw"),r("return"),i[Symbol.asyncIterator]=function(){return this},i);function r(s){i[s]=t[s]&&function(a){return new Promise(function(o,c){a=t[s](a),n(o,c,a.done,a.value)})}}function n(s,a,o,c){Promise.resolve(c).then(function(u){s({value:u,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;function pe(t){return typeof t=="function"}function Fr(t){var e=function(r){Error.call(r),r.stack=new Error().stack},i=t(e);return i.prototype=Object.create(Error.prototype),i.prototype.constructor=i,i}var Ln=Fr(function(t){return function(i){t(this),this.message=i?i.length+` errors occurred during unsubscription:
|
|
64
64
|
`+i.map(function(r,n){return n+1+") "+r.toString()}).join(`
|
|
65
|
-
`):"",this.name="UnsubscriptionError",this.errors=i}});function Ur(t,e){if(t){var i=t.indexOf(e);0<=i&&t.splice(i,1)}}var Ai=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,i,r,n,s;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var o=Si(a),c=o.next();!c.done;c=o.next()){var u=c.value;u.remove(this)}}catch(y){e={error:y}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(e)throw e.error}}else a.remove(this);var h=this.initialTeardown;if(pe(h))try{h()}catch(y){s=y instanceof Ln?y.errors:[y]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var f=Si(p),m=f.next();!m.done;m=f.next()){var R=m.value;try{ha(R)}catch(y){s=s??[],y instanceof Ln?s=gt(gt([],pt(s)),pt(y.errors)):s.push(y)}}}catch(y){r={error:y}}finally{try{m&&!m.done&&(n=f.return)&&n.call(f)}finally{if(r)throw r.error}}}if(s)throw new Ln(s)}},t.prototype.add=function(e){var i;if(e&&e!==this)if(this.closed)ha(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(i=this._finalizers)!==null&&i!==void 0?i:[]).push(e)}},t.prototype._hasParent=function(e){var i=this._parentage;return i===e||Array.isArray(i)&&i.includes(e)},t.prototype._addParent=function(e){var i=this._parentage;this._parentage=Array.isArray(i)?(i.push(e),i):i?[i,e]:e},t.prototype._removeParent=function(e){var i=this._parentage;i===e?this._parentage=null:Array.isArray(i)&&Ur(i,e)},t.prototype.remove=function(e){var i=this._finalizers;i&&Ur(i,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})(),ua=Ai.EMPTY;function da(t){return t instanceof Ai||t&&"closed"in t&&pe(t.remove)&&pe(t.add)&&pe(t.unsubscribe)}function ha(t){pe(t)?t():t.unsubscribe()}var Su={Promise:void 0},Cu={setTimeout:function(t,e){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return setTimeout.apply(void 0,gt([t,e],pt(i)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function pa(t){Cu.setTimeout(function(){throw t})}function rr(){}function Nr(t){t()}var Fn=(function(t){We(e,t);function e(i){var r=t.call(this)||this;return r.isStopped=!1,i?(r.destination=i,da(i)&&i.add(r)):r.destination=Eu,r}return e.create=function(i,r,n){return new Ti(i,r,n)},e.prototype.next=function(i){this.isStopped||this._next(i)},e.prototype.error=function(i){this.isStopped||(this.isStopped=!0,this._error(i))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(i){this.destination.next(i)},e.prototype._error=function(i){try{this.destination.error(i)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Ai),Au=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var i=this.partialObserver;if(i.next)try{i.next(e)}catch(r){Br(r)}},t.prototype.error=function(e){var i=this.partialObserver;if(i.error)try{i.error(e)}catch(r){Br(r)}else Br(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(i){Br(i)}},t})(),Ti=(function(t){We(e,t);function e(i,r,n){var s=t.call(this)||this,a;return pe(i)||!i?a={next:i??void 0,error:r??void 0,complete:n??void 0}:a=i,s.destination=new Au(a),s}return e})(Fn);function Br(t){pa(t)}function Tu(t){throw t}var Eu={closed:!0,next:rr,error:Tu,complete:rr},Un=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function jt(t){return t}function zr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return ga(t)}function ga(t){return t.length===0?jt:t.length===1?t[0]:function(i){return t.reduce(function(r,n){return n(r)},i)}}var be=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var i=new t;return i.source=this,i.operator=e,i},t.prototype.subscribe=function(e,i,r){var n=this,s=xu(e)?e:new Ti(e,i,r);return Nr(function(){var a=n,o=a.operator,c=a.source;s.add(o?o.call(s,c):c?n._subscribe(s):n._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(i){e.error(i)}},t.prototype.forEach=function(e,i){var r=this;return i=fa(i),new i(function(n,s){var a=new Ti({next:function(o){try{e(o)}catch(c){s(c),a.unsubscribe()}},error:s,complete:n});r.subscribe(a)})},t.prototype._subscribe=function(e){var i;return(i=this.source)===null||i===void 0?void 0:i.subscribe(e)},t.prototype[Un]=function(){return this},t.prototype.pipe=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return ga(e)(this)},t.prototype.toPromise=function(e){var i=this;return e=fa(e),new e(function(r,n){var s;i.subscribe(function(a){return s=a},function(a){return n(a)},function(){return r(s)})})},t.create=function(e){return new t(e)},t})();function fa(t){var e;return(e=t??Su.Promise)!==null&&e!==void 0?e:Promise}function ku(t){return t&&pe(t.next)&&pe(t.error)&&pe(t.complete)}function xu(t){return t&&t instanceof Fn||ku(t)&&da(t)}function Du(t){return pe(t==null?void 0:t.lift)}function le(t){return function(e){if(Du(e))return e.lift(function(i){try{return t(i,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function ae(t,e,i,r,n){return new Iu(t,e,i,r,n)}var Iu=(function(t){We(e,t);function e(i,r,n,s,a,o){var c=t.call(this,i)||this;return c.onFinalize=a,c.shouldUnsubscribe=o,c._next=r?function(u){try{r(u)}catch(h){i.error(h)}}:t.prototype._next,c._error=s?function(u){try{s(u)}catch(h){i.error(h)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=n?function(){try{n()}catch(u){i.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var i;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((i=this.onFinalize)===null||i===void 0||i.call(this))}},e})(Fn),va={schedule:function(t){var e=requestAnimationFrame,i=cancelAnimationFrame,r=e(function(n){i=void 0,t(n)});return new Ai(function(){return i==null?void 0:i(r)})},requestAnimationFrame:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return requestAnimationFrame.apply(void 0,gt([],pt(t)))},cancelAnimationFrame:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return cancelAnimationFrame.apply(void 0,gt([],pt(t)))},delegate:void 0},Mu=Fr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ei=(function(t){We(e,t);function e(){var i=t.call(this)||this;return i.closed=!1,i.currentObservers=null,i.observers=[],i.isStopped=!1,i.hasError=!1,i.thrownError=null,i}return e.prototype.lift=function(i){var r=new ba(this,this);return r.operator=i,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new Mu},e.prototype.next=function(i){var r=this;Nr(function(){var n,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var a=Si(r.currentObservers),o=a.next();!o.done;o=a.next()){var c=o.value;c.next(i)}}catch(u){n={error:u}}finally{try{o&&!o.done&&(s=a.return)&&s.call(a)}finally{if(n)throw n.error}}}})},e.prototype.error=function(i){var r=this;Nr(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=i;for(var n=r.observers;n.length;)n.shift().error(i)}})},e.prototype.complete=function(){var i=this;Nr(function(){if(i._throwIfClosed(),!i.isStopped){i.isStopped=!0;for(var r=i.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var i;return((i=this.observers)===null||i===void 0?void 0:i.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(i){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,i)},e.prototype._subscribe=function(i){return this._throwIfClosed(),this._checkFinalizedStatuses(i),this._innerSubscribe(i)},e.prototype._innerSubscribe=function(i){var r=this,n=this,s=n.hasError,a=n.isStopped,o=n.observers;return s||a?ua:(this.currentObservers=null,o.push(i),new Ai(function(){r.currentObservers=null,Ur(o,i)}))},e.prototype._checkFinalizedStatuses=function(i){var r=this,n=r.hasError,s=r.thrownError,a=r.isStopped;n?i.error(s):a&&i.complete()},e.prototype.asObservable=function(){var i=new be;return i.source=this,i},e.create=function(i,r){return new ba(i,r)},e})(be),ba=(function(t){We(e,t);function e(i,r){var n=t.call(this)||this;return n.destination=i,n.source=r,n}return e.prototype.next=function(i){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.next)===null||n===void 0||n.call(r,i)},e.prototype.error=function(i){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.error)===null||n===void 0||n.call(r,i)},e.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)},e.prototype._subscribe=function(i){var r,n;return(n=(r=this.source)===null||r===void 0?void 0:r.subscribe(i))!==null&&n!==void 0?n:ua},e})(Ei),Ru=(function(t){We(e,t);function e(i){var r=t.call(this)||this;return r._value=i,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(i){var r=t.prototype._subscribe.call(this,i);return!r.closed&&i.next(this._value),r},e.prototype.getValue=function(){var i=this,r=i.hasError,n=i.thrownError,s=i._value;if(r)throw n;return this._throwIfClosed(),s},e.prototype.next=function(i){t.prototype.next.call(this,this._value=i)},e})(Ei),Nn={now:function(){return(Nn.delegate||Date).now()},delegate:void 0},Bn=(function(t){We(e,t);function e(i,r,n){i===void 0&&(i=1/0),r===void 0&&(r=1/0),n===void 0&&(n=Nn);var s=t.call(this)||this;return s._bufferSize=i,s._windowTime=r,s._timestampProvider=n,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,i),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(i){var r=this,n=r.isStopped,s=r._buffer,a=r._infiniteTimeWindow,o=r._timestampProvider,c=r._windowTime;n||(s.push(i),!a&&s.push(o.now()+c)),this._trimBuffer(),t.prototype.next.call(this,i)},e.prototype._subscribe=function(i){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(i),n=this,s=n._infiniteTimeWindow,a=n._buffer,o=a.slice(),c=0;c<o.length&&!i.closed;c+=s?1:2)i.next(o[c]);return this._checkFinalizedStatuses(i),r},e.prototype._trimBuffer=function(){var i=this,r=i._bufferSize,n=i._timestampProvider,s=i._buffer,a=i._infiniteTimeWindow,o=(a?1:2)*r;if(r<1/0&&o<s.length&&s.splice(0,s.length-o),!a){for(var c=n.now(),u=0,h=1;h<s.length&&s[h]<=c;h+=2)u=h;u&&s.splice(0,u+1)}},e})(Ei),Pu=(function(t){We(e,t);function e(i,r){return t.call(this)||this}return e.prototype.schedule=function(i,r){return this},e})(Ai),ma={setInterval:function(t,e){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return setInterval.apply(void 0,gt([t,e],pt(i)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},zn=(function(t){We(e,t);function e(i,r){var n=t.call(this,i,r)||this;return n.scheduler=i,n.work=r,n.pending=!1,n}return e.prototype.schedule=function(i,r){var n;if(r===void 0&&(r=0),this.closed)return this;this.state=i;var s=this.id,a=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(a,s,r)),this.pending=!0,this.delay=r,this.id=(n=this.id)!==null&&n!==void 0?n:this.requestAsyncId(a,this.id,r),this},e.prototype.requestAsyncId=function(i,r,n){return n===void 0&&(n=0),ma.setInterval(i.flush.bind(i,this),n)},e.prototype.recycleAsyncId=function(i,r,n){if(n===void 0&&(n=0),n!=null&&this.delay===n&&this.pending===!1)return r;r!=null&&ma.clearInterval(r)},e.prototype.execute=function(i,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(i,r);if(n)return n;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(i,r){var n=!1,s;try{this.work(i)}catch(a){n=!0,s=a||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var i=this,r=i.id,n=i.scheduler,s=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Ur(s,this),r!=null&&(this.id=this.recycleAsyncId(n,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e})(Pu),Ou=1,Vn,Hn={};function ya(t){return t in Hn?(delete Hn[t],!0):!1}var wa={setImmediate:function(t){var e=Ou++;return Hn[e]=!0,Vn||(Vn=Promise.resolve()),Vn.then(function(){return ya(e)&&t()}),e},clearImmediate:function(t){ya(t)}},_u=wa.setImmediate,Lu=wa.clearImmediate,Sa={setImmediate:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return _u.apply(void 0,gt([],pt(t)))},clearImmediate:function(t){return Lu(t)},delegate:void 0},Fu=(function(t){We(e,t);function e(i,r){var n=t.call(this,i,r)||this;return n.scheduler=i,n.work=r,n}return e.prototype.requestAsyncId=function(i,r,n){return n===void 0&&(n=0),n!==null&&n>0?t.prototype.requestAsyncId.call(this,i,r,n):(i.actions.push(this),i._scheduled||(i._scheduled=Sa.setImmediate(i.flush.bind(i,void 0))))},e.prototype.recycleAsyncId=function(i,r,n){var s;if(n===void 0&&(n=0),n!=null?n>0:this.delay>0)return t.prototype.recycleAsyncId.call(this,i,r,n);var a=i.actions;r!=null&&((s=a[a.length-1])===null||s===void 0?void 0:s.id)!==r&&(Sa.clearImmediate(r),i._scheduled===r&&(i._scheduled=void 0))},e})(zn),Ca=(function(){function t(e,i){i===void 0&&(i=t.now),this.schedulerActionCtor=e,this.now=i}return t.prototype.schedule=function(e,i,r){return i===void 0&&(i=0),new this.schedulerActionCtor(this,e).schedule(r,i)},t.now=Nn.now,t})(),jn=(function(t){We(e,t);function e(i,r){r===void 0&&(r=Ca.now);var n=t.call(this,i,r)||this;return n.actions=[],n._active=!1,n}return e.prototype.flush=function(i){var r=this.actions;if(this._active){r.push(i);return}var n;this._active=!0;do if(n=i.execute(i.state,i.delay))break;while(i=r.shift());if(this._active=!1,n){for(;i=r.shift();)i.unsubscribe();throw n}},e})(Ca),Uu=(function(t){We(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.flush=function(i){this._active=!0;var r=this._scheduled;this._scheduled=void 0;var n=this.actions,s;i=i||n.shift();do if(s=i.execute(i.state,i.delay))break;while((i=n[0])&&i.id===r&&n.shift());if(this._active=!1,s){for(;(i=n[0])&&i.id===r&&n.shift();)i.unsubscribe();throw s}},e})(jn),Aa=new Uu(Fu),nr=new jn(zn),Nu=nr,Bu=(function(t){We(e,t);function e(i,r){var n=t.call(this,i,r)||this;return n.scheduler=i,n.work=r,n}return e.prototype.requestAsyncId=function(i,r,n){return n===void 0&&(n=0),n!==null&&n>0?t.prototype.requestAsyncId.call(this,i,r,n):(i.actions.push(this),i._scheduled||(i._scheduled=va.requestAnimationFrame(function(){return i.flush(void 0)})))},e.prototype.recycleAsyncId=function(i,r,n){var s;if(n===void 0&&(n=0),n!=null?n>0:this.delay>0)return t.prototype.recycleAsyncId.call(this,i,r,n);var a=i.actions;r!=null&&r===i._scheduled&&((s=a[a.length-1])===null||s===void 0?void 0:s.id)!==r&&(va.cancelAnimationFrame(r),i._scheduled=void 0)},e})(zn),zu=(function(t){We(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.flush=function(i){this._active=!0;var r;i?r=i.id:(r=this._scheduled,this._scheduled=void 0);var n=this.actions,s;i=i||n.shift();do if(s=i.execute(i.state,i.delay))break;while((i=n[0])&&i.id===r&&n.shift());if(this._active=!1,s){for(;(i=n[0])&&i.id===r&&n.shift();)i.unsubscribe();throw s}},e})(jn),Ta=new zu(Bu),Jt=new be(function(t){return t.complete()});function Ea(t){return t&&pe(t.schedule)}function Wn(t){return t[t.length-1]}function ka(t){return pe(Wn(t))?t.pop():void 0}function sr(t){return Ea(Wn(t))?t.pop():void 0}function Vu(t,e){return typeof Wn(t)=="number"?t.pop():e}var xa=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function Da(t){return pe(t==null?void 0:t.then)}function Ia(t){return pe(t[Un])}function Ma(t){return Symbol.asyncIterator&&pe(t==null?void 0:t[Symbol.asyncIterator])}function Ra(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Hu(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Pa=Hu();function Oa(t){return pe(t==null?void 0:t[Pa])}function _a(t){return yu(this,arguments,function(){var i,r,n,s;return la(this,function(a){switch(a.label){case 0:i=t.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Ci(i.read())];case 3:return r=a.sent(),n=r.value,s=r.done,s?[4,Ci(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Ci(n)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return i.releaseLock(),[7];case 10:return[2]}})})}function La(t){return pe(t==null?void 0:t.getReader)}function Ee(t){if(t instanceof be)return t;if(t!=null){if(Ia(t))return ju(t);if(xa(t))return Wu(t);if(Da(t))return Gu(t);if(Ma(t))return Fa(t);if(Oa(t))return qu(t);if(La(t))return Xu(t)}throw Ra(t)}function ju(t){return new be(function(e){var i=t[Un]();if(pe(i.subscribe))return i.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Wu(t){return new be(function(e){for(var i=0;i<t.length&&!e.closed;i++)e.next(t[i]);e.complete()})}function Gu(t){return new be(function(e){t.then(function(i){e.closed||(e.next(i),e.complete())},function(i){return e.error(i)}).then(null,pa)})}function qu(t){return new be(function(e){var i,r;try{for(var n=Si(t),s=n.next();!s.done;s=n.next()){var a=s.value;if(e.next(a),e.closed)return}}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}e.complete()})}function Fa(t){return new be(function(e){Yu(t,e).catch(function(i){return e.error(i)})})}function Xu(t){return Fa(_a(t))}function Yu(t,e){var i,r,n,s;return mu(this,void 0,void 0,function(){var a,o;return la(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),i=wu(t),c.label=1;case 1:return[4,i.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(a=r.value,e.next(a),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return o=c.sent(),n={error:o},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=i.return)?[4,s.call(i)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(n)throw n.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Ot(t,e,i,r,n){r===void 0&&(r=0),n===void 0&&(n=!1);var s=e.schedule(function(){i(),n?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!n)return s}function Vr(t,e){return e===void 0&&(e=0),le(function(i,r){i.subscribe(ae(r,function(n){return Ot(r,t,function(){return r.next(n)},e)},function(){return Ot(r,t,function(){return r.complete()},e)},function(n){return Ot(r,t,function(){return r.error(n)},e)}))})}function Ua(t,e){return e===void 0&&(e=0),le(function(i,r){r.add(t.schedule(function(){return i.subscribe(r)},e))})}function Ku(t,e){return Ee(t).pipe(Ua(e),Vr(e))}function Zu(t,e){return Ee(t).pipe(Ua(e),Vr(e))}function Qu(t,e){return new be(function(i){var r=0;return e.schedule(function(){r===t.length?i.complete():(i.next(t[r++]),i.closed||this.schedule())})})}function Ju(t,e){return new be(function(i){var r;return Ot(i,e,function(){r=t[Pa](),Ot(i,e,function(){var n,s,a;try{n=r.next(),s=n.value,a=n.done}catch(o){i.error(o);return}a?i.complete():i.next(s)},0,!0)}),function(){return pe(r==null?void 0:r.return)&&r.return()}})}function Na(t,e){if(!t)throw new Error("Iterable cannot be null");return new be(function(i){Ot(i,e,function(){var r=t[Symbol.asyncIterator]();Ot(i,e,function(){r.next().then(function(n){n.done?i.complete():i.next(n.value)})},0,!0)})})}function $u(t,e){return Na(_a(t),e)}function ed(t,e){if(t!=null){if(Ia(t))return Ku(t,e);if(xa(t))return Qu(t,e);if(Da(t))return Zu(t,e);if(Ma(t))return Na(t,e);if(Oa(t))return Ju(t,e);if(La(t))return $u(t,e)}throw Ra(t)}function Ie(t,e){return e?ed(t,e):Ee(t)}function At(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t);return Ie(t,i)}function td(t,e){var i=pe(t)?t:function(){return t},r=function(n){return n.error(i())};return new be(r)}var Hr=Fr(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Ba(t,e){return new Promise(function(i,r){var n=!1,s;t.subscribe({next:function(a){s=a,n=!0},error:r,complete:function(){n?i(s):r(new Hr)}})})}function Ge(t,e){return new Promise(function(i,r){var n=new Ti({next:function(s){i(s),n.unsubscribe()},error:r,complete:function(){r(new Hr)}});t.subscribe(n)})}function za(t){return t instanceof Date&&!isNaN(t)}var Va=Fr(function(t){return function(i){i===void 0&&(i=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=i}});function ar(t,e){var i=za(t)?{first:t}:typeof t=="number"?{each:t}:t,r=i.first,n=i.each,s=i.with,a=s===void 0?id:s,o=i.scheduler,c=o===void 0?nr:o,u=i.meta,h=u===void 0?null:u;if(r==null&&n==null)throw new TypeError("No timeout provided.");return le(function(p,f){var m,R,y=null,I=0,x=function(v){R=Ot(f,c,function(){try{m.unsubscribe(),Ee(a({meta:h,lastValue:y,seen:I})).subscribe(f)}catch(b){f.error(b)}},v)};m=p.subscribe(ae(f,function(v){R==null||R.unsubscribe(),I++,f.next(y=v),n>0&&x(n)},void 0,void 0,function(){R!=null&&R.closed||R==null||R.unsubscribe(),y=null})),!I&&x(r!=null?typeof r=="number"?r:+r-c.now():n)})}function id(t){throw new Va(t)}function E(t,e){return le(function(i,r){var n=0;i.subscribe(ae(r,function(s){r.next(t.call(e,s,n++))}))})}var rd=Array.isArray;function nd(t,e){return rd(e)?t.apply(void 0,gt([],pt(e))):t(e)}function sd(t){return E(function(e){return nd(t,e)})}var ad=Array.isArray,od=Object.getPrototypeOf,cd=Object.prototype,ld=Object.keys;function ud(t){if(t.length===1){var e=t[0];if(ad(e))return{args:e,keys:null};if(dd(e)){var i=ld(e);return{args:i.map(function(r){return e[r]}),keys:i}}}return{args:t,keys:null}}function dd(t){return t&&typeof t=="object"&&od(t)===cd}function hd(t,e){return t.reduce(function(i,r,n){return i[r]=e[n],i},{})}function Ha(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t),r=ka(t),n=ud(t),s=n.args,a=n.keys;if(s.length===0)return Ie([],i);var o=new be(pd(s,i,a?function(c){return hd(a,c)}:jt));return r?o.pipe(sd(r)):o}function pd(t,e,i){return i===void 0&&(i=jt),function(r){ja(e,function(){for(var n=t.length,s=new Array(n),a=n,o=n,c=function(h){ja(e,function(){var p=Ie(t[h],e),f=!1;p.subscribe(ae(r,function(m){s[h]=m,f||(f=!0,o--),o||r.next(i(s.slice()))},function(){--a||r.complete()}))},r)},u=0;u<n;u++)c(u)},r)}}function ja(t,e,i){t?Ot(i,t,e):e()}function gd(t,e,i,r,n,s,a,o){var c=[],u=0,h=0,p=!1,f=function(){p&&!c.length&&!u&&e.complete()},m=function(y){return u<r?R(y):c.push(y)},R=function(y){u++;var I=!1;Ee(i(y,h++)).subscribe(ae(e,function(x){e.next(x)},function(){I=!0},void 0,function(){if(I)try{u--;for(var x=function(){var v=c.shift();a||R(v)};c.length&&u<r;)x();f()}catch(v){e.error(v)}}))};return t.subscribe(ae(e,m,function(){p=!0,f()})),function(){}}function Gn(t,e,i){return i===void 0&&(i=1/0),pe(e)?Gn(function(r,n){return E(function(s,a){return e(r,s,n,a)})(Ee(t(r,n)))},i):(typeof e=="number"&&(i=e),le(function(r,n){return gd(r,n,t,i)}))}function Wa(t){return t===void 0&&(t=1/0),Gn(jt,t)}function fd(){return Wa(1)}function Ga(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return fd()(Ie(t,sr(t)))}function $t(t){return new be(function(e){Ee(t()).subscribe(e)})}function ki(t,e,i){t===void 0&&(t=0),i===void 0&&(i=Nu);var r=-1;return e!=null&&(Ea(e)?i=e:r=e),new be(function(n){var s=za(t)?+t-i.now():t;s<0&&(s=0);var a=0;return i.schedule(function(){n.closed||(n.next(a++),0<=r?this.schedule(void 0,r):n.complete())},s)})}function jr(t,e){return t===void 0&&(t=0),e===void 0&&(e=nr),t<0&&(t=0),ki(t,t,e)}function xi(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t),r=Vu(t,1/0),n=t;return n.length?n.length===1?Ee(n[0]):Wa(r)(Ie(n,i)):Jt}var vd=new be(rr),bd=Array.isArray;function md(t){return t.length===1&&bd(t[0])?t[0]:t}function B(t,e){return le(function(i,r){var n=0;i.subscribe(ae(r,function(s){return t.call(e,s,n++)&&r.next(s)}))})}function or(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t=md(t),t.length===1?Ee(t[0]):new be(yd(t))}function yd(t){return function(e){for(var i=[],r=function(s){i.push(Ee(t[s]).subscribe(ae(e,function(a){if(i){for(var o=0;o<i.length;o++)o!==s&&i[o].unsubscribe();i=null}e.next(a)})))},n=0;i&&!e.closed&&n<t.length;n++)r(n)}}function wd(t){return le(function(e,i){var r=!1,n=null,s=null,a=!1,o=function(){if(s==null||s.unsubscribe(),s=null,r){r=!1;var u=n;n=null,i.next(u)}a&&i.complete()},c=function(){s=null,a&&i.complete()};e.subscribe(ae(i,function(u){r=!0,n=u,s||Ee(t(u)).subscribe(s=ae(i,o,c))},function(){a=!0,(!r||!s||s.closed)&&i.complete()}))})}function Sd(t,e){return e===void 0&&(e=nr),wd(function(){return ki(t,e)})}function ei(t){return le(function(e,i){var r=null,n=!1,s;r=e.subscribe(ae(i,void 0,void 0,function(a){s=Ee(t(a,ei(t)(e))),r?(r.unsubscribe(),r=null,s.subscribe(i)):n=!0})),n&&(r.unsubscribe(),r=null,s.subscribe(i))})}function qa(t,e,i,r,n){return function(s,a){var o=i,c=e,u=0;s.subscribe(ae(a,function(h){var p=u++;c=o?t(c,h,p):(o=!0,h),r&&a.next(c)},n&&(function(){o&&a.next(c),a.complete()})))}}function Cd(t,e){return le(qa(t,e,arguments.length>=2,!1,!0))}var Ad=function(t,e){return t.push(e),t};function Td(){return le(function(t,e){Cd(Ad,[])(t).subscribe(e)})}function Xa(t,e){return e===void 0&&(e=nr),le(function(i,r){var n=null,s=null,a=null,o=function(){if(n){n.unsubscribe(),n=null;var u=s;s=null,r.next(u)}};function c(){var u=a+t,h=e.now();if(h<u){n=this.schedule(void 0,u-h),r.add(n);return}o()}i.subscribe(ae(r,function(u){s=u,a=e.now(),n||(n=e.schedule(c,t),r.add(n))},function(){o(),r.complete()},void 0,function(){s=n=null}))})}function Ed(t){return le(function(e,i){var r=!1;e.subscribe(ae(i,function(n){r=!0,i.next(n)},function(){r||i.next(t),i.complete()}))})}function Me(t){return t<=0?function(){return Jt}:le(function(e,i){var r=0;e.subscribe(ae(i,function(n){++r<=t&&(i.next(n),t<=r&&i.complete())}))})}function L(t,e){return e===void 0&&(e=jt),t=t??kd,le(function(i,r){var n,s=!0;i.subscribe(ae(r,function(a){var o=e(a);(s||!t(n,o))&&(s=!1,n=o,r.next(a))}))})}function kd(t,e){return t===e}function xd(t){return t===void 0&&(t=Dd),le(function(e,i){var r=!1;e.subscribe(ae(i,function(n){r=!0,i.next(n)},function(){return r?i.complete():i.error(t())}))})}function Dd(){return new Hr}function qn(t,e){return le(function(i,r){var n=0,s=null,a=!1;i.subscribe(ae(r,function(o){s||(s=ae(r,void 0,function(){s=null,a&&r.complete()}),Ee(t(o,n++)).subscribe(s))},function(){a=!0,!s&&r.complete()}))})}function Ya(t,e){var i=arguments.length>=2;return function(r){return r.pipe(jt,Me(1),i?Ed(e):xd(function(){return new Hr}))}}function Ka(t,e){return le(qa(t,e,arguments.length>=2,!0))}function Tt(t){t===void 0&&(t={});var e=t.connector,i=e===void 0?function(){return new Ei}:e,r=t.resetOnError,n=r===void 0?!0:r,s=t.resetOnComplete,a=s===void 0?!0:s,o=t.resetOnRefCountZero,c=o===void 0?!0:o;return function(u){var h,p,f,m=0,R=!1,y=!1,I=function(){p==null||p.unsubscribe(),p=void 0},x=function(){I(),h=f=void 0,R=y=!1},v=function(){var b=h;x(),b==null||b.unsubscribe()};return le(function(b,w){m++,!y&&!R&&I();var A=f=f??i();w.add(function(){m--,m===0&&!y&&!R&&(p=Xn(v,c))}),A.subscribe(w),!h&&m>0&&(h=new Ti({next:function(D){return A.next(D)},error:function(D){y=!0,I(),p=Xn(x,n,D),A.error(D)},complete:function(){R=!0,I(),p=Xn(x,a),A.complete()}}),Ee(b).subscribe(h))})(u)}}function Xn(t,e){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];if(e===!0){t();return}if(e!==!1){var n=new Ti({next:function(){n.unsubscribe(),t()}});return Ee(e.apply(void 0,gt([],pt(i)))).subscribe(n)}}function et(t,e,i){var r,n=!1;return r=t,Tt({connector:function(){return new Bn(r,e,i)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:n})}function Wr(t){return B(function(e,i){return t<=i})}function Id(t){return le(function(e,i){var r=!1,n=0;e.subscribe(ae(i,function(s){return(r||(r=!t(s,n++)))&&i.next(s)}))})}function Md(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t);return le(function(r,n){(i?Ga(t,r,i):Ga(t,r)).subscribe(n)})}function Ke(t,e){return le(function(i,r){var n=null,s=0,a=!1,o=function(){return a&&!n&&r.complete()};i.subscribe(ae(r,function(c){n==null||n.unsubscribe();var u=0,h=s++;Ee(t(c,h)).subscribe(n=ae(r,function(p){return r.next(e?e(c,p,h,u++):p)},function(){n=null,o()}))},function(){a=!0,o()}))})}function S(t){return le(function(e,i){Ee(t).subscribe(ae(i,function(){return i.complete()},rr)),!i.closed&&e.subscribe(i)})}function Se(t,e,i){var r=pe(t)||e||i?{next:t,error:e,complete:i}:t;return r?le(function(n,s){var a;(a=r.subscribe)===null||a===void 0||a.call(r);var o=!0;n.subscribe(ae(s,function(c){var u;(u=r.next)===null||u===void 0||u.call(r,c),s.next(c)},function(){var c;o=!1,(c=r.complete)===null||c===void 0||c.call(r),s.complete()},function(c){var u;o=!1,(u=r.error)===null||u===void 0||u.call(r,c),s.error(c)},function(){var c,u;o&&((c=r.unsubscribe)===null||c===void 0||c.call(r)),(u=r.finalize)===null||u===void 0||u.call(r)}))}):jt}function Za(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=ka(t);return le(function(r,n){for(var s=t.length,a=new Array(s),o=t.map(function(){return!1}),c=!1,u=function(p){Ee(t[p]).subscribe(ae(n,function(f){a[p]=f,!c&&!o[p]&&(o[p]=!0,(c=o.every(jt))&&(o=null))},rr))},h=0;h<s;h++)u(h);r.subscribe(ae(n,function(p){if(c){var f=gt([p],pt(a));n.next(i?i.apply(void 0,gt([],pt(f))):f)}}))})}var Qa=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qr={exports:{}},Rd=qr.exports,Ja;function Pd(){return Ja||(Ja=1,(function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(Rd,function(){var e=function(){},i="undefined",r=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},a=null;function o(y,I){var x=y[I];if(typeof x.bind=="function")return x.bind(y);try{return Function.prototype.bind.call(x,y)}catch{return function(){return Function.prototype.apply.apply(x,[y,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 u(y){return y==="debug"&&(y="log"),typeof console===i?!1:y==="trace"&&r?c:console[y]!==void 0?o(console,y):console.log!==void 0?o(console,"log"):e}function h(){for(var y=this.getLevel(),I=0;I<n.length;I++){var x=n[I];this[x]=I<y?e:this.methodFactory(x,y,this.name)}if(this.log=this.debug,typeof console===i&&y<this.levels.SILENT)return"No console available for logging"}function p(y){return function(){typeof console!==i&&(h.call(this),this[y].apply(this,arguments))}}function f(y,I,x){return u(y)||p.apply(this,arguments)}function m(y,I){var x=this,v,b,w,A="loglevel";typeof y=="string"?A+=":"+y:typeof y=="symbol"&&(A=void 0);function D(U){var ee=(n[U]||"silent").toUpperCase();if(!(typeof window===i||!A)){try{window.localStorage[A]=ee;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+ee+";"}catch{}}}function F(){var U;if(!(typeof window===i||!A)){try{U=window.localStorage[A]}catch{}if(typeof U===i)try{var ee=window.document.cookie,ct=encodeURIComponent(A),It=ee.indexOf(ct+"=");It!==-1&&(U=/^([^;]+)/.exec(ee.slice(It+ct.length+1))[1])}catch{}return x.levels[U]===void 0&&(U=void 0),U}}function K(){if(!(typeof window===i||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function _(U){var ee=U;if(typeof ee=="string"&&x.levels[ee.toUpperCase()]!==void 0&&(ee=x.levels[ee.toUpperCase()]),typeof ee=="number"&&ee>=0&&ee<=x.levels.SILENT)return ee;throw new TypeError("log.setLevel() called with invalid level: "+U)}x.name=y,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=I||f,x.getLevel=function(){return w??b??v},x.setLevel=function(U,ee){return w=_(U),ee!==!1&&D(w),h.call(x)},x.setDefaultLevel=function(U){b=_(U),F()||x.setLevel(U,!1)},x.resetLevel=function(){w=null,K(),h.call(x)},x.enableAll=function(U){x.setLevel(x.levels.TRACE,U)},x.disableAll=function(U){x.setLevel(x.levels.SILENT,U)},x.rebuild=function(){if(a!==x&&(v=_(a.getLevel())),h.call(x),a===x)for(var U in s)s[U].rebuild()},v=_(a?a.getLevel():"WARN");var te=F();te!=null&&(w=_(te)),h.call(x)}a=new m,a.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var x=s[I];return x||(x=s[I]=new m(I,a.methodFactory)),x};var R=typeof window!==i?window.log:void 0;return a.noConflict=function(){return typeof window!==i&&window.log===a&&(window.log=R),a},a.getLoggers=function(){return s},a.default=a,a})})(qr)),qr.exports}var Od=Pd();const _d=Gr(Od);var Di=class extends Error{constructor(t,e){super(`Unexpected Error${t?` at ${t}`:""}`,e),this.at=t,this.name="UnexpectedError"}},ft=class extends Error{constructor(t="Not Implemented",e){super(t,e),this.reason=t,this.name="UnimplementedError"}},ti=class extends Error{constructor(t="Invalid Credentials",e){super(t,e),this.reason=t,this.name="InvalidCredentialsError"}},$a=class extends Error{constructor(t,e){super(t,e),this.name="WebSocketConnectionError"}},eo=class extends Error{constructor(t,e){super(t,e),this.name="TransportConnectionError"}},Ld=class extends Error{constructor(t,e){super(t,e),this.name="WebSocketTimeoutError"}},to=class extends Error{constructor(t,e){super(t,e),this.name="RequestTimeoutError"}},Fd=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Xr=class extends Error{constructor(t,e,i){super(`RPC request ${t} timed out after ${e}ms`,i),this.requestId=t,this.timeoutMs=e,this.name="RPCTimeoutError"}},Yn=class extends Error{constructor(t=null,e){super("Error handling authorization state update",{...e,cause:(e==null?void 0:e.cause)??(t instanceof Error?t:void 0)}),this.error=t,this.name="AuthStateHandlerError"}},Kn=class extends Error{constructor(t="localStorage",e){super(`${t} is not available in this environment`,e),this.storageType=t,this.name="StorageNotAvailableError"}},Ud=class extends Error{constructor(t,e){super(`Failed to serialize value for key "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="SerializationError"}},Nd=class extends Error{constructor(t,e){super(`Failed to deserialize value for key "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="DeserializationError"}},Zn=class extends Error{constructor(t,e){super(`Failed to write to storage for key "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="StorageWriteError"}},Bd=class extends Error{constructor(t,e){super(`Failed to read from storage "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="StorageReadError"}},Q=class extends Error{constructor(t,e){super(`Dependency ${t} is not set or available.`,e),this.description=t,this.name="DependencyError"}},io=class extends Error{constructor(t,e=null,i="outbound",r){super(t,{...r,cause:(r==null?void 0:r.cause)??(e instanceof Error?e:void 0)}),this.message=t,this.error=e,this.direction=i,this.name="CallCreateError"}},_t=class extends Error{constructor(t,e,i,r,n){super(e,r),this.code=t,this.data=i,this.requestId=n,this.name="JSONRPCError"}},ro=class extends Error{constructor(t,e){super(t,e),this.message=t,this.name="InvalidParams"}},no=class extends Error{constructor(t,e){super(t,e),this.message=t,this.name="ConversationError"}},zd=class extends Error{constructor(t=null,e){super("Error handling Verto invite",{...e,cause:(e==null?void 0:e.cause)??(t instanceof Error?t:void 0)}),this.error=t,this.name="VertoInviteHandlerError"}},Vd=class extends Error{constructor(t=null,e){super("Error handling Verto attach",{...e,cause:(e==null?void 0:e.cause)??(t instanceof Error?t:void 0)}),this.error=t,this.name="VertoAttachHandlerError"}},Yr=class extends Error{constructor(t,e){super(t,e),this.name="ValidationError"}},so=class extends Error{constructor(t){super("Failed to send Verto pong - call may disconnect",{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="VertoPongError"}},Hd=class extends Error{constructor(t){super("Failed to parse incoming WebSocket message",{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="MessageParseError"}},ao=class extends Error{constructor(t,e){super(`Collection fetch failed during ${t}`,{cause:e instanceof Error?e:void 0}),this.operation=t,this.originalError=e,this.name="CollectionFetchError"}},Ii=class extends Error{constructor(t,e,i){super(`Media track ${t} failed for ${e}`,{cause:i instanceof Error?i:void 0}),this.operation=t,this.kind=e,this.originalError=i,this.name="MediaTrackError"}},Kr=class extends Error{constructor(t,e="Failed to initialize DPoP key pair"){super(e,{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="DPoPInitError"}},jd=class extends Error{constructor(t,e){super(`Preflight test failed during ${t}`,{cause:e instanceof Error?e:void 0}),this.phase=t,this.originalError=e,this.name="PreflightError"}},oo=class extends Error{constructor(t,e){super(t,{cause:e instanceof Error?e:void 0}),this.originalError=e,this.name="DeviceTokenError"}},ii=class extends Error{constructor(t,e){super(t,{cause:e instanceof Error?e:void 0}),this.originalError=e,this.name="TokenRefreshError"}};const Wd=()=>new Date().toISOString(),Mi=_d.getLogger("signalwire"),Gd=Mi.methodFactory;Mi.methodFactory=(t,e,i)=>{const r=Gd(t,e,i);return function(...n){const s=[Wd(),"-",...n];r.apply(void 0,s)}};const qd=Mi.levels.WARN;Mi.setLevel(qd);let co=null;const Xd=t=>{co=t};let Zr={};const Yd=t=>{if(t==null){Zr={};return}Zr={...Zr,...t}},Kd=t=>{Mi.setLevel(t)},Qn=()=>co??Mi,Zd=t=>t!=null&&typeof t=="object"&&"method"in t?t.method!=="signalwire.ping":!0,Qd=t=>{const{logWsTraffic:e}=Zr;if(!e)return;const i=Qn();let r;if("raw"in t)try{r=JSON.parse(t.raw)}catch{i.debug(`[WebSocket] ${t.type.toUpperCase()}: non-JSON message`);return}else({payload:r}=t);const n=Zd(r)?JSON.stringify(r,null,2):r;i.debug(`${t.type.toUpperCase()}:
|
|
65
|
+
`):"",this.name="UnsubscriptionError",this.errors=i}});function Ur(t,e){if(t){var i=t.indexOf(e);0<=i&&t.splice(i,1)}}var Ai=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,i,r,n,s;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var o=Si(a),c=o.next();!c.done;c=o.next()){var u=c.value;u.remove(this)}}catch(y){e={error:y}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(e)throw e.error}}else a.remove(this);var h=this.initialTeardown;if(pe(h))try{h()}catch(y){s=y instanceof Ln?y.errors:[y]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var f=Si(p),m=f.next();!m.done;m=f.next()){var R=m.value;try{ha(R)}catch(y){s=s??[],y instanceof Ln?s=gt(gt([],pt(s)),pt(y.errors)):s.push(y)}}}catch(y){r={error:y}}finally{try{m&&!m.done&&(n=f.return)&&n.call(f)}finally{if(r)throw r.error}}}if(s)throw new Ln(s)}},t.prototype.add=function(e){var i;if(e&&e!==this)if(this.closed)ha(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(i=this._finalizers)!==null&&i!==void 0?i:[]).push(e)}},t.prototype._hasParent=function(e){var i=this._parentage;return i===e||Array.isArray(i)&&i.includes(e)},t.prototype._addParent=function(e){var i=this._parentage;this._parentage=Array.isArray(i)?(i.push(e),i):i?[i,e]:e},t.prototype._removeParent=function(e){var i=this._parentage;i===e?this._parentage=null:Array.isArray(i)&&Ur(i,e)},t.prototype.remove=function(e){var i=this._finalizers;i&&Ur(i,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})(),ua=Ai.EMPTY;function da(t){return t instanceof Ai||t&&"closed"in t&&pe(t.remove)&&pe(t.add)&&pe(t.unsubscribe)}function ha(t){pe(t)?t():t.unsubscribe()}var Su={Promise:void 0},Cu={setTimeout:function(t,e){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return setTimeout.apply(void 0,gt([t,e],pt(i)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function pa(t){Cu.setTimeout(function(){throw t})}function rr(){}function Nr(t){t()}var Fn=(function(t){We(e,t);function e(i){var r=t.call(this)||this;return r.isStopped=!1,i?(r.destination=i,da(i)&&i.add(r)):r.destination=Eu,r}return e.create=function(i,r,n){return new Ti(i,r,n)},e.prototype.next=function(i){this.isStopped||this._next(i)},e.prototype.error=function(i){this.isStopped||(this.isStopped=!0,this._error(i))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(i){this.destination.next(i)},e.prototype._error=function(i){try{this.destination.error(i)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Ai),Au=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var i=this.partialObserver;if(i.next)try{i.next(e)}catch(r){Br(r)}},t.prototype.error=function(e){var i=this.partialObserver;if(i.error)try{i.error(e)}catch(r){Br(r)}else Br(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(i){Br(i)}},t})(),Ti=(function(t){We(e,t);function e(i,r,n){var s=t.call(this)||this,a;return pe(i)||!i?a={next:i??void 0,error:r??void 0,complete:n??void 0}:a=i,s.destination=new Au(a),s}return e})(Fn);function Br(t){pa(t)}function Tu(t){throw t}var Eu={closed:!0,next:rr,error:Tu,complete:rr},Un=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function jt(t){return t}function zr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return ga(t)}function ga(t){return t.length===0?jt:t.length===1?t[0]:function(i){return t.reduce(function(r,n){return n(r)},i)}}var be=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var i=new t;return i.source=this,i.operator=e,i},t.prototype.subscribe=function(e,i,r){var n=this,s=xu(e)?e:new Ti(e,i,r);return Nr(function(){var a=n,o=a.operator,c=a.source;s.add(o?o.call(s,c):c?n._subscribe(s):n._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(i){e.error(i)}},t.prototype.forEach=function(e,i){var r=this;return i=fa(i),new i(function(n,s){var a=new Ti({next:function(o){try{e(o)}catch(c){s(c),a.unsubscribe()}},error:s,complete:n});r.subscribe(a)})},t.prototype._subscribe=function(e){var i;return(i=this.source)===null||i===void 0?void 0:i.subscribe(e)},t.prototype[Un]=function(){return this},t.prototype.pipe=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return ga(e)(this)},t.prototype.toPromise=function(e){var i=this;return e=fa(e),new e(function(r,n){var s;i.subscribe(function(a){return s=a},function(a){return n(a)},function(){return r(s)})})},t.create=function(e){return new t(e)},t})();function fa(t){var e;return(e=t??Su.Promise)!==null&&e!==void 0?e:Promise}function ku(t){return t&&pe(t.next)&&pe(t.error)&&pe(t.complete)}function xu(t){return t&&t instanceof Fn||ku(t)&&da(t)}function Du(t){return pe(t==null?void 0:t.lift)}function le(t){return function(e){if(Du(e))return e.lift(function(i){try{return t(i,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function ae(t,e,i,r,n){return new Iu(t,e,i,r,n)}var Iu=(function(t){We(e,t);function e(i,r,n,s,a,o){var c=t.call(this,i)||this;return c.onFinalize=a,c.shouldUnsubscribe=o,c._next=r?function(u){try{r(u)}catch(h){i.error(h)}}:t.prototype._next,c._error=s?function(u){try{s(u)}catch(h){i.error(h)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=n?function(){try{n()}catch(u){i.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var i;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((i=this.onFinalize)===null||i===void 0||i.call(this))}},e})(Fn),va={schedule:function(t){var e=requestAnimationFrame,i=cancelAnimationFrame,r=e(function(n){i=void 0,t(n)});return new Ai(function(){return i==null?void 0:i(r)})},requestAnimationFrame:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return requestAnimationFrame.apply(void 0,gt([],pt(t)))},cancelAnimationFrame:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return cancelAnimationFrame.apply(void 0,gt([],pt(t)))},delegate:void 0},Mu=Fr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ei=(function(t){We(e,t);function e(){var i=t.call(this)||this;return i.closed=!1,i.currentObservers=null,i.observers=[],i.isStopped=!1,i.hasError=!1,i.thrownError=null,i}return e.prototype.lift=function(i){var r=new ba(this,this);return r.operator=i,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new Mu},e.prototype.next=function(i){var r=this;Nr(function(){var n,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var a=Si(r.currentObservers),o=a.next();!o.done;o=a.next()){var c=o.value;c.next(i)}}catch(u){n={error:u}}finally{try{o&&!o.done&&(s=a.return)&&s.call(a)}finally{if(n)throw n.error}}}})},e.prototype.error=function(i){var r=this;Nr(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=i;for(var n=r.observers;n.length;)n.shift().error(i)}})},e.prototype.complete=function(){var i=this;Nr(function(){if(i._throwIfClosed(),!i.isStopped){i.isStopped=!0;for(var r=i.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var i;return((i=this.observers)===null||i===void 0?void 0:i.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(i){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,i)},e.prototype._subscribe=function(i){return this._throwIfClosed(),this._checkFinalizedStatuses(i),this._innerSubscribe(i)},e.prototype._innerSubscribe=function(i){var r=this,n=this,s=n.hasError,a=n.isStopped,o=n.observers;return s||a?ua:(this.currentObservers=null,o.push(i),new Ai(function(){r.currentObservers=null,Ur(o,i)}))},e.prototype._checkFinalizedStatuses=function(i){var r=this,n=r.hasError,s=r.thrownError,a=r.isStopped;n?i.error(s):a&&i.complete()},e.prototype.asObservable=function(){var i=new be;return i.source=this,i},e.create=function(i,r){return new ba(i,r)},e})(be),ba=(function(t){We(e,t);function e(i,r){var n=t.call(this)||this;return n.destination=i,n.source=r,n}return e.prototype.next=function(i){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.next)===null||n===void 0||n.call(r,i)},e.prototype.error=function(i){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.error)===null||n===void 0||n.call(r,i)},e.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)},e.prototype._subscribe=function(i){var r,n;return(n=(r=this.source)===null||r===void 0?void 0:r.subscribe(i))!==null&&n!==void 0?n:ua},e})(Ei),Ru=(function(t){We(e,t);function e(i){var r=t.call(this)||this;return r._value=i,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(i){var r=t.prototype._subscribe.call(this,i);return!r.closed&&i.next(this._value),r},e.prototype.getValue=function(){var i=this,r=i.hasError,n=i.thrownError,s=i._value;if(r)throw n;return this._throwIfClosed(),s},e.prototype.next=function(i){t.prototype.next.call(this,this._value=i)},e})(Ei),Nn={now:function(){return(Nn.delegate||Date).now()},delegate:void 0},Bn=(function(t){We(e,t);function e(i,r,n){i===void 0&&(i=1/0),r===void 0&&(r=1/0),n===void 0&&(n=Nn);var s=t.call(this)||this;return s._bufferSize=i,s._windowTime=r,s._timestampProvider=n,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,i),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(i){var r=this,n=r.isStopped,s=r._buffer,a=r._infiniteTimeWindow,o=r._timestampProvider,c=r._windowTime;n||(s.push(i),!a&&s.push(o.now()+c)),this._trimBuffer(),t.prototype.next.call(this,i)},e.prototype._subscribe=function(i){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(i),n=this,s=n._infiniteTimeWindow,a=n._buffer,o=a.slice(),c=0;c<o.length&&!i.closed;c+=s?1:2)i.next(o[c]);return this._checkFinalizedStatuses(i),r},e.prototype._trimBuffer=function(){var i=this,r=i._bufferSize,n=i._timestampProvider,s=i._buffer,a=i._infiniteTimeWindow,o=(a?1:2)*r;if(r<1/0&&o<s.length&&s.splice(0,s.length-o),!a){for(var c=n.now(),u=0,h=1;h<s.length&&s[h]<=c;h+=2)u=h;u&&s.splice(0,u+1)}},e})(Ei),Pu=(function(t){We(e,t);function e(i,r){return t.call(this)||this}return e.prototype.schedule=function(i,r){return this},e})(Ai),ma={setInterval:function(t,e){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return setInterval.apply(void 0,gt([t,e],pt(i)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},zn=(function(t){We(e,t);function e(i,r){var n=t.call(this,i,r)||this;return n.scheduler=i,n.work=r,n.pending=!1,n}return e.prototype.schedule=function(i,r){var n;if(r===void 0&&(r=0),this.closed)return this;this.state=i;var s=this.id,a=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(a,s,r)),this.pending=!0,this.delay=r,this.id=(n=this.id)!==null&&n!==void 0?n:this.requestAsyncId(a,this.id,r),this},e.prototype.requestAsyncId=function(i,r,n){return n===void 0&&(n=0),ma.setInterval(i.flush.bind(i,this),n)},e.prototype.recycleAsyncId=function(i,r,n){if(n===void 0&&(n=0),n!=null&&this.delay===n&&this.pending===!1)return r;r!=null&&ma.clearInterval(r)},e.prototype.execute=function(i,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(i,r);if(n)return n;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(i,r){var n=!1,s;try{this.work(i)}catch(a){n=!0,s=a||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var i=this,r=i.id,n=i.scheduler,s=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Ur(s,this),r!=null&&(this.id=this.recycleAsyncId(n,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e})(Pu),Ou=1,Vn,Hn={};function ya(t){return t in Hn?(delete Hn[t],!0):!1}var wa={setImmediate:function(t){var e=Ou++;return Hn[e]=!0,Vn||(Vn=Promise.resolve()),Vn.then(function(){return ya(e)&&t()}),e},clearImmediate:function(t){ya(t)}},_u=wa.setImmediate,Lu=wa.clearImmediate,Sa={setImmediate:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return _u.apply(void 0,gt([],pt(t)))},clearImmediate:function(t){return Lu(t)},delegate:void 0},Fu=(function(t){We(e,t);function e(i,r){var n=t.call(this,i,r)||this;return n.scheduler=i,n.work=r,n}return e.prototype.requestAsyncId=function(i,r,n){return n===void 0&&(n=0),n!==null&&n>0?t.prototype.requestAsyncId.call(this,i,r,n):(i.actions.push(this),i._scheduled||(i._scheduled=Sa.setImmediate(i.flush.bind(i,void 0))))},e.prototype.recycleAsyncId=function(i,r,n){var s;if(n===void 0&&(n=0),n!=null?n>0:this.delay>0)return t.prototype.recycleAsyncId.call(this,i,r,n);var a=i.actions;r!=null&&((s=a[a.length-1])===null||s===void 0?void 0:s.id)!==r&&(Sa.clearImmediate(r),i._scheduled===r&&(i._scheduled=void 0))},e})(zn),Ca=(function(){function t(e,i){i===void 0&&(i=t.now),this.schedulerActionCtor=e,this.now=i}return t.prototype.schedule=function(e,i,r){return i===void 0&&(i=0),new this.schedulerActionCtor(this,e).schedule(r,i)},t.now=Nn.now,t})(),jn=(function(t){We(e,t);function e(i,r){r===void 0&&(r=Ca.now);var n=t.call(this,i,r)||this;return n.actions=[],n._active=!1,n}return e.prototype.flush=function(i){var r=this.actions;if(this._active){r.push(i);return}var n;this._active=!0;do if(n=i.execute(i.state,i.delay))break;while(i=r.shift());if(this._active=!1,n){for(;i=r.shift();)i.unsubscribe();throw n}},e})(Ca),Uu=(function(t){We(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.flush=function(i){this._active=!0;var r=this._scheduled;this._scheduled=void 0;var n=this.actions,s;i=i||n.shift();do if(s=i.execute(i.state,i.delay))break;while((i=n[0])&&i.id===r&&n.shift());if(this._active=!1,s){for(;(i=n[0])&&i.id===r&&n.shift();)i.unsubscribe();throw s}},e})(jn),Aa=new Uu(Fu),nr=new jn(zn),Nu=nr,Bu=(function(t){We(e,t);function e(i,r){var n=t.call(this,i,r)||this;return n.scheduler=i,n.work=r,n}return e.prototype.requestAsyncId=function(i,r,n){return n===void 0&&(n=0),n!==null&&n>0?t.prototype.requestAsyncId.call(this,i,r,n):(i.actions.push(this),i._scheduled||(i._scheduled=va.requestAnimationFrame(function(){return i.flush(void 0)})))},e.prototype.recycleAsyncId=function(i,r,n){var s;if(n===void 0&&(n=0),n!=null?n>0:this.delay>0)return t.prototype.recycleAsyncId.call(this,i,r,n);var a=i.actions;r!=null&&r===i._scheduled&&((s=a[a.length-1])===null||s===void 0?void 0:s.id)!==r&&(va.cancelAnimationFrame(r),i._scheduled=void 0)},e})(zn),zu=(function(t){We(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.flush=function(i){this._active=!0;var r;i?r=i.id:(r=this._scheduled,this._scheduled=void 0);var n=this.actions,s;i=i||n.shift();do if(s=i.execute(i.state,i.delay))break;while((i=n[0])&&i.id===r&&n.shift());if(this._active=!1,s){for(;(i=n[0])&&i.id===r&&n.shift();)i.unsubscribe();throw s}},e})(jn),Ta=new zu(Bu),Jt=new be(function(t){return t.complete()});function Ea(t){return t&&pe(t.schedule)}function Wn(t){return t[t.length-1]}function ka(t){return pe(Wn(t))?t.pop():void 0}function sr(t){return Ea(Wn(t))?t.pop():void 0}function Vu(t,e){return typeof Wn(t)=="number"?t.pop():e}var xa=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function Da(t){return pe(t==null?void 0:t.then)}function Ia(t){return pe(t[Un])}function Ma(t){return Symbol.asyncIterator&&pe(t==null?void 0:t[Symbol.asyncIterator])}function Ra(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Hu(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Pa=Hu();function Oa(t){return pe(t==null?void 0:t[Pa])}function _a(t){return yu(this,arguments,function(){var i,r,n,s;return la(this,function(a){switch(a.label){case 0:i=t.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Ci(i.read())];case 3:return r=a.sent(),n=r.value,s=r.done,s?[4,Ci(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Ci(n)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return i.releaseLock(),[7];case 10:return[2]}})})}function La(t){return pe(t==null?void 0:t.getReader)}function Ee(t){if(t instanceof be)return t;if(t!=null){if(Ia(t))return ju(t);if(xa(t))return Wu(t);if(Da(t))return Gu(t);if(Ma(t))return Fa(t);if(Oa(t))return qu(t);if(La(t))return Xu(t)}throw Ra(t)}function ju(t){return new be(function(e){var i=t[Un]();if(pe(i.subscribe))return i.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Wu(t){return new be(function(e){for(var i=0;i<t.length&&!e.closed;i++)e.next(t[i]);e.complete()})}function Gu(t){return new be(function(e){t.then(function(i){e.closed||(e.next(i),e.complete())},function(i){return e.error(i)}).then(null,pa)})}function qu(t){return new be(function(e){var i,r;try{for(var n=Si(t),s=n.next();!s.done;s=n.next()){var a=s.value;if(e.next(a),e.closed)return}}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}e.complete()})}function Fa(t){return new be(function(e){Yu(t,e).catch(function(i){return e.error(i)})})}function Xu(t){return Fa(_a(t))}function Yu(t,e){var i,r,n,s;return mu(this,void 0,void 0,function(){var a,o;return la(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),i=wu(t),c.label=1;case 1:return[4,i.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(a=r.value,e.next(a),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return o=c.sent(),n={error:o},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=i.return)?[4,s.call(i)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(n)throw n.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Ot(t,e,i,r,n){r===void 0&&(r=0),n===void 0&&(n=!1);var s=e.schedule(function(){i(),n?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!n)return s}function Vr(t,e){return e===void 0&&(e=0),le(function(i,r){i.subscribe(ae(r,function(n){return Ot(r,t,function(){return r.next(n)},e)},function(){return Ot(r,t,function(){return r.complete()},e)},function(n){return Ot(r,t,function(){return r.error(n)},e)}))})}function Ua(t,e){return e===void 0&&(e=0),le(function(i,r){r.add(t.schedule(function(){return i.subscribe(r)},e))})}function Ku(t,e){return Ee(t).pipe(Ua(e),Vr(e))}function Zu(t,e){return Ee(t).pipe(Ua(e),Vr(e))}function Qu(t,e){return new be(function(i){var r=0;return e.schedule(function(){r===t.length?i.complete():(i.next(t[r++]),i.closed||this.schedule())})})}function Ju(t,e){return new be(function(i){var r;return Ot(i,e,function(){r=t[Pa](),Ot(i,e,function(){var n,s,a;try{n=r.next(),s=n.value,a=n.done}catch(o){i.error(o);return}a?i.complete():i.next(s)},0,!0)}),function(){return pe(r==null?void 0:r.return)&&r.return()}})}function Na(t,e){if(!t)throw new Error("Iterable cannot be null");return new be(function(i){Ot(i,e,function(){var r=t[Symbol.asyncIterator]();Ot(i,e,function(){r.next().then(function(n){n.done?i.complete():i.next(n.value)})},0,!0)})})}function $u(t,e){return Na(_a(t),e)}function ed(t,e){if(t!=null){if(Ia(t))return Ku(t,e);if(xa(t))return Qu(t,e);if(Da(t))return Zu(t,e);if(Ma(t))return Na(t,e);if(Oa(t))return Ju(t,e);if(La(t))return $u(t,e)}throw Ra(t)}function Ie(t,e){return e?ed(t,e):Ee(t)}function Tt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t);return Ie(t,i)}function td(t,e){var i=pe(t)?t:function(){return t},r=function(n){return n.error(i())};return new be(r)}var Hr=Fr(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Ba(t,e){return new Promise(function(i,r){var n=!1,s;t.subscribe({next:function(a){s=a,n=!0},error:r,complete:function(){n?i(s):r(new Hr)}})})}function Ge(t,e){return new Promise(function(i,r){var n=new Ti({next:function(s){i(s),n.unsubscribe()},error:r,complete:function(){r(new Hr)}});t.subscribe(n)})}function za(t){return t instanceof Date&&!isNaN(t)}var Va=Fr(function(t){return function(i){i===void 0&&(i=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=i}});function ar(t,e){var i=za(t)?{first:t}:typeof t=="number"?{each:t}:t,r=i.first,n=i.each,s=i.with,a=s===void 0?id:s,o=i.scheduler,c=o===void 0?nr:o,u=i.meta,h=u===void 0?null:u;if(r==null&&n==null)throw new TypeError("No timeout provided.");return le(function(p,f){var m,R,y=null,I=0,x=function(v){R=Ot(f,c,function(){try{m.unsubscribe(),Ee(a({meta:h,lastValue:y,seen:I})).subscribe(f)}catch(b){f.error(b)}},v)};m=p.subscribe(ae(f,function(v){R==null||R.unsubscribe(),I++,f.next(y=v),n>0&&x(n)},void 0,void 0,function(){R!=null&&R.closed||R==null||R.unsubscribe(),y=null})),!I&&x(r!=null?typeof r=="number"?r:+r-c.now():n)})}function id(t){throw new Va(t)}function E(t,e){return le(function(i,r){var n=0;i.subscribe(ae(r,function(s){r.next(t.call(e,s,n++))}))})}var rd=Array.isArray;function nd(t,e){return rd(e)?t.apply(void 0,gt([],pt(e))):t(e)}function sd(t){return E(function(e){return nd(t,e)})}var ad=Array.isArray,od=Object.getPrototypeOf,cd=Object.prototype,ld=Object.keys;function ud(t){if(t.length===1){var e=t[0];if(ad(e))return{args:e,keys:null};if(dd(e)){var i=ld(e);return{args:i.map(function(r){return e[r]}),keys:i}}}return{args:t,keys:null}}function dd(t){return t&&typeof t=="object"&&od(t)===cd}function hd(t,e){return t.reduce(function(i,r,n){return i[r]=e[n],i},{})}function Ha(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t),r=ka(t),n=ud(t),s=n.args,a=n.keys;if(s.length===0)return Ie([],i);var o=new be(pd(s,i,a?function(c){return hd(a,c)}:jt));return r?o.pipe(sd(r)):o}function pd(t,e,i){return i===void 0&&(i=jt),function(r){ja(e,function(){for(var n=t.length,s=new Array(n),a=n,o=n,c=function(h){ja(e,function(){var p=Ie(t[h],e),f=!1;p.subscribe(ae(r,function(m){s[h]=m,f||(f=!0,o--),o||r.next(i(s.slice()))},function(){--a||r.complete()}))},r)},u=0;u<n;u++)c(u)},r)}}function ja(t,e,i){t?Ot(i,t,e):e()}function gd(t,e,i,r,n,s,a,o){var c=[],u=0,h=0,p=!1,f=function(){p&&!c.length&&!u&&e.complete()},m=function(y){return u<r?R(y):c.push(y)},R=function(y){u++;var I=!1;Ee(i(y,h++)).subscribe(ae(e,function(x){e.next(x)},function(){I=!0},void 0,function(){if(I)try{u--;for(var x=function(){var v=c.shift();a||R(v)};c.length&&u<r;)x();f()}catch(v){e.error(v)}}))};return t.subscribe(ae(e,m,function(){p=!0,f()})),function(){}}function Gn(t,e,i){return i===void 0&&(i=1/0),pe(e)?Gn(function(r,n){return E(function(s,a){return e(r,s,n,a)})(Ee(t(r,n)))},i):(typeof e=="number"&&(i=e),le(function(r,n){return gd(r,n,t,i)}))}function Wa(t){return t===void 0&&(t=1/0),Gn(jt,t)}function fd(){return Wa(1)}function Ga(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return fd()(Ie(t,sr(t)))}function $t(t){return new be(function(e){Ee(t()).subscribe(e)})}function ki(t,e,i){t===void 0&&(t=0),i===void 0&&(i=Nu);var r=-1;return e!=null&&(Ea(e)?i=e:r=e),new be(function(n){var s=za(t)?+t-i.now():t;s<0&&(s=0);var a=0;return i.schedule(function(){n.closed||(n.next(a++),0<=r?this.schedule(void 0,r):n.complete())},s)})}function jr(t,e){return t===void 0&&(t=0),e===void 0&&(e=nr),t<0&&(t=0),ki(t,t,e)}function xi(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t),r=Vu(t,1/0),n=t;return n.length?n.length===1?Ee(n[0]):Wa(r)(Ie(n,i)):Jt}var vd=new be(rr),bd=Array.isArray;function md(t){return t.length===1&&bd(t[0])?t[0]:t}function B(t,e){return le(function(i,r){var n=0;i.subscribe(ae(r,function(s){return t.call(e,s,n++)&&r.next(s)}))})}function or(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t=md(t),t.length===1?Ee(t[0]):new be(yd(t))}function yd(t){return function(e){for(var i=[],r=function(s){i.push(Ee(t[s]).subscribe(ae(e,function(a){if(i){for(var o=0;o<i.length;o++)o!==s&&i[o].unsubscribe();i=null}e.next(a)})))},n=0;i&&!e.closed&&n<t.length;n++)r(n)}}function wd(t){return le(function(e,i){var r=!1,n=null,s=null,a=!1,o=function(){if(s==null||s.unsubscribe(),s=null,r){r=!1;var u=n;n=null,i.next(u)}a&&i.complete()},c=function(){s=null,a&&i.complete()};e.subscribe(ae(i,function(u){r=!0,n=u,s||Ee(t(u)).subscribe(s=ae(i,o,c))},function(){a=!0,(!r||!s||s.closed)&&i.complete()}))})}function Sd(t,e){return e===void 0&&(e=nr),wd(function(){return ki(t,e)})}function ei(t){return le(function(e,i){var r=null,n=!1,s;r=e.subscribe(ae(i,void 0,void 0,function(a){s=Ee(t(a,ei(t)(e))),r?(r.unsubscribe(),r=null,s.subscribe(i)):n=!0})),n&&(r.unsubscribe(),r=null,s.subscribe(i))})}function qa(t,e,i,r,n){return function(s,a){var o=i,c=e,u=0;s.subscribe(ae(a,function(h){var p=u++;c=o?t(c,h,p):(o=!0,h),r&&a.next(c)},n&&(function(){o&&a.next(c),a.complete()})))}}function Cd(t,e){return le(qa(t,e,arguments.length>=2,!1,!0))}var Ad=function(t,e){return t.push(e),t};function Td(){return le(function(t,e){Cd(Ad,[])(t).subscribe(e)})}function Xa(t,e){return e===void 0&&(e=nr),le(function(i,r){var n=null,s=null,a=null,o=function(){if(n){n.unsubscribe(),n=null;var u=s;s=null,r.next(u)}};function c(){var u=a+t,h=e.now();if(h<u){n=this.schedule(void 0,u-h),r.add(n);return}o()}i.subscribe(ae(r,function(u){s=u,a=e.now(),n||(n=e.schedule(c,t),r.add(n))},function(){o(),r.complete()},void 0,function(){s=n=null}))})}function Ed(t){return le(function(e,i){var r=!1;e.subscribe(ae(i,function(n){r=!0,i.next(n)},function(){r||i.next(t),i.complete()}))})}function Me(t){return t<=0?function(){return Jt}:le(function(e,i){var r=0;e.subscribe(ae(i,function(n){++r<=t&&(i.next(n),t<=r&&i.complete())}))})}function L(t,e){return e===void 0&&(e=jt),t=t??kd,le(function(i,r){var n,s=!0;i.subscribe(ae(r,function(a){var o=e(a);(s||!t(n,o))&&(s=!1,n=o,r.next(a))}))})}function kd(t,e){return t===e}function xd(t){return t===void 0&&(t=Dd),le(function(e,i){var r=!1;e.subscribe(ae(i,function(n){r=!0,i.next(n)},function(){return r?i.complete():i.error(t())}))})}function Dd(){return new Hr}function qn(t,e){return le(function(i,r){var n=0,s=null,a=!1;i.subscribe(ae(r,function(o){s||(s=ae(r,void 0,function(){s=null,a&&r.complete()}),Ee(t(o,n++)).subscribe(s))},function(){a=!0,!s&&r.complete()}))})}function Ya(t,e){var i=arguments.length>=2;return function(r){return r.pipe(jt,Me(1),i?Ed(e):xd(function(){return new Hr}))}}function Ka(t,e){return le(qa(t,e,arguments.length>=2,!0))}function Et(t){t===void 0&&(t={});var e=t.connector,i=e===void 0?function(){return new Ei}:e,r=t.resetOnError,n=r===void 0?!0:r,s=t.resetOnComplete,a=s===void 0?!0:s,o=t.resetOnRefCountZero,c=o===void 0?!0:o;return function(u){var h,p,f,m=0,R=!1,y=!1,I=function(){p==null||p.unsubscribe(),p=void 0},x=function(){I(),h=f=void 0,R=y=!1},v=function(){var b=h;x(),b==null||b.unsubscribe()};return le(function(b,w){m++,!y&&!R&&I();var A=f=f??i();w.add(function(){m--,m===0&&!y&&!R&&(p=Xn(v,c))}),A.subscribe(w),!h&&m>0&&(h=new Ti({next:function(D){return A.next(D)},error:function(D){y=!0,I(),p=Xn(x,n,D),A.error(D)},complete:function(){R=!0,I(),p=Xn(x,a),A.complete()}}),Ee(b).subscribe(h))})(u)}}function Xn(t,e){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];if(e===!0){t();return}if(e!==!1){var n=new Ti({next:function(){n.unsubscribe(),t()}});return Ee(e.apply(void 0,gt([],pt(i)))).subscribe(n)}}function et(t,e,i){var r,n=!1;return r=t,Et({connector:function(){return new Bn(r,e,i)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:n})}function Wr(t){return B(function(e,i){return t<=i})}function Id(t){return le(function(e,i){var r=!1,n=0;e.subscribe(ae(i,function(s){return(r||(r=!t(s,n++)))&&i.next(s)}))})}function Md(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=sr(t);return le(function(r,n){(i?Ga(t,r,i):Ga(t,r)).subscribe(n)})}function Ke(t,e){return le(function(i,r){var n=null,s=0,a=!1,o=function(){return a&&!n&&r.complete()};i.subscribe(ae(r,function(c){n==null||n.unsubscribe();var u=0,h=s++;Ee(t(c,h)).subscribe(n=ae(r,function(p){return r.next(e?e(c,p,h,u++):p)},function(){n=null,o()}))},function(){a=!0,o()}))})}function S(t){return le(function(e,i){Ee(t).subscribe(ae(i,function(){return i.complete()},rr)),!i.closed&&e.subscribe(i)})}function Se(t,e,i){var r=pe(t)||e||i?{next:t,error:e,complete:i}:t;return r?le(function(n,s){var a;(a=r.subscribe)===null||a===void 0||a.call(r);var o=!0;n.subscribe(ae(s,function(c){var u;(u=r.next)===null||u===void 0||u.call(r,c),s.next(c)},function(){var c;o=!1,(c=r.complete)===null||c===void 0||c.call(r),s.complete()},function(c){var u;o=!1,(u=r.error)===null||u===void 0||u.call(r,c),s.error(c)},function(){var c,u;o&&((c=r.unsubscribe)===null||c===void 0||c.call(r)),(u=r.finalize)===null||u===void 0||u.call(r)}))}):jt}function Za(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=ka(t);return le(function(r,n){for(var s=t.length,a=new Array(s),o=t.map(function(){return!1}),c=!1,u=function(p){Ee(t[p]).subscribe(ae(n,function(f){a[p]=f,!c&&!o[p]&&(o[p]=!0,(c=o.every(jt))&&(o=null))},rr))},h=0;h<s;h++)u(h);r.subscribe(ae(n,function(p){if(c){var f=gt([p],pt(a));n.next(i?i.apply(void 0,gt([],pt(f))):f)}}))})}var Qa=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qr={exports:{}},Rd=qr.exports,Ja;function Pd(){return Ja||(Ja=1,(function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(Rd,function(){var e=function(){},i="undefined",r=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},a=null;function o(y,I){var x=y[I];if(typeof x.bind=="function")return x.bind(y);try{return Function.prototype.bind.call(x,y)}catch{return function(){return Function.prototype.apply.apply(x,[y,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 u(y){return y==="debug"&&(y="log"),typeof console===i?!1:y==="trace"&&r?c:console[y]!==void 0?o(console,y):console.log!==void 0?o(console,"log"):e}function h(){for(var y=this.getLevel(),I=0;I<n.length;I++){var x=n[I];this[x]=I<y?e:this.methodFactory(x,y,this.name)}if(this.log=this.debug,typeof console===i&&y<this.levels.SILENT)return"No console available for logging"}function p(y){return function(){typeof console!==i&&(h.call(this),this[y].apply(this,arguments))}}function f(y,I,x){return u(y)||p.apply(this,arguments)}function m(y,I){var x=this,v,b,w,A="loglevel";typeof y=="string"?A+=":"+y:typeof y=="symbol"&&(A=void 0);function D(U){var ee=(n[U]||"silent").toUpperCase();if(!(typeof window===i||!A)){try{window.localStorage[A]=ee;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+ee+";"}catch{}}}function F(){var U;if(!(typeof window===i||!A)){try{U=window.localStorage[A]}catch{}if(typeof U===i)try{var ee=window.document.cookie,ct=encodeURIComponent(A),It=ee.indexOf(ct+"=");It!==-1&&(U=/^([^;]+)/.exec(ee.slice(It+ct.length+1))[1])}catch{}return x.levels[U]===void 0&&(U=void 0),U}}function K(){if(!(typeof window===i||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function _(U){var ee=U;if(typeof ee=="string"&&x.levels[ee.toUpperCase()]!==void 0&&(ee=x.levels[ee.toUpperCase()]),typeof ee=="number"&&ee>=0&&ee<=x.levels.SILENT)return ee;throw new TypeError("log.setLevel() called with invalid level: "+U)}x.name=y,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=I||f,x.getLevel=function(){return w??b??v},x.setLevel=function(U,ee){return w=_(U),ee!==!1&&D(w),h.call(x)},x.setDefaultLevel=function(U){b=_(U),F()||x.setLevel(U,!1)},x.resetLevel=function(){w=null,K(),h.call(x)},x.enableAll=function(U){x.setLevel(x.levels.TRACE,U)},x.disableAll=function(U){x.setLevel(x.levels.SILENT,U)},x.rebuild=function(){if(a!==x&&(v=_(a.getLevel())),h.call(x),a===x)for(var U in s)s[U].rebuild()},v=_(a?a.getLevel():"WARN");var te=F();te!=null&&(w=_(te)),h.call(x)}a=new m,a.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var x=s[I];return x||(x=s[I]=new m(I,a.methodFactory)),x};var R=typeof window!==i?window.log:void 0;return a.noConflict=function(){return typeof window!==i&&window.log===a&&(window.log=R),a},a.getLoggers=function(){return s},a.default=a,a})})(qr)),qr.exports}var Od=Pd();const _d=Gr(Od);var Di=class extends Error{constructor(t,e){super(`Unexpected Error${t?` at ${t}`:""}`,e),this.at=t,this.name="UnexpectedError"}},ft=class extends Error{constructor(t="Not Implemented",e){super(t,e),this.reason=t,this.name="UnimplementedError"}},ti=class extends Error{constructor(t="Invalid Credentials",e){super(t,e),this.reason=t,this.name="InvalidCredentialsError"}},$a=class extends Error{constructor(t,e){super(t,e),this.name="WebSocketConnectionError"}},eo=class extends Error{constructor(t,e){super(t,e),this.name="TransportConnectionError"}},Ld=class extends Error{constructor(t,e){super(t,e),this.name="WebSocketTimeoutError"}},to=class extends Error{constructor(t,e){super(t,e),this.name="RequestTimeoutError"}},Fd=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Xr=class extends Error{constructor(t,e,i){super(`RPC request ${t} timed out after ${e}ms`,i),this.requestId=t,this.timeoutMs=e,this.name="RPCTimeoutError"}},Yn=class extends Error{constructor(t=null,e){super("Error handling authorization state update",{...e,cause:(e==null?void 0:e.cause)??(t instanceof Error?t:void 0)}),this.error=t,this.name="AuthStateHandlerError"}},Kn=class extends Error{constructor(t="localStorage",e){super(`${t} is not available in this environment`,e),this.storageType=t,this.name="StorageNotAvailableError"}},Ud=class extends Error{constructor(t,e){super(`Failed to serialize value for key "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="SerializationError"}},Nd=class extends Error{constructor(t,e){super(`Failed to deserialize value for key "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="DeserializationError"}},Zn=class extends Error{constructor(t,e){super(`Failed to write to storage for key "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="StorageWriteError"}},Bd=class extends Error{constructor(t,e){super(`Failed to read from storage "${t}": ${e.message}`,{cause:e}),this.key=t,this.originalError=e,this.name="StorageReadError"}},Q=class extends Error{constructor(t,e){super(`Dependency ${t} is not set or available.`,e),this.description=t,this.name="DependencyError"}},io=class extends Error{constructor(t,e=null,i="outbound",r){super(t,{...r,cause:(r==null?void 0:r.cause)??(e instanceof Error?e:void 0)}),this.message=t,this.error=e,this.direction=i,this.name="CallCreateError"}},_t=class extends Error{constructor(t,e,i,r,n){super(e,r),this.code=t,this.data=i,this.requestId=n,this.name="JSONRPCError"}},ro=class extends Error{constructor(t,e){super(t,e),this.message=t,this.name="InvalidParams"}},no=class extends Error{constructor(t,e){super(t,e),this.message=t,this.name="ConversationError"}},zd=class extends Error{constructor(t=null,e){super("Error handling Verto invite",{...e,cause:(e==null?void 0:e.cause)??(t instanceof Error?t:void 0)}),this.error=t,this.name="VertoInviteHandlerError"}},Vd=class extends Error{constructor(t=null,e){super("Error handling Verto attach",{...e,cause:(e==null?void 0:e.cause)??(t instanceof Error?t:void 0)}),this.error=t,this.name="VertoAttachHandlerError"}},Yr=class extends Error{constructor(t,e){super(t,e),this.name="ValidationError"}},so=class extends Error{constructor(t){super("Failed to send Verto pong - call may disconnect",{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="VertoPongError"}},Hd=class extends Error{constructor(t){super("Failed to parse incoming WebSocket message",{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="MessageParseError"}},ao=class extends Error{constructor(t,e){super(`Collection fetch failed during ${t}`,{cause:e instanceof Error?e:void 0}),this.operation=t,this.originalError=e,this.name="CollectionFetchError"}},Ii=class extends Error{constructor(t,e,i){super(`Media track ${t} failed for ${e}`,{cause:i instanceof Error?i:void 0}),this.operation=t,this.kind=e,this.originalError=i,this.name="MediaTrackError"}},Kr=class extends Error{constructor(t,e="Failed to initialize DPoP key pair"){super(e,{cause:t instanceof Error?t:void 0}),this.originalError=t,this.name="DPoPInitError"}},jd=class extends Error{constructor(t,e){super(`Preflight test failed during ${t}`,{cause:e instanceof Error?e:void 0}),this.phase=t,this.originalError=e,this.name="PreflightError"}},oo=class extends Error{constructor(t,e){super(t,{cause:e instanceof Error?e:void 0}),this.originalError=e,this.name="DeviceTokenError"}},ii=class extends Error{constructor(t,e){super(t,{cause:e instanceof Error?e:void 0}),this.originalError=e,this.name="TokenRefreshError"}};const Wd=()=>new Date().toISOString(),Mi=_d.getLogger("signalwire"),Gd=Mi.methodFactory;Mi.methodFactory=(t,e,i)=>{const r=Gd(t,e,i);return function(...n){const s=[Wd(),"-",...n];r.apply(void 0,s)}};const qd=Mi.levels.WARN;Mi.setLevel(qd);let co=null;const Xd=t=>{co=t};let Zr={};const Yd=t=>{if(t==null){Zr={};return}Zr={...Zr,...t}},Kd=t=>{Mi.setLevel(t)},Qn=()=>co??Mi,Zd=t=>t!=null&&typeof t=="object"&&"method"in t?t.method!=="signalwire.ping":!0,Qd=t=>{const{logWsTraffic:e}=Zr;if(!e)return;const i=Qn();let r;if("raw"in t)try{r=JSON.parse(t.raw)}catch{i.debug(`[WebSocket] ${t.type.toUpperCase()}: non-JSON message`);return}else({payload:r}=t);const n=Zd(r)?JSON.stringify(r,null,2):r;i.debug(`${t.type.toUpperCase()}:
|
|
66
66
|
`,n,`
|
|
67
|
-
`)},W=()=>{const t=Qn();return new Proxy(t,{get(e,i,r){if(i==="wsTraffic")return Qd;const n=Qn(),s=Reflect.get(n,i);return typeof s=="function"?s.bind(n):s}})};function ue(){return B(t=>t!=null)}const tt=(t,e,i)=>{const r=e.split(".");let n=t;for(const s of r)if(n&&typeof n=="object"&&s in n)n=n[s];else return i;return n===void 0?i:n};function Jd(t,e){return zr(B(t),E(e))}function fe(t,e){return zr(Jd(t,i=>tt(i,e)),B(i=>i!==void 0))}const lo=W();function uo(){return E(t=>{if(t.error)throw lo.error("[throwOnRPCError] RPC error response:",{code:t.error.code,message:t.error.message,data:t.error.data}),new _t(t.error.code,t.error.message,t.error.data);return lo.debug("[throwOnRPCError] RPC successful response:",t),t})}class cr extends Error{}cr.prototype.name="InvalidTokenError";function $d(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,i)=>{let r=i.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function eh(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return $d(e)}catch{return atob(e)}}function th(t,e){if(typeof t!="string")throw new cr("Invalid token specified: must be a string");e||(e={});const i=e.header===!0?0:1,r=t.split(".")[i];if(typeof r!="string")throw new cr(`Invalid token specified: missing part #${i+1}`);let n;try{n=eh(r)}catch(s){throw new cr(`Invalid token specified: invalid base64 for part #${i+1} (${s.message})`)}try{return JSON.parse(n)}catch(s){throw new cr(`Invalid token specified: invalid json for part #${i+1} (${s.message})`)}}const Re=[];for(let t=0;t<256;++t)Re.push((t+256).toString(16).slice(1));function ih(t,e=0){return(Re[t[e+0]]+Re[t[e+1]]+Re[t[e+2]]+Re[t[e+3]]+"-"+Re[t[e+4]]+Re[t[e+5]]+"-"+Re[t[e+6]]+Re[t[e+7]]+"-"+Re[t[e+8]]+Re[t[e+9]]+"-"+Re[t[e+10]]+Re[t[e+11]]+Re[t[e+12]]+Re[t[e+13]]+Re[t[e+14]]+Re[t[e+15]]).toLowerCase()}let Jn;const rh=new Uint8Array(16);function nh(){if(!Jn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Jn=crypto.getRandomValues.bind(crypto)}return Jn(rh)}const ho={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function sh(t,e,i){var n;t=t||{};const r=t.random??((n=t.rng)==null?void 0:n.call(t))??nh();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,ih(r)}function Qr(t,e,i){return ho.randomUUID&&!t?ho.randomUUID():sh(t)}var ie=class{constructor(){this.subscriptions=[],this.subjects=[],this._destroyed$=new Ei}destroy(){var t;(t=this._observableCache)==null||t.clear(),this.subscriptions.forEach(e=>e.unsubscribe()),this.subjects.forEach(e=>e.complete()),this._destroyed$.next(),this._destroyed$.complete()}cachedObservable(t,e){this._observableCache??(this._observableCache=new Map);let i=this._observableCache.get(t);return i||(i=e(),this._observableCache.set(t,i)),i}publicCachedObservable(t,e){const i=`public:${t}`;this._observableCache??(this._observableCache=new Map);let r=this._observableCache.get(i);return r||(r=e().pipe(Vr(Aa)),this._observableCache.set(i,r)),r}deferEmission(t){return t.pipe(Vr(Aa))}subscribeTo(t,e){const i=t.subscribe(e);this.subscriptions.push(i)}createSubject(){const t=new Ei;return this.subjects.push(t),t}createReplaySubject(t,e){const i=new Bn(t,e);return this.subjects.push(i),i}createBehaviorSubject(t){const e=new Ru(t);return this.subjects.push(e),e}get destroyed$(){return this._destroyed$.asObservable()}};const ah=10,oh=100,ch=1,lh=({delayLimit:t=Number.MAX_SAFE_INTEGER,initialDelay:e=oh,variation:i=ch})=>{if(e<0)throw new Yr("initialDelay must be gte 0");if(t<0)throw new Yr("upperDelayLimit must be gte 0");if(i<0)throw new Yr("variation must be gte 0");if(e>t)throw new Yr("initialDelay must be lte delayLimit");let r=Math.min(e,t);return()=>{if(r===t)return t;const n=r;return r=Math.min(r+i,t),n}},uh=async({asyncCallable:t,maxRetries:e=ah,delayFn:i,validator:r,expectedErrorHandler:n})=>{let s=e-1,a=0;const o=async()=>{try{let c;return a<=0?c=await t():c=await new Promise((u,h)=>setTimeout(()=>{t().then(u).catch(h)},a)),s&&(r==null||r(c)),c}catch(c){if(s-- >0&&!(n!=null&&n(c)))return a=(i==null?void 0:i())??0,W().debug(`Retrying request: ${e-s} of ${e}`),o();throw c}};return o()},Ri=W(),$n={method:"GET",headers:{Accept:"application/json"}},Jr={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};var dh=(je=class extends ie{constructor(e,i,r={}){super(),this.baseURL=e,this.getCredential=i,this._responses$=this.createSubject(),this._errors$=this.createSubject(),this._status$=this.createBehaviorSubject("idle"),this.maxRetries=r.maxRetries??je.defaultMaxRetries,this.retryDelayMin=r.retryDelayMin??je.defaultRetryDelayMinMs,this.retryDelayMax=r.retryDelayMax??je.defaultRetryDelayMaxMs,this.requestTimeout=r.requestTimeout??je.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(e){this._status$.next("requesting");try{const i=await this.executeWithRetry(e);return this._status$.next("success"),this._responses$.next(i),i}catch(i){Ri.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(e){const i=Math.ceil((this.retryDelayMax-this.retryDelayMin)/Math.max(this.maxRetries-1,1)),r=lh({initialDelay:this.retryDelayMin,variation:i,delayLimit:this.retryDelayMax});return uh({asyncCallable:async()=>this.executeRequest(e),maxRetries:this.maxRetries,delayFn:r,validator:n=>{if(n.status>=500&&n.status<600)throw new Di(`Server error: ${n.status} ${n.statusText}`)}})}async executeRequest(e){const i=this.buildURL(e.url),r=this.buildHeaders(e.headers),n=e.timeout??this.requestTimeout;Ri.debug("[HTTPRequestController] Executing request:",{method:e.method,url:i,headers:Object.keys(r).reduce((o,c)=>(o[c]=c==="Authorization"?`${r[c].substring(0,20)}...`:r[c],o),{}),body:this.sanitizeBody(e.body)});const s=new AbortController,a=setTimeout(()=>s.abort(),n);try{const o=await fetch(i,{method:e.method,headers:r,body:e.body,signal:s.signal});clearTimeout(a);const c=await this.convertResponse(o);return Ri.debug("[HTTPRequestController] Response received:",{status:o.status,statusText:o.statusText,headers:[...o.headers.entries()],body:c.body?c.body.substring(0,200):"(empty)"}),c}catch(o){throw clearTimeout(a),o instanceof Error&&o.name==="AbortError"?new to(`Request timeout after ${n}ms`,{cause:o}):(Ri.error("[HTTPRequestController] Request failed:",o),o)}}buildURL(e){const i=typeof e=="string"?e:e.toString();return i.startsWith("http://")||i.startsWith("https://")?i:`${this.baseURL.endsWith("/")?this.baseURL.slice(0,-1):this.baseURL}${i.startsWith("/")?i:`/${i}`}`}buildHeaders(e){const i={...e??{}},r=this.getCredential();return r.token?(i.Authorization=`Bearer ${r.token}`,Ri.debug("[HTTPRequestController] Using Bearer token auth, token length:",r.token.length)):Ri.warn("[HTTPRequestController] No credentials available for authentication"),i}sanitizeBody(e){if(!e||typeof e!="string")return e?"(non-string body)":void 0;try{const i={...JSON.parse(e)};for(const r of Object.keys(i))je.SENSITIVE_BODY_FIELDS.has(r)&&typeof i[r]=="string"&&(i[r]=`${i[r].substring(0,20)}...[redacted]`);return JSON.stringify(i)}catch{return e.length>200?`${e.substring(0,200)}...`:e}}async convertResponse(e){const i={};e.headers.forEach((n,s)=>{i[s]=n});const r=await e.text();return{status:e.status,statusText:e.statusText,headers:i,body:r,ok:e.ok,url:e.url}}},je.defaultMaxRetries=3,je.defaultRetryDelayMinMs=1e3,je.defaultRetryDelayMaxMs=3e4,je.defaultRequestTimeoutMs=3e4,je.SENSITIVE_BODY_FIELDS=new Set(["dpop_token","token","jwt_token"]),je);const hh=5,ph=(t,e)=>({deviceId:t.deviceId,label:t.label,groupId:t.groupId,kind:e});var gh=class{constructor(){this._stacks={audioinput:[],audiooutput:[],videoinput:[]}}push(t,e){const i=ph(e,t),r=this._stacks[t];if(r.length>0&&r[0].deviceId===i.deviceId)return;const n=r.filter(s=>s.deviceId!==i.deviceId);this._stacks[t]=[i,...n].slice(0,hh)}pop(t){const e=this._stacks[t];if(e.length===0)return;const[i,...r]=e;return this._stacks[t]=r,i}findInHistory(t,e){const i=this._stacks[t];for(const r of i){const n=e.find(a=>a.deviceId===r.deviceId);if(n)return n;const s=e.find(a=>a.groupId===r.groupId&&a.label===r.label);if(s)return s}}getHistory(t){return this._stacks[t]}clear(){this._stacks.audioinput=[],this._stacks.audiooutput=[],this._stacks.videoinput=[]}};const fh=1e3,po=600,go=6e3,vh=300*1e3,bh=1e4,mh=100,yh=3e3,wh=1500,Sh=0,fo="sw:preferences",Ch="sat:refresh",vo="/api/fabric/subscriber/devices/token",bo="/api/fabric/subscriber/devices/refresh",lr=900,Ah=3e4,mo=3,Th=1e3,yo=5,Eh=1e3,kh=3e4,xh=5e3,wo=-32003,So=-32602,Co=-32002,Dh=1e3,Ih=10,Mh=2e3,Rh=3,Ph=.05,Oh=4,_h=30,Lh=3,Fh=3e3,Uh=1e4,Nh=1e4,Bh=3,zh=5e3,Vh=2e3,Hh=1e4,jh=3e3,Wh=5e3,Gh=3,qh=1e4,Xh=5e3,Yh=100,Ao=33,Kh=.03,Zh=250,Qh=!0,Jh=!0,$h="sw:device:audioinput",ep="sw:device:audiooutput",tp="sw:device:videoinput",ip=!1,rp=!0,np=!0,sp=!0,ap=150,op=300,cp=!0,lp=!0,up=!0,dp=!1,hp=51e4;function it(t){return t*1e3}function rt(t){return Math.round(t/100)/10}const To=W();var g=class jl{static get instance(){return this._instance??(this._instance=new jl),this._instance}constructor(){this.deviceDebounceTime=wh,this.devicePollingInterval=Sh,this.reconnectCallsTimeout=vh,this.connectionTimeout=bh,this.reconnectDelayMin=mh,this.reconnectDelayMax=yh,this.disableUdpIceServers=!1,this.relayOnly=!1,this.iceCandidateTimeout=po,this.iceGatheringTimeout=go,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=Dh,this.statsBaselineSamples=Ih,this.statsNoPacketThreshold=Mh,this.statsRttSpikeMultiplier=Rh,this.statsPacketLossThreshold=Ph,this.statsJitterSpikeMultiplier=Oh,this.statsHistorySize=_h,this.keyframeMaxBurst=Lh,this.keyframeBurstWindow=Fh,this.keyframeCooldown=Uh,this.reinviteDebounceTime=Nh,this.reinviteMaxAttempts=Bh,this.reinviteTimeout=zh,this.recoveryDebounceTime=Vh,this.recoveryCooldown=Hh,this.iceDisconnectedGracePeriod=jh,this.iceRestartTimeout=Wh,this.maxRecoveryAttempts=Gh,this.enableRelayFallback=cp,this.enableNetworkChangeDetection=lp,this.enableServerHangupInterception=up,this.persistDeviceSelection=Qh,this.syncDevicesToActiveCalls=Jh,this.autoMuteVideoOnHidden=ip,this.refreshDevicesOnVisible=rp,this.checkConnectionOnVisible=np,this.defaultAudioConstraints=void 0,this.defaultVideoConstraints=void 0,this.stereoAudio=dp,this.enableAutoDegradation=sp,this.degradationBitrateThreshold=ap,this.degradationRecoveryThreshold=op,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(e){this._inputAudioDeviceConstraints=e}get inputVideoDeviceConstraints(){return this._inputVideoDeviceConstraints}set inputVideoDeviceConstraints(e){this._inputVideoDeviceConstraints=e}};const pp=["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"],gp=["receiveVideo","receiveAudio","disableUdpIceServers","relayOnly","enableRelayFallback","enableNetworkChangeDetection","enableServerHangupInterception","persistDeviceSelection","syncDevicesToActiveCalls","autoMuteVideoOnHidden","refreshDevicesOnVisible","checkConnectionOnVisible","stereoAudio","enableAutoDegradation"];function fp(){const t=g.instance;return{connectionTimeout:t.connectionTimeout,reconnectCallsTimeout:t.reconnectCallsTimeout,reconnectDelayMin:t.reconnectDelayMin,reconnectDelayMax:t.reconnectDelayMax,relayHost:t.relayHost,receiveVideo:t.receiveVideo,receiveAudio:t.receiveAudio,disableUdpIceServers:t.disableUdpIceServers,relayOnly:t.relayOnly,iceCandidateTimeout:t.iceCandidateTimeout,iceGatheringTimeout:t.iceGatheringTimeout,deviceDebounceTime:t.deviceDebounceTime,devicePollingInterval:t.devicePollingInterval,iceServers:t.iceServers,userVariables:t.userVariables,statsPollingInterval:t.statsPollingInterval,statsBaselineSamples:t.statsBaselineSamples,statsNoPacketThreshold:t.statsNoPacketThreshold,statsRttSpikeMultiplier:t.statsRttSpikeMultiplier,statsPacketLossThreshold:t.statsPacketLossThreshold,statsJitterSpikeMultiplier:t.statsJitterSpikeMultiplier,statsHistorySize:t.statsHistorySize,keyframeMaxBurst:t.keyframeMaxBurst,keyframeBurstWindow:t.keyframeBurstWindow,keyframeCooldown:t.keyframeCooldown,reinviteDebounceTime:t.reinviteDebounceTime,reinviteMaxAttempts:t.reinviteMaxAttempts,reinviteTimeout:t.reinviteTimeout,recoveryDebounceTime:t.recoveryDebounceTime,recoveryCooldown:t.recoveryCooldown,iceDisconnectedGracePeriod:t.iceDisconnectedGracePeriod,iceRestartTimeout:t.iceRestartTimeout,maxRecoveryAttempts:t.maxRecoveryAttempts,enableRelayFallback:t.enableRelayFallback,enableNetworkChangeDetection:t.enableNetworkChangeDetection,enableServerHangupInterception:t.enableServerHangupInterception,persistDeviceSelection:t.persistDeviceSelection,syncDevicesToActiveCalls:t.syncDevicesToActiveCalls,autoMuteVideoOnHidden:t.autoMuteVideoOnHidden,refreshDevicesOnVisible:t.refreshDevicesOnVisible,checkConnectionOnVisible:t.checkConnectionOnVisible,stereoAudio:t.stereoAudio,enableAutoDegradation:t.enableAutoDegradation,degradationBitrateThreshold:t.degradationBitrateThreshold,degradationRecoveryThreshold:t.degradationRecoveryThreshold,preferredVideoCodecs:t.preferredVideoCodecs,preferredAudioCodecs:t.preferredAudioCodecs}}function vp(t){const e=g.instance;for(const i of pp)t[i]!==void 0&&(e[i]=t[i]);for(const i of gp)t[i]!==void 0&&(e[i]=t[i]);t.relayHost!==void 0&&(e.relayHost=t.relayHost),t.iceServers!==void 0&&(e.iceServers=t.iceServers),t.userVariables!==void 0&&(e.userVariables=t.userVariables),t.preferredVideoCodecs!==void 0&&(e.preferredVideoCodecs=t.preferredVideoCodecs),t.preferredAudioCodecs!==void 0&&(e.preferredAudioCodecs=t.preferredAudioCodecs)}var bp=class{constructor(){this._storage=null}enableSavePreferences(t){this._storage=t,this._loadFromStorage()}get connectionTimeout(){return rt(g.instance.connectionTimeout)}set connectionTimeout(t){g.instance.connectionTimeout=it(t),this._saveToStorage()}get reconnectCallsTimeout(){return rt(g.instance.reconnectCallsTimeout)}set reconnectCallsTimeout(t){g.instance.reconnectCallsTimeout=it(t),this._saveToStorage()}get reconnectDelayMin(){return rt(g.instance.reconnectDelayMin)}set reconnectDelayMin(t){g.instance.reconnectDelayMin=it(t),this._saveToStorage()}get reconnectDelayMax(){return rt(g.instance.reconnectDelayMax)}set reconnectDelayMax(t){g.instance.reconnectDelayMax=it(t),this._saveToStorage()}get relayHost(){return g.instance.relayHost??""}set relayHost(t){g.instance.relayHost=t,this._saveToStorage()}get receiveVideo(){return g.instance.receiveVideo}set receiveVideo(t){g.instance.receiveVideo=t,this._saveToStorage()}get receiveAudio(){return g.instance.receiveAudio}set receiveAudio(t){g.instance.receiveAudio=t,this._saveToStorage()}get preferredAudioInput(){return g.instance.preferredAudioInput}set preferredAudioInput(t){g.instance.preferredAudioInput=t}get preferredAudioOutput(){return g.instance.preferredAudioOutput}set preferredAudioOutput(t){g.instance.preferredAudioOutput=t}get preferredVideoInput(){return g.instance.preferredVideoInput}set preferredVideoInput(t){g.instance.preferredVideoInput=t}get inputAudioConstraints(){return g.instance.inputAudioDeviceConstraints}set inputAudioConstraints(t){g.instance.inputAudioDeviceConstraints=t}get inputVideoConstraints(){return g.instance.inputVideoDeviceConstraints}set inputVideoConstraints(t){g.instance.inputVideoDeviceConstraints=t}get deviceDebounceTime(){return rt(g.instance.deviceDebounceTime)}set deviceDebounceTime(t){g.instance.deviceDebounceTime=it(t),this._saveToStorage()}get devicePollingInterval(){return rt(g.instance.devicePollingInterval)}set devicePollingInterval(t){g.instance.devicePollingInterval=it(t),this._saveToStorage()}get disableUdpIceServers(){return g.instance.disableUdpIceServers}set disableUdpIceServers(t){g.instance.disableUdpIceServers=t,this._saveToStorage()}get relayOnly(){return g.instance.relayOnly}set relayOnly(t){g.instance.relayOnly=t,this._saveToStorage()}get iceCandidateTimeout(){return rt(g.instance.iceCandidateTimeout)}set iceCandidateTimeout(t){g.instance.iceCandidateTimeout=it(t),this._saveToStorage()}get iceGatheringTimeout(){return rt(g.instance.iceGatheringTimeout)}set iceGatheringTimeout(t){g.instance.iceGatheringTimeout=it(t),this._saveToStorage()}get iceServers(){return g.instance.iceServers}set iceServers(t){g.instance.iceServers=t,this._saveToStorage()}get userVariables(){return g.instance.userVariables}set userVariables(t){g.instance.userVariables=t,this._saveToStorage()}get statsPollingInterval(){return g.instance.statsPollingInterval}set statsPollingInterval(t){g.instance.statsPollingInterval=t,this._saveToStorage()}get statsBaselineSamples(){return g.instance.statsBaselineSamples}set statsBaselineSamples(t){g.instance.statsBaselineSamples=t,this._saveToStorage()}get statsNoPacketThreshold(){return g.instance.statsNoPacketThreshold}set statsNoPacketThreshold(t){g.instance.statsNoPacketThreshold=t,this._saveToStorage()}get statsRttSpikeMultiplier(){return g.instance.statsRttSpikeMultiplier}set statsRttSpikeMultiplier(t){g.instance.statsRttSpikeMultiplier=t,this._saveToStorage()}get statsPacketLossThreshold(){return g.instance.statsPacketLossThreshold}set statsPacketLossThreshold(t){g.instance.statsPacketLossThreshold=t,this._saveToStorage()}get statsJitterSpikeMultiplier(){return g.instance.statsJitterSpikeMultiplier}set statsJitterSpikeMultiplier(t){g.instance.statsJitterSpikeMultiplier=t,this._saveToStorage()}get statsHistorySize(){return g.instance.statsHistorySize}set statsHistorySize(t){g.instance.statsHistorySize=t,this._saveToStorage()}get keyframeMaxBurst(){return g.instance.keyframeMaxBurst}set keyframeMaxBurst(t){g.instance.keyframeMaxBurst=t,this._saveToStorage()}get keyframeBurstWindow(){return g.instance.keyframeBurstWindow}set keyframeBurstWindow(t){g.instance.keyframeBurstWindow=t,this._saveToStorage()}get keyframeCooldown(){return g.instance.keyframeCooldown}set keyframeCooldown(t){g.instance.keyframeCooldown=t,this._saveToStorage()}get reinviteDebounceTime(){return g.instance.reinviteDebounceTime}set reinviteDebounceTime(t){g.instance.reinviteDebounceTime=t,this._saveToStorage()}get reinviteMaxAttempts(){return g.instance.reinviteMaxAttempts}set reinviteMaxAttempts(t){g.instance.reinviteMaxAttempts=t,this._saveToStorage()}get reinviteTimeout(){return g.instance.reinviteTimeout}set reinviteTimeout(t){g.instance.reinviteTimeout=t,this._saveToStorage()}get recoveryDebounceTime(){return rt(g.instance.recoveryDebounceTime)}set recoveryDebounceTime(t){g.instance.recoveryDebounceTime=it(t),this._saveToStorage()}get recoveryCooldown(){return rt(g.instance.recoveryCooldown)}set recoveryCooldown(t){g.instance.recoveryCooldown=it(t),this._saveToStorage()}get iceDisconnectedGracePeriod(){return rt(g.instance.iceDisconnectedGracePeriod)}set iceDisconnectedGracePeriod(t){g.instance.iceDisconnectedGracePeriod=it(t),this._saveToStorage()}get iceRestartTimeout(){return rt(g.instance.iceRestartTimeout)}set iceRestartTimeout(t){g.instance.iceRestartTimeout=it(t),this._saveToStorage()}get maxRecoveryAttempts(){return g.instance.maxRecoveryAttempts}set maxRecoveryAttempts(t){g.instance.maxRecoveryAttempts=t,this._saveToStorage()}get enableRelayFallback(){return g.instance.enableRelayFallback}set enableRelayFallback(t){g.instance.enableRelayFallback=t,this._saveToStorage()}get enableNetworkChangeDetection(){return g.instance.enableNetworkChangeDetection}set enableNetworkChangeDetection(t){g.instance.enableNetworkChangeDetection=t,this._saveToStorage()}get enableServerHangupInterception(){return g.instance.enableServerHangupInterception}set enableServerHangupInterception(t){g.instance.enableServerHangupInterception=t,this._saveToStorage()}get persistDeviceSelection(){return g.instance.persistDeviceSelection}set persistDeviceSelection(t){g.instance.persistDeviceSelection=t,this._saveToStorage()}get syncDevicesToActiveCalls(){return g.instance.syncDevicesToActiveCalls}set syncDevicesToActiveCalls(t){g.instance.syncDevicesToActiveCalls=t,this._saveToStorage()}get autoMuteVideoOnHidden(){return g.instance.autoMuteVideoOnHidden}set autoMuteVideoOnHidden(t){g.instance.autoMuteVideoOnHidden=t,this._saveToStorage()}get refreshDevicesOnVisible(){return g.instance.refreshDevicesOnVisible}set refreshDevicesOnVisible(t){g.instance.refreshDevicesOnVisible=t,this._saveToStorage()}get checkConnectionOnVisible(){return g.instance.checkConnectionOnVisible}set checkConnectionOnVisible(t){g.instance.checkConnectionOnVisible=t,this._saveToStorage()}get defaultAudioConstraints(){return g.instance.defaultAudioConstraints}set defaultAudioConstraints(t){g.instance.defaultAudioConstraints=t}get defaultVideoConstraints(){return g.instance.defaultVideoConstraints}set defaultVideoConstraints(t){g.instance.defaultVideoConstraints=t}get stereoAudio(){return g.instance.stereoAudio}set stereoAudio(t){g.instance.stereoAudio=t,this._saveToStorage()}get enableAutoDegradation(){return g.instance.enableAutoDegradation}set enableAutoDegradation(t){g.instance.enableAutoDegradation=t,this._saveToStorage()}get degradationBitrateThreshold(){return g.instance.degradationBitrateThreshold}set degradationBitrateThreshold(t){g.instance.degradationBitrateThreshold=t,this._saveToStorage()}get degradationRecoveryThreshold(){return g.instance.degradationRecoveryThreshold}set degradationRecoveryThreshold(t){g.instance.degradationRecoveryThreshold=t,this._saveToStorage()}get preferredVideoCodecs(){return g.instance.preferredVideoCodecs}set preferredVideoCodecs(t){g.instance.preferredVideoCodecs=t,this._saveToStorage()}get preferredAudioCodecs(){return g.instance.preferredAudioCodecs}set preferredAudioCodecs(t){g.instance.preferredAudioCodecs=t,this._saveToStorage()}_saveToStorage(){if(!this._storage)return;const t=fp();this._storage.setItem(fo,t,"local").catch(e=>{To.error(`[ClientPreferences] Failed to save preferences: ${String(e)}`)})}_loadFromStorage(){this._storage&&this._storage.getItem(fo,"local").then(t=>{t&&vp(t)}).catch(t=>{To.error(`[ClientPreferences] Failed to load preferences: ${String(t)}`)})}};function Et(t){return t instanceof Error?t:new Error(String(t))}const nt=W(),Eo={audioinput:$h,audiooutput:ep,videoinput:tp},mp={audioinput:[],audiooutput:[],videoinput:[]},ko={audioinput:null,audiooutput:null,videoinput:null};var yp=class extends ie{constructor(t,e){super(),this.webRTCApiProvider=t,this.deviceChangeHandler=()=>{nt.debug("[DeviceController] Device change detected"),this.enumerateDevices()},this._devicesState$=this.createBehaviorSubject(mp),this._selectedDevicesState$=this.createBehaviorSubject(ko),this._errors$=this.createReplaySubject(1),this._deviceHistory=new gh,this._deviceRecovered$=this.createSubject(),this._audioInputDisabled$=this.createBehaviorSubject(!1),this._videoInputDisabled$=this.createBehaviorSubject(!1),this._lastAudioInputBeforeDisable=null,this._lastVideoInputBeforeDisable=null,this._persistedDevices={},this._storageManager=e,this.init()}setStorageManager(t){this._storageManager=t,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(t){if(!(t!=null&&t.deviceId)||t.deviceId.trim()==="")return{};const e=t.kind==="audioinput"?this.audioInputDevices:this.videoInputDevices,i=e.find(r=>r.deviceId===t.deviceId)??e.find(r=>r.label===t.label);return i?{deviceId:{exact:i.deviceId}}:{}}get errors$(){return this.cachedObservable("errors$",()=>this._errors$.asObservable().pipe(S(this.destroyed$)))}get deviceRecovered$(){return this._deviceRecovered$.asObservable().pipe(S(this.destroyed$))}get videoInputDisabled$(){return this.cachedObservable("videoInputDisabled$",()=>this._videoInputDisabled$.asObservable().pipe(L(),S(this.destroyed$)))}get audioInputDisabled$(){return this.cachedObservable("audioInputDisabled$",()=>this._audioInputDisabled$.asObservable().pipe(L(),S(this.destroyed$)))}get videoInputDisabled(){return this._videoInputDisabled$.value}get audioInputDisabled(){return this._audioInputDisabled$.value}get audioInputDevices$(){return this.cachedObservable("audioInputDevices$",()=>this._devicesState$.pipe(E(t=>t.audioinput),L(),S(this.destroyed$)))}get audioOutputDevices$(){return this.cachedObservable("audioOutputDevices$",()=>this._devicesState$.pipe(E(t=>t.audiooutput),L(),S(this.destroyed$)))}get videoInputDevices$(){return this.cachedObservable("videoInputDevices$",()=>this._devicesState$.pipe(E(t=>t.videoinput),L(),S(this.destroyed$)))}get selectedAudioInputDevice$(){return this.cachedObservable("selectedAudioInputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(E(t=>t.audioinput),L(),S(this.destroyed$),Se(t=>nt.debug("[DeviceController] Selected audio input device changed:",t))))}get selectedAudioOutputDevice$(){return this.cachedObservable("selectedAudioOutputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(E(t=>t.audiooutput),L(),S(this.destroyed$),Se(t=>nt.debug("[DeviceController] Selected audio output device changed:",t))))}get selectedVideoInputDevice$(){return this.cachedObservable("selectedVideoInputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(E(t=>t.videoinput),L(),S(this.destroyed$),Se(t=>nt.debug("[DeviceController] Selected video input device changed:",t))))}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 t=this._lastAudioInputBeforeDisable??this.audioInputDevices[0];this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audioinput:t}),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 t=this._lastVideoInputBeforeDisable??this.videoInputDevices[0];this._selectedDevicesState$.next({...this._selectedDevicesState$.value,videoinput:t}),this._lastVideoInputBeforeDisable=null}}selectAudioInputDevice(t){this._audioInputDisabled$.value&&t&&this._audioInputDisabled$.next(!1);const e=this._selectedDevicesState$.value.audioinput;e&&e.deviceId!==(t==null?void 0:t.deviceId)&&this._deviceHistory.push("audioinput",e),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audioinput:t}),t&&this.persistDeviceSelection("audioinput",t)}selectVideoInputDevice(t){nt.debug("[DeviceController] Setting selected video input device:",t),this._videoInputDisabled$.value&&t&&this._videoInputDisabled$.next(!1);const e=this._selectedDevicesState$.value.videoinput;e&&e.deviceId!==(t==null?void 0:t.deviceId)&&this._deviceHistory.push("videoinput",e),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,videoinput:t}),t&&this.persistDeviceSelection("videoinput",t)}selectAudioOutputDevice(t){const e=this._selectedDevicesState$.value.audiooutput;e&&e.deviceId!==(t==null?void 0:t.deviceId)&&this._deviceHistory.push("audiooutput",e),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audiooutput:t}),t&&this.persistDeviceSelection("audiooutput",t)}init(){this.loadPersistedDevices(),this.subscribeTo(this._devicesState$.pipe(Xa(g.instance.deviceDebounceTime)),t=>{const e=this._selectedDevicesState$.value,i=this._audioInputDisabled$.value?null:this.resolveDevice("audioinput",t.audioinput,e.audioinput,g.instance.preferredAudioInput),r=this.resolveDevice("audiooutput",t.audiooutput,e.audiooutput,g.instance.preferredAudioOutput),n=this._videoInputDisabled$.value?null:this.resolveDevice("videoinput",t.videoinput,e.videoinput,g.instance.preferredVideoInput);if(i!==e.audioinput||r!==e.audiooutput||n!==e.videoinput){const s=g.instance.syncDevicesToActiveCalls;this._selectedDevicesState$.next({audioinput:s||!e.audioinput?i:e.audioinput,audiooutput:s||!e.audiooutput?r:e.audiooutput,videoinput:s||!e.videoinput?n:e.videoinput})}}),this.enumerateDevices()}resolveDevice(t,e,i,r){if(e.length===0)return null;if(i){if(e.find(c=>c.deviceId===i.deviceId))return i;const s=e.filter(c=>c.label===i.label);if(s.length===1)return s[0];if(s.length>1){const c=s.find(u=>u.groupId===i.groupId);return c||(this.emitDeviceRecovered(t,i,null,"ambiguous_match"),null)}const a=this._deviceHistory.findInHistory(t,e);if(a)return nt.debug(`[DeviceController] Device disappeared, falling back to history: ${a.label}`),this.emitDeviceRecovered(t,i,a,"device_disconnected"),a;const o=(r?e.find(c=>c.deviceId===r.deviceId||c.label===r.label):void 0)??e[0];return this.emitDeviceRecovered(t,i,o,"fallback_to_default"),o}const n=this._persistedDevices[t];if(n){const s=this.resolvePersistedDevice(t,n,e);if(s)return s}if(r){const s=e.find(a=>a.deviceId===r.deviceId||a.label===r.label);if(s)return s}return e[0]}resolvePersistedDevice(t,e,i){const r=i.find(a=>a.deviceId===e.deviceId);if(r)return r;const n=i.find(a=>a.groupId===e.groupId&&a.label===e.label);if(n)return n;const s=i.filter(a=>a.label===e.label);return s.length===1?s[0]:null}emitDeviceRecovered(t,e,i,r){try{this._deviceRecovered$.next({kind:t,previousDevice:e,newDevice:i,reason:r})}catch{}}async persistDeviceSelection(t,e){if(!this._storageManager||!g.instance.persistDeviceSelection)return;const i={deviceId:e.deviceId,label:e.label,kind:e.kind,groupId:e.groupId};try{await this._storageManager.setItem(Eo[t],i,"local")}catch(r){nt.error(`[DeviceController] Failed to persist device selection for ${t}:`,r)}}async loadPersistedDevices(){if(!(!this._storageManager||!g.instance.persistDeviceSelection))for(const t of["audioinput","audiooutput","videoinput"])try{const e=await this._storageManager.getItem(Eo[t],"local");e&&(this._persistedDevices={...this._persistedDevices,[t]:e})}catch(e){nt.error(`[DeviceController] Failed to load persisted device for ${t}:`,e)}}async clearDeviceState(){this._deviceHistory.clear(),this._persistedDevices={},this._lastAudioInputBeforeDisable=null,this._lastVideoInputBeforeDisable=null,this._audioInputDisabled$.next(!1),this._videoInputDisabled$.next(!1),this._selectedDevicesState$.next(ko),await this.enumerateDevices()}enableDeviceMonitoring(){this.disableDeviceMonitoring(),this.webRTCApiProvider.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler),g.instance.devicePollingInterval>0&&(this._devicesPoolingSubscription=jr(g.instance.devicePollingInterval).subscribe(()=>{nt.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 t=(await this.webRTCApiProvider.mediaDevices.enumerateDevices()).reduce((e,i)=>{const r=i.kind;return{...e,[r]:[...e[r],i]}},{audioinput:[],audiooutput:[],videoinput:[]});this._devicesState$.next(t),nt.debug("[DeviceController] Devices enumerated:",{audioInputs:t.audioinput.length,audioOutputs:t.audiooutput.length,videoInputs:t.videoinput.length})}catch(t){nt.error("[DeviceController] Failed to enumerate devices:",t),this._errors$.next(Et(t))}}async getDeviceCapabilities(t){if(t.kind==="audiooutput")return null;try{const e=this.deviceInfoToConstraints(t),i=await this.webRTCApiProvider.mediaDevices.getUserMedia({audio:t.kind==="audioinput"?e:!1,video:t.kind==="videoinput"?e:!1}),r=(t.kind==="audioinput"?i.getAudioTracks()[0]:i.getVideoTracks()[0]).getCapabilities();return i.getTracks().forEach(n=>n.stop()),r}catch(e){throw nt.error("[DeviceController] Failed to get device capabilities:",e),this._errors$.next(Et(e)),e}}async isValidDevice(t){if(!t||t.kind==="audiooutput")return!1;try{return await this.getDeviceCapabilities(t)!==null}catch{return!1}}destroy(){this.disableDeviceMonitoring(),super.destroy()}},xo=class{constructor(){if(typeof localStorage>"u")throw new Kn("localStorage");if(typeof sessionStorage>"u")throw new Kn("sessionStorage");try{const t="__storage_test__";localStorage.setItem(t,"test"),localStorage.removeItem(t)}catch(t){throw W().error("LocalStorage is not accessible:",t),new Kn("localStorage")}}storage(t){return t==="local"?localStorage:sessionStorage}async setItem(t,e,i="session"){return this.storage(i).setItem(t,e),Promise.resolve()}async getItem(t,e="session"){return Promise.resolve(this.storage(e).getItem(t))}async removeItem(t,e="session"){return this.storage(e).removeItem(t),Promise.resolve()}async clear(t="session"){const e=this.storage(t),i=[];for(let r=0;r<e.length;r++){const n=e.key(r);n!=null&&n.startsWith("sw:")&&i.push(n)}for(const r of i)e.removeItem(r);return Promise.resolve()}},wp=class{constructor(t=new xo){this.storageImpl=t}serialize(t,e){if(t==null)return null;try{return JSON.stringify(t)}catch(i){throw new Ud(e??"unknown",i)}}async setItem(t,e,i="session"){const r=this.serialize(e,t);try{await this.storageImpl.setItem(t,r,i)}catch(n){throw new Zn(t,n)}}async getItem(t,e="session"){let i;try{i=await this.storageImpl.getItem(t,e)}catch(r){throw new Bd(t,r)}if(!i)return null;try{return JSON.parse(i)}catch(r){throw new Nd(t,r)}}async removeItem(t,e="session"){try{await this.storageImpl.removeItem(t,e)}catch(i){throw new Zn(t,i)}}async clearAll(){try{await this.storageImpl.clear("local"),await this.storageImpl.clear("session")}catch(t){throw new Zn("clearAll",t)}}},Sp=class{constructor(){this.persistSession=!1,this._webSocketConstructor=typeof WebSocket<"u"?WebSocket:void 0,this._baseURL=this.apiHost,this._credential={}}get userId(){return this.user.id}get user(){if(!this._user)throw new Q("User");return this._user}set user(t){this._user=t}get storage(){return this._storageManager||(this._storageImpl??(this._storageImpl=new xo),this._storageManager=new wp(this._storageImpl)),this._storageManager}get http(){return this._httpRequestController??(this._httpRequestController=new dh(this._baseURL,()=>this._credential)),this._httpRequestController}get conversationManager(){if(!this._conversationManager)throw new Q("ConversationsManager");return this._conversationManager}set conversationManager(t){this._conversationManager=t}get WebSocket(){if(!this._webSocketConstructor)throw new Q("WebSocket constructor");return this._webSocketConstructor}set WebSocket(t){this._webSocketConstructor=t}get deviceController(){return this._deviceController??(this._deviceController=new yp(this.webRTCApiProvider,this.storage)),this._deviceController}get webRTCApiProvider(){if(!this._webRTCApiProvider){if(typeof RTCPeerConnection>"u"||typeof navigator>"u")throw new Q("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(t){this._webRTCApiProvider=t,this._deviceController=void 0}get authorizationStateKey(){return`sw:${this.userId}:as`}get protocolKey(){return`sw:${this.userId}:pt`}get attachedCallsKey(){return`sw:${this.userId}:att`}getUserFromAddressId(){var t;return((t=this.user.addresses[0])==null?void 0:t.id)??""}set baseURL(t){this._baseURL=t,this._httpRequestController=void 0}get credential(){return this._credential}set credential(t){this._credential=t}set storageImpl(t){this._storageImpl=t,this._storageManager=void 0}set ch(t){if(!t)return;const e=t.indexOf(".");e!==-1&&(this._host=t.substring(0,e),this._domain=t.substring(e+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 Wt=W(),Cp="sw-dpop",Ap=1,Gt="keys",es="dpop-keypair",$r=t=>{const e=new Uint8Array(t);let i="";for(const r of e)i+=String.fromCharCode(r);return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},Do=t=>$r(new TextEncoder().encode(t).buffer),Io=async t=>{if(t.kty!=="RSA")throw new Error(`Unsupported key type for JWK Thumbprint: ${t.kty}. Only RSA is supported.`);const e=JSON.stringify({e:t.e,kty:t.kty,n:t.n});return $r(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))};async function ts(){return new Promise((t,e)=>{const i=indexedDB.open(Cp,Ap);i.onupgradeneeded=()=>{const r=i.result;r.objectStoreNames.contains(Gt)||r.createObjectStore(Gt)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error??new Error("Failed to open IndexedDB"))})}async function Tp(){try{const t=await ts();return await new Promise((e,i)=>{const r=t.transaction(Gt,"readonly"),n=r.objectStore(Gt).get(es);n.onsuccess=()=>e(n.result??null),n.onerror=()=>i(n.error??new Error("Failed to load key pair from IndexedDB")),r.oncomplete=()=>t.close()})}catch(t){return Wt.warn("[DPoP] Failed to load key pair from IndexedDB:",t),null}}async function Ep(t){try{const e=await ts();await new Promise((i,r)=>{const n=e.transaction(Gt,"readwrite");n.objectStore(Gt).put(t,es),n.oncomplete=()=>{e.close(),i()},n.onerror=()=>{e.close(),r(n.error??new Error("Failed to save key pair to IndexedDB"))}})}catch(e){Wt.warn("[DPoP] Failed to save key pair to IndexedDB:",e)}}async function Mo(){try{const t=await ts();await new Promise((e,i)=>{const r=t.transaction(Gt,"readwrite");r.objectStore(Gt).delete(es),r.oncomplete=()=>{t.close(),e()},r.onerror=()=>{t.close(),i(r.error??new Error("Failed to delete key pair from IndexedDB"))}})}catch(t){Wt.warn("[DPoP] Failed to delete key pair from IndexedDB:",t)}}var kp=class{constructor(){this._keyPair=null,this._publicJwk=null,this._fingerprint=null,this._initialized=!1}async init(){if(this._initialized)return this.fingerprint;const t=await Tp();if(t)try{const e=new TextEncoder().encode("dpop-key-check");return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",t.privateKey,e),this._keyPair=t,this._publicJwk=await crypto.subtle.exportKey("jwk",t.publicKey),this._fingerprint=await Io(this._publicJwk),this._initialized=!0,Wt.debug("[DPoP] Key pair restored from IndexedDB, fingerprint:",this._fingerprint),this._fingerprint}catch(e){Wt.warn("[DPoP] Stored key pair unusable, generating new one:",e),await Mo()}return Wt.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 Io(this._publicJwk),this._initialized=!0,await Ep(this._keyPair),Wt.debug("[DPoP] Key pair generated and persisted, fingerprint:",this._fingerprint),this._fingerprint}get fingerprint(){if(!this._fingerprint)throw new Kr("CryptoController not initialized. Call init() first.");return this._fingerprint}get initialized(){return this._initialized}async createHttpProof(t){const e={jti:crypto.randomUUID(),htm:t.method,htu:t.uri,iat:Math.floor(Date.now()/1e3)};return t.accessToken&&(e.ath=$r(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t.accessToken)))),this.signProof(e)}async createRpcProof(t){const e={jti:crypto.randomUUID(),rpc:"request",mth:t.method,iat:Math.floor(Date.now()/1e3)};return this.signProof(e)}destroy(){this._keyPair=null,this._publicJwk=null,this._fingerprint=null,this._initialized=!1,Mo(),Wt.debug("[DPoP] Controller destroyed")}get publicJwk(){if(!this._publicJwk)throw new Kr("CryptoController not initialized. Call init() first.");return this._publicJwk}get privateKey(){if(!this._keyPair)throw new Kr("CryptoController not initialized. Call init() first.");return this._keyPair.privateKey}async signProof(t){const e={typ:"dpop+jwt",alg:"RS256",jwk:this.publicJwk},i=`${Do(JSON.stringify(e))}.${Do(JSON.stringify(t))}`;return`${i}.${$r(await crypto.subtle.sign("RSASSA-PKCS1-v1_5",this.privateKey,new TextEncoder().encode(i)))}`}};const Pi=W();function Ro(){return typeof window<"u"&&typeof window.addEventListener=="function"}function Po(){if(typeof navigator>"u")return;const{connection:t}=navigator;return(t==null?void 0:t.effectiveType)??void 0}function Oo(){if(!(typeof navigator>"u"))return navigator.connection??void 0}var xp=class extends ie{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(S(this._destroyed$))}get isOnline(){return this._isOnline$.value}get networkChange$(){return this._networkChange$.asObservable().pipe(S(this._destroyed$))}destroy(){this.removeListeners(),super.destroy()}attachListeners(){if(!Ro()){Pi.debug("NetworkMonitor: no browser environment detected, skipping event listeners");return}window.addEventListener("online",this._onOnline),window.addEventListener("offline",this._onOffline);const t=Oo();t&&t.addEventListener("change",this._onConnectionChange),this._listenersAttached=!0,Pi.debug("NetworkMonitor: event listeners attached")}removeListeners(){if(this._listenersAttached){if(Ro()){window.removeEventListener("online",this._onOnline),window.removeEventListener("offline",this._onOffline);const t=Oo();t&&t.removeEventListener("change",this._onConnectionChange)}this._listenersAttached=!1,Pi.debug("NetworkMonitor: event listeners removed")}}handleOnline(){Pi.info("NetworkMonitor: browser went online"),this._isOnline$.next(!0),this._networkChange$.next({type:"online",timestamp:Date.now(),networkType:Po()})}handleOffline(){Pi.info("NetworkMonitor: browser went offline"),this._isOnline$.next(!1),this._networkChange$.next({type:"offline",timestamp:Date.now()})}handleConnectionChange(){const t=Po();Pi.info(`NetworkMonitor: connection changed — effectiveType=${t??"unknown"}`),this._networkChange$.next({type:"connection_change",timestamp:Date.now(),networkType:t})}};function _o(t){if(typeof RTCRtpSender>"u"||typeof RTCRtpSender.getCapabilities!="function")return[];const e=RTCRtpSender.getCapabilities(t);if(!e)return[];const i=new Set,r=[];for(const n of e.codecs){const s=Dp(n.mimeType);s&&!i.has(s)&&(i.add(s),r.push(s))}return r}function Dp(t){const e=t.indexOf("/");return e>=0?t.substring(e+1):t}function Ip(){return typeof globalThis>"u"?!1:"RTCRtpScriptTransform"in globalThis||"MediaStreamTrackProcessor"in globalThis}function Mp(){return typeof HTMLMediaElement>"u"?!1:"setSinkId"in HTMLMediaElement.prototype}function Rp(){return typeof RTCRtpSender>"u"?!1:typeof RTCRtpSender.prototype.setParameters=="function"}function Lo(t){const e=(t==null?void 0:t.mediaDevices)??Fo(),i=typeof(e==null?void 0:e.getUserMedia)=="function",r=typeof(e==null?void 0:e.getDisplayMedia)=="function",n={webrtc:t?typeof t.RTCPeerConnection=="function":typeof globalThis<"u"&&"RTCPeerConnection"in globalThis,getUserMedia:i,getDisplayMedia:r,screenShare:r,screenShareAudio:Pp(),simulcast:Rp(),insertableStreams:Ip(),audioOutputSelection:Mp(),videoCodecs:_o("video"),audioCodecs:_o("audio")};return Object.freeze(n)}function Pp(){if(typeof navigator>"u")return!1;const t=Fo();return!t||typeof t.getDisplayMedia!="function"?!1:navigator.userAgent.includes("Chrome/")}function Fo(){return typeof navigator<"u"?navigator.mediaDevices:null}const en=W(),Op=10,_p=1e4,Lp=5e3,Fp=5e3;var Up=class extends ie{constructor(t,e,i,r,n,s={}){super(),this.deviceController=t,this.iceServers=e,this.isConnected=i,this.transportRttMs=r,this.dialFn=n,this._options={duration:s.duration??Op,skipMediaTest:s.skipMediaTest??!1,audioDevice:s.audioDevice,videoDevice:s.videoDevice}}async run(t){const e=[];try{const i=this.testSignaling();i.reachable||e.push("WebSocket not connected");const r=await this.testDevices();r.audioInput.working||e.push("Audio input device not working"),r.videoInput.working||e.push("Video input device not working");const n=await this.testIceConnectivity();n.type==="failed"?e.push("No ICE connectivity (neither STUN nor TURN reachable)"):n.type==="relay"&&e.push("Only TURN relay connectivity available (no direct path)"),n.turnReachable||e.push("TURN servers not reachable");let s=null;if(!this._options.skipMediaTest)try{s=await this.testMediaBandwidth(t)}catch(a){en.warn("[PreflightRunner] Media bandwidth test failed:",a),e.push("Media bandwidth test failed")}return{ok:i.reachable&&n.type!=="failed"&&r.audioInput.working,signaling:i,connectivity:n,bandwidth:s,devices:r,warnings:e}}catch(i){throw en.error("[PreflightRunner] Preflight test failed:",i),new jd("preflight",i instanceof Error?i:new Error(String(i)))}finally{this.destroy()}}testSignaling(){return{reachable:this.isConnected,rttMs:this.transportRttMs}}async testDevices(){const t=this._options.audioDevice??this.deviceController.selectedAudioInputDevice,e=this._options.videoDevice??this.deviceController.selectedVideoInputDevice,i=this.deviceController.selectedAudioOutputDevice;let r=!1,n=!1,s;try{const a={};t?a.audio={deviceId:{exact:t.deviceId}}:a.audio=!0,e?a.video={deviceId:{exact:e.deviceId}}:a.video=!0,s=await Promise.race([navigator.mediaDevices.getUserMedia(a),new Promise((o,c)=>setTimeout(()=>c(new Error("getUserMedia timeout")),Fp))]);for(const o of s.getTracks())o.kind==="audio"&&o.readyState==="live"&&(r=!0),o.kind==="video"&&o.readyState==="live"&&(n=!0)}catch(a){en.warn("[PreflightRunner] Device test failed:",a)}finally{s&&s.getTracks().forEach(a=>a.stop())}return{audioInput:{working:r,device:t},videoInput:{working:n,device:e},audioOutput:{available:!!i,device:i}}}async testIceConnectivity(){let t;try{t=new RTCPeerConnection({iceServers:this.iceServers});const e=t,i=new Set,r=Date.now(),n=new Promise(p=>{const f=setTimeout(p,_p);e.onicecandidate=m=>{if(m.candidate){const R=m.candidate.candidate;R.includes("typ host")&&i.add("host"),R.includes("typ srflx")&&i.add("srflx"),R.includes("typ relay")&&i.add("relay")}else clearTimeout(f),p()}});t.createDataChannel("preflight-test");const s=await t.createOffer();await t.setLocalDescription(s),await n;const a=Date.now()-r,o=i.has("srflx"),c=i.has("relay"),u=i.has("host");let h="failed";return u||o?h="direct":c&&(h="relay"),{type:h,turnReachable:c,stunReachable:o,rttMs:a}}catch(e){return en.warn("[PreflightRunner] ICE connectivity test failed:",e),{type:"failed",turnReachable:!1,stunReachable:!1,rttMs:0}}finally{t&&t.close()}}async testMediaBandwidth(t){let e;try{e=await this.dialFn(t,{audio:!0,video:!1}),await Ge(e.status$.pipe(B(a=>a==="connected"),Me(1),ar(Lp)));const i=this._options.duration*1e3;await new Promise(a=>setTimeout(a,i));const r=e.networkMetrics;let n=0,s=0;if(r.length>0){const a=r[r.length-1];a.availableOutgoingBitrate!==void 0&&(n=Math.round(a.availableOutgoingBitrate/1e3));const o=a.audio.packetsReceived+a.video.packetsReceived;i>0&&o>0&&(s=n)}return{uploadKbps:n,downloadKbps:s}}finally{if(e)try{await e.hangup()}catch{}}}destroy(){super.destroy()}};const tn=W();function Np(){try{return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.visibilityState=="string"}catch{return!1}}function Uo(){try{if(typeof document<"u"&&typeof document.visibilityState=="string")return document.visibilityState==="visible"?"visible":"hidden"}catch{}return"visible"}var Bp=class extends ie{constructor(){super(),this._visibility$=this.createBehaviorSubject(Uo()),this._visibilityChange$=this.createSubject(),this._hasVisibilityApi=Np(),this._boundHandler=this._handleVisibilityChange.bind(this),this._hasVisibilityApi?(document.addEventListener("visibilitychange",this._boundHandler),tn.debug("VisibilityController: listening for visibilitychange events")):tn.debug("VisibilityController: document visibility API not available, defaulting to visible")}get visibility$(){return this._visibility$.pipe(S(this._destroyed$))}get visibility(){return this._visibility$.value}get visibilityChange$(){return this._visibilityChange$.pipe(S(this._destroyed$))}destroy(){this._hasVisibilityApi&&(document.removeEventListener("visibilitychange",this._boundHandler),tn.debug("VisibilityController: removed visibilitychange listener")),super.destroy()}_handleVisibilityChange(){const t=Uo(),e=this._visibility$.value;if(t===e)return;this._visibility$.next(t);const i={from:e,to:t,timestamp:Date.now()};this._visibilityChange$.next(i),tn.debug("VisibilityController: visibility changed",{from:e,to:t})}},zp=class extends ie{constructor(t,e){super(),this.fromPath=t,this.http=e,this.fetched$=$t(()=>Ie(this.fetch())).pipe(et(1),S(this.destroyed$))}async fetch(){const t=await this.http.request({url:this.fromPath,method:"GET",headers:{Accept:"application/json"}});if(t.ok&&t.body){const e=JSON.parse(t.body);return this.populateInstance(e),!0}return!1}},Vp=class extends zp{constructor(t){super("/api/fabric/subscriber/info",t)}populateInstance(t){this.id=t.id,this.email=t.email,this.firstName=t.first_name,this.lastName=t.last_name,this.displayName=t.display_name,this.jobTitle=t.job_title,this.timeZone=t.time_zone,this.country=t.country,this.region=t.region,this.companyName=t.company_name,this.pushNotificationKey=t.push_notification_key,this.appSettings=t.app_settings?{displayName:t.app_settings.display_name,scopes:t.app_settings.scopes}:void 0,this.addresses=t.fabric_addresses,this.satClaims=t.sat_claims}};const Oi=t=>({jsonrpc:"2.0",id:t.id??Qr(),...t}),No=t=>({jsonrpc:"2.0",...t}),Hp={major:4,minor:0,revision:0},jp=t=>Oi({method:"signalwire.connect",params:{version:Hp,event_acks:!0,...t}}),Wp=t=>{const{dpop_token:e,...i}=t;return Oi({method:"signalwire.reauthenticate",params:{authentication:i,...e?{dpop_token:e}:{}}})},Gp=(t,e)=>No({id:t,result:{timestamp:Date.now()/1e3}}),is=({method:t,params:e})=>Oi({method:t,params:e}),qp={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"},Xp=new Set(["remoteSdp","localStream","remoteStream"]),Yp=t=>{if(!Object.prototype.hasOwnProperty.call(t,"dialogParams"))return t;const e=t.dialogParams,i=Object.entries(e).reduce((r,[n,s])=>{if(Xp.has(n))return r;const a=qp[n]??n;return{...r,[a]:s}},{});return{...t,dialogParams:i}},ri=t=>(e={})=>Oi({method:t,params:Yp(e)}),Bo=t=>Oi({method:"webrtc.verto",params:t}),Kp=ri("verto.invite"),Zp=ri("verto.bye"),rn=ri("verto.modify"),Qp=ri("verto.info"),Jp=ri("verto.answer"),$p=ri("verto.subscribe"),eg=ri("verto.pong"),tg={NORMAL_CLEARING:"16",USER_BUSY:"17",MEDIA_TIMEOUT:"804"},ig=t=>No({id:t,result:{}}),_i=W();var rg=class{constructor(t,e,i,r){this.storage=t,this.deviceController=e,this.reconnectCallsTimeout=i,this.attachKey=r,this.writeQueue=Promise.resolve()}async detachAll(){await this.mutate(t=>({}))}setSession(t){this.session=t}async readAttached(){try{return await this.storage.getItem(this.attachKey)??{}}catch(t){return _i.warn("[AttachManager] Failed to retrieve attached calls from storage",t),{}}}async writeAttached(t){try{await this.storage.setItem(this.attachKey,t)}catch(e){_i.warn("[AttachManager] Failed to write attached calls to storage",e)}}async mutate(t){const e=this.writeQueue.then(async()=>{const i=await t(await this.readAttached());await this.writeAttached(i)});return this.writeQueue=e.catch(()=>{}),e}async attach(t){if(!t.to){_i.warn("[AttachManager] Skip attach for calls with no destination");return}const e=t.to,i={nodeId:t.nodeId,destination:e,mediaDirections:t.mediaDirections,audioInputDevice:t.mediaDirections.audio!=="inactive"?this.deviceController.selectedAudioInputDevice:null,videoInputDevice:t.mediaDirections.video!=="inactive"?this.deviceController.selectedVideoInputDevice:null,attachedAt:Date.now()};await this.mutate(r=>({...r,[t.id]:i}))}async detach(t){await this.mutate(e=>{const{[t.id]:i,...r}=e;return r})}async flush(){await this.mutate(()=>({}))}async reattachCalls(){const t=await this.readAttached();await this.detachExpired();for(const[e,i]of Object.entries(t)){const{destination:r}=i,n=this.buildCallOptions(i);let s=!1;for(let a=1;a<=3;a++)try{await this.session.createOutboundCall(r,{callId:e,...n}),_i.info(`[AttachManager] Reattached call ${e} (attempt ${a})`),s=!0;break}catch(o){_i.warn(`[AttachManager] Reattach attempt ${a}/3 failed for call ${e}:`,o),a<3&&await new Promise(c=>setTimeout(c,(a+1)*1e3))}s||(_i.warn(`[AttachManager] Reattach failed after 3 attempts for call ${e}, removing reference`),await this.detach({id:e,mediaDirections:i.mediaDirections}))}}buildCallOptions(t){const{audio:e,video:i}=t.mediaDirections,{audioInputDevice:r,videoInputDevice:n,nodeId:s}=t,a=e.includes("recv"),o=i.includes("recv"),c=e.includes("send"),u=i.includes("send");return{nodeId:s,receiveAudio:a,receiveVideo:o,inputAudioDeviceConstraints:c?{audio:!0,...this.deviceController.deviceInfoToConstraints(r)}:void 0,inputVideoDeviceConstraints:u?{video:!0,...this.deviceController.deviceInfoToConstraints(n)}:void 0,reattach:!0}}async consumePendingAttachment(t){const e=await this.readAttached();if(Object.hasOwn(e,t))return this.buildCallOptions(e[t])}async detachExpired(){const t=Date.now(),e=this.reconnectCallsTimeout;await this.mutate(i=>{const r={...i};let n=!1;for(const[s,a]of Object.entries(i))t-a.attachedAt>e&&(delete r[s],n=!0);return n?r:i})}};const ni={on:!1,off:!1},rs={muteAudio:ni,muteVideo:ni,deaf:ni,raisehand:ni,microphoneVolume:!1,microphoneSensitivity:!1,speakerVolume:!1,position:!1,meta:!1,remove:!1,audioFlags:!1},zo={self:rs,member:rs,end:!1,setLayout:!1,sendDigit:!1,vmutedHide:ni,lock:ni,device:!1,screenshare:!1};function Li(t){return t.length===0?ni:{on:t.some(e=>!e.endsWith(".off")),off:t.some(e=>!e.endsWith(".on"))}}function Vo(t,e,i,r){return t.filter(n=>n===e||n===`${e}.${i}`||n.startsWith(`${e}.${i}.${r}`))}function si(t,e,i,r){return t.some(n=>n===e||i!==null&&n===`${e}.${i}`||n.startsWith(`${e}.${i?`${i}.`:""}${r}`))}function Ho(t,e){return t.filter(i=>i.startsWith(e)||i===e).length===0?rs:{muteAudio:Li(Vo(t,e,"mute","audio")),muteVideo:Li(Vo(t,e,"mute","video")),deaf:Li(t.filter(i=>i===e||i.startsWith(`${e}.deaf`))),raisehand:Li(t.filter(i=>i===e||i.startsWith(`${e}.raisehand`))),microphoneVolume:si(t,e,"microphone","volume"),microphoneSensitivity:si(t,e,"microphone","sensitivity"),speakerVolume:si(t,e,"speaker","volume"),position:si(t,e,null,"position"),meta:si(t,e,null,"meta"),remove:si(t,e,null,"remove"),audioFlags:si(t,e,null,"audioflags")}}function ng(t){return t.length===0?zo:{self:Ho(t,"self"),member:Ho(t,"member"),end:t.some(e=>e==="end"),setLayout:t.some(e=>e.startsWith("layout")),sendDigit:t.some(e=>e.startsWith("digit")),vmutedHide:Li(t.filter(e=>e.startsWith("vmuted"))),lock:Li(t.filter(e=>e.startsWith("lock"))),device:t.some(e=>e==="device"),screenshare:t.some(e=>e==="screenshare")}}var sg=class extends ie{constructor(...t){super(...t),this._state$=this.createBehaviorSubject(zo)}updateFromRaw(t){const e=ng(t);this._state$.next(e)}get self$(){return this.cachedObservable("self$",()=>this._state$.pipe(E(t=>t.self),L()))}get self(){return this._state$.value.self}get member$(){return this.cachedObservable("member$",()=>this._state$.pipe(E(t=>t.member),L()))}get member(){return this._state$.value.member}get end$(){return this.cachedObservable("end$",()=>this._state$.pipe(E(t=>t.end),L()))}get end(){return this._state$.value.end}get setLayout$(){return this.cachedObservable("setLayout$",()=>this._state$.pipe(E(t=>t.setLayout),L()))}get setLayout(){return this._state$.value.setLayout}get sendDigit$(){return this.cachedObservable("sendDigit$",()=>this._state$.pipe(E(t=>t.sendDigit),L()))}get sendDigit(){return this._state$.value.sendDigit}get vmutedHide$(){return this.cachedObservable("vmutedHide$",()=>this._state$.pipe(E(t=>t.vmutedHide),L()))}get vmutedHide(){return this._state$.value.vmutedHide}get lock$(){return this.cachedObservable("lock$",()=>this._state$.pipe(E(t=>t.lock),L()))}get lock(){return this._state$.value.lock}get device$(){return this.cachedObservable("device$",()=>this._state$.pipe(E(t=>t.device),L()))}get device(){return this._state$.value.device}get screenshare$(){return this.cachedObservable("screenshare$",()=>this._state$.pipe(E(t=>t.screenshare),L()))}get screenshare(){return this._state$.value.screenshare}get state$(){return this._state$.asObservable()}get state(){return this._state$.value}};function ag(t){return t?"call.undeaf":"call.deaf"}function og(t){return t?"call.lowerhand":"call.raisehand"}const ai=W(),cg={};var jo=class extends ie{constructor(t,e,i){super(),this.executeMethod=e,this.deviceController=i,this._state$=this.createBehaviorSubject(cg),this.id=t}upnext(t){this._state$.next({...this._state$.value,...t})}get name$(){return this.cachedObservable("name$",()=>this._state$.pipe(E(t=>t.name),L()))}get type$(){return this.cachedObservable("type$",()=>this._state$.pipe(E(t=>t.type),L()))}get handraised$(){return this.cachedObservable("handraised$",()=>this._state$.pipe(E(t=>t.handraised),L()))}get visible$(){return this.cachedObservable("visible$",()=>this._state$.pipe(E(t=>t.visible),L()))}get audioMuted$(){return this.cachedObservable("audioMuted$",()=>this._state$.pipe(E(t=>t.audio_muted),L()))}get videoMuted$(){return this.cachedObservable("videoMuted$",()=>this._state$.pipe(E(t=>t.video_muted),L()))}get deaf$(){return this.cachedObservable("deaf$",()=>this._state$.pipe(E(t=>t.deaf),L()))}get inputVolume$(){return this.cachedObservable("inputVolume$",()=>this._state$.pipe(E(t=>t.input_volume),L()))}get outputVolume$(){return this.cachedObservable("outputVolume$",()=>this._state$.pipe(E(t=>t.output_volume),L()))}get inputSensitivity$(){return this.cachedObservable("inputSensitivity$",()=>this._state$.pipe(E(t=>t.input_sensitivity),L()))}get echoCancellation$(){return this.cachedObservable("echoCancellation$",()=>this._state$.pipe(E(t=>t.echo_cancellation),L()))}get autoGain$(){return this.cachedObservable("autoGain$",()=>this._state$.pipe(E(t=>t.auto_gain),L()))}get noiseSuppression$(){return this.cachedObservable("noiseSuppression$",()=>this._state$.pipe(E(t=>t.noise_suppression),L()))}get lowbitrate$(){return this.cachedObservable("lowbitrate$",()=>this._state$.pipe(E(t=>t.lowbitrate),L()))}get denoise$(){return this.cachedObservable("denoise$",()=>this._state$.pipe(E(t=>t.denoise),L()))}get meta$(){return this.cachedObservable("meta$",()=>this._state$.pipe(E(t=>t.meta),L()))}get userId$(){return this.cachedObservable("userId$",()=>this._state$.pipe(E(t=>t.subscriber_id),L()))}get addressId$(){return this.cachedObservable("addressId$",()=>this._state$.pipe(E(t=>t.address_id),L()))}get nodeId$(){return this.cachedObservable("nodeId$",()=>this._state$.pipe(E(t=>t.node_id),L()))}get isTalking$(){return this.cachedObservable("isTalking$",()=>this._state$.pipe(E(t=>t.talking),L()))}get isTalking(){return this._state$.value.talking??!1}get position$(){return this.cachedObservable("position$",()=>this._state$.pipe(E(t=>t.position),L()))}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 userId(){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 t=ag(this.deaf);await this.executeMethod(this.id,t,{})}async toggleHandraise(){await this.executeMethod(this.id,og(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 ft}async setAudioInputSensitivity(t){await this.executeMethod(this.id,"call.microphone.sensitivity.set",{sensitivity:t})}async setAudioInputVolume(t){await this.executeMethod(this.id,"call.microphone.volume.set",{volume:t})}async setAudioOutputVolume(t){await this.executeMethod(this.id,"call.speaker.volume.set",{volume:t})}async setPosition(t){await this.executeMethod(this.id,"call.member.position.set",{position:t})}async remove(){const t=this._state$.value,e={member_id:this.id,call_id:t.call_id??"",node_id:t.node_id??""};await this.executeMethod(e,"call.member.remove",{})}async end(){await this.executeMethod(this.id,"call.end",{})}async setMeta(t){throw new ft}async updateMeta(t){throw new ft}destroy(){this.executeMethod=void 0,super.destroy()}},Wo=class extends jo{constructor(t,e,i,r){super(t,e,r),this.vertoManager=i,this._studioAudio$=this.createBehaviorSubject(!1),this.capabilities=new sg}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(t){ai.error("[Participant.startScreenShare] Screen share error:",t)}}get screenShareStatus$(){return this.vertoManager.screenShareStatus$}get screenShareStatus(){return this.vertoManager.screenShareStatus}async stopScreenShare(){return this.vertoManager.removeScreenMedia()}async addAdditionalDevice(t){try{await this.vertoManager.addInputDevice(t)}catch(e){ai.error("[Participant.startScreenShare] Screen share error:",e)}}async removeAdditionalDevice(t){return this.vertoManager.removeInputDevices(t)}async addAudioInputDevice({constraints:t,stream:e}={}){const i=t??e?void 0:!0;return this.vertoManager.addMainInputDevices({audio:i,inputAudioDeviceConstraints:t,inputAudioStream:e})}async addVideoInputDevice({constraints:t,stream:e}={}){const i=t??e?void 0:!0;return this.vertoManager.addMainInputDevices({video:i,inputVideoDeviceConstraints:t,inputVideoStream:e})}async addInputDevices(t={}){await this.vertoManager.addMainInputDevices(t)}selectAudioInputDevice(t,e={}){this.deviceController.selectAudioInputDevice(t),e.savePreference&&(g.instance.preferredAudioInput=t)}async setAudioInputDeviceConstraints(t){await this.vertoManager.updateMediaConstraints({audio:t})}async setInputDevicesConstraints(t){await this.vertoManager.updateMediaConstraints(t)}selectVideoInputDevice(t,e={}){this.deviceController.selectVideoInputDevice(t),e.savePreference&&(g.instance.preferredVideoInput=t)}async setVideoInputDeviceConstraints(t){await this.vertoManager.updateMediaConstraints({video:t})}selectAudioOutputDevice(t,e={}){this.deviceController.selectAudioOutputDevice(t),e.savePreference&&(g.instance.preferredAudioOutput=t)}exitStudioModeIfActive(){this._studioAudio$.value&&(ai.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(t){ai.warn("[Participant.toggleAudioInput] Server Error while muting audio input, proceeding with local toggle anyway",t)}finally{this.vertoManager.muteMainAudioInputDevice()}}async unmute(){try{await super.unmute()}catch(t){ai.warn("[Participant.toggleAudioInput] Server Error while unmuting audio input, proceeding with local toggle anyway",t)}finally{await this.vertoManager.unmuteMainAudioInputDevice()}}async muteVideo(){try{await super.muteVideo()}catch(t){ai.warn("[Participant.toggleVideoInput] Server Error while muting video input, proceeding with local toggle anyway",t)}finally{this.vertoManager.muteMainVideoInputDevice()}}async unmuteVideo(){try{await super.unmuteVideo()}catch(t){ai.warn("[Participant.toggleVideoInput] Server Error while unmuting video input, proceeding with local toggle anyway",t)}finally{await this.vertoManager.unmuteMainVideoInputDevice()}}};const Go=t=>t instanceof Wo;function ke(t){return typeof t=="object"&&t!==null}function G(t,e){return e in t}function ns(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")&&typeof t.id=="string"&&G(t,"method")&&typeof t.method=="string"}function ss(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")&&typeof t.id=="string"&&(G(t,"result")||G(t,"error"))}function lg(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")&&typeof t.id=="string"&&(G(t,"error")&&ke(t.error)&&G(t.error,"code")&&G(t.error,"message")||G(t,"result")&&ke(t.result)&&G(t.result,"code")&&t.result.code!=="200"&&G(t.result,"message"))}function Le(t){return e=>qo(e)&&e.event_type===t}function as(t){return ns(t)&&t.method==="signalwire.event"&&ke(t.params)&&G(t.params,"event_type")}function qo(t){return ke(t)&&G(t,"event_type")&&typeof t.event_type=="string"&&G(t,"params")}function ug(t){return qo(t)&&(hg(t)||pg(t)||Xo(t)||Yo(t)||gg(t)||fg(t)||vg(t)||Ko(t)||Zo(t)||Qo(t)||Jo(t)||os(t)||nn(t)||$o(t)||ec(t))}const dg=Le("signalwire.authorization.state"),nn=Le("webrtc.message"),hg=Le("call.joined"),pg=Le("call.left"),Xo=Le("call.updated"),Yo=Le("call.state"),gg=Le("call.play"),fg=Le("call.connect"),vg=Le("room.updated"),Ko=Le("member.updated"),Zo=Le("member.joined"),Qo=Le("member.left"),Jo=Le("member.talking"),os=Le("layout.changed"),$o=Le("conversation.message"),ec=Le("conversation.message.updated");function tc(t){return ke(t)&&G(t,"room_session")&&G(t,"call_id")&&G(t,"member_id")&&G(t,"capabilities")}function bg(t){return ke(t)&&G(t,"room_id")&&G(t,"room_session_id")&&G(t,"layout")}const Ze=W(),mg={};var yg=class extends ie{constructor(t,e={}){super(),this.webRtcCallSession=t,this.options=e,this.callIds=new Set,this.roomSessionIds=new Set,this._participants$=this.createBehaviorSubject({}),this._self$=this.createBehaviorSubject(null),this._sessionState$=this.createBehaviorSubject(mg),this.initSubscriptions()}get participants$(){return this.cachedObservable("participants$",()=>this._participants$.asObservable().pipe(E(t=>Object.values(t))))}get participants(){return Object.values(this._participants$.value)}get self$(){return this.cachedObservable("self$",()=>this._self$.asObservable().pipe(ue()))}isRoomSessionIdValid(t){return this.roomSessionIds.has(t)}addCallId(t){this.callIds.add(t)}isCallIdValid(t){return this.callIds.has(t)}get recording$(){return this.cachedObservable("recording$",()=>this._sessionState$.pipe(E(t=>t.recording),L(),ue()))}get recordings$(){return this.cachedObservable("recordings$",()=>this._sessionState$.pipe(E(t=>t.recordings),L(),ue()))}get streaming$(){return this.cachedObservable("streaming$",()=>this._sessionState$.pipe(E(t=>t.streaming),L(),ue()))}get streams$(){return this.cachedObservable("streams$",()=>this._sessionState$.pipe(E(t=>t.streams),L(),ue()))}get playbacks$(){return this.cachedObservable("playbacks$",()=>this._sessionState$.pipe(E(t=>t.playbacks),L(),ue()))}get raiseHandPriority$(){return this.cachedObservable("raiseHandPriority$",()=>this._sessionState$.pipe(E(t=>t.prioritize_handraise),L(),ue()))}get locked$(){return this.cachedObservable("locked$",()=>this._sessionState$.pipe(E(t=>t.locked),L(),ue()))}get meta$(){return this.cachedObservable("meta$",()=>this._sessionState$.pipe(E(t=>t.meta),L(),ue()))}get capabilities$(){return this.cachedObservable("capabilities$",()=>this._sessionState$.pipe(E(t=>t.capabilities),L(),ue()))}get layout$(){return this.cachedObservable("layout$",()=>this._sessionState$.pipe(E(t=>t.layout_name),L(),ue()))}get layouts$(){return this.cachedObservable("layouts$",()=>this._sessionState$.pipe(E(t=>t.layouts),L(),ue()))}get layoutLayers$(){return this.cachedObservable("layoutLayers$",()=>this._sessionState$.pipe(E(t=>t.layout_layers),L(),ue()))}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(t){return this.callIds.has(t)||this.roomSessionIds.has(t)}initSubscriptions(){this.subscribeTo(this.callJoinedEvent$,t=>{var r,n;Ze.debug("[CallEventsManager] Handling call.joined event for call/session IDs:",{callId:t.call_id,roomSessionId:t.room_session_id});const e=t.room_session,i=t.capabilities;this.selfId=this.selfId??t.member_id,this.originCallId=this.originCallId??t.origin_call_id,this.callIds.add(t.call_id),this.roomSessionIds.add(t.room_session_id),this._sessionState$.next({...this._sessionState$.value,recording:e.recording,recordings:e.recordings,streaming:e.streaming,streams:e.streams,playbacks:e.playbacks,prioritize_handraise:e.prioritize_handraise,locked:e.locked,meta:e.meta,capabilities:i}),this.updateParticipants(e.members),(r=this._self$.value)==null||r.capabilities.updateFromRaw(i),(n=this._self$.value)!=null&&n.capabilities.setLayout&&this.updateLayouts()}),this.subscribeTo(this.memberUpdates$,t=>{Ze.debug("[CallEventsManager] Handling member update event for member ID:",t),this.upsertParticipant(t)}),this.subscribeTo(this.webRtcCallSession.memberLeft$,t=>{Ze.debug("[CallEventsManager] Handling member.left event for member ID:",t.member.member_id);const e={...this._participants$.value};t.member.member_id in e?(delete e[t.member.member_id],this._participants$.next(e)):Ze.warn(`[CallEventsManager] Received member.left event for unknown member ID: ${t.member.member_id}`)}),this.subscribeTo(this.webRtcCallSession.callUpdated$,t=>{Ze.debug("[CallEventsManager] Handling call.updated event:",t);const e=t.room_session;this._sessionState$.next({...this._sessionState$.value,recording:e.recording,recordings:e.recordings,streaming:e.streaming,streams:e.streams,playbacks:e.playbacks,prioritize_handraise:e.prioritize_handraise,locked:e.locked,meta:e.meta})}),this.subscribeTo(this.layoutChangedEvent$,t=>{Ze.debug("[CallEventsManager] Handling layout.changed event:",t),this._sessionState$.next({...this._sessionState$.value,layout_name:t.id,layout_layers:t.layers}),this.updateParticipantPositions(t)})}updateParticipantPositions(t){Object.keys(this._participants$.value).length>0&&!t.layers.some(e=>!!e.member_id)&&Ze.warn("[CallEventsManager] No layers with member_id found in layout.changed event. Nothing to update."),t.layers.filter(e=>!!e.member_id).filter(e=>e.member_id in this._participants$.value?!0:(Ze.warn(`[CallEventsManager] Skipping layout layer for unknown member_id: ${e.member_id}`),!1)).map(e=>(this._participants$.value[e.member_id].upnext({position:e}),this._participants$.value[e.member_id])).forEach(e=>{Go(e)&&this._self$.next(e),this._participants$.next({...this._participants$.value,[e.id]:e})})}updateLayouts(){this.selfId&&this.webRtcCallSession.executeMethod(this.selfId,"call.layout.list",{}).then(t=>{this._sessionState$.next({...this._sessionState$.value,layouts:t.result.layouts})}).catch(t=>{Ze.error("[CallEventsManager] Error fetching layouts:",t)})}updateParticipants(t){t.forEach(e=>this.upsertParticipant(e))}upsertParticipant(t){if(!(t.member_id in this._participants$.value)){const r=this.webRtcCallSession.createParticipant(t.member_id,this.selfId);this._participants$.next({...this._participants$.value,[t.member_id]:r})}const e=this._participants$.value[t.member_id],i=e.value;Ze.debug("[CallEventsManager] Updating participant:",t.member_id,{oldValue:i,newValue:t}),e.upnext({...i,...t}),Go(e)&&this._self$.next(e),this._participants$.next(this._participants$.value)}get callJoinedEvent$(){return this.cachedObservable("callJoinedEvent$",()=>this.webRtcCallSession.callEvent$.pipe(B(tc),Se(t=>{Ze.debug("[CallEventsManager] Call joined event:",t)})))}get layoutChangedEvent$(){return this.cachedObservable("layoutChangedEvent$",()=>this.webRtcCallSession.callEvent$.pipe(fe(bg,"layout"),Se(t=>{Ze.debug("[CallEventsManager] Layout changed event:",t)})))}get memberUpdates$(){return this.cachedObservable("memberUpdates$",()=>xi(this.webRtcCallSession.memberJoined$,this.webRtcCallSession.memberUpdated$,this.webRtcCallSession.memberTalking$).pipe(E(t=>t.member),Se(t=>{Ze.debug("[CallEventsManager] Member update event:",t)})))}destroy(){Object.values(this._participants$.value).forEach(t=>{t.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 wg=new Set(["sendrecv","sendonly","recvonly","inactive"]);function Sg(t){const e={audio:"inactive",video:"inactive"};if(!t)return e;const i=t.split(/\r?\n/);let r=null,n=null;for(const s of i)if(s.startsWith("m="))r&&(e[r]=n??"sendrecv"),s.startsWith("m=audio")?r="audio":s.startsWith("m=video")?r="video":r=null,n=null;else if(r&&s.startsWith("a=")){const a=s.substring(2).trim();wg.has(a)&&(n=a)}return r&&(e[r]=n??"sendrecv"),e}function ic(t){if(!t)return!1;const e=t.split(`\r
|
|
67
|
+
`)},W=()=>{const t=Qn();return new Proxy(t,{get(e,i,r){if(i==="wsTraffic")return Qd;const n=Qn(),s=Reflect.get(n,i);return typeof s=="function"?s.bind(n):s}})};function ue(){return B(t=>t!=null)}const tt=(t,e,i)=>{const r=e.split(".");let n=t;for(const s of r)if(n&&typeof n=="object"&&s in n)n=n[s];else return i;return n===void 0?i:n};function Jd(t,e){return zr(B(t),E(e))}function fe(t,e){return zr(Jd(t,i=>tt(i,e)),B(i=>i!==void 0))}const lo=W();function uo(){return E(t=>{if(t.error)throw lo.error("[throwOnRPCError] RPC error response:",{code:t.error.code,message:t.error.message,data:t.error.data}),new _t(t.error.code,t.error.message,t.error.data);return lo.debug("[throwOnRPCError] RPC successful response:",t),t})}class cr extends Error{}cr.prototype.name="InvalidTokenError";function $d(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,i)=>{let r=i.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function eh(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return $d(e)}catch{return atob(e)}}function th(t,e){if(typeof t!="string")throw new cr("Invalid token specified: must be a string");e||(e={});const i=e.header===!0?0:1,r=t.split(".")[i];if(typeof r!="string")throw new cr(`Invalid token specified: missing part #${i+1}`);let n;try{n=eh(r)}catch(s){throw new cr(`Invalid token specified: invalid base64 for part #${i+1} (${s.message})`)}try{return JSON.parse(n)}catch(s){throw new cr(`Invalid token specified: invalid json for part #${i+1} (${s.message})`)}}const Re=[];for(let t=0;t<256;++t)Re.push((t+256).toString(16).slice(1));function ih(t,e=0){return(Re[t[e+0]]+Re[t[e+1]]+Re[t[e+2]]+Re[t[e+3]]+"-"+Re[t[e+4]]+Re[t[e+5]]+"-"+Re[t[e+6]]+Re[t[e+7]]+"-"+Re[t[e+8]]+Re[t[e+9]]+"-"+Re[t[e+10]]+Re[t[e+11]]+Re[t[e+12]]+Re[t[e+13]]+Re[t[e+14]]+Re[t[e+15]]).toLowerCase()}let Jn;const rh=new Uint8Array(16);function nh(){if(!Jn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Jn=crypto.getRandomValues.bind(crypto)}return Jn(rh)}const ho={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function sh(t,e,i){var n;t=t||{};const r=t.random??((n=t.rng)==null?void 0:n.call(t))??nh();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,ih(r)}function Qr(t,e,i){return ho.randomUUID&&!t?ho.randomUUID():sh(t)}var ie=class{constructor(){this.subscriptions=[],this.subjects=[],this._destroyed$=new Ei}destroy(){var t;(t=this._observableCache)==null||t.clear(),this.subscriptions.forEach(e=>e.unsubscribe()),this.subjects.forEach(e=>e.complete()),this._destroyed$.next(),this._destroyed$.complete()}cachedObservable(t,e){this._observableCache??(this._observableCache=new Map);let i=this._observableCache.get(t);return i||(i=e(),this._observableCache.set(t,i)),i}publicCachedObservable(t,e){const i=`public:${t}`;this._observableCache??(this._observableCache=new Map);let r=this._observableCache.get(i);return r||(r=e().pipe(Vr(Aa)),this._observableCache.set(i,r)),r}deferEmission(t){return t.pipe(Vr(Aa))}subscribeTo(t,e){const i=t.subscribe(e);this.subscriptions.push(i)}createSubject(){const t=new Ei;return this.subjects.push(t),t}createReplaySubject(t,e){const i=new Bn(t,e);return this.subjects.push(i),i}createBehaviorSubject(t){const e=new Ru(t);return this.subjects.push(e),e}get destroyed$(){return this._destroyed$.asObservable()}};const ah=10,oh=100,ch=1,lh=({delayLimit:t=Number.MAX_SAFE_INTEGER,initialDelay:e=oh,variation:i=ch})=>{if(e<0)throw new Yr("initialDelay must be gte 0");if(t<0)throw new Yr("upperDelayLimit must be gte 0");if(i<0)throw new Yr("variation must be gte 0");if(e>t)throw new Yr("initialDelay must be lte delayLimit");let r=Math.min(e,t);return()=>{if(r===t)return t;const n=r;return r=Math.min(r+i,t),n}},uh=async({asyncCallable:t,maxRetries:e=ah,delayFn:i,validator:r,expectedErrorHandler:n})=>{let s=e-1,a=0;const o=async()=>{try{let c;return a<=0?c=await t():c=await new Promise((u,h)=>setTimeout(()=>{t().then(u).catch(h)},a)),s&&(r==null||r(c)),c}catch(c){if(s-- >0&&!(n!=null&&n(c)))return a=(i==null?void 0:i())??0,W().debug(`Retrying request: ${e-s} of ${e}`),o();throw c}};return o()},Ri=W(),$n={method:"GET",headers:{Accept:"application/json"}},Jr={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};var dh=(je=class extends ie{constructor(e,i,r={}){super(),this.baseURL=e,this.getCredential=i,this._responses$=this.createSubject(),this._errors$=this.createSubject(),this._status$=this.createBehaviorSubject("idle"),this.maxRetries=r.maxRetries??je.defaultMaxRetries,this.retryDelayMin=r.retryDelayMin??je.defaultRetryDelayMinMs,this.retryDelayMax=r.retryDelayMax??je.defaultRetryDelayMaxMs,this.requestTimeout=r.requestTimeout??je.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(e){this._status$.next("requesting");try{const i=await this.executeWithRetry(e);return this._status$.next("success"),this._responses$.next(i),i}catch(i){Ri.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(e){const i=Math.ceil((this.retryDelayMax-this.retryDelayMin)/Math.max(this.maxRetries-1,1)),r=lh({initialDelay:this.retryDelayMin,variation:i,delayLimit:this.retryDelayMax});return uh({asyncCallable:async()=>this.executeRequest(e),maxRetries:this.maxRetries,delayFn:r,validator:n=>{if(n.status>=500&&n.status<600)throw new Di(`Server error: ${n.status} ${n.statusText}`)}})}async executeRequest(e){const i=this.buildURL(e.url),r=this.buildHeaders(e.headers),n=e.timeout??this.requestTimeout;Ri.debug("[HTTPRequestController] Executing request:",{method:e.method,url:i,headers:Object.keys(r).reduce((o,c)=>(o[c]=c==="Authorization"?`${r[c].substring(0,20)}...`:r[c],o),{}),body:this.sanitizeBody(e.body)});const s=new AbortController,a=setTimeout(()=>s.abort(),n);try{const o=await fetch(i,{method:e.method,headers:r,body:e.body,signal:s.signal});clearTimeout(a);const c=await this.convertResponse(o);return Ri.debug("[HTTPRequestController] Response received:",{status:o.status,statusText:o.statusText,headers:[...o.headers.entries()],body:c.body?c.body.substring(0,200):"(empty)"}),c}catch(o){throw clearTimeout(a),o instanceof Error&&o.name==="AbortError"?new to(`Request timeout after ${n}ms`,{cause:o}):(Ri.error("[HTTPRequestController] Request failed:",o),o)}}buildURL(e){const i=typeof e=="string"?e:e.toString();return i.startsWith("http://")||i.startsWith("https://")?i:`${this.baseURL.endsWith("/")?this.baseURL.slice(0,-1):this.baseURL}${i.startsWith("/")?i:`/${i}`}`}buildHeaders(e){const i={...e??{}},r=this.getCredential();return r.token?(i.Authorization=`Bearer ${r.token}`,Ri.debug("[HTTPRequestController] Using Bearer token auth, token length:",r.token.length)):Ri.warn("[HTTPRequestController] No credentials available for authentication"),i}sanitizeBody(e){if(!e||typeof e!="string")return e?"(non-string body)":void 0;try{const i={...JSON.parse(e)};for(const r of Object.keys(i))je.SENSITIVE_BODY_FIELDS.has(r)&&typeof i[r]=="string"&&(i[r]=`${i[r].substring(0,20)}...[redacted]`);return JSON.stringify(i)}catch{return e.length>200?`${e.substring(0,200)}...`:e}}async convertResponse(e){const i={};e.headers.forEach((n,s)=>{i[s]=n});const r=await e.text();return{status:e.status,statusText:e.statusText,headers:i,body:r,ok:e.ok,url:e.url}}},je.defaultMaxRetries=3,je.defaultRetryDelayMinMs=1e3,je.defaultRetryDelayMaxMs=3e4,je.defaultRequestTimeoutMs=3e4,je.SENSITIVE_BODY_FIELDS=new Set(["dpop_token","token","jwt_token"]),je);const hh=5,ph=(t,e)=>({deviceId:t.deviceId,label:t.label,groupId:t.groupId,kind:e});var gh=class{constructor(){this._stacks={audioinput:[],audiooutput:[],videoinput:[]}}push(t,e){const i=ph(e,t),r=this._stacks[t];if(r.length>0&&r[0].deviceId===i.deviceId)return;const n=r.filter(s=>s.deviceId!==i.deviceId);this._stacks[t]=[i,...n].slice(0,hh)}pop(t){const e=this._stacks[t];if(e.length===0)return;const[i,...r]=e;return this._stacks[t]=r,i}findInHistory(t,e){const i=this._stacks[t];for(const r of i){const n=e.find(a=>a.deviceId===r.deviceId);if(n)return n;const s=e.find(a=>a.groupId===r.groupId&&a.label===r.label);if(s)return s}}getHistory(t){return this._stacks[t]}clear(){this._stacks.audioinput=[],this._stacks.audiooutput=[],this._stacks.videoinput=[]}};const fh=1e3,po=600,go=6e3,vh=300*1e3,bh=1e4,mh=100,yh=3e3,wh=1500,Sh=0,fo="sw:preferences",Ch="sat:refresh",vo="/api/fabric/subscriber/devices/token",bo="/api/fabric/subscriber/devices/refresh",lr=900,Ah=3e4,mo=3,Th=1e3,yo=5,Eh=1e3,kh=3e4,xh=5e3,wo=-32003,So=-32602,Co=-32002,Dh=1e3,Ih=10,Mh=2e3,Rh=3,Ph=.05,Oh=4,_h=30,Lh=3,Fh=3e3,Uh=1e4,Nh=1e4,Bh=3,zh=5e3,Vh=2e3,Hh=1e4,jh=3e3,Wh=5e3,Gh=3,qh=1e4,Xh=5e3,Yh=100,Ao=33,Kh=.03,Zh=250,Qh=!0,Jh=!0,$h="sw:device:audioinput",ep="sw:device:audiooutput",tp="sw:device:videoinput",ip=!1,rp=!0,np=!0,sp=!0,ap=150,op=300,cp=!0,lp=!0,up=!0,dp=!1,hp=51e4;function it(t){return t*1e3}function rt(t){return Math.round(t/100)/10}const To=W();var g=class jl{static get instance(){return this._instance??(this._instance=new jl),this._instance}constructor(){this.deviceDebounceTime=wh,this.devicePollingInterval=Sh,this.reconnectCallsTimeout=vh,this.connectionTimeout=bh,this.reconnectDelayMin=mh,this.reconnectDelayMax=yh,this.disableUdpIceServers=!1,this.relayOnly=!1,this.iceCandidateTimeout=po,this.iceGatheringTimeout=go,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=Dh,this.statsBaselineSamples=Ih,this.statsNoPacketThreshold=Mh,this.statsRttSpikeMultiplier=Rh,this.statsPacketLossThreshold=Ph,this.statsJitterSpikeMultiplier=Oh,this.statsHistorySize=_h,this.keyframeMaxBurst=Lh,this.keyframeBurstWindow=Fh,this.keyframeCooldown=Uh,this.reinviteDebounceTime=Nh,this.reinviteMaxAttempts=Bh,this.reinviteTimeout=zh,this.recoveryDebounceTime=Vh,this.recoveryCooldown=Hh,this.iceDisconnectedGracePeriod=jh,this.iceRestartTimeout=Wh,this.maxRecoveryAttempts=Gh,this.enableRelayFallback=cp,this.enableNetworkChangeDetection=lp,this.enableServerHangupInterception=up,this.persistDeviceSelection=Qh,this.syncDevicesToActiveCalls=Jh,this.autoMuteVideoOnHidden=ip,this.refreshDevicesOnVisible=rp,this.checkConnectionOnVisible=np,this.defaultAudioConstraints=void 0,this.defaultVideoConstraints=void 0,this.stereoAudio=dp,this.enableAutoDegradation=sp,this.degradationBitrateThreshold=ap,this.degradationRecoveryThreshold=op,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(e){this._inputAudioDeviceConstraints=e}get inputVideoDeviceConstraints(){return this._inputVideoDeviceConstraints}set inputVideoDeviceConstraints(e){this._inputVideoDeviceConstraints=e}};const pp=["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"],gp=["receiveVideo","receiveAudio","disableUdpIceServers","relayOnly","enableRelayFallback","enableNetworkChangeDetection","enableServerHangupInterception","persistDeviceSelection","syncDevicesToActiveCalls","autoMuteVideoOnHidden","refreshDevicesOnVisible","checkConnectionOnVisible","stereoAudio","enableAutoDegradation"];function fp(){const t=g.instance;return{connectionTimeout:t.connectionTimeout,reconnectCallsTimeout:t.reconnectCallsTimeout,reconnectDelayMin:t.reconnectDelayMin,reconnectDelayMax:t.reconnectDelayMax,relayHost:t.relayHost,receiveVideo:t.receiveVideo,receiveAudio:t.receiveAudio,disableUdpIceServers:t.disableUdpIceServers,relayOnly:t.relayOnly,iceCandidateTimeout:t.iceCandidateTimeout,iceGatheringTimeout:t.iceGatheringTimeout,deviceDebounceTime:t.deviceDebounceTime,devicePollingInterval:t.devicePollingInterval,iceServers:t.iceServers,userVariables:t.userVariables,statsPollingInterval:t.statsPollingInterval,statsBaselineSamples:t.statsBaselineSamples,statsNoPacketThreshold:t.statsNoPacketThreshold,statsRttSpikeMultiplier:t.statsRttSpikeMultiplier,statsPacketLossThreshold:t.statsPacketLossThreshold,statsJitterSpikeMultiplier:t.statsJitterSpikeMultiplier,statsHistorySize:t.statsHistorySize,keyframeMaxBurst:t.keyframeMaxBurst,keyframeBurstWindow:t.keyframeBurstWindow,keyframeCooldown:t.keyframeCooldown,reinviteDebounceTime:t.reinviteDebounceTime,reinviteMaxAttempts:t.reinviteMaxAttempts,reinviteTimeout:t.reinviteTimeout,recoveryDebounceTime:t.recoveryDebounceTime,recoveryCooldown:t.recoveryCooldown,iceDisconnectedGracePeriod:t.iceDisconnectedGracePeriod,iceRestartTimeout:t.iceRestartTimeout,maxRecoveryAttempts:t.maxRecoveryAttempts,enableRelayFallback:t.enableRelayFallback,enableNetworkChangeDetection:t.enableNetworkChangeDetection,enableServerHangupInterception:t.enableServerHangupInterception,persistDeviceSelection:t.persistDeviceSelection,syncDevicesToActiveCalls:t.syncDevicesToActiveCalls,autoMuteVideoOnHidden:t.autoMuteVideoOnHidden,refreshDevicesOnVisible:t.refreshDevicesOnVisible,checkConnectionOnVisible:t.checkConnectionOnVisible,stereoAudio:t.stereoAudio,enableAutoDegradation:t.enableAutoDegradation,degradationBitrateThreshold:t.degradationBitrateThreshold,degradationRecoveryThreshold:t.degradationRecoveryThreshold,preferredVideoCodecs:t.preferredVideoCodecs,preferredAudioCodecs:t.preferredAudioCodecs}}function vp(t){const e=g.instance;for(const i of pp)t[i]!==void 0&&(e[i]=t[i]);for(const i of gp)t[i]!==void 0&&(e[i]=t[i]);t.relayHost!==void 0&&(e.relayHost=t.relayHost),t.iceServers!==void 0&&(e.iceServers=t.iceServers),t.userVariables!==void 0&&(e.userVariables=t.userVariables),t.preferredVideoCodecs!==void 0&&(e.preferredVideoCodecs=t.preferredVideoCodecs),t.preferredAudioCodecs!==void 0&&(e.preferredAudioCodecs=t.preferredAudioCodecs)}var bp=class{constructor(){this._storage=null}enableSavePreferences(t){this._storage=t,this._loadFromStorage()}get connectionTimeout(){return rt(g.instance.connectionTimeout)}set connectionTimeout(t){g.instance.connectionTimeout=it(t),this._saveToStorage()}get reconnectCallsTimeout(){return rt(g.instance.reconnectCallsTimeout)}set reconnectCallsTimeout(t){g.instance.reconnectCallsTimeout=it(t),this._saveToStorage()}get reconnectDelayMin(){return rt(g.instance.reconnectDelayMin)}set reconnectDelayMin(t){g.instance.reconnectDelayMin=it(t),this._saveToStorage()}get reconnectDelayMax(){return rt(g.instance.reconnectDelayMax)}set reconnectDelayMax(t){g.instance.reconnectDelayMax=it(t),this._saveToStorage()}get relayHost(){return g.instance.relayHost??""}set relayHost(t){g.instance.relayHost=t,this._saveToStorage()}get receiveVideo(){return g.instance.receiveVideo}set receiveVideo(t){g.instance.receiveVideo=t,this._saveToStorage()}get receiveAudio(){return g.instance.receiveAudio}set receiveAudio(t){g.instance.receiveAudio=t,this._saveToStorage()}get preferredAudioInput(){return g.instance.preferredAudioInput}set preferredAudioInput(t){g.instance.preferredAudioInput=t}get preferredAudioOutput(){return g.instance.preferredAudioOutput}set preferredAudioOutput(t){g.instance.preferredAudioOutput=t}get preferredVideoInput(){return g.instance.preferredVideoInput}set preferredVideoInput(t){g.instance.preferredVideoInput=t}get inputAudioConstraints(){return g.instance.inputAudioDeviceConstraints}set inputAudioConstraints(t){g.instance.inputAudioDeviceConstraints=t}get inputVideoConstraints(){return g.instance.inputVideoDeviceConstraints}set inputVideoConstraints(t){g.instance.inputVideoDeviceConstraints=t}get deviceDebounceTime(){return rt(g.instance.deviceDebounceTime)}set deviceDebounceTime(t){g.instance.deviceDebounceTime=it(t),this._saveToStorage()}get devicePollingInterval(){return rt(g.instance.devicePollingInterval)}set devicePollingInterval(t){g.instance.devicePollingInterval=it(t),this._saveToStorage()}get disableUdpIceServers(){return g.instance.disableUdpIceServers}set disableUdpIceServers(t){g.instance.disableUdpIceServers=t,this._saveToStorage()}get relayOnly(){return g.instance.relayOnly}set relayOnly(t){g.instance.relayOnly=t,this._saveToStorage()}get iceCandidateTimeout(){return rt(g.instance.iceCandidateTimeout)}set iceCandidateTimeout(t){g.instance.iceCandidateTimeout=it(t),this._saveToStorage()}get iceGatheringTimeout(){return rt(g.instance.iceGatheringTimeout)}set iceGatheringTimeout(t){g.instance.iceGatheringTimeout=it(t),this._saveToStorage()}get iceServers(){return g.instance.iceServers}set iceServers(t){g.instance.iceServers=t,this._saveToStorage()}get userVariables(){return g.instance.userVariables}set userVariables(t){g.instance.userVariables=t,this._saveToStorage()}get statsPollingInterval(){return g.instance.statsPollingInterval}set statsPollingInterval(t){g.instance.statsPollingInterval=t,this._saveToStorage()}get statsBaselineSamples(){return g.instance.statsBaselineSamples}set statsBaselineSamples(t){g.instance.statsBaselineSamples=t,this._saveToStorage()}get statsNoPacketThreshold(){return g.instance.statsNoPacketThreshold}set statsNoPacketThreshold(t){g.instance.statsNoPacketThreshold=t,this._saveToStorage()}get statsRttSpikeMultiplier(){return g.instance.statsRttSpikeMultiplier}set statsRttSpikeMultiplier(t){g.instance.statsRttSpikeMultiplier=t,this._saveToStorage()}get statsPacketLossThreshold(){return g.instance.statsPacketLossThreshold}set statsPacketLossThreshold(t){g.instance.statsPacketLossThreshold=t,this._saveToStorage()}get statsJitterSpikeMultiplier(){return g.instance.statsJitterSpikeMultiplier}set statsJitterSpikeMultiplier(t){g.instance.statsJitterSpikeMultiplier=t,this._saveToStorage()}get statsHistorySize(){return g.instance.statsHistorySize}set statsHistorySize(t){g.instance.statsHistorySize=t,this._saveToStorage()}get keyframeMaxBurst(){return g.instance.keyframeMaxBurst}set keyframeMaxBurst(t){g.instance.keyframeMaxBurst=t,this._saveToStorage()}get keyframeBurstWindow(){return g.instance.keyframeBurstWindow}set keyframeBurstWindow(t){g.instance.keyframeBurstWindow=t,this._saveToStorage()}get keyframeCooldown(){return g.instance.keyframeCooldown}set keyframeCooldown(t){g.instance.keyframeCooldown=t,this._saveToStorage()}get reinviteDebounceTime(){return g.instance.reinviteDebounceTime}set reinviteDebounceTime(t){g.instance.reinviteDebounceTime=t,this._saveToStorage()}get reinviteMaxAttempts(){return g.instance.reinviteMaxAttempts}set reinviteMaxAttempts(t){g.instance.reinviteMaxAttempts=t,this._saveToStorage()}get reinviteTimeout(){return g.instance.reinviteTimeout}set reinviteTimeout(t){g.instance.reinviteTimeout=t,this._saveToStorage()}get recoveryDebounceTime(){return rt(g.instance.recoveryDebounceTime)}set recoveryDebounceTime(t){g.instance.recoveryDebounceTime=it(t),this._saveToStorage()}get recoveryCooldown(){return rt(g.instance.recoveryCooldown)}set recoveryCooldown(t){g.instance.recoveryCooldown=it(t),this._saveToStorage()}get iceDisconnectedGracePeriod(){return rt(g.instance.iceDisconnectedGracePeriod)}set iceDisconnectedGracePeriod(t){g.instance.iceDisconnectedGracePeriod=it(t),this._saveToStorage()}get iceRestartTimeout(){return rt(g.instance.iceRestartTimeout)}set iceRestartTimeout(t){g.instance.iceRestartTimeout=it(t),this._saveToStorage()}get maxRecoveryAttempts(){return g.instance.maxRecoveryAttempts}set maxRecoveryAttempts(t){g.instance.maxRecoveryAttempts=t,this._saveToStorage()}get enableRelayFallback(){return g.instance.enableRelayFallback}set enableRelayFallback(t){g.instance.enableRelayFallback=t,this._saveToStorage()}get enableNetworkChangeDetection(){return g.instance.enableNetworkChangeDetection}set enableNetworkChangeDetection(t){g.instance.enableNetworkChangeDetection=t,this._saveToStorage()}get enableServerHangupInterception(){return g.instance.enableServerHangupInterception}set enableServerHangupInterception(t){g.instance.enableServerHangupInterception=t,this._saveToStorage()}get persistDeviceSelection(){return g.instance.persistDeviceSelection}set persistDeviceSelection(t){g.instance.persistDeviceSelection=t,this._saveToStorage()}get syncDevicesToActiveCalls(){return g.instance.syncDevicesToActiveCalls}set syncDevicesToActiveCalls(t){g.instance.syncDevicesToActiveCalls=t,this._saveToStorage()}get autoMuteVideoOnHidden(){return g.instance.autoMuteVideoOnHidden}set autoMuteVideoOnHidden(t){g.instance.autoMuteVideoOnHidden=t,this._saveToStorage()}get refreshDevicesOnVisible(){return g.instance.refreshDevicesOnVisible}set refreshDevicesOnVisible(t){g.instance.refreshDevicesOnVisible=t,this._saveToStorage()}get checkConnectionOnVisible(){return g.instance.checkConnectionOnVisible}set checkConnectionOnVisible(t){g.instance.checkConnectionOnVisible=t,this._saveToStorage()}get defaultAudioConstraints(){return g.instance.defaultAudioConstraints}set defaultAudioConstraints(t){g.instance.defaultAudioConstraints=t}get defaultVideoConstraints(){return g.instance.defaultVideoConstraints}set defaultVideoConstraints(t){g.instance.defaultVideoConstraints=t}get stereoAudio(){return g.instance.stereoAudio}set stereoAudio(t){g.instance.stereoAudio=t,this._saveToStorage()}get enableAutoDegradation(){return g.instance.enableAutoDegradation}set enableAutoDegradation(t){g.instance.enableAutoDegradation=t,this._saveToStorage()}get degradationBitrateThreshold(){return g.instance.degradationBitrateThreshold}set degradationBitrateThreshold(t){g.instance.degradationBitrateThreshold=t,this._saveToStorage()}get degradationRecoveryThreshold(){return g.instance.degradationRecoveryThreshold}set degradationRecoveryThreshold(t){g.instance.degradationRecoveryThreshold=t,this._saveToStorage()}get preferredVideoCodecs(){return g.instance.preferredVideoCodecs}set preferredVideoCodecs(t){g.instance.preferredVideoCodecs=t,this._saveToStorage()}get preferredAudioCodecs(){return g.instance.preferredAudioCodecs}set preferredAudioCodecs(t){g.instance.preferredAudioCodecs=t,this._saveToStorage()}_saveToStorage(){if(!this._storage)return;const t=fp();this._storage.setItem(fo,t,"local").catch(e=>{To.error(`[ClientPreferences] Failed to save preferences: ${String(e)}`)})}_loadFromStorage(){this._storage&&this._storage.getItem(fo,"local").then(t=>{t&&vp(t)}).catch(t=>{To.error(`[ClientPreferences] Failed to load preferences: ${String(t)}`)})}};function vt(t){return t instanceof Error?t:new Error(String(t))}const nt=W(),Eo={audioinput:$h,audiooutput:ep,videoinput:tp},mp={audioinput:[],audiooutput:[],videoinput:[]},ko={audioinput:null,audiooutput:null,videoinput:null};var yp=class extends ie{constructor(t,e){super(),this.webRTCApiProvider=t,this.deviceChangeHandler=()=>{nt.debug("[DeviceController] Device change detected"),this.enumerateDevices()},this._devicesState$=this.createBehaviorSubject(mp),this._selectedDevicesState$=this.createBehaviorSubject(ko),this._errors$=this.createReplaySubject(1),this._deviceHistory=new gh,this._deviceRecovered$=this.createSubject(),this._audioInputDisabled$=this.createBehaviorSubject(!1),this._videoInputDisabled$=this.createBehaviorSubject(!1),this._lastAudioInputBeforeDisable=null,this._lastVideoInputBeforeDisable=null,this._persistedDevices={},this._storageManager=e,this.init()}setStorageManager(t){this._storageManager=t,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(t){if(!(t!=null&&t.deviceId)||t.deviceId.trim()==="")return{};const e=t.kind==="audioinput"?this.audioInputDevices:this.videoInputDevices,i=e.find(r=>r.deviceId===t.deviceId)??e.find(r=>r.label===t.label);return i?{deviceId:{exact:i.deviceId}}:{}}get errors$(){return this.cachedObservable("errors$",()=>this._errors$.asObservable().pipe(S(this.destroyed$)))}get deviceRecovered$(){return this._deviceRecovered$.asObservable().pipe(S(this.destroyed$))}get videoInputDisabled$(){return this.cachedObservable("videoInputDisabled$",()=>this._videoInputDisabled$.asObservable().pipe(L(),S(this.destroyed$)))}get audioInputDisabled$(){return this.cachedObservable("audioInputDisabled$",()=>this._audioInputDisabled$.asObservable().pipe(L(),S(this.destroyed$)))}get videoInputDisabled(){return this._videoInputDisabled$.value}get audioInputDisabled(){return this._audioInputDisabled$.value}get audioInputDevices$(){return this.cachedObservable("audioInputDevices$",()=>this._devicesState$.pipe(E(t=>t.audioinput),L(),S(this.destroyed$)))}get audioOutputDevices$(){return this.cachedObservable("audioOutputDevices$",()=>this._devicesState$.pipe(E(t=>t.audiooutput),L(),S(this.destroyed$)))}get videoInputDevices$(){return this.cachedObservable("videoInputDevices$",()=>this._devicesState$.pipe(E(t=>t.videoinput),L(),S(this.destroyed$)))}get selectedAudioInputDevice$(){return this.cachedObservable("selectedAudioInputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(E(t=>t.audioinput),L(),S(this.destroyed$),Se(t=>nt.debug("[DeviceController] Selected audio input device changed:",t))))}get selectedAudioOutputDevice$(){return this.cachedObservable("selectedAudioOutputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(E(t=>t.audiooutput),L(),S(this.destroyed$),Se(t=>nt.debug("[DeviceController] Selected audio output device changed:",t))))}get selectedVideoInputDevice$(){return this.cachedObservable("selectedVideoInputDevice$",()=>this._selectedDevicesState$.asObservable().pipe(E(t=>t.videoinput),L(),S(this.destroyed$),Se(t=>nt.debug("[DeviceController] Selected video input device changed:",t))))}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 t=this._lastAudioInputBeforeDisable??this.audioInputDevices[0];this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audioinput:t}),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 t=this._lastVideoInputBeforeDisable??this.videoInputDevices[0];this._selectedDevicesState$.next({...this._selectedDevicesState$.value,videoinput:t}),this._lastVideoInputBeforeDisable=null}}selectAudioInputDevice(t){this._audioInputDisabled$.value&&t&&this._audioInputDisabled$.next(!1);const e=this._selectedDevicesState$.value.audioinput;e&&e.deviceId!==(t==null?void 0:t.deviceId)&&this._deviceHistory.push("audioinput",e),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audioinput:t}),t&&this.persistDeviceSelection("audioinput",t)}selectVideoInputDevice(t){nt.debug("[DeviceController] Setting selected video input device:",t),this._videoInputDisabled$.value&&t&&this._videoInputDisabled$.next(!1);const e=this._selectedDevicesState$.value.videoinput;e&&e.deviceId!==(t==null?void 0:t.deviceId)&&this._deviceHistory.push("videoinput",e),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,videoinput:t}),t&&this.persistDeviceSelection("videoinput",t)}selectAudioOutputDevice(t){const e=this._selectedDevicesState$.value.audiooutput;e&&e.deviceId!==(t==null?void 0:t.deviceId)&&this._deviceHistory.push("audiooutput",e),this._selectedDevicesState$.next({...this._selectedDevicesState$.value,audiooutput:t}),t&&this.persistDeviceSelection("audiooutput",t)}init(){this.loadPersistedDevices(),this.subscribeTo(this._devicesState$.pipe(Xa(g.instance.deviceDebounceTime)),t=>{const e=this._selectedDevicesState$.value,i=this._audioInputDisabled$.value?null:this.resolveDevice("audioinput",t.audioinput,e.audioinput,g.instance.preferredAudioInput),r=this.resolveDevice("audiooutput",t.audiooutput,e.audiooutput,g.instance.preferredAudioOutput),n=this._videoInputDisabled$.value?null:this.resolveDevice("videoinput",t.videoinput,e.videoinput,g.instance.preferredVideoInput);if(i!==e.audioinput||r!==e.audiooutput||n!==e.videoinput){const s=g.instance.syncDevicesToActiveCalls;this._selectedDevicesState$.next({audioinput:s||!e.audioinput?i:e.audioinput,audiooutput:s||!e.audiooutput?r:e.audiooutput,videoinput:s||!e.videoinput?n:e.videoinput})}}),this.enumerateDevices()}resolveDevice(t,e,i,r){if(e.length===0)return null;if(i){if(e.find(c=>c.deviceId===i.deviceId))return i;const s=e.filter(c=>c.label===i.label);if(s.length===1)return s[0];if(s.length>1){const c=s.find(u=>u.groupId===i.groupId);return c||(this.emitDeviceRecovered(t,i,null,"ambiguous_match"),null)}const a=this._deviceHistory.findInHistory(t,e);if(a)return nt.debug(`[DeviceController] Device disappeared, falling back to history: ${a.label}`),this.emitDeviceRecovered(t,i,a,"device_disconnected"),a;const o=(r?e.find(c=>c.deviceId===r.deviceId||c.label===r.label):void 0)??e[0];return this.emitDeviceRecovered(t,i,o,"fallback_to_default"),o}const n=this._persistedDevices[t];if(n){const s=this.resolvePersistedDevice(t,n,e);if(s)return s}if(r){const s=e.find(a=>a.deviceId===r.deviceId||a.label===r.label);if(s)return s}return e[0]}resolvePersistedDevice(t,e,i){const r=i.find(a=>a.deviceId===e.deviceId);if(r)return r;const n=i.find(a=>a.groupId===e.groupId&&a.label===e.label);if(n)return n;const s=i.filter(a=>a.label===e.label);return s.length===1?s[0]:null}emitDeviceRecovered(t,e,i,r){try{this._deviceRecovered$.next({kind:t,previousDevice:e,newDevice:i,reason:r})}catch{}}async persistDeviceSelection(t,e){if(!this._storageManager||!g.instance.persistDeviceSelection)return;const i={deviceId:e.deviceId,label:e.label,kind:e.kind,groupId:e.groupId};try{await this._storageManager.setItem(Eo[t],i,"local")}catch(r){nt.error(`[DeviceController] Failed to persist device selection for ${t}:`,r)}}async loadPersistedDevices(){if(!(!this._storageManager||!g.instance.persistDeviceSelection))for(const t of["audioinput","audiooutput","videoinput"])try{const e=await this._storageManager.getItem(Eo[t],"local");e&&(this._persistedDevices={...this._persistedDevices,[t]:e})}catch(e){nt.error(`[DeviceController] Failed to load persisted device for ${t}:`,e)}}async clearDeviceState(){this._deviceHistory.clear(),this._persistedDevices={},this._lastAudioInputBeforeDisable=null,this._lastVideoInputBeforeDisable=null,this._audioInputDisabled$.next(!1),this._videoInputDisabled$.next(!1),this._selectedDevicesState$.next(ko),await this.enumerateDevices()}enableDeviceMonitoring(){this.disableDeviceMonitoring(),this.webRTCApiProvider.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler),g.instance.devicePollingInterval>0&&(this._devicesPoolingSubscription=jr(g.instance.devicePollingInterval).subscribe(()=>{nt.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 t=(await this.webRTCApiProvider.mediaDevices.enumerateDevices()).reduce((e,i)=>{const r=i.kind;return{...e,[r]:[...e[r],i]}},{audioinput:[],audiooutput:[],videoinput:[]});this._devicesState$.next(t),nt.debug("[DeviceController] Devices enumerated:",{audioInputs:t.audioinput.length,audioOutputs:t.audiooutput.length,videoInputs:t.videoinput.length})}catch(t){nt.error("[DeviceController] Failed to enumerate devices:",t),this._errors$.next(vt(t))}}async getDeviceCapabilities(t){if(t.kind==="audiooutput")return null;try{const e=this.deviceInfoToConstraints(t),i=await this.webRTCApiProvider.mediaDevices.getUserMedia({audio:t.kind==="audioinput"?e:!1,video:t.kind==="videoinput"?e:!1}),r=(t.kind==="audioinput"?i.getAudioTracks()[0]:i.getVideoTracks()[0]).getCapabilities();return i.getTracks().forEach(n=>n.stop()),r}catch(e){throw nt.error("[DeviceController] Failed to get device capabilities:",e),this._errors$.next(vt(e)),e}}async isValidDevice(t){if(!t||t.kind==="audiooutput")return!1;try{return await this.getDeviceCapabilities(t)!==null}catch{return!1}}destroy(){this.disableDeviceMonitoring(),super.destroy()}},xo=class{constructor(){if(typeof localStorage>"u")throw new Kn("localStorage");if(typeof sessionStorage>"u")throw new Kn("sessionStorage");try{const t="__storage_test__";localStorage.setItem(t,"test"),localStorage.removeItem(t)}catch(t){throw W().error("LocalStorage is not accessible:",t),new Kn("localStorage")}}storage(t){return t==="local"?localStorage:sessionStorage}async setItem(t,e,i="session"){return this.storage(i).setItem(t,e),Promise.resolve()}async getItem(t,e="session"){return Promise.resolve(this.storage(e).getItem(t))}async removeItem(t,e="session"){return this.storage(e).removeItem(t),Promise.resolve()}async clear(t="session"){const e=this.storage(t),i=[];for(let r=0;r<e.length;r++){const n=e.key(r);n!=null&&n.startsWith("sw:")&&i.push(n)}for(const r of i)e.removeItem(r);return Promise.resolve()}},wp=class{constructor(t=new xo){this.storageImpl=t}serialize(t,e){if(t==null)return null;try{return JSON.stringify(t)}catch(i){throw new Ud(e??"unknown",i)}}async setItem(t,e,i="session"){const r=this.serialize(e,t);try{await this.storageImpl.setItem(t,r,i)}catch(n){throw new Zn(t,n)}}async getItem(t,e="session"){let i;try{i=await this.storageImpl.getItem(t,e)}catch(r){throw new Bd(t,r)}if(!i)return null;try{return JSON.parse(i)}catch(r){throw new Nd(t,r)}}async removeItem(t,e="session"){try{await this.storageImpl.removeItem(t,e)}catch(i){throw new Zn(t,i)}}async clearAll(){try{await this.storageImpl.clear("local"),await this.storageImpl.clear("session")}catch(t){throw new Zn("clearAll",t)}}},Sp=class{constructor(){this.persistSession=!1,this._webSocketConstructor=typeof WebSocket<"u"?WebSocket:void 0,this._baseURL=this.apiHost,this._credential={}}get userId(){return this.user.id}get user(){if(!this._user)throw new Q("User");return this._user}set user(t){this._user=t}get storage(){return this._storageManager||(this._storageImpl??(this._storageImpl=new xo),this._storageManager=new wp(this._storageImpl)),this._storageManager}get http(){return this._httpRequestController??(this._httpRequestController=new dh(this._baseURL,()=>this._credential)),this._httpRequestController}get conversationManager(){if(!this._conversationManager)throw new Q("ConversationsManager");return this._conversationManager}set conversationManager(t){this._conversationManager=t}get WebSocket(){if(!this._webSocketConstructor)throw new Q("WebSocket constructor");return this._webSocketConstructor}set WebSocket(t){this._webSocketConstructor=t}get deviceController(){return this._deviceController??(this._deviceController=new yp(this.webRTCApiProvider,this.storage)),this._deviceController}get webRTCApiProvider(){if(!this._webRTCApiProvider){if(typeof RTCPeerConnection>"u"||typeof navigator>"u")throw new Q("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(t){this._webRTCApiProvider=t,this._deviceController=void 0}get authorizationStateKey(){return`sw:${this.userId}:as`}get protocolKey(){return`sw:${this.userId}:pt`}get attachedCallsKey(){return`sw:${this.userId}:att`}getUserFromAddressId(){var t;return((t=this.user.addresses[0])==null?void 0:t.id)??""}set baseURL(t){this._baseURL=t,this._httpRequestController=void 0}get credential(){return this._credential}set credential(t){this._credential=t}set storageImpl(t){this._storageImpl=t,this._storageManager=void 0}set ch(t){if(!t)return;const e=t.indexOf(".");e!==-1&&(this._host=t.substring(0,e),this._domain=t.substring(e+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 Wt=W(),Cp="sw-dpop",Ap=1,Gt="keys",es="dpop-keypair",$r=t=>{const e=new Uint8Array(t);let i="";for(const r of e)i+=String.fromCharCode(r);return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},Do=t=>$r(new TextEncoder().encode(t).buffer),Io=async t=>{if(t.kty!=="RSA")throw new Error(`Unsupported key type for JWK Thumbprint: ${t.kty}. Only RSA is supported.`);const e=JSON.stringify({e:t.e,kty:t.kty,n:t.n});return $r(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))};async function ts(){return new Promise((t,e)=>{const i=indexedDB.open(Cp,Ap);i.onupgradeneeded=()=>{const r=i.result;r.objectStoreNames.contains(Gt)||r.createObjectStore(Gt)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error??new Error("Failed to open IndexedDB"))})}async function Tp(){try{const t=await ts();return await new Promise((e,i)=>{const r=t.transaction(Gt,"readonly"),n=r.objectStore(Gt).get(es);n.onsuccess=()=>e(n.result??null),n.onerror=()=>i(n.error??new Error("Failed to load key pair from IndexedDB")),r.oncomplete=()=>t.close()})}catch(t){return Wt.warn("[DPoP] Failed to load key pair from IndexedDB:",t),null}}async function Ep(t){try{const e=await ts();await new Promise((i,r)=>{const n=e.transaction(Gt,"readwrite");n.objectStore(Gt).put(t,es),n.oncomplete=()=>{e.close(),i()},n.onerror=()=>{e.close(),r(n.error??new Error("Failed to save key pair to IndexedDB"))}})}catch(e){Wt.warn("[DPoP] Failed to save key pair to IndexedDB:",e)}}async function Mo(){try{const t=await ts();await new Promise((e,i)=>{const r=t.transaction(Gt,"readwrite");r.objectStore(Gt).delete(es),r.oncomplete=()=>{t.close(),e()},r.onerror=()=>{t.close(),i(r.error??new Error("Failed to delete key pair from IndexedDB"))}})}catch(t){Wt.warn("[DPoP] Failed to delete key pair from IndexedDB:",t)}}var kp=class{constructor(){this._keyPair=null,this._publicJwk=null,this._fingerprint=null,this._initialized=!1}async init(){if(this._initialized)return this.fingerprint;const t=await Tp();if(t)try{const e=new TextEncoder().encode("dpop-key-check");return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",t.privateKey,e),this._keyPair=t,this._publicJwk=await crypto.subtle.exportKey("jwk",t.publicKey),this._fingerprint=await Io(this._publicJwk),this._initialized=!0,Wt.debug("[DPoP] Key pair restored from IndexedDB, fingerprint:",this._fingerprint),this._fingerprint}catch(e){Wt.warn("[DPoP] Stored key pair unusable, generating new one:",e),await Mo()}return Wt.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 Io(this._publicJwk),this._initialized=!0,await Ep(this._keyPair),Wt.debug("[DPoP] Key pair generated and persisted, fingerprint:",this._fingerprint),this._fingerprint}get fingerprint(){if(!this._fingerprint)throw new Kr("CryptoController not initialized. Call init() first.");return this._fingerprint}get initialized(){return this._initialized}async createHttpProof(t){const e={jti:crypto.randomUUID(),htm:t.method,htu:t.uri,iat:Math.floor(Date.now()/1e3)};return t.accessToken&&(e.ath=$r(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t.accessToken)))),this.signProof(e)}async createRpcProof(t){const e={jti:crypto.randomUUID(),rpc:"request",mth:t.method,iat:Math.floor(Date.now()/1e3)};return this.signProof(e)}destroy(){this._keyPair=null,this._publicJwk=null,this._fingerprint=null,this._initialized=!1,Mo(),Wt.debug("[DPoP] Controller destroyed")}get publicJwk(){if(!this._publicJwk)throw new Kr("CryptoController not initialized. Call init() first.");return this._publicJwk}get privateKey(){if(!this._keyPair)throw new Kr("CryptoController not initialized. Call init() first.");return this._keyPair.privateKey}async signProof(t){const e={typ:"dpop+jwt",alg:"RS256",jwk:this.publicJwk},i=`${Do(JSON.stringify(e))}.${Do(JSON.stringify(t))}`;return`${i}.${$r(await crypto.subtle.sign("RSASSA-PKCS1-v1_5",this.privateKey,new TextEncoder().encode(i)))}`}};const Pi=W();function Ro(){return typeof window<"u"&&typeof window.addEventListener=="function"}function Po(){if(typeof navigator>"u")return;const{connection:t}=navigator;return(t==null?void 0:t.effectiveType)??void 0}function Oo(){if(!(typeof navigator>"u"))return navigator.connection??void 0}var xp=class extends ie{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(S(this._destroyed$))}get isOnline(){return this._isOnline$.value}get networkChange$(){return this._networkChange$.asObservable().pipe(S(this._destroyed$))}destroy(){this.removeListeners(),super.destroy()}attachListeners(){if(!Ro()){Pi.debug("NetworkMonitor: no browser environment detected, skipping event listeners");return}window.addEventListener("online",this._onOnline),window.addEventListener("offline",this._onOffline);const t=Oo();t&&t.addEventListener("change",this._onConnectionChange),this._listenersAttached=!0,Pi.debug("NetworkMonitor: event listeners attached")}removeListeners(){if(this._listenersAttached){if(Ro()){window.removeEventListener("online",this._onOnline),window.removeEventListener("offline",this._onOffline);const t=Oo();t&&t.removeEventListener("change",this._onConnectionChange)}this._listenersAttached=!1,Pi.debug("NetworkMonitor: event listeners removed")}}handleOnline(){Pi.info("NetworkMonitor: browser went online"),this._isOnline$.next(!0),this._networkChange$.next({type:"online",timestamp:Date.now(),networkType:Po()})}handleOffline(){Pi.info("NetworkMonitor: browser went offline"),this._isOnline$.next(!1),this._networkChange$.next({type:"offline",timestamp:Date.now()})}handleConnectionChange(){const t=Po();Pi.info(`NetworkMonitor: connection changed — effectiveType=${t??"unknown"}`),this._networkChange$.next({type:"connection_change",timestamp:Date.now(),networkType:t})}};function _o(t){if(typeof RTCRtpSender>"u"||typeof RTCRtpSender.getCapabilities!="function")return[];const e=RTCRtpSender.getCapabilities(t);if(!e)return[];const i=new Set,r=[];for(const n of e.codecs){const s=Dp(n.mimeType);s&&!i.has(s)&&(i.add(s),r.push(s))}return r}function Dp(t){const e=t.indexOf("/");return e>=0?t.substring(e+1):t}function Ip(){return typeof globalThis>"u"?!1:"RTCRtpScriptTransform"in globalThis||"MediaStreamTrackProcessor"in globalThis}function Mp(){return typeof HTMLMediaElement>"u"?!1:"setSinkId"in HTMLMediaElement.prototype}function Rp(){return typeof RTCRtpSender>"u"?!1:typeof RTCRtpSender.prototype.setParameters=="function"}function Lo(t){const e=(t==null?void 0:t.mediaDevices)??Fo(),i=typeof(e==null?void 0:e.getUserMedia)=="function",r=typeof(e==null?void 0:e.getDisplayMedia)=="function",n={webrtc:t?typeof t.RTCPeerConnection=="function":typeof globalThis<"u"&&"RTCPeerConnection"in globalThis,getUserMedia:i,getDisplayMedia:r,screenShare:r,screenShareAudio:Pp(),simulcast:Rp(),insertableStreams:Ip(),audioOutputSelection:Mp(),videoCodecs:_o("video"),audioCodecs:_o("audio")};return Object.freeze(n)}function Pp(){if(typeof navigator>"u")return!1;const t=Fo();return!t||typeof t.getDisplayMedia!="function"?!1:navigator.userAgent.includes("Chrome/")}function Fo(){return typeof navigator<"u"?navigator.mediaDevices:null}const en=W(),Op=10,_p=1e4,Lp=5e3,Fp=5e3;var Up=class extends ie{constructor(t,e,i,r,n,s={}){super(),this.deviceController=t,this.iceServers=e,this.isConnected=i,this.transportRttMs=r,this.dialFn=n,this._options={duration:s.duration??Op,skipMediaTest:s.skipMediaTest??!1,audioDevice:s.audioDevice,videoDevice:s.videoDevice}}async run(t){const e=[];try{const i=this.testSignaling();i.reachable||e.push("WebSocket not connected");const r=await this.testDevices();r.audioInput.working||e.push("Audio input device not working"),r.videoInput.working||e.push("Video input device not working");const n=await this.testIceConnectivity();n.type==="failed"?e.push("No ICE connectivity (neither STUN nor TURN reachable)"):n.type==="relay"&&e.push("Only TURN relay connectivity available (no direct path)"),n.turnReachable||e.push("TURN servers not reachable");let s=null;if(!this._options.skipMediaTest)try{s=await this.testMediaBandwidth(t)}catch(a){en.warn("[PreflightRunner] Media bandwidth test failed:",a),e.push("Media bandwidth test failed")}return{ok:i.reachable&&n.type!=="failed"&&r.audioInput.working,signaling:i,connectivity:n,bandwidth:s,devices:r,warnings:e}}catch(i){throw en.error("[PreflightRunner] Preflight test failed:",i),new jd("preflight",i instanceof Error?i:new Error(String(i)))}finally{this.destroy()}}testSignaling(){return{reachable:this.isConnected,rttMs:this.transportRttMs}}async testDevices(){const t=this._options.audioDevice??this.deviceController.selectedAudioInputDevice,e=this._options.videoDevice??this.deviceController.selectedVideoInputDevice,i=this.deviceController.selectedAudioOutputDevice;let r=!1,n=!1,s;try{const a={};t?a.audio={deviceId:{exact:t.deviceId}}:a.audio=!0,e?a.video={deviceId:{exact:e.deviceId}}:a.video=!0,s=await Promise.race([navigator.mediaDevices.getUserMedia(a),new Promise((o,c)=>setTimeout(()=>c(new Error("getUserMedia timeout")),Fp))]);for(const o of s.getTracks())o.kind==="audio"&&o.readyState==="live"&&(r=!0),o.kind==="video"&&o.readyState==="live"&&(n=!0)}catch(a){en.warn("[PreflightRunner] Device test failed:",a)}finally{s&&s.getTracks().forEach(a=>a.stop())}return{audioInput:{working:r,device:t},videoInput:{working:n,device:e},audioOutput:{available:!!i,device:i}}}async testIceConnectivity(){let t;try{t=new RTCPeerConnection({iceServers:this.iceServers});const e=t,i=new Set,r=Date.now(),n=new Promise(p=>{const f=setTimeout(p,_p);e.onicecandidate=m=>{if(m.candidate){const R=m.candidate.candidate;R.includes("typ host")&&i.add("host"),R.includes("typ srflx")&&i.add("srflx"),R.includes("typ relay")&&i.add("relay")}else clearTimeout(f),p()}});t.createDataChannel("preflight-test");const s=await t.createOffer();await t.setLocalDescription(s),await n;const a=Date.now()-r,o=i.has("srflx"),c=i.has("relay"),u=i.has("host");let h="failed";return u||o?h="direct":c&&(h="relay"),{type:h,turnReachable:c,stunReachable:o,rttMs:a}}catch(e){return en.warn("[PreflightRunner] ICE connectivity test failed:",e),{type:"failed",turnReachable:!1,stunReachable:!1,rttMs:0}}finally{t&&t.close()}}async testMediaBandwidth(t){let e;try{e=await this.dialFn(t,{audio:!0,video:!1}),await Ge(e.status$.pipe(B(a=>a==="connected"),Me(1),ar(Lp)));const i=this._options.duration*1e3;await new Promise(a=>setTimeout(a,i));const r=e.networkMetrics;let n=0,s=0;if(r.length>0){const a=r[r.length-1];a.availableOutgoingBitrate!==void 0&&(n=Math.round(a.availableOutgoingBitrate/1e3));const o=a.audio.packetsReceived+a.video.packetsReceived;i>0&&o>0&&(s=n)}return{uploadKbps:n,downloadKbps:s}}finally{if(e)try{await e.hangup()}catch{}}}destroy(){super.destroy()}};const tn=W();function Np(){try{return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.visibilityState=="string"}catch{return!1}}function Uo(){try{if(typeof document<"u"&&typeof document.visibilityState=="string")return document.visibilityState==="visible"?"visible":"hidden"}catch{}return"visible"}var Bp=class extends ie{constructor(){super(),this._visibility$=this.createBehaviorSubject(Uo()),this._visibilityChange$=this.createSubject(),this._hasVisibilityApi=Np(),this._boundHandler=this._handleVisibilityChange.bind(this),this._hasVisibilityApi?(document.addEventListener("visibilitychange",this._boundHandler),tn.debug("VisibilityController: listening for visibilitychange events")):tn.debug("VisibilityController: document visibility API not available, defaulting to visible")}get visibility$(){return this._visibility$.pipe(S(this._destroyed$))}get visibility(){return this._visibility$.value}get visibilityChange$(){return this._visibilityChange$.pipe(S(this._destroyed$))}destroy(){this._hasVisibilityApi&&(document.removeEventListener("visibilitychange",this._boundHandler),tn.debug("VisibilityController: removed visibilitychange listener")),super.destroy()}_handleVisibilityChange(){const t=Uo(),e=this._visibility$.value;if(t===e)return;this._visibility$.next(t);const i={from:e,to:t,timestamp:Date.now()};this._visibilityChange$.next(i),tn.debug("VisibilityController: visibility changed",{from:e,to:t})}},zp=class extends ie{constructor(t,e){super(),this.fromPath=t,this.http=e,this.fetched$=$t(()=>Ie(this.fetch())).pipe(et(1),S(this.destroyed$))}async fetch(){const t=await this.http.request({url:this.fromPath,method:"GET",headers:{Accept:"application/json"}});if(t.ok&&t.body){const e=JSON.parse(t.body);return this.populateInstance(e),!0}return!1}},Vp=class extends zp{constructor(t){super("/api/fabric/subscriber/info",t)}populateInstance(t){this.id=t.id,this.email=t.email,this.firstName=t.first_name,this.lastName=t.last_name,this.displayName=t.display_name,this.jobTitle=t.job_title,this.timeZone=t.time_zone,this.country=t.country,this.region=t.region,this.companyName=t.company_name,this.pushNotificationKey=t.push_notification_key,this.appSettings=t.app_settings?{displayName:t.app_settings.display_name,scopes:t.app_settings.scopes}:void 0,this.addresses=t.fabric_addresses,this.satClaims=t.sat_claims}};const Oi=t=>({jsonrpc:"2.0",id:t.id??Qr(),...t}),No=t=>({jsonrpc:"2.0",...t}),Hp={major:4,minor:0,revision:0},jp=t=>Oi({method:"signalwire.connect",params:{version:Hp,event_acks:!0,...t}}),Wp=t=>{const{dpop_token:e,...i}=t;return Oi({method:"signalwire.reauthenticate",params:{authentication:i,...e?{dpop_token:e}:{}}})},Gp=(t,e)=>No({id:t,result:{timestamp:Date.now()/1e3}}),is=({method:t,params:e})=>Oi({method:t,params:e}),qp={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"},Xp=new Set(["remoteSdp","localStream","remoteStream"]),Yp=t=>{if(!Object.prototype.hasOwnProperty.call(t,"dialogParams"))return t;const e=t.dialogParams,i=Object.entries(e).reduce((r,[n,s])=>{if(Xp.has(n))return r;const a=qp[n]??n;return{...r,[a]:s}},{});return{...t,dialogParams:i}},ri=t=>(e={})=>Oi({method:t,params:Yp(e)}),Bo=t=>Oi({method:"webrtc.verto",params:t}),Kp=ri("verto.invite"),Zp=ri("verto.bye"),rn=ri("verto.modify"),Qp=ri("verto.info"),Jp=ri("verto.answer"),$p=ri("verto.subscribe"),eg=ri("verto.pong"),tg={NORMAL_CLEARING:"16",USER_BUSY:"17",MEDIA_TIMEOUT:"804"},ig=t=>No({id:t,result:{}}),_i=W();var rg=class{constructor(t,e,i,r){this.storage=t,this.deviceController=e,this.reconnectCallsTimeout=i,this.attachKey=r,this.writeQueue=Promise.resolve()}async detachAll(){await this.mutate(t=>({}))}setSession(t){this.session=t}async readAttached(){try{return await this.storage.getItem(this.attachKey)??{}}catch(t){return _i.warn("[AttachManager] Failed to retrieve attached calls from storage",t),{}}}async writeAttached(t){try{await this.storage.setItem(this.attachKey,t)}catch(e){_i.warn("[AttachManager] Failed to write attached calls to storage",e)}}async mutate(t){const e=this.writeQueue.then(async()=>{const i=await t(await this.readAttached());await this.writeAttached(i)});return this.writeQueue=e.catch(()=>{}),e}async attach(t){if(!t.to){_i.warn("[AttachManager] Skip attach for calls with no destination");return}const e=t.to,i={nodeId:t.nodeId,destination:e,mediaDirections:t.mediaDirections,audioInputDevice:t.mediaDirections.audio!=="inactive"?this.deviceController.selectedAudioInputDevice:null,videoInputDevice:t.mediaDirections.video!=="inactive"?this.deviceController.selectedVideoInputDevice:null,attachedAt:Date.now()};await this.mutate(r=>({...r,[t.id]:i}))}async detach(t){await this.mutate(e=>{const{[t.id]:i,...r}=e;return r})}async flush(){await this.mutate(()=>({}))}async reattachCalls(){const t=await this.readAttached();await this.detachExpired();for(const[e,i]of Object.entries(t)){const{destination:r}=i,n=this.buildCallOptions(i);let s=!1;for(let a=1;a<=3;a++)try{await this.session.createOutboundCall(r,{callId:e,...n}),_i.info(`[AttachManager] Reattached call ${e} (attempt ${a})`),s=!0;break}catch(o){_i.warn(`[AttachManager] Reattach attempt ${a}/3 failed for call ${e}:`,o),a<3&&await new Promise(c=>setTimeout(c,(a+1)*1e3))}s||(_i.warn(`[AttachManager] Reattach failed after 3 attempts for call ${e}, removing reference`),await this.detach({id:e,mediaDirections:i.mediaDirections}))}}buildCallOptions(t){const{audio:e,video:i}=t.mediaDirections,{audioInputDevice:r,videoInputDevice:n,nodeId:s}=t,a=e.includes("recv"),o=i.includes("recv"),c=e.includes("send"),u=i.includes("send");return{nodeId:s,receiveAudio:a,receiveVideo:o,inputAudioDeviceConstraints:c?{audio:!0,...this.deviceController.deviceInfoToConstraints(r)}:void 0,inputVideoDeviceConstraints:u?{video:!0,...this.deviceController.deviceInfoToConstraints(n)}:void 0,reattach:!0}}async consumePendingAttachment(t){const e=await this.readAttached();if(Object.hasOwn(e,t))return this.buildCallOptions(e[t])}async detachExpired(){const t=Date.now(),e=this.reconnectCallsTimeout;await this.mutate(i=>{const r={...i};let n=!1;for(const[s,a]of Object.entries(i))t-a.attachedAt>e&&(delete r[s],n=!0);return n?r:i})}};const ni={on:!1,off:!1},rs={muteAudio:ni,muteVideo:ni,deaf:ni,raisehand:ni,microphoneVolume:!1,microphoneSensitivity:!1,speakerVolume:!1,position:!1,meta:!1,remove:!1,audioFlags:!1},zo={self:rs,member:rs,end:!1,setLayout:!1,sendDigit:!1,vmutedHide:ni,lock:ni,device:!1,screenshare:!1};function Li(t){return t.length===0?ni:{on:t.some(e=>!e.endsWith(".off")),off:t.some(e=>!e.endsWith(".on"))}}function Vo(t,e,i,r){return t.filter(n=>n===e||n===`${e}.${i}`||n.startsWith(`${e}.${i}.${r}`))}function si(t,e,i,r){return t.some(n=>n===e||i!==null&&n===`${e}.${i}`||n.startsWith(`${e}.${i?`${i}.`:""}${r}`))}function Ho(t,e){return t.filter(i=>i.startsWith(e)||i===e).length===0?rs:{muteAudio:Li(Vo(t,e,"mute","audio")),muteVideo:Li(Vo(t,e,"mute","video")),deaf:Li(t.filter(i=>i===e||i.startsWith(`${e}.deaf`))),raisehand:Li(t.filter(i=>i===e||i.startsWith(`${e}.raisehand`))),microphoneVolume:si(t,e,"microphone","volume"),microphoneSensitivity:si(t,e,"microphone","sensitivity"),speakerVolume:si(t,e,"speaker","volume"),position:si(t,e,null,"position"),meta:si(t,e,null,"meta"),remove:si(t,e,null,"remove"),audioFlags:si(t,e,null,"audioflags")}}function ng(t){return t.length===0?zo:{self:Ho(t,"self"),member:Ho(t,"member"),end:t.some(e=>e==="end"),setLayout:t.some(e=>e.startsWith("layout")),sendDigit:t.some(e=>e.startsWith("digit")),vmutedHide:Li(t.filter(e=>e.startsWith("vmuted"))),lock:Li(t.filter(e=>e.startsWith("lock"))),device:t.some(e=>e==="device"),screenshare:t.some(e=>e==="screenshare")}}var sg=class extends ie{constructor(...t){super(...t),this._state$=this.createBehaviorSubject(zo)}updateFromRaw(t){const e=ng(t);this._state$.next(e)}get self$(){return this.cachedObservable("self$",()=>this._state$.pipe(E(t=>t.self),L()))}get self(){return this._state$.value.self}get member$(){return this.cachedObservable("member$",()=>this._state$.pipe(E(t=>t.member),L()))}get member(){return this._state$.value.member}get end$(){return this.cachedObservable("end$",()=>this._state$.pipe(E(t=>t.end),L()))}get end(){return this._state$.value.end}get setLayout$(){return this.cachedObservable("setLayout$",()=>this._state$.pipe(E(t=>t.setLayout),L()))}get setLayout(){return this._state$.value.setLayout}get sendDigit$(){return this.cachedObservable("sendDigit$",()=>this._state$.pipe(E(t=>t.sendDigit),L()))}get sendDigit(){return this._state$.value.sendDigit}get vmutedHide$(){return this.cachedObservable("vmutedHide$",()=>this._state$.pipe(E(t=>t.vmutedHide),L()))}get vmutedHide(){return this._state$.value.vmutedHide}get lock$(){return this.cachedObservable("lock$",()=>this._state$.pipe(E(t=>t.lock),L()))}get lock(){return this._state$.value.lock}get device$(){return this.cachedObservable("device$",()=>this._state$.pipe(E(t=>t.device),L()))}get device(){return this._state$.value.device}get screenshare$(){return this.cachedObservable("screenshare$",()=>this._state$.pipe(E(t=>t.screenshare),L()))}get screenshare(){return this._state$.value.screenshare}get state$(){return this._state$.asObservable()}get state(){return this._state$.value}};function ag(t){return t?"call.undeaf":"call.deaf"}function og(t){return t?"call.lowerhand":"call.raisehand"}const ai=W(),cg={};var jo=class extends ie{constructor(t,e,i){super(),this.executeMethod=e,this.deviceController=i,this._state$=this.createBehaviorSubject(cg),this.id=t}upnext(t){this._state$.next({...this._state$.value,...t})}get name$(){return this.cachedObservable("name$",()=>this._state$.pipe(E(t=>t.name),L()))}get type$(){return this.cachedObservable("type$",()=>this._state$.pipe(E(t=>t.type),L()))}get handraised$(){return this.cachedObservable("handraised$",()=>this._state$.pipe(E(t=>t.handraised),L()))}get visible$(){return this.cachedObservable("visible$",()=>this._state$.pipe(E(t=>t.visible),L()))}get audioMuted$(){return this.cachedObservable("audioMuted$",()=>this._state$.pipe(E(t=>t.audio_muted),L()))}get videoMuted$(){return this.cachedObservable("videoMuted$",()=>this._state$.pipe(E(t=>t.video_muted),L()))}get deaf$(){return this.cachedObservable("deaf$",()=>this._state$.pipe(E(t=>t.deaf),L()))}get inputVolume$(){return this.cachedObservable("inputVolume$",()=>this._state$.pipe(E(t=>t.input_volume),L()))}get outputVolume$(){return this.cachedObservable("outputVolume$",()=>this._state$.pipe(E(t=>t.output_volume),L()))}get inputSensitivity$(){return this.cachedObservable("inputSensitivity$",()=>this._state$.pipe(E(t=>t.input_sensitivity),L()))}get echoCancellation$(){return this.cachedObservable("echoCancellation$",()=>this._state$.pipe(E(t=>t.echo_cancellation),L()))}get autoGain$(){return this.cachedObservable("autoGain$",()=>this._state$.pipe(E(t=>t.auto_gain),L()))}get noiseSuppression$(){return this.cachedObservable("noiseSuppression$",()=>this._state$.pipe(E(t=>t.noise_suppression),L()))}get lowbitrate$(){return this.cachedObservable("lowbitrate$",()=>this._state$.pipe(E(t=>t.lowbitrate),L()))}get denoise$(){return this.cachedObservable("denoise$",()=>this._state$.pipe(E(t=>t.denoise),L()))}get meta$(){return this.cachedObservable("meta$",()=>this._state$.pipe(E(t=>t.meta),L()))}get userId$(){return this.cachedObservable("userId$",()=>this._state$.pipe(E(t=>t.subscriber_id),L()))}get addressId$(){return this.cachedObservable("addressId$",()=>this._state$.pipe(E(t=>t.address_id),L()))}get nodeId$(){return this.cachedObservable("nodeId$",()=>this._state$.pipe(E(t=>t.node_id),L()))}get isTalking$(){return this.cachedObservable("isTalking$",()=>this._state$.pipe(E(t=>t.talking),L()))}get isTalking(){return this._state$.value.talking??!1}get position$(){return this.cachedObservable("position$",()=>this._state$.pipe(E(t=>t.position),L()))}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 userId(){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 t=ag(this.deaf);await this.executeMethod(this.id,t,{})}async toggleHandraise(){await this.executeMethod(this.id,og(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 ft}async setAudioInputSensitivity(t){await this.executeMethod(this.id,"call.microphone.sensitivity.set",{sensitivity:t})}async setAudioInputVolume(t){await this.executeMethod(this.id,"call.microphone.volume.set",{volume:t})}async setAudioOutputVolume(t){await this.executeMethod(this.id,"call.speaker.volume.set",{volume:t})}async setPosition(t){await this.executeMethod(this.id,"call.member.position.set",{position:t})}async remove(){const t=this._state$.value,e={member_id:this.id,call_id:t.call_id??"",node_id:t.node_id??""};await this.executeMethod(e,"call.member.remove",{})}async end(){await this.executeMethod(this.id,"call.end",{})}async setMeta(t){throw new ft}async updateMeta(t){throw new ft}destroy(){this.executeMethod=void 0,super.destroy()}},Wo=class extends jo{constructor(t,e,i,r){super(t,e,r),this.vertoManager=i,this._studioAudio$=this.createBehaviorSubject(!1),this.capabilities=new sg}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(t){ai.error("[Participant.startScreenShare] Screen share error:",t)}}get screenShareStatus$(){return this.vertoManager.screenShareStatus$}get screenShareStatus(){return this.vertoManager.screenShareStatus}async stopScreenShare(){return this.vertoManager.removeScreenMedia()}async addAdditionalDevice(t){try{await this.vertoManager.addInputDevice(t)}catch(e){ai.error("[Participant.startScreenShare] Screen share error:",e)}}async removeAdditionalDevice(t){return this.vertoManager.removeInputDevices(t)}async addAudioInputDevice({constraints:t,stream:e}={}){const i=t??e?void 0:!0;return this.vertoManager.addMainInputDevices({audio:i,inputAudioDeviceConstraints:t,inputAudioStream:e})}async addVideoInputDevice({constraints:t,stream:e}={}){const i=t??e?void 0:!0;return this.vertoManager.addMainInputDevices({video:i,inputVideoDeviceConstraints:t,inputVideoStream:e})}async addInputDevices(t={}){await this.vertoManager.addMainInputDevices(t)}selectAudioInputDevice(t,e={}){this.deviceController.selectAudioInputDevice(t),e.savePreference&&(g.instance.preferredAudioInput=t)}async setAudioInputDeviceConstraints(t){await this.vertoManager.updateMediaConstraints({audio:t})}async setInputDevicesConstraints(t){await this.vertoManager.updateMediaConstraints(t)}selectVideoInputDevice(t,e={}){this.deviceController.selectVideoInputDevice(t),e.savePreference&&(g.instance.preferredVideoInput=t)}async setVideoInputDeviceConstraints(t){await this.vertoManager.updateMediaConstraints({video:t})}selectAudioOutputDevice(t,e={}){this.deviceController.selectAudioOutputDevice(t),e.savePreference&&(g.instance.preferredAudioOutput=t)}exitStudioModeIfActive(){this._studioAudio$.value&&(ai.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(t){ai.warn("[Participant.toggleAudioInput] Server Error while muting audio input, proceeding with local toggle anyway",t)}finally{this.vertoManager.muteMainAudioInputDevice()}}async unmute(){try{await super.unmute()}catch(t){ai.warn("[Participant.toggleAudioInput] Server Error while unmuting audio input, proceeding with local toggle anyway",t)}finally{await this.vertoManager.unmuteMainAudioInputDevice()}}async muteVideo(){try{await super.muteVideo()}catch(t){ai.warn("[Participant.toggleVideoInput] Server Error while muting video input, proceeding with local toggle anyway",t)}finally{this.vertoManager.muteMainVideoInputDevice()}}async unmuteVideo(){try{await super.unmuteVideo()}catch(t){ai.warn("[Participant.toggleVideoInput] Server Error while unmuting video input, proceeding with local toggle anyway",t)}finally{await this.vertoManager.unmuteMainVideoInputDevice()}}};const Go=t=>t instanceof Wo;function ke(t){return typeof t=="object"&&t!==null}function G(t,e){return e in t}function ns(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")&&typeof t.id=="string"&&G(t,"method")&&typeof t.method=="string"}function ss(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")&&typeof t.id=="string"&&(G(t,"result")||G(t,"error"))}function lg(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")&&typeof t.id=="string"&&(G(t,"error")&&ke(t.error)&&G(t.error,"code")&&G(t.error,"message")||G(t,"result")&&ke(t.result)&&G(t.result,"code")&&t.result.code!=="200"&&G(t.result,"message"))}function Le(t){return e=>qo(e)&&e.event_type===t}function as(t){return ns(t)&&t.method==="signalwire.event"&&ke(t.params)&&G(t.params,"event_type")}function qo(t){return ke(t)&&G(t,"event_type")&&typeof t.event_type=="string"&&G(t,"params")}function ug(t){return qo(t)&&(hg(t)||pg(t)||Xo(t)||Yo(t)||gg(t)||fg(t)||vg(t)||Ko(t)||Zo(t)||Qo(t)||Jo(t)||os(t)||nn(t)||$o(t)||ec(t))}const dg=Le("signalwire.authorization.state"),nn=Le("webrtc.message"),hg=Le("call.joined"),pg=Le("call.left"),Xo=Le("call.updated"),Yo=Le("call.state"),gg=Le("call.play"),fg=Le("call.connect"),vg=Le("room.updated"),Ko=Le("member.updated"),Zo=Le("member.joined"),Qo=Le("member.left"),Jo=Le("member.talking"),os=Le("layout.changed"),$o=Le("conversation.message"),ec=Le("conversation.message.updated");function tc(t){return ke(t)&&G(t,"room_session")&&G(t,"call_id")&&G(t,"member_id")&&G(t,"capabilities")}function bg(t){return ke(t)&&G(t,"room_id")&&G(t,"room_session_id")&&G(t,"layout")}const Ze=W(),mg={};var yg=class extends ie{constructor(t,e={}){super(),this.webRtcCallSession=t,this.options=e,this.callIds=new Set,this.roomSessionIds=new Set,this._participants$=this.createBehaviorSubject({}),this._self$=this.createBehaviorSubject(null),this._sessionState$=this.createBehaviorSubject(mg),this.initSubscriptions()}get participants$(){return this.cachedObservable("participants$",()=>this._participants$.asObservable().pipe(E(t=>Object.values(t))))}get participants(){return Object.values(this._participants$.value)}get self$(){return this.cachedObservable("self$",()=>this._self$.asObservable().pipe(ue()))}isRoomSessionIdValid(t){return this.roomSessionIds.has(t)}addCallId(t){this.callIds.add(t)}isCallIdValid(t){return this.callIds.has(t)}get recording$(){return this.cachedObservable("recording$",()=>this._sessionState$.pipe(E(t=>t.recording),L(),ue()))}get recordings$(){return this.cachedObservable("recordings$",()=>this._sessionState$.pipe(E(t=>t.recordings),L(),ue()))}get streaming$(){return this.cachedObservable("streaming$",()=>this._sessionState$.pipe(E(t=>t.streaming),L(),ue()))}get streams$(){return this.cachedObservable("streams$",()=>this._sessionState$.pipe(E(t=>t.streams),L(),ue()))}get playbacks$(){return this.cachedObservable("playbacks$",()=>this._sessionState$.pipe(E(t=>t.playbacks),L(),ue()))}get raiseHandPriority$(){return this.cachedObservable("raiseHandPriority$",()=>this._sessionState$.pipe(E(t=>t.prioritize_handraise),L(),ue()))}get locked$(){return this.cachedObservable("locked$",()=>this._sessionState$.pipe(E(t=>t.locked),L(),ue()))}get meta$(){return this.cachedObservable("meta$",()=>this._sessionState$.pipe(E(t=>t.meta),L(),ue()))}get capabilities$(){return this.cachedObservable("capabilities$",()=>this._sessionState$.pipe(E(t=>t.capabilities),L(),ue()))}get layout$(){return this.cachedObservable("layout$",()=>this._sessionState$.pipe(E(t=>t.layout_name),L(),ue()))}get layouts$(){return this.cachedObservable("layouts$",()=>this._sessionState$.pipe(E(t=>t.layouts),L(),ue()))}get layoutLayers$(){return this.cachedObservable("layoutLayers$",()=>this._sessionState$.pipe(E(t=>t.layout_layers),L(),ue()))}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(t){return this.callIds.has(t)||this.roomSessionIds.has(t)}initSubscriptions(){this.subscribeTo(this.callJoinedEvent$,t=>{var r,n;Ze.debug("[CallEventsManager] Handling call.joined event for call/session IDs:",{callId:t.call_id,roomSessionId:t.room_session_id});const e=t.room_session,i=t.capabilities;this.selfId=this.selfId??t.member_id,this.originCallId=this.originCallId??t.origin_call_id,this.callIds.add(t.call_id),this.roomSessionIds.add(t.room_session_id),this._sessionState$.next({...this._sessionState$.value,recording:e.recording,recordings:e.recordings,streaming:e.streaming,streams:e.streams,playbacks:e.playbacks,prioritize_handraise:e.prioritize_handraise,locked:e.locked,meta:e.meta,capabilities:i}),this.updateParticipants(e.members),(r=this._self$.value)==null||r.capabilities.updateFromRaw(i),(n=this._self$.value)!=null&&n.capabilities.setLayout&&this.updateLayouts()}),this.subscribeTo(this.memberUpdates$,t=>{Ze.debug("[CallEventsManager] Handling member update event for member ID:",t),this.upsertParticipant(t)}),this.subscribeTo(this.webRtcCallSession.memberLeft$,t=>{Ze.debug("[CallEventsManager] Handling member.left event for member ID:",t.member.member_id);const e={...this._participants$.value};t.member.member_id in e?(delete e[t.member.member_id],this._participants$.next(e)):Ze.warn(`[CallEventsManager] Received member.left event for unknown member ID: ${t.member.member_id}`)}),this.subscribeTo(this.webRtcCallSession.callUpdated$,t=>{Ze.debug("[CallEventsManager] Handling call.updated event:",t);const e=t.room_session;this._sessionState$.next({...this._sessionState$.value,recording:e.recording,recordings:e.recordings,streaming:e.streaming,streams:e.streams,playbacks:e.playbacks,prioritize_handraise:e.prioritize_handraise,locked:e.locked,meta:e.meta})}),this.subscribeTo(this.layoutChangedEvent$,t=>{Ze.debug("[CallEventsManager] Handling layout.changed event:",t),this._sessionState$.next({...this._sessionState$.value,layout_name:t.id,layout_layers:t.layers}),this.updateParticipantPositions(t)})}updateParticipantPositions(t){Object.keys(this._participants$.value).length>0&&!t.layers.some(e=>!!e.member_id)&&Ze.warn("[CallEventsManager] No layers with member_id found in layout.changed event. Nothing to update."),t.layers.filter(e=>!!e.member_id).filter(e=>e.member_id in this._participants$.value?!0:(Ze.warn(`[CallEventsManager] Skipping layout layer for unknown member_id: ${e.member_id}`),!1)).map(e=>(this._participants$.value[e.member_id].upnext({position:e}),this._participants$.value[e.member_id])).forEach(e=>{Go(e)&&this._self$.next(e),this._participants$.next({...this._participants$.value,[e.id]:e})})}updateLayouts(){this.selfId&&this.webRtcCallSession.executeMethod(this.selfId,"call.layout.list",{}).then(t=>{this._sessionState$.next({...this._sessionState$.value,layouts:t.result.layouts})}).catch(t=>{Ze.error("[CallEventsManager] Error fetching layouts:",t)})}updateParticipants(t){t.forEach(e=>this.upsertParticipant(e))}upsertParticipant(t){if(!(t.member_id in this._participants$.value)){const r=this.webRtcCallSession.createParticipant(t.member_id,this.selfId);this._participants$.next({...this._participants$.value,[t.member_id]:r})}const e=this._participants$.value[t.member_id],i=e.value;Ze.debug("[CallEventsManager] Updating participant:",t.member_id,{oldValue:i,newValue:t}),e.upnext({...i,...t}),Go(e)&&this._self$.next(e),this._participants$.next(this._participants$.value)}get callJoinedEvent$(){return this.cachedObservable("callJoinedEvent$",()=>this.webRtcCallSession.callEvent$.pipe(B(tc),Se(t=>{Ze.debug("[CallEventsManager] Call joined event:",t)})))}get layoutChangedEvent$(){return this.cachedObservable("layoutChangedEvent$",()=>this.webRtcCallSession.callEvent$.pipe(fe(bg,"layout"),Se(t=>{Ze.debug("[CallEventsManager] Layout changed event:",t)})))}get memberUpdates$(){return this.cachedObservable("memberUpdates$",()=>xi(this.webRtcCallSession.memberJoined$,this.webRtcCallSession.memberUpdated$,this.webRtcCallSession.memberTalking$).pipe(E(t=>t.member),Se(t=>{Ze.debug("[CallEventsManager] Member update event:",t)})))}destroy(){Object.values(this._participants$.value).forEach(t=>{t.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 wg=new Set(["sendrecv","sendonly","recvonly","inactive"]);function Sg(t){const e={audio:"inactive",video:"inactive"};if(!t)return e;const i=t.split(/\r?\n/);let r=null,n=null;for(const s of i)if(s.startsWith("m="))r&&(e[r]=n??"sendrecv"),s.startsWith("m=audio")?r="audio":s.startsWith("m=video")?r="video":r=null,n=null;else if(r&&s.startsWith("a=")){const a=s.substring(2).trim();wg.has(a)&&(n=a)}return r&&(e[r]=n??"sendrecv"),e}function ic(t){if(!t)return!1;const e=t.split(`\r
|
|
68
68
|
`),i=[];let r=-1;for(const n of e)if(n.startsWith("m="))r+=1,i[r]=0;else if(n.startsWith("a=candidate:")){const s=/\styp\s+(host|srflx|prflx|relay)/.exec(n);s&&s[1]!=="host"&&(i[r]+=1)}return!i.length||i.every(n=>n>0)}function Cg(t,e=[],i=[]){if(!t||e.length===0&&i.length===0)return t;const r=Eg(t),n=[r[0]];for(let s=1;s<r.length;s++){const a=r[s],o=a.split(/\r?\n/)[0];o.startsWith("m=video")&&e.length>0?n.push(rc(a,e)):o.startsWith("m=audio")&&i.length>0?n.push(rc(a,i)):n.push(a)}return n.join("")}function Ag(t,e=hp){if(!t)return t;const i=kg(t);if(i===null)return t;const r=t.split(/\r?\n/),n=[],s=`a=fmtp:${i} `;let a=!1;for(const o of r)o.startsWith(s)?(a=!0,n.push(xg(o,e))):n.push(o);if(!a){const o=`a=rtpmap:${i} `,c=[];for(const u of n)c.push(u),u.startsWith(o)&&c.push(`a=fmtp:${i} stereo=1;sprop-stereo=1;maxaveragebitrate=${e}`);return c.join(`\r
|
|
69
69
|
`)}return n.join(`\r
|
|
70
70
|
`)}function Tg(t,e=[],i=[]){return Cg(t,i,e)}function Eg(t){return t.split(/(?=m=)/)}function rc(t,e){var h;const i=t.split(/\r?\n/),r=i[0].split(" ");if(r.length<4)return t;const n=r.slice(3),s=new Map;for(const p of i){const f=/^a=rtpmap:(\d+)\s+([^\s/]+)/.exec(p);f&&s.set(f[1],f[2])}const a=e.map(p=>p.toUpperCase()),o=[],c=[];for(const p of n){const f=((h=s.get(p))==null?void 0:h.toUpperCase())??"";a.indexOf(f)>=0?o.push(p):c.push(p)}o.sort((p,f)=>{var y,I;const m=((y=s.get(p))==null?void 0:y.toUpperCase())??"",R=((I=s.get(f))==null?void 0:I.toUpperCase())??"";return a.indexOf(m)-a.indexOf(R)});const u=[...o,...c];return[[...r.slice(0,3),...u].join(" "),...i.slice(1)].join(`\r
|
|
71
71
|
`)}function kg(t){const e=/a=rtpmap:(\d+)\s+opus\/48000/i.exec(t);return e?e[1]:null}function xg(t,e){let i=t;return i.includes("stereo=")||(i+=";stereo=1"),i.includes("sprop-stereo=")||(i+=";sprop-stereo=1"),i.includes("maxaveragebitrate=")||(i+=`;maxaveragebitrate=${e}`),i}const Ne=W();var Dg=class extends ie{constructor(t,e,i={}){super(),this.peerConnection=t,this.peerConnectionControllerNegotiating$=e,this.onicegatheringstatechangeHandler=()=>{const{iceGatheringState:r}=this.peerConnection;Ne.debug(`[ICEGatheringController] ICE gathering state changed to: ${r}`),r==="gathering"&&this._iceCandidatesState.next({state:"gathering",validSDP:!1})},this.onicecandidateHandler=r=>{Ne.debug("[ICEGatheringController] ICE candidate event received:",r.candidate),this.removeTimer("iceCandidateTimer"),r.candidate?this.iceCandidateTimer=setTimeout(()=>{this.peerConnection.iceGatheringState!=="complete"&&(Ne.warn("[ICEGatheringController] ICE candidate timeout, using current SDP"),this.handleICECandidateTimeout())},this.iceCandidateTimeout):(Ne.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??po,this.iceGatheringTimeout=i.iceGatheringTimeout??go,this.relayOnly=i.relayOnly??!1,this.setupEventListeners(),this.subscribeTo(this.peerConnectionControllerNegotiating$.pipe(B(r=>r)),r=>{r&&(this.setupEventListeners(),this.iceGatheringTimer=setTimeout(()=>{this.peerConnection.iceGatheringState!=="complete"&&(Ne.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(Za(this.peerConnectionControllerNegotiating$),B(([t,e])=>e),E(([t,e])=>t.state))}get hasValidLocalDescriptionSDP(){var e;const t=(e=this.peerConnection.localDescription)==null?void 0:e.sdp;return ic(t??"")}get isRelayOnly(){return this.relayOnly}setRelayOnly(t){this.relayOnly=t}handleICEGatheringComplete(){Ne.debug("[ICEGatheringController] Handling ICE gathering complete"),Ne.debug(`[ICEGatheringController] Checking ICE gathering state: ${this.peerConnection.iceGatheringState}`),Ne.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 e;this.removeTimer("iceGatheringTimer");const t=this.hasValidLocalDescriptionSDP;t?(Ne.debug("[ICEGatheringController] Local SDP is valid"),this._iceCandidatesState.next({state:"timeout",validSDP:t}),this.stopGathering()):Ne.debug(`### ICE gathering timeout
|
|
72
|
-
`,(e=this.peerConnection.localDescription)==null?void 0:e.sdp)}handleICECandidateTimeout(){this.iceCandidateTimer&&this.removeTimer("iceCandidateTimer"),Ne.warn("[ICEGatheringController] ICE candidate timeout");const t=this.hasValidLocalDescriptionSDP;!t&&!this.relayOnly?this.restartICEGatheringWithRelayOnly():(Ne.debug("[ICEGatheringController] Using current SDP due to ICE candidate timeout"),this._iceCandidatesState.next({state:"timeout",validSDP:t}),this.stopGathering())}restartICEGatheringWithRelayOnly(){Ne.debug("[ICEGatheringController] Restarting ICE gathering with relay-only candidates"),this.relayOnly=!0,this.peerConnection.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:"relay"}),this.peerConnection.restartIce()}removeTimer(t){this[t]&&(clearTimeout(this[t]),this[t]=void 0)}clearAllTimers(){Ne.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(){Ne.debug("[ICEGatheringController] Destroying ICEGatheringController"),this.clearAllTimers(),this.removeEventListeners(),super.destroy()}};const cs=W();var Ig=class extends ie{constructor(t={}){super(),this._inputSource=null,this._inputStream=null,this._lastSpokeAt=0,this._gain$=this.createBehaviorSubject(1),this._pttMultiplier=1,this._audioContext=(t.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=t.speakingThreshold??Kh,this._speakingHoldMs=t.speakingHoldMs??Zh,this._pollIntervalMs=t.pollIntervalMs??Ao;const e=t.initialGain??1;this._gain$.next(e),this.applyEffectiveGain()}get gain$(){return this._gain$.asObservable()}get gain(){return this._gain$.value}get outputTrack(){const[t]=this._destination.stream.getAudioTracks();return t}get level$(){return this.deferEmission(jr(this._pollIntervalMs,Ta).pipe(E(()=>this.computeLevel())))}get speaking$(){return this.deferEmission(this.level$.pipe(E(t=>this.evaluateSpeaking(t)),L()))}setGain(t){const e=Math.max(0,Math.min(2,t));this._gain$.next(e),this.applyEffectiveGain()}setPTTActive(t){this._pttMultiplier=t?1:0,this.applyEffectiveGain()}applyEffectiveGain(){this._gainNode.gain.value=this._gain$.value*this._pttMultiplier}setInputTrack(t){if(this._inputSource){try{this._inputSource.disconnect()}catch(e){cs.debug("[LocalAudioPipeline] input disconnect warning:",e)}this._inputSource=null}this._inputStream&&(this._inputStream=null),t&&(this._inputStream=new MediaStream([t]),this._inputSource=this._audioContext.createMediaStreamSource(this._inputStream),this._inputSource.connect(this._gainNode),this._audioContext.state==="suspended"&&this._audioContext.resume().catch(e=>{cs.warn("[LocalAudioPipeline] AudioContext resume failed:",e)}))}destroy(){if(this._inputSource){try{this._inputSource.disconnect()}catch{}this._inputSource=null}try{this._gainNode.disconnect(),this._analyser.disconnect()}catch{}this._audioContext.close().catch(t=>{cs.debug("[LocalAudioPipeline] audio context close warning:",t)}),super.destroy()}computeLevel(){if(!this._inputSource)return 0;this._analyser.getByteTimeDomainData(this._analyserBuffer);let t=0;for(const e of this._analyserBuffer){const i=(e-128)/128;t+=i*i}return Math.sqrt(t/this._analyserBuffer.length)}evaluateSpeaking(t){const e=Date.now();return t>=this._speakingThreshold?(this._lastSpokeAt=e,!0):e-this._lastSpokeAt<this._speakingHoldMs}};const Lt=W();var Mg=class extends ie{constructor(t){super(),this.options=t,this.mediaTrackEndedHandler=e=>{this._mediaTrackEnded$.next(e)},this._localStream$=this.createBehaviorSubject(null),this._localAudioTracks$=this.createBehaviorSubject([]),this._localVideoTracks$=this.createBehaviorSubject([]),this._mediaTrackEnded$=this.createSubject()}get localStream$(){return this._localStream$.asObservable().pipe(S(this.destroyed$))}get localAudioTracks$(){return this._localAudioTracks$.asObservable().pipe(S(this.destroyed$))}get localVideoTracks$(){return this._localVideoTracks$.asObservable().pipe(S(this.destroyed$))}get mediaTrackEnded$(){return this._mediaTrackEnded$.asObservable().pipe(S(this.destroyed$))}get localStream(){return this._localStream$.value}get localAudioTracks(){return this._localAudioTracks$.value}get localVideoTracks(){return this._localVideoTracks$.value}async buildLocalStream(){var e,i;Lt.debug("[LocalStreamController] Building local media stream.");let t;if(this.options.inputAudioStream??this.options.inputVideoStream){const r=[...((e=this.options.inputAudioStream)==null?void 0:e.getTracks())??[],...((i=this.options.inputVideoStream)==null?void 0:i.getTracks())??[]];t=new MediaStream(r)}else if(this.options.propose==="screenshare")Lt.debug("[LocalStreamController] Requesting display media for screen sharing with audio:",!!this.options.inputAudioDeviceConstraints),t=await this.options.getDisplayMedia({video:!0,audio:!!this.options.inputAudioDeviceConstraints}),Lt.debug("[LocalStreamController] Screen share media obtained:",t);else{const r={audio:this.options.inputAudioDeviceConstraints,video:this.options.inputVideoDeviceConstraints};Lt.debug("[LocalStreamController] Requesting user media with constraints:",r),t=await this.options.getUserMedia(r),Lt.debug("[LocalStreamController] User media obtained:",t)}return this._localStream$.next(t),t}addTrack(t){const e=this._localStream$.value??new MediaStream;return t.addEventListener("ended",this.mediaTrackEndedHandler),e.addTrack(t),this._localStream$.next(e),t.kind==="video"?this._localVideoTracks$.next(e.getVideoTracks()):this._localAudioTracks$.next(e.getAudioTracks()),Lt.debug(`[LocalStreamController] ${t.kind} track added:`,t.id),e}removeTrack(t){const e=this._localStream$.value,i=e==null?void 0:e.getTracks().find(r=>r.id===t);if(!i){Lt.debug(`[LocalStreamController] track not found: ${t}`);return}return i.removeEventListener("ended",this.mediaTrackEndedHandler),e==null||e.removeTrack(i),i.stop(),this._localStream$.next(e),i.kind==="video"?this._localVideoTracks$.next((e==null?void 0:e.getVideoTracks())??[]):this._localAudioTracks$.next((e==null?void 0:e.getAudioTracks())??[]),Lt.debug(`[LocalStreamController] ${i.kind} track removed:`,t),i}getOrCreateLocalStream(){return this._localStream$.value??new MediaStream}setLocalStream(t){this._localStream$.next(t)}addTrackEndedListener(t){t.addEventListener("ended",this.mediaTrackEndedHandler)}updateOptions(t){this.options={...this.options,...t}}stopAllTracks(){var t;(t=this._localStream$.value)==null||t.getTracks().forEach(e=>{Lt.debug(`[LocalStreamController] Stopping local track: ${e.kind}`),e.removeEventListener("ended",this.mediaTrackEndedHandler),e.stop()})}destroy(){this.stopAllTracks(),super.destroy()}};const Be=W(),nc=(t,e)=>t&&e?"sendrecv":t&&!e?"sendonly":!t&&e?"recvonly":"inactive";var Rg=class extends ie{constructor(t){super(),this.peerConnection=t.peerConnection,this.options=t}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:t}=this,e=t==null?void 0:t.getAudioTracks().some(n=>n.enabled),i=!!this.inputAudioDeviceConstraints,r=!!this.receiveAudio;return nc(e||i,r)}get videoDirection(){if(this.isAdditionalDevice||this.isScreenShare)return"sendonly";if(this.isSFU)return"recvonly";const{localStream:t}=this,e=t==null?void 0:t.getVideoTracks().some(n=>n.enabled),i=!!this.inputVideoDeviceConstraints,r=!!this.receiveVideo;return nc(e||i,r)}get sendEncodings(){if(this.isSimulcast)return["0","1","2"].map(t=>({active:!0,rid:t,scaleResolutionDownBy:Number(t)*6||1}))}getConstraintsFor(t){const e=t==="audio"?this.inputAudioDeviceConstraints:this.inputVideoDeviceConstraints;return typeof e=="boolean"?{}:e}transceiverByKind(t){return this.peerConnection.getTransceivers().filter(e=>t==="both"||e.receiver.track.kind===t)}get audioTransceivers(){return this.transceiverByKind("audio")}get videoTransceivers(){return this.transceiverByKind("video")}async setupTransceiverSender(t,e,i){var a;const r=t.kind==="audio",n=r?this.audioDirection:this.videoDirection,s={direction:n,sendEncodings:r?void 0:this.sendEncodings,streams:n==="recvonly"?void 0:[e]};Be.debug(`[TransceiverController] Setting up transceiver sender for local ${t.kind} track:`,{transceiver:i,transceiverParams:s}),s.direction&&["sendonly","sendrecv"].includes(s.direction)&&(i?(await i.sender.replaceTrack(t),i.direction=s.direction,(a=s.streams)!=null&&a.some(o=>!!o)&&(Be.debug(`[TransceiverController] Setting streams for transceiver sender for local ${t.kind} track:`,s.streams),i.sender.setStreams(...s.streams))):(Be.debug(`[TransceiverController] Adding new transceiver for local ${t.kind} track:`,t.id),this.peerConnection.addTransceiver(t,s)))}stopTrackSender(t,e={updateTransceiverDirection:!1}){var i,r,n;try{const s=this.transceiverByKind(t);for(const a of s)if(((i=a.sender.track)==null?void 0:i.readyState)==="live"){const o=a.sender.track.id;a.sender.track.stop(),this.options.localStreamController.removeTrack(o),e.updateTransceiverDirection&&(a.direction="inactive")}}catch(s){Be.error("[TransceiverController] stopTrackSender error",t,s),(n=(r=this.options).onError)==null||n.call(r,new Ii("stopTrackSender",t,s))}}async restoreTrackSender(t){var e,i;try{Be.debug("[TransceiverController] restoreTrackSender called",t);const r={},n=this.transceiverByKind(t);for(const a of n){const{track:o}=a.sender;if(!o||o.readyState==="ended"){const c=(o==null?void 0:o.kind)??a.receiver.track.kind;(c==="audio"||c==="video")&&(r[c]=this.getConstraintsFor(c))}}if(Be.debug("[TransceiverController] restoreTrackSender constraints:",r),Object.keys(r).length===0){Be.warn("[TransceiverController] restoreTrackSender: no tracks need restoration",t);return}const s=(await this.options.getUserMedia(r)).getTracks();Be.debug("[TransceiverController] restoreTrackSender new tracks:",s);for(const a of s){this.options.localStreamController.addTrack(a);const o=a.kind,c=this.transceiverByKind(o)[0];c.direction=o==="audio"?this.audioDirection:this.videoDirection,Be.debug("[TransceiverController] restoreTrackSender setting direction for",o,c.direction),await c.sender.replaceTrack(a)}}catch(r){Be.error("[TransceiverController] restoreTrackSender error",t,r),(i=(e=this.options).onError)==null||i.call(e,new Ii("restoreTrackSender",t,r))}}async replaceSenderTrack(t,e){const i=t==="audio"?this.audioTransceivers:this.videoTransceivers;for(const r of i)await r.sender.replaceTrack(e)}async setupRemoteTransceivers(t){if(t!=="answer"){for(const e of["audio","video"]){const i=e==="audio"?this.audioTransceivers:this.videoTransceivers;for(const r of i){const n=e==="audio"?this.audioDirection:this.videoDirection;["inactive","recvonly"].includes(n)&&(r.direction=n,await r.sender.replaceTrack(null),r.sender.setStreams())}}if(this.videoDirection==="recvonly"&&this.isSFU&&this.useAddTransceivers){const{msStreamsNumber:e=5}=this.options;for(let i=0;i<Number(e);i++)this.peerConnection.addTransceiver("video",{direction:"recvonly"})}}}async updateSendersConstraints(t,e){var r,n;if(!e)return this.stopTrackSender(t),Promise.resolve();const i=this.peerConnection.getSenders().filter(s=>{var a;return((a=s.track)==null?void 0:a.kind)===t&&s.track.readyState==="live"});for(const s of i){const{track:a}=s;if(a){const o={...a.getConstraints(),...e};try{await a.applyConstraints(o),Be.debug(`[TransceiverController] Updated ${t} sender constraints:`,o),Be.debug(`[TransceiverController] Updated ${t} sender constraints:`,a.getConstraints())}catch(c){Be.warn(`[TransceiverController] applyConstraints failed for ${t} track ${a.id}, attempting track replacement fallback:`,c);try{await this.replaceTrackFallback(s,a,t,o)}catch(u){Be.warn(`[TransceiverController] Track replacement fallback also failed for ${t} track:`,u),(n=(r=this.options).onError)==null||n.call(r,new Ii("updateSendersConstraints",t,u))}}}}}async replaceTrackFallback(t,e,i,r){const{deviceId:n}=e.getSettings(),s={...r,...n?{deviceId:{exact:n}}:{}},a=e.id;e.stop(),this.options.localStreamController.removeTrack(a);const o=(await this.options.getUserMedia({[i]:s})).getTracks().find(c=>c.kind===i);if(!o)throw new Ii("replaceTrackFallback",i,new Error("getUserMedia returned no track of the requested kind"));await t.replaceTrack(o),this.options.localStreamController.addTrack(o),Be.debug(`[TransceiverController] Track replacement fallback succeeded for ${i}. New track: ${o.id}`)}getMediaDirections(){return this.peerConnection.connectionState==="connected"?this.peerConnection.getTransceivers().reduce((t,e)=>({...t,[e.receiver.track.kind]:e.direction}),{audio:"inactive",video:"inactive"}):{audio:this.audioDirection,video:this.videoDirection}}updatePeerConnection(t){this.peerConnection=t}updateOptions(t){this.options={...this.options,...t}}};const z=W();var sc=class extends ie{constructor(t={},e,i){super(),this.options=t,this.firstSDPExchangeCompleted=!1,this.negotiationNeeded$=this.createSubject(),this.localDescription$=$t(()=>Ie(this.init())).pipe(Ke(()=>this.iceGatheringController.iceCandidatesState$.pipe(B(n=>!["new","gathering"].includes(n)),Se(()=>{this.negotiationEnded()}),B(()=>this.shouldEmitLocalDescription),E(()=>{var n;return(n=this.peerConnection)==null?void 0:n.localDescription}),ue(),Se(n=>{n.type==="answer"&&(this._type="offer")}))),et(1),S(this.destroyed$)),this.connectionTimeout=3e3,this.oniceconnectionstatechangeHandler=()=>{if(this.peerConnection){const{iceConnectionState:n}=this.peerConnection;z.debug(`[RTCPeerConnectionController] ICE connection state changed to: ${n}`),this._iceConnectionState$.next(this.peerConnection.iceConnectionState)}},this.onconnectionstatechangeHandler=()=>{if(this.peerConnection){const{connectionState:n}=this.peerConnection;z.debug(`[RTCPeerConnectionController] Connection state changed to: ${n}`),n==="connected"&&this.removeConnectionTimer(),this._connectionState$.next(this.peerConnection.connectionState)}},this.onsignalingstatechangeHandler=()=>{var n;z.debug(`[RTCPeerConnectionController] Signaling state changed to: ${(n=this.peerConnection)==null?void 0:n.signalingState}`)},this.onicegatheringstatechangeHandler=()=>{this.peerConnection&&this._iceGatheringState$.next(this.peerConnection.iceGatheringState)},this.onnegotiationneededHandler=n=>{z.debug("[RTCPeerConnectionController] Negotiation needed event received.",n),this.negotiationNeeded$.next()},this.updateSelectedInputDevice=async(n,s)=>{var a,o,c;try{const{localStream:u}=this;if(!u){z.warn("[RTCPeerConnectionController] No local stream available to update input device.");return}z.debug(`[RTCPeerConnectionController] Updating selected ${n} input device:`,u.getTracks());const h=u.getTracks().find(p=>p.kind===n);if(h){if((a=this.transceiverController)==null||a.stopTrackSender(n),this.localStreamController.removeTrack(h.id),z.debug(`[RTCPeerConnectionController] Stopped existing ${n} track: ${h.id}`,u.getTracks()),!s){z.debug(`[RTCPeerConnectionController] ${n} input device selected: none`);return}const p=(await this.getUserMedia({[n]:{...h.getConstraints(),...this.deviceController.deviceInfoToConstraints(s)}})).getTracks().find(f=>f.kind===n);p&&(z.debug(`[RTCPeerConnectionController] Adding new ${n} track: ${p.id}`),this.localStreamController.addTrack(p),await((o=this.transceiverController)==null?void 0:o.replaceSenderTrack(n,p)),z.debug(`[RTCPeerConnectionController] Added new ${n} track: ${p.id}`,(c=this.localStream)==null?void 0:c.getTracks()))}z.debug(`[RTCPeerConnectionController] ${n} input device selected:`,s==null?void 0:s.label)}catch(u){throw z.error(`[RTCPeerConnectionController] Failed to select ${n} input device:`,u),this._errors$.next(Et(u)),u}},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=t.callId??Qr(),this._type=e?"answer":"offer",this.sdpInit=e?{type:"offer",sdp:e}:void 0,this._remoteOfferMediaDirections=e?Sg(e):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={...t,audio:t.audio??r.audio,video:t.video??r.video,receiveAudio:t.receiveAudio??r.receiveAudio??g.instance.receiveAudio,receiveVideo:t.receiveVideo??r.receiveVideo??g.instance.receiveVideo},this.localStreamController=new Mg({propose:this.propose,inputAudioStream:this.options.inputAudioStream,inputVideoStream:this.options.inputVideoStream,inputAudioDeviceConstraints:this.inputAudioDeviceConstraints,inputVideoDeviceConstraints:this.inputVideoDeviceConstraints,getUserMedia:async n=>this.getUserMedia(n),getDisplayMedia:async n=>this.getDisplayMedia(n)})}get iceGatheringController(){if(!this._iceGatheringController)throw new Q("ICEGatheringController is not initialized");return this._iceGatheringController}get shouldEmitLocalDescription(){if(!this.peerConnection)return!1;const{localDescription:t,signalingState:e}=this.peerConnection;return!t||!ic(t.sdp)?!1:t.type==="offer"&&e==="have-local-offer"||t.type==="answer"&&e==="stable"}removeConnectionTimer(){this.connectionTimer&&(clearTimeout(this.connectionTimer),this.connectionTimer=void 0)}setMemberId(t){this._memberId=t}get memberId(){return this._memberId}stopTrackSender(t,e={updateTransceiverDirection:!1}){var i;(i=this.transceiverController)==null||i.stopTrackSender(t,e)}get isNegotiating$(){return this._isNegotiating$.asObservable()}get isNegotiating(){return this._isNegotiating$.value}updateMediaDevicesOptions(t){this.options={...this.options,...t}}get iceGatheringState$(){return this.cachedObservable("iceGatheringState$",()=>this._iceGatheringState$.asObservable().pipe(S(this.destroyed$)))}get mediaTrackEnded$(){return this.cachedObservable("mediaTrackEnded$",()=>this.localStreamController.mediaTrackEnded$.pipe(S(this.destroyed$)))}get errors$(){return this.cachedObservable("errors$",()=>this._errors$.asObservable().pipe(S(this.destroyed$)))}get iceCandidates$(){return this.cachedObservable("iceCandidates$",()=>this._iceCandidates$.asObservable().pipe(S(this.destroyed$)))}get initialized$(){return this.cachedObservable("initialized$",()=>this._initialized$.asObservable().pipe(B(t=>t),S(this.destroyed$)))}get remoteDescription$(){return this.cachedObservable("remoteDescription$",()=>this._remoteDescription$.asObservable().pipe(S(this.destroyed$)))}get localStream$(){return this.cachedObservable("localStream$",()=>this.localStreamController.localStream$.pipe(S(this.destroyed$)))}get remoteStream$(){return this.cachedObservable("remoteStream$",()=>this._remoteStream$.asObservable().pipe(S(this.destroyed$)))}get localAudioTracks$(){return this.cachedObservable("localAudioTracks$",()=>this.localStreamController.localAudioTracks$.pipe(S(this.destroyed$)))}get localVideoTracks$(){return this.cachedObservable("localVideoTracks$",()=>this.localStreamController.localVideoTracks$.pipe(S(this.destroyed$)))}get iceConnectionState$(){return this.cachedObservable("iceConnectionState$",()=>this._iceConnectionState$.asObservable().pipe(S(this.destroyed$)))}get connectionState$(){return this.cachedObservable("connectionState$",()=>this._connectionState$.asObservable().pipe(S(this.destroyed$)))}get signalingState$(){return this.cachedObservable("signalingState$",()=>this._signalingState$.asObservable().pipe(S(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 t="transport=tcp";return(this.options.iceServers??[]).map(e=>{const i=Array.isArray(e.urls)?e.urls:[e.urls];return{...e,urls:i.filter(r=>r.includes(t))}})}get rtcConfiguration(){const{iceServers:t,...e}=this.options;return{bundlePolicy:"max-compat",iceCandidatePoolSize:10,iceServers:this.iceServers,iceTransportPolicy:this.options.relayOnly?"relay":"all",sdpSemantics:"unified-plan",...e}}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 t=this.deviceController.selectedAudioInputDeviceConstraints;return t===!1?!1:{...typeof this.options.inputAudioDeviceConstraints=="object"?this.options.inputAudioDeviceConstraints:{},...typeof t=="object"?t:{}}}get inputVideoDeviceConstraints(){if(!this.options.video&&!this.options.inputVideoDeviceConstraints)return!1;const t=this.deviceController.selectedVideoInputDeviceConstraints;return t===!1?!1:{...typeof this.options.inputVideoDeviceConstraints=="object"?this.options.inputVideoDeviceConstraints:{},...typeof t=="object"?t:{}}}get WebRTCPeerConnectionConstructor(){var t;return((t=this.options.webRTCApiProvider)==null?void 0:t.RTCPeerConnection)??RTCPeerConnection}get offerOptions(){const t={iceRestart:this.firstSDPExchangeCompleted?!0:void 0};switch(this.propose){case"screenshare":case"additional-device":return{...t,offerToReceiveAudio:!1,offerToReceiveVideo:!1};case"main":default:return{...t,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(Sd(0),qn(async()=>this.startNegotiation())),{next:()=>{z.debug("[RTCPeerConnectionController] Start Negotiation completed successfully")},error:t=>{z.error("[RTCPeerConnectionController] Start Negotiation error:",t),this._errors$.next(Et(t))}}),this.subscribeTo(xi(this.deviceController.selectedAudioInputDevice$.pipe(E(t=>["audio",t])),this.deviceController.selectedVideoInputDevice$.pipe(E(t=>["video",t]))).pipe(Id(()=>!this.localStreamController.localStream)),async([t,e])=>{z.debug("[RTCPeerConnectionController] Selected input device changed for:",{kind:t,deviceInfo:e}),await this.updateSelectedInputDevice(t,e)}),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(t){z.error("[RTCPeerConnectionController] Initialization error:",t),this._errors$.next(Et(t)),this.destroy()}}setupPeerConnection(){this.peerConnection=new this.WebRTCPeerConnectionConstructor(this.rtcConfiguration),this.peerConnection.addEventListener("negotiationneeded",this.onnegotiationneededHandler),this._iceGatheringController=new Dg(this.peerConnection,this.isNegotiating$,{iceCandidateTimeout:this.options.iceCandidateTimeout,iceGatheringTimeout:this.options.iceGatheringTimeout,relayOnly:this.options.relayOnly}),this.transceiverController=new Rg({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 t=>this.getUserMedia(t),onError:t=>{this._errors$.next(t)}})}async startNegotiation(){if(this.isNegotiating){z.debug("[RTCPeerConnectionController] Negotiation already in progress, skipping.");return}if(this.setupEventListeners(),this.type==="answer"){z.debug("[RTCPeerConnectionController] This is an answer type still, skipping offer creation.");return}this._isNegotiating$.next(!0),z.debug("[RTCPeerConnectionController] Starting negotiation.");try{const{offerOptions:t}=this;z.debug("[RTCPeerConnectionController] Creating offer with options:",t),await this.createOffer(t)}catch(t){z.error("[RTCPeerConnectionController] Error during negotiation:",t),this._errors$.next(Et(t))}}async createOffer(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=await this.peerConnection.createOffer(t);await this.setLocalDescription(e)}async updateAnswerStatus({status:t,sdp:e}){let i=t!=="failed";try{t==="received"&&e&&(z.debug("[RTCPeerConnectionController] Received answer SDP:",e),await this._setRemoteDescription({type:"answer",sdp:e}))}catch(r){z.error("[RTCPeerConnectionController] Error updating answer status:",r),this._errors$.next(Et(r)),i=!1}finally{i?this.readyToConnect():this.iceGatheringController.restartICEGatheringWithRelayOnly()}}async updateOfferStatus({status:t,sdp:e}){switch(t){case"received":this._type="answer",this.sdpInit={type:"offer",sdp:e},await this.handleOfferReceived();break;case"failed":z.error("[RTCPeerConnectionController] Offer failed to be processed by remote.");break}}async acceptInbound(t){var i;if(t){const{audio:r,video:n,receiveAudio:s,receiveVideo:a}=t;this.options={...this.options,...r!==void 0?{audio:r}:{},...n!==void 0?{video:n}:{},...s!==void 0?{receiveAudio:s}:{},...a!==void 0?{receiveVideo:a}:{}},(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:e}=this;z.debug("[RTCPeerConnectionController] Creating inbound answer with options:",e),await this.createAnswer(e)}async handleOfferReceived(){if(!this.sdpInit)throw new Q("SDP initialization parameters are not set");this._isNegotiating$.next(!0),await this._setRemoteDescription(this.sdpInit);const{answerOptions:t}=this;z.debug("[RTCPeerConnectionController] Creating answer with options:",t),await this.createAnswer(t)}readyToConnect(){this.firstSDPExchangeCompleted=!0,this.connectionTimer=setTimeout(()=>{var t;this.removeConnectionTimer(),((t=this.peerConnection)==null?void 0:t.connectionState)!=="connected"&&(z.debug("[RTCPeerConnectionController] Connection timeout, restarting ICE gathering with relay only."),this.iceGatheringController.restartICEGatheringWithRelayOnly())},this.connectionTimeout)}async setRemoteDescriptionBefore(t=""){return Promise.resolve(t)}async setLocalDescription(t){var i;const e=await this.setLocalDescriptionBefore(t.sdp);return(i=this.peerConnection)==null?void 0:i.setLocalDescription({...t,sdp:e})}async setLocalDescriptionBefore(t=""){let e=t;const i=this.options.preferredAudioCodecs??g.instance.preferredAudioCodecs,r=this.options.preferredVideoCodecs??g.instance.preferredVideoCodecs,n=this.options.stereo??g.instance.stereoAudio;return(i.length>0||r.length>0)&&(e=Tg(e,i,r),z.debug("[RTCPeerConnectionController] Applied codec preferences to SDP",{preferredAudioCodecs:i,preferredVideoCodecs:r})),n&&(e=Ag(e),z.debug("[RTCPeerConnectionController] Applied stereo Opus to SDP")),Promise.resolve(e)}async createAnswer(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=await this.peerConnection.createAnswer(t);await this.setLocalDescription(e)}setupEventListeners(){if(!this.peerConnection)throw new Q("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(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=t&&!this.options.relayOnly;if(e)try{this.peerConnection.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:"relay"}),z.debug("[RTCPeerConnectionController] ICE transport policy set to relay-only")}catch(i){z.warn("[RTCPeerConnectionController] Failed to set relay-only policy:",i)}this.setupEventListeners(),this._isNegotiating$.next(!0),z.debug(`[RTCPeerConnectionController] Triggering ICE restart${t?" (relay-only)":""}.`);try{const i=await this.peerConnection.createOffer({iceRestart:!0});await this.setLocalDescription(i)}catch(i){throw z.error("[RTCPeerConnectionController] ICE restart offer failed:",i),this._errors$.next(Et(i)),this.negotiationEnded(),e&&this.restoreIceTransportPolicy(),i}e&&Ge(or(this._iceGatheringState$.pipe(B(i=>i==="complete"),Me(1)),ki(qh).pipe(E(()=>"timeout")))).then(()=>this.restoreIceTransportPolicy()).catch(i=>{z.warn("[RTCPeerConnectionController] Error waiting for ICE gathering to complete:",i),this.restoreIceTransportPolicy()})}restoreIceTransportPolicy(){var t;try{(t=this.peerConnection)==null||t.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:this.options.relayOnly?"relay":"all"}),z.debug("[RTCPeerConnectionController] ICE transport policy restored")}catch(e){z.warn("[RTCPeerConnectionController] Failed to restore ICE transport policy:",e)}}async setupTrackHandling(){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");await this.setupLocalTracks(),await this.setupRemoteTracks()}async setupLocalTracks(){var e,i,r,n,s,a,o;z.debug("[RTCPeerConnectionController] Setting up local tracks/transceivers.");const t=this.localStream??await this.localStreamController.buildLocalStream();if(((e=this.transceiverController)==null?void 0:e.useAddStream)??!1){z.warn("[RTCPeerConnectionController] Using deprecated addStream API to add local stream."),(i=this.peerConnection)==null||i.addStream(t),this.isNegotiating||(z.debug("[RTCPeerConnectionController] Forcing negotiationneeded after local tracks setup."),this.negotiationNeeded$.next());return}for(const c of["audio","video"]){const u=(c==="audio"?t.getAudioTracks():t.getVideoTracks()).map((h,p)=>({index:p,track:h}));for(const{index:h,track:p}of u)if(this.localStreamController.addTrackEndedListener(p),((r=this.transceiverController)==null?void 0:r.useAddTransceivers)??!1){const f=(c==="audio"?(n=this.transceiverController)==null?void 0:n.audioTransceivers:(s=this.transceiverController)==null?void 0:s.videoTransceivers)??[];await((a=this.transceiverController)==null?void 0:a.setupTransceiverSender(p,t,f[h]))}else z.debug(`[RTCPeerConnectionController] Using addTrack for local ${c} track:`,p.id),(o=this.peerConnection)==null||o.addTrack(p,t)}}async getUserMedia(t){var e;return(((e=this.options.webRTCApiProvider)==null?void 0:e.mediaDevices)??navigator.mediaDevices).getUserMedia(t)}async getDisplayMedia(t){var i;const e=((i=this.options.webRTCApiProvider)==null?void 0:i.mediaDevices)??navigator.mediaDevices;if(!e.getDisplayMedia)throw new Q("getDisplayMedia is not supported by the current WebRTC provider");return e.getDisplayMedia(t)}async setupRemoteTracks(){var t;if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");this.peerConnection.ontrack=e=>{var i;if(z.debug("[RTCPeerConnectionController] Remote track received:",e.track.kind),e.streams[0])this._remoteStream$.next(e.streams[0]);else{const r=((i=this._remoteStream$.value)==null?void 0:i.getTracks())??[],n=new MediaStream([...r,e.track]);this._remoteStream$.next(n)}},await((t=this.transceiverController)==null?void 0:t.setupRemoteTransceivers(this.type))}async restoreTrackSender(t){var e;await((e=this.transceiverController)==null?void 0:e.restoreTrackSender(t)),t!=="video"&&this._localAudioPipeline&&await this.applyLocalAudioPipelineToSender()}ensureLocalAudioPipeline(){if(this._localAudioPipeline)return this._localAudioPipeline;if(!this.peerConnection)return null;try{this._localAudioPipeline=new Ig}catch(t){return z.warn("[RTCPeerConnectionController] Failed to create LocalAudioPipeline:",t),null}return this.subscribeTo(this.localStreamController.localAudioTracks$,()=>{this.applyLocalAudioPipelineToSender()}),this.applyLocalAudioPipelineToSender(),this._localAudioPipeline}get localAudioPipeline(){return this._localAudioPipeline}async applyLocalAudioPipelineToSender(){var i,r;if(!this._localAudioPipeline||!this.peerConnection)return;const t=this.localStreamController.localAudioTracks.at(0);this._localAudioPipeline.setInputTrack(t??null);const e=((r=(i=this.transceiverController)==null?void 0:i.audioTransceivers.at(0))==null?void 0:r.sender)??this.peerConnection.getSenders().find(n=>{var s;return((s=n.track)==null?void 0:s.kind)==="audio"});if(!(!e||!t))try{await e.replaceTrack(this._localAudioPipeline.outputTrack)}catch(n){z.warn("[RTCPeerConnectionController] Failed to route audio sender through pipeline:",n)}}addLocalTrack(t){if(!this.peerConnection){const e=new Q("RTCPeerConnection is not initialized");throw this._errors$.next(e),e}try{const e=this.localStreamController.addTrack(t);this.peerConnection.addTrack(t,e),z.debug(`[RTCPeerConnectionController] ${t.kind} track added:`,t.id)}catch(e){throw z.error(`[RTCPeerConnectionController] Failed to add ${t.kind} track:`,e),this._errors$.next(Et(e)),e}}removeLocalTrack(t){var i,r;if(!this.peerConnection){const n=new Q("RTCPeerConnection is not initialized");throw this._errors$.next(n),n}const e=this.peerConnection.getSenders().find(n=>{var s;return((s=n.track)==null?void 0:s.id)===t});if(!e){z.debug(`[RTCPeerConnectionController] track not found: ${t}`);return}try{this.peerConnection.removeTrack(e),this.localStreamController.removeTrack(t),z.debug(`[RTCPeerConnectionController] ${(i=e.track)==null?void 0:i.kind} track removed:`,t)}catch(n){throw z.error(`[RTCPeerConnectionController] Failed to remove ${(r=e.track)==null?void 0:r.kind} track:`,n),this._errors$.next(Et(n)),n}}setLocalTrack(t){const e=[...t.kind==="audio"?this.localStreamController.localAudioTracks:this.localStreamController.localVideoTracks];for(const i of e)this.removeLocalTrack(i.id);this.addLocalTrack(t)}async updateSendersConstraints(t,e){var i;await((i=this.transceiverController)==null?void 0:i.updateSendersConstraints(t,e))}async replaceAudioTrackWithConstraints(t){var i;const e=(i=this.peerConnection)==null?void 0:i.getSenders().filter(r=>{var n;return((n=r.track)==null?void 0:n.kind)==="audio"&&r.track.readyState==="live"});if(!e||e.length===0){z.warn("[RTCPeerConnectionController] No live audio sender to replace");return}for(const r of e){const n=r.track;if(!n)continue;const{deviceId:s}=n.getSettings(),a={...n.getConstraints(),...t,...s?{deviceId:{exact:s}}:{}},o=n.id;n.stop(),this.localStreamController.removeTrack(o);const c=(await this.getUserMedia({audio:a})).getAudioTracks()[0];await r.replaceTrack(c),this.localStreamController.addTrack(c),z.debug(`[RTCPeerConnectionController] Audio track replaced for server-pushed params. New track: ${c.id}`)}}destroy(){var t,e,i;z.debug(`[RTCPeerConnectionController] Destroying RTCPeerConnectionController. ${this.propose}`),this.removeConnectionTimer(),(t=this._iceGatheringController)==null||t.destroy(),(e=this._localAudioPipeline)==null||e.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 t;(t=this._remoteStream$.value)==null||t.getTracks().forEach(e=>{z.debug(`[RTCPeerConnectionController] Stopping remote track: ${e.kind}`),e.stop()})}get mediaDirections(){var t;return((t=this.transceiverController)==null?void 0:t.getMediaDirections())??this._remoteOfferMediaDirections??{audio:"inactive",video:"inactive"}}async _setRemoteDescription(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=await this.setRemoteDescriptionBefore(t.sdp),i={...t,sdp:e};return z.debug("[RTCPeerConnectionController] Setting remote description:",i),this.peerConnection.setRemoteDescription(i)}};function ls(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")}function ac(t){if(!ls(t))return!1;const e=t;return e.method==="verto.invite"&&ke(e.params)&&G(e.params,"sdp")&&G(e.params,"callID")}function us(t){return ls(t)?t.method==="verto.bye":!1}function oc(t){return ls(t)?t.method==="verto.attach":!1}function Pg(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.answer"&&ke(t.params)&&G(t.params,"callID")}function Og(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.media"&&ke(t.params)&&G(t.params,"callID")&&G(t.params,"sdp")}function _g(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.mediaParams"&&ke(t.params)&&G(t.params,"mediaParams")}function Lg(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.ping"}const V=W();function Fg(t){return t.isInvite&&!t.reattach&&!t.explicitNodeId?"":t.currentNodeId??""}var Ug=class extends ie{constructor(t){super(),this.callSession=t}destroy(){this.callSession=void 0,super.destroy()}},Ng=class extends Ug{constructor(t,e,i,r,n={}){super(t),this.webRtcCallSession=t,this.attachManager=e,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(n.nodeId??null),this.onError=n.onError,this.onModifyFailed=n.onModifyFailed,this.initSubscriptions(),this.initMainPeerConnection()}async hold(){const t=rn({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},action:"hold"});try{await this.executeVerto(t)}catch(e){throw V.warn("[WebRTCManager] Call might already be disconnected, error sending Verto hold:",e),e}}async unhold(){const t=rn({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},action:"unhold"});try{await this.executeVerto(t)}catch(e){throw V.warn("[WebRTCManager] Call might already be disconnected, error sending Verto unhold:",e),e}}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 t;return((t=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id))==null?void 0:t.localStream)??null}get remoteStream(){var t;return((t=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id))==null?void 0:t.remoteStream)??null}get nodeId(){return this._nodeId$.value}get screenShareStatus(){return this._screenShareStatus$.value}get screenShareStatus$(){return this._screenShareStatus$.asObservable()}get mainPeerConnection(){const t=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id);if(!t)throw new Q("Main peer connection not found");return t}get signalingStatus$(){return this.cachedObservable("signalingStatus$",()=>xi(this._signalingStatus$.asObservable(),this.mainPeerConnection.connectionState$.pipe(B(t=>["connected","disconnected","failed"].includes(t)))))}initSubscriptions(){this.subscribeTo(this.callJoinedEvent$,t=>{var i;const e=(i=t.room_session.members.find(r=>r.call_id===t.call_id))==null?void 0:i.node_id;e&&this.setNodeIdIfNull(e),t.member_id&&this.setSelfIdIfNull(t.member_id)}),this.subscribeTo(this.vertoMedia$,t=>{var r;V.debug("[WebRTCManager] Received Verto media event (early media SDP):",t),this._signalingStatus$.next("ringing");const{sdp:e,callID:i}=t;(r=this._rtcPeerConnectionsMap.get(i))==null||r.updateAnswerStatus({status:"received",sdp:e})}),this.subscribeTo(this.vertoAnswer$,t=>{var r;V.debug("[WebRTCManager] Received Verto answer event:",t),this._signalingStatus$.next("connecting");const{sdp:e,callID:i}=t;(r=this._rtcPeerConnectionsMap.get(i))==null||r.updateAnswerStatus({status:"received",sdp:e})}),this.subscribeTo(this.vertoMediaParams$,t=>{V.debug("[WebRTCManager] Received Verto mediaParams event:",t);const{mediaParams:e,callID:i}=t,r=this._rtcPeerConnectionsMap.get(i),{audio:n,video:s}=e;(async()=>{var a;try{n&&r&&await r.replaceAudioTrackWithConstraints(n),s&&await(r==null?void 0:r.updateSendersConstraints("video",s)),this.webRtcCallSession.emitMediaParamsUpdated({audio:n,video:s,timestamp:Date.now()})}catch(o){V.warn("[WebRTCManager] Error applying server-pushed media params:",o),(a=this.onError)==null||a.call(this,o instanceof Error?o:new Error(String(o),{cause:o}))}})()}),this.subscribeTo(this.vertoPing$,t=>{this.attachManager.attach(this.buildAttachableCall()),this.sendVertoPong(t)})}setNodeIdIfNull(t){!this._nodeId$.value&&t&&(V.debug(`[WebRTCManager] Early node_id set: ${t}`),this._nodeId$.next(t))}setSelfIdIfNull(t){!this._selfId$.value&&t&&(V.debug(`[WebRTCManager] Early selfId set: ${t}`),this._selfId$.next(t))}async sendVertoPong(t){var e;try{const i=eg({...t});await this.executeVerto(i)}catch(i){V.warn("[WebRTCManager] Call might disconnect, error sending Verto pong:",i),(e=this.onError)==null||e.call(this,new so(i))}}async updateMediaConstraints(t={}){var r;const{audio:e,video:i}=t;try{e&&await this.mainPeerConnection.updateSendersConstraints("audio",e),i&&await this.mainPeerConnection.updateSendersConstraints("video",i)}catch(n){throw V.warn("[WebRTCManager] Error updating media constraints:",n),(r=this.onError)==null||r.call(this,n instanceof Error?n:new Error(String(n),{cause:n})),n}}get selfId(){return this._selfId$.value}buildAttachableCall(t){return{nodeId:this.nodeId??void 0,id:t??this.webRtcCallSession.id,to:this.webRtcCallSession.to,mediaDirections:this.webRtcCallSession.mediaDirections}}requestKeyframe(){try{const t=this.mainPeerConnection.peerConnection;if(!t){V.warn("[WebRTCManager] No peer connection for keyframe request");return}const e=t.getReceivers().find(i=>i.track.kind==="video");if(!e){V.warn("[WebRTCManager] No video receiver for keyframe request");return}typeof e.requestKeyFrame=="function"?(e.requestKeyFrame(),V.debug("[WebRTCManager] Keyframe requested via RTCRtpReceiver.requestKeyFrame()")):V.debug("[WebRTCManager] requestKeyFrame() not supported, skipping")}catch(t){V.warn("[WebRTCManager] Keyframe request failed (non-fatal):",t)}}async requestIceRestart(t){try{const e=this.mainPeerConnection;if(!e.peerConnection){V.warn("[WebRTCManager] No peer connection for ICE restart");return}await e.triggerIceRestart(t),V.info(`[WebRTCManager] ICE restart initiated${t?" (relay-only)":""}`)}catch(e){throw V.error("[WebRTCManager] ICE restart failed:",e),e}}async requestIceRestartAll(t){const e=Array.from(this._rtcPeerConnectionsMap.entries());for(const[i,r]of e)try{if(!r.peerConnection){V.debug(`[WebRTCManager] No peer connection for leg ${i}, skipping ICE restart`);continue}await r.triggerIceRestart(t),V.info(`[WebRTCManager] ICE restart initiated for leg ${i}${t?" (relay-only)":""}`)}catch(n){V.warn(`[WebRTCManager] ICE restart failed for leg ${i}:`,n)}}requestKeyframeAll(){for(const[t,e]of this._rtcPeerConnectionsMap){if(e.isScreenShare){V.debug(`[WebRTCManager] Skipping keyframe for send-only screen share leg ${t}`);continue}try{const i=e.peerConnection;if(!i)continue;const r=i.getReceivers().find(n=>n.track.kind==="video");if(!r)continue;typeof r.requestKeyFrame=="function"&&(r.requestKeyFrame(),V.debug(`[WebRTCManager] Keyframe requested for leg ${t}`))}catch(i){V.warn(`[WebRTCManager] Keyframe request failed for leg ${t} (non-fatal):`,i)}}}get callJoinedEvent$(){return this.webRtcCallSession.callEvent$.pipe(B(tc),S(this.destroyed$))}get vertoMedia$(){return this.webRtcCallSession.webrtcMessages$.pipe(fe(Og,"params"),S(this.destroyed$))}get vertoAnswer$(){return this.cachedObservable("vertoAnswer$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(Pg,"params"),S(this.destroyed$)))}get vertoMediaParams$(){return this.cachedObservable("vertoMediaParams$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(_g,"params"),S(this.destroyed$)))}get vertoBye$(){return this.cachedObservable("vertoBye$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(us,"params"),S(this.destroyed$)))}get vertoAttach$(){return this.cachedObservable("vertoAttach$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(oc,"params"),S(this.destroyed$)))}get vertoPing$(){return this.cachedObservable("vertoPing$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(Lg,"params"),S(this.destroyed$)))}async executeVerto(t,e={}){var s,a;const i=Bo({callID:e.callID??this.webRtcCallSession.id,node_id:e.node_id??this._nodeId$.value??"",message:t,subscribe:e.subscribe}),r=await this.webRtcCallSession.execute(i);if(r.error){const o=new _t(r.error.code,r.error.message,r.error.data);return(s=this.onError)==null||s.call(this,o),r}const n=tt(r,"result.result");if(n!=null&&n.error){const o=new _t(n.error.code,n.error.message,n.error.data);return(a=this.onError)==null||a.call(this,o),r}return r}async sendLocalDescription(t,e){var n,s;const i=t.method,r=this.getSendLocalSDPOptionalParams(e,t);try{const a=await this.executeVerto(t,r);switch(i){case"verto.invite":this.processInviteResponse(a,e);break;case"verto.modify":await this.processModifyResponse(a,e);break;default:}}catch(a){V.error(`[WebRTCManager] Error sending Verto ${i}:`,a),(n=this.onError)==null||n.call(this,a instanceof Error?a:new Error(String(a),{cause:a})),i==="verto.modify"&&((s=this.onModifyFailed)==null||s.call(this))}}async processModifyResponse(t,e){var i;if(!t.error){const r=tt(t,"result.result.result.action"),n=tt(t,"result.result.result.sdp");if(r==="updateMedia"&&n)try{await e.updateAnswerStatus({status:"received",sdp:n})}catch(s){V.warn("[WebRTCManager] Error processing modify response:",s);const a=s instanceof Error?s:new Error(String(s),{cause:s});(i=this.onError)==null||i.call(this,a)}}}processInviteResponse(t,e){var i;if(!t.error&&tt(t,"result.result.result.message")==="CALL CREATED"){this._signalingStatus$.next("trying"),this._nodeId$.next(tt(t,"result.node_id")??null);const r=tt(t,"result.result.result.memberID")??null,n=tt(t,"result.result.result.callID")??null;V.debug("[WebRTCManager] Verto invite response:",{callId:n,memberId:r,response:t}),this._selfId$.next(r),e.setMemberId(r),n?(this.webRtcCallSession.addCallId(n),this.attachManager.attach(this.buildAttachableCall(n))):V.warn("[WebRTCManager] Cannot attach call, missing callId:",{nodeId:this.nodeId,callId:n}),V.info("[WebRTCManager] Verto invite successful"),V.debug(`[WebRTCManager] nodeid: ${this._nodeId$.value}, selfId: ${this._selfId$.value}`)}else{V.error("[WebRTCManager] Verto invite failed:",t);const r=t.error?new _t(t.error.code,t.error.message,t.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??g.instance.iceServers,relayOnly:g.instance.relayOnly||g.instance.disableUdpIceServers,disableUdpIceServers:g.instance.disableUdpIceServers,iceCandidateTimeout:g.instance.iceCandidateTimeout,iceGatheringTimeout:g.instance.iceGatheringTimeout}}initMainPeerConnection(){const{options:t}=this.webRtcCallSession,e=new sc({propose:"main",callId:this.webRtcCallSession.id,audio:t.audio,video:t.video,inputAudioDeviceConstraints:t.inputAudioDeviceConstraints,inputVideoDeviceConstraints:t.inputVideoDeviceConstraints,inputAudioStream:t.inputAudioStream,inputVideoStream:t.inputVideoStream,receiveAudio:t.receiveAudio,receiveVideo:t.receiveVideo,webRTCApiProvider:this.webRTCApiProvider,preferredVideoCodecs:t.preferredVideoCodecs,preferredAudioCodecs:t.preferredAudioCodecs,stereo:t.stereo,...this.RTCPeerConnectionConfig},t.initOffer,this.deviceController);this.setupLocalDescriptionHandler(e),this.setupVertoByeHandler(),this.setupVertoAttachHandler(),this.initObservables(e),this._rtcPeerConnectionsMap.set(e.id,e),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values())),this.subscribeTo(e.errors$,i=>{var r;(r=this.onError)==null||r.call(this,i)}),t.initOffer&&this.handleInboundAnswer(e)}async handleInboundAnswer(t){var i,r,n;V.debug("[WebRTCManager] Waiting for inbound call to be accepted or rejected");const e=await Ge(or(this.vertoBye$,this.webRtcCallSession.answered$).pipe(S(this.destroyed$))).catch(()=>null);if(e===null){V.debug("[WebRTCManager] Inbound answer handler aborted (destroyed).");return}if(us(e))V.info("[WebRTCManager] Inbound call ended by remote before answer."),(i=this.callSession)==null||i.destroy();else if(e){V.debug("[WebRTCManager] Inbound call accepted, creating SDP answer");const s=this.webRtcCallSession.answerMediaOptions;try{await t.acceptInbound(s)}catch(a){V.error("[WebRTCManager] Error creating inbound answer:",a),(n=this.onError)==null||n.call(this,a instanceof Error?a:new Error(String(a),{cause:a}))}}else{V.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 t=>{V.debug("[WebRTCManager] Received Verto attach event for existing call:",t);const{callID:e}=t;await this.attachManager.attach({nodeId:this.nodeId??void 0,id:e,to:t.callee_id_number,mediaDirections:{audio:"sendrecv",video:"inactive"}})})}initObservables(t){this.mediaDirections$=t.connectionState$.pipe(B(e=>e==="connected"),E(()=>t.mediaDirections),Md(t.mediaDirections),S(this.destroyed$)),this.localStream$=t.localStream$.pipe(ue(),S(this.destroyed$)),this.remoteStream$=t.remoteStream$.pipe(ue(),S(this.destroyed$))}setupLocalDescriptionHandler(t){this.subscribeTo(t.localDescription$.pipe(B(e=>e!==null),S(this.destroyed$)),e=>{const{type:i,sdp:r}=e,n=this.dialogParams(t),s=!t.firstSDPExchangeCompleted;if(i==="answer"){const a=Jp({dialogParams:n,sdp:r});this.sendLocalDescriptionOnceAccepted(a,t)}else if(s){const a=Kp({dialogParams:n,sdp:r});this.sendLocalDescription(a,t)}else{const a=rn({dialogParams:n,sdp:r,action:"updateMedia"});this.sendLocalDescription(a,t)}})}setupVertoByeHandler(){this.subscribeTo(this.vertoBye$,()=>{var t;this._signalingStatus$.next("disconnected"),this.attachManager.detach(this.buildAttachableCall()),(t=this.callSession)==null||t.destroy()})}getSendLocalSDPOptionalParams(t,e){let i;return t.firstSDPExchangeCompleted||(i=[],t.isMainDevice?i.push(...g.instance.inviteSubscribeMainDevice):t.isAdditionalDevice?i.push(...g.instance.inviteSubscribeAdditionalDevice):t.isScreenShare&&i.push(...g.instance.inviteSubscribeScreenshare)),{callID:t.id,node_id:Fg({isInvite:ac(e),reattach:this.webRtcCallSession.options.reattach===!0,explicitNodeId:this.webRtcCallSession.options.nodeId,currentNodeId:this._nodeId$.value}),subscribe:i}}async sendLocalDescriptionOnceAccepted(t,e){var r,n,s;V.debug("[WebRTCManager] Waiting for call to be accepted or ended before sending answer");const i=await Ge(or(this.vertoBye$,this.webRtcCallSession.answered$).pipe(S(this.destroyed$))).catch(()=>null);if(i===null){V.debug("[WebRTCManager] Destroyed while waiting for call acceptance");return}if(us(i))V.info("[WebRTCManager] Call ended before answer was sent."),(r=this.callSession)==null||r.destroy();else if(i){V.debug("[WebRTCManager] Call accepted, sending answer");try{this._signalingStatus$.next("connecting"),await this.sendLocalDescription(t,e),await e.updateAnswerStatus({status:"sent"}),await this.attachManager.attach(this.buildAttachableCall())}catch(a){V.error("[WebRTCManager] Error sending Verto answer:",a),(s=this.onError)==null||s.call(this,a instanceof Error?a:new Error(String(a),{cause:a})),await e.updateAnswerStatus({status:"failed"})}}else{V.info("[WebRTCManager] Call was not accepted, sending verto.bye.");try{await this.bye("USER_BUSY")}finally{this._signalingStatus$.next("disconnected"),(n=this.callSession)==null||n.destroy()}}}dialogParams(t){const e=t.memberId??this._selfId$.value??void 0,i=t.propose==="main"&&!t.firstSDPExchangeCompleted&&this.webRtcCallSession.options.reattach;return{id:t.isMainDevice?this.webRtcCallSession.id:t.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:e,...this.webRtcCallSession.userVariables},screenShare:t.isScreenShare,additionalDevice:t.isAdditionalDevice,pingSupported:!0,version:fh}}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(t={audio:!1,video:!0}){return this.initAdditionalPeerConnection("additional-device",t)}async addMainInputDevices(t={audio:!0}){var r;let e;const{mediaDirections:i}=this.mainPeerConnection;if((t.audio??t.inputAudioDeviceConstraints??(t.inputAudioStream&&i.audio.startsWith("send")))&&(e="audio"),(t.video??t.inputVideoDeviceConstraints??(t.inputVideoStream&&!i.video.startsWith("send")))&&(e=e==="audio"?"both":"video"),e)this.mainPeerConnection.updateMediaDevicesOptions(t),await this.mainPeerConnection.restoreTrackSender(e);else{const n=new ro("No valid device to be added");throw(r=this.onError)==null||r.call(this,n),n}}async addScreenMedia(t={audio:!1}){await this.initAdditionalPeerConnection("screenshare",t)}async initAdditionalPeerConnection(t,e){var r;let i=null;try{return this._screenShareStatus$.next("starting"),i=new sc({...e,...this.RTCPeerConnectionConfig,propose:t,webRTCApiProvider:this.webRTCApiProvider},void 0,this.deviceController),this.setupLocalDescriptionHandler(i),t==="screenshare"&&(this._screenShareId=i.id),this._rtcPeerConnectionsMap.set(i.id,i),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values())),this.subscribeTo(i.errors$,n=>{var s;(s=this.onError)==null||s.call(this,n)}),await Ge(i.connectionState$.pipe(B(n=>n==="connected"),Me(1),ar(this._screenShareTimeoutMs),S(this.destroyed$))),this._screenShareStatus$.next("started"),V.info("[WebRTCManager] Screen share started successfully."),i.id}catch(n){V.warn("[WebRTCManager] Error initializing additional peer connection:",n),(r=this.onError)==null||r.call(this,n instanceof Error?n:new Error(String(n),{cause:n})),i&&i.destroy(),this._screenShareStatus$.next("none")}}async removeInputDevices(t){return this.removeAdditionalPeerConnection(t)}removeMainInputDevice(t={removeAudio:!1,removeVideo:!0}){let e;if(t.removeAudio&&(e="audio"),t.removeVideo&&(e=e==="audio"?"both":"video"),e)return this.mainPeerConnection.stopTrackSender(e,{updateTransceiverDirection:!0})}async removeScreenMedia(){if(["starting","started"].includes(this._screenShareStatus$.value)||V.warn("[WebRTCManager] No active screen share to stop."),!this._screenShareId){V.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(t){const e=this._rtcPeerConnectionsMap.get(t);try{e&&await this.executeVertoBye(e)}finally{e==null||e.destroy(),this._rtcPeerConnectionsMap.delete(t),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values()))}}async executeVertoBye(t,e){try{const i=e?{cause:e,causeCode:tg[e]}:{};await this.executeVerto(Zp({...i,dialogParams:this.dialogParams(t)}))}catch(i){throw V.warn("[WebRTCManager] Call might already be disconnected, error sending Verto bye:",i),i}}async bye(t){this.attachManager.detach(this.buildAttachableCall());const e=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id);e&&await this.executeVertoBye(e,t)}async sendDigits(t){const e=Qp({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},dtmf:t});try{await this.executeVerto(e)}catch(i){throw V.warn("[WebRTCManager] Error sending DTMF digits:",i),i}}async transfer(t){const e=rn({...t,dialogParams:this.dialogParams(this.mainPeerConnection),action:"transfer"});try{V.debug("[WebRTCManager] Transferring call with options:",t),await this.executeVerto(e)}catch(i){throw V.error("[WebRTCManager] Error transferring call:",i),i}}destroy(){this._rtcPeerConnectionsMap.forEach(t=>{t.destroy()}),this._rtcPeerConnectionsMap.clear(),this._rtcPeerConnections$.complete(),super.destroy()}};const cc=W();var Bg=class extends ie{constructor(t={}){super(),this._source=null,this._stream=null,this._audioContext=(t.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=t.pollIntervalMs??Ao}get level$(){return this.deferEmission(jr(this._pollIntervalMs,Ta).pipe(E(()=>this.computeLevel())))}setStream(t){if(this._source){try{this._source.disconnect()}catch(e){cc.debug("[RemoteAudioMeter] source disconnect warning:",e)}this._source=null,this._stream=null}!t||t.getAudioTracks().length===0||(this._stream=new MediaStream(t.getAudioTracks()),this._source=this._audioContext.createMediaStreamSource(this._stream))}destroy(){if(this._source){try{this._source.disconnect()}catch{}this._source=null}this._audioContext.close().catch(t=>{cc.debug("[RemoteAudioMeter] audio context close warning:",t)}),super.destroy()}computeLevel(){if(!this._source)return 0;this._analyser.getByteTimeDomainData(this._analyserBuffer);let t=0;for(const e of this._analyserBuffer){const i=(e-128)/128;t+=i*i}return Math.sqrt(t/this._analyserBuffer.length)}};const ur=W(),zg=1e3,Vg=10,Hg=2e3,jg=3e3,Wg=3,Gg=5,qg=5,Xg=10,Yg=4,Kg=30;function Zg(t,e){const i=t+e;return i===0?0:t/i*100}function Qg(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="inbound-rtp"}function Jg(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="candidate-pair"}var $g=class extends ie{constructor(t,e={}){super(),this.peerConnection=t,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=e.pollingIntervalMs??zg,this.baselineSampleCount=e.baselineSamples??Vg,this.noAudioPacketThresholdMs=e.noAudioPacketThresholdMs??Hg,this.noVideoPacketThresholdMs=e.noVideoPacketThresholdMs??jg,this.rttSpikeWarningMultiplier=e.rttSpikeWarningMultiplier??Wg,this.rttSpikeCriticalMultiplier=e.rttSpikeCriticalMultiplier??Gg,this.packetLossWarningPercent=e.packetLossWarningPercent??qg,this.packetLossCriticalPercent=e.packetLossCriticalPercent??Xg,this.jitterSpikeMultiplier=e.jitterSpikeMultiplier??Yg,this.historyWindowSeconds=e.historyWindowSeconds??Kg}get networkIssues$(){return this._networkIssues$.asObservable()}get networkIssues(){return[...this._networkIssues$.value]}get isNetworkHealthy$(){return this.cachedObservable("isNetworkHealthy$",()=>this._networkIssues$.pipe(E(t=>t.length===0),L(),S(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(Gn(t=>Ie(t.filter(e=>e.severity==="critical"))),S(this.destroyed$)))}get sample$(){return this._sample$.asObservable()}start(){if(this.running)return;this.running=!0;const t=Date.now();this.lastAudioPacketChangeTime=t,this.lastVideoPacketChangeTime=t,ur.debug("[RTCStatsMonitor] Starting stats monitoring"),this.subscribeTo(jr(this.pollingIntervalMs).pipe(B(()=>this.running),Ke(()=>Ie(this.peerConnection.getStats()).pipe(ei(e=>(ur.warn("[RTCStatsMonitor] Failed to get stats:",e),Jt)))),B(()=>this.running),E(e=>this.extractSample(e))),e=>this._sample$.next(e)),this.subscribeTo(this._sample$.pipe(Me(this.baselineSampleCount),Td(),E(e=>({rtt:e.reduce((i,r)=>i+r.roundTripTime,0)/e.length,jitter:e.reduce((i,r)=>i+r.audioJitter,0)/e.length,ready:!0}))),e=>{ur.debug(`[RTCStatsMonitor] Baseline established: rtt=${e.rtt.toFixed(1)}ms, jitter=${e.jitter.toFixed(1)}ms`),this._baseline$.next(e)}),this.subscribeTo(this._sample$.pipe(Ka((e,i)=>({prev:e.current,current:i}),{prev:null,current:null}),B(e=>e.current!==null)),({prev:e,current:i})=>{const r=i.timestamp;this.updatePacketTracking(i,r);const n=this.detectIssues(i,e,r);this._networkIssues$.next(n)}),this.subscribeTo(this._sample$.pipe(Ka((e,i)=>{const r=i.timestamp-this.historyWindowSeconds*1e3,n={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[...e.filter(s=>s.timestamp>r),n]},[])),e=>this._networkMetrics$.next(e))}stop(){this.running&&(this.running=!1,ur.debug("[RTCStatsMonitor] Stopping stats monitoring"))}destroy(){ur.debug("[RTCStatsMonitor] Destroying RTCStatsMonitor"),this.stop(),super.destroy()}extractSample(t){let e=0,i=0,r=0,n=0,s=0,a=0,o;return t.forEach(c=>{Qg(c)&&(c.kind==="audio"?(e+=c.packetsReceived??0,i+=c.packetsLost??0,r=Math.max(r,(c.jitter??0)*1e3)):(n+=c.packetsReceived??0,s+=c.packetsLost??0)),Jg(c)&&c.state==="succeeded"&&c.nominated&&(a=c.currentRoundTripTime?c.currentRoundTripTime*1e3:this.lastRoundTripTime,o=c.availableOutgoingBitrate??this.lastAvailableOutgoingBitrate)}),{audioPacketsReceived:e,audioPacketsLost:i,audioJitter:r,videoPacketsReceived:n,videoPacketsLost:s,roundTripTime:a,availableOutgoingBitrate:o,timestamp:Date.now()}}updatePacketTracking(t,e){t.audioPacketsReceived!==this.lastAudioPacketsReceived&&(this.lastAudioPacketsReceived=t.audioPacketsReceived,this.lastAudioPacketChangeTime=e),t.videoPacketsReceived!==this.lastVideoPacketsReceived&&(this.lastVideoPacketsReceived=t.videoPacketsReceived,this.lastVideoPacketChangeTime=e),t.roundTripTime>0&&(this.lastRoundTripTime=t.roundTripTime),t.availableOutgoingBitrate!==void 0&&(this.lastAvailableOutgoingBitrate=t.availableOutgoingBitrate)}detectIssues(t,e,i){const r=[],n=this._baseline$.value,s=i-this.lastAudioPacketChangeTime;s>this.noAudioPacketThresholdMs&&r.push({type:"no_inbound_audio",severity:"critical",timestamp:i,value:s,threshold:this.noAudioPacketThresholdMs});const a=i-this.lastVideoPacketChangeTime;if(a>this.noVideoPacketThresholdMs&&r.push({type:"no_inbound_video",severity:"warning",timestamp:i,value:a,threshold:this.noVideoPacketThresholdMs}),n.ready){const o=t.roundTripTime,c=n.rtt;if(c>0){const p=o/c;p>this.rttSpikeCriticalMultiplier?r.push({type:"high_rtt",severity:"critical",timestamp:i,value:o,threshold:c*this.rttSpikeCriticalMultiplier}):p>this.rttSpikeWarningMultiplier&&r.push({type:"high_rtt",severity:"warning",timestamp:i,value:o,threshold:c*this.rttSpikeWarningMultiplier})}const u=t.audioJitter,h=n.jitter;h>0&&u/h>this.jitterSpikeMultiplier&&r.push({type:"high_jitter",severity:"warning",timestamp:i,value:u,threshold:h*this.jitterSpikeMultiplier})}if(e){const o=Math.max(0,t.audioPacketsReceived-e.audioPacketsReceived),c=Math.max(0,t.audioPacketsLost-e.audioPacketsLost),u=Math.max(0,t.videoPacketsReceived-e.videoPacketsReceived),h=Math.max(0,t.videoPacketsLost-e.videoPacketsLost),p=o+u,f=Zg(c+h,p);f>this.packetLossCriticalPercent?r.push({type:"high_packet_loss",severity:"critical",timestamp:i,value:f,threshold:this.packetLossCriticalPercent}):f>this.packetLossWarningPercent&&r.push({type:"high_packet_loss",severity:"warning",timestamp:i,value:f,threshold:this.packetLossWarningPercent})}return r}};const oe=W(),ef=2e3,tf=1e4,rf=3e3,nf=5e3,sf=3,af=3,of=3e3,cf=1e4,lf=150,uf=300,df=5,hf=new Set(["high_rtt","high_jitter","high_packet_loss"]);var pf=class extends ie{constructor(t,e,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=t,this._inputs=e,this._config={debounceTimeMs:i.debounceTimeMs??ef,cooldownMs:i.cooldownMs??tf,iceGracePeriodMs:i.iceGracePeriodMs??rf,iceRestartTimeoutMs:i.iceRestartTimeoutMs??nf,maxAttempts:i.maxAttempts??sf,enableRelayFallback:i.enableRelayFallback??!0,keyframeMaxBurst:i.keyframeMaxBurst??af,keyframeBurstWindowMs:i.keyframeBurstWindowMs??of,keyframeCooldownMs:i.keyframeCooldownMs??cf,degradationBitrateThreshold:i.degradationBitrateThreshold??lf,degradationRecoveryThreshold:i.degradationRecoveryThreshold??uf,enableAutoDegradation:i.enableAutoDegradation??!0,packetLossRecoveryDelaySec:i.packetLossRecoveryDelaySec??df},this.initPipeline(),this.initDegradationRecoveryPipeline()}get recoveryState$(){return this._recoveryState$.asObservable().pipe(S(this._destroyed$))}get recoveryState(){return this._recoveryState$.value}get recoveryEvent$(){return this._recoveryEvent$.asObservable().pipe(S(this._destroyed$))}get bandwidthConstrained$(){return this._bandwidthConstrained$.asObservable().pipe(S(this._destroyed$))}get bandwidthConstrained(){return this._bandwidthConstrained$.value}pushTrigger(t){this._trigger$.next(t)}async requestIceRestart(){if(this._recoveryState$.value==="recovering"){oe.info("CallRecoveryManager: manual ICE restart skipped — recovery already in progress");return}oe.info("CallRecoveryManager: manual ICE restart requested"),this.transitionTo("recovering"),await this.executeIceRestart(!1),this.startCooldown()}requestKeyframe(){this.executeKeyframe("manual request")}reset(){oe.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")&&(oe.info("CallRecoveryManager: verto.modify failed — re-entering recovery"),this._cooldownUntil=0,this.transitionTo("idle"),this.pushTrigger({source:"network",detail:"modify_failed_during_recovery"}))}reportBandwidth(t){if(!this._config.enableAutoDegradation)return;const e=this._bandwidthConstrained$.value;!e&&t<this._config.degradationBitrateThreshold?(this._bandwidthConstrained$.next(!0),this._callbacks.disableVideo(),this.emitEvent({action:"video_disabled",reason:`bandwidth ${t}kbps below threshold ${this._config.degradationBitrateThreshold}kbps`,timestamp:Date.now()}),oe.warn(`CallRecoveryManager: disabling video — bandwidth ${t}kbps < ${this._config.degradationBitrateThreshold}kbps`)):e&&t>=this._config.degradationRecoveryThreshold&&(this._bandwidthConstrained$.next(!1),this._callbacks.enableVideo(),this.emitEvent({action:"video_restored",reason:`bandwidth ${t}kbps recovered above ${this._config.degradationRecoveryThreshold}kbps`,timestamp:Date.now()}),oe.info(`CallRecoveryManager: restoring video — bandwidth ${t}kbps >= ${this._config.degradationRecoveryThreshold}kbps`))}reportNetworkIssues(t){const e=t.some(i=>i.type==="high_packet_loss");e!==this._hasPacketLoss$.value&&this._hasPacketLoss$.next(e)}handleWebSocketReconnect(){const t=this._callbacks.getPeerConnectionState();t==="connected"||t==="completed"?(oe.info("CallRecoveryManager: signal-only reconnect — peer connection still alive"),this.emitEvent({action:"signal_reconnect",reason:"WebSocket reconnected, peer connection still connected",timestamp:Date.now()})):(oe.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(Se(()=>{this._recoveryState$.value==="idle"&&this.transitionTo("debouncing")}),Xa(this._config.debounceTimeMs),Za(this._inputs.signalingReady$),B(([,t])=>this.passGateChecks(t)),E(([t])=>t),qn(t=>this.executeTieredRecovery(t)),S(xi(this._destroyed$,this._pipelineStop$))),{next:()=>{},error:t=>{oe.error("CallRecoveryManager: pipeline error",t),this.transitionTo("idle")}})}initDegradationRecoveryPipeline(){if(!this._config.enableAutoDegradation)return;const t=this._config.packetLossRecoveryDelaySec*1e3;this.subscribeTo(Ha([this._bandwidthConstrained$,this._hasPacketLoss$]).pipe(Ke(([e,i])=>e&&!i?ki(t):Jt),S(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()}),oe.info(`CallRecoveryManager: restoring video — no packet loss for ${this._config.packetLossRecoveryDelaySec}s`)})}passGateChecks(t){return this._callbacks.isNegotiating()?(oe.debug("CallRecoveryManager: gate blocked — negotiation in progress"),this.transitionTo("idle"),!1):t?this._callbacks.isCallConnected()?this.isCooldownActive()?(oe.debug("CallRecoveryManager: gate blocked — cooldown active"),this.transitionTo("cooldown"),!1):!0:(oe.debug("CallRecoveryManager: gate blocked — call not connected"),this.transitionTo("idle"),!1):(oe.debug("CallRecoveryManager: gate blocked — signaling not ready"),this.transitionTo("idle"),!1)}isCooldownActive(){return Date.now()<this._cooldownUntil}executeTieredRecovery(t){return this.transitionTo("recovering"),oe.info(`CallRecoveryManager: starting tiered recovery — source=${t.source} detail=${t.detail}`),Ie(this.runTiers(t)).pipe(Se(()=>this.startCooldown()),ei(e=>(oe.error("CallRecoveryManager: tiered recovery failed",e),this.startCooldown(),Jt)))}async runTiers(t){if(this.executeKeyframe(t.detail),t.issueType&&hf.has(t.issueType)){oe.debug(`CallRecoveryManager: degradation-only issue (${t.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()}),oe.warn("CallRecoveryManager: max recovery attempts reached"))}executeKeyframe(t){const e=Date.now();if(e<this._keyframeCooldownUntil){oe.debug("CallRecoveryManager: keyframe request skipped — cooldown active");return}if(e-this._keyframeBurstStart>this._config.keyframeBurstWindowMs&&(this._keyframeBurstCount=0,this._keyframeBurstStart=e),this._keyframeBurstCount>=this._config.keyframeMaxBurst){this._keyframeCooldownUntil=e+this._config.keyframeCooldownMs,oe.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:t,timestamp:e}),oe.debug(`CallRecoveryManager: keyframe requested (burst ${this._keyframeBurstCount}/${this._config.keyframeMaxBurst})`)}async executeIceRestart(t){this._attemptCount+=1;const e=t?"Tier 3 (relay-only)":"Tier 2 (standard)";oe.info(`CallRecoveryManager: ${e} ICE restart — attempt ${this._attemptCount}/${this._config.maxAttempts}`),this.emitEvent({action:"reinvite_started",reason:`${e} ICE restart`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()});try{return await this.withTimeout(this._callbacks.requestIceRestart(t),this._config.iceRestartTimeoutMs)?(this.emitEvent({action:"reinvite_succeeded",reason:`${e} ICE restart succeeded`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),oe.info(`CallRecoveryManager: ${e} ICE restart succeeded`),this._attemptCount=0,!0):(this.emitEvent({action:"reinvite_failed",reason:`${e} ICE restart returned false`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),oe.warn(`CallRecoveryManager: ${e} ICE restart failed`),!1)}catch{return this.emitEvent({action:"reinvite_timeout",reason:`${e} ICE restart timed out after ${this._config.iceRestartTimeoutMs}ms`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),oe.warn(`CallRecoveryManager: ${e} ICE restart timed out`),!1}}async withTimeout(t,e){return new Promise((i,r)=>{const n=setTimeout(()=>{r(new Error(`Timeout after ${e}ms`))},e);t.then(s=>{clearTimeout(n),i(s)},s=>{clearTimeout(n),r(s instanceof Error?s:new Error(String(s)))})})}transitionTo(t){const e=this._recoveryState$.value;e!==t&&(oe.debug(`CallRecoveryManager: state ${e} -> ${t}`),this._recoveryState$.next(t))}startCooldown(){this._cooldownUntil=Date.now()+this._config.cooldownMs,this.transitionTo("cooldown"),this._cooldownSubscription&&this._cooldownSubscription.unsubscribe(),this._cooldownSubscription=ki(this._config.cooldownMs).pipe(Me(1),S(this._destroyed$),B(()=>this._recoveryState$.value==="cooldown")).subscribe(()=>this.transitionTo("idle"))}emitEvent(t){this._recoveryEvent$.next(t)}},gf=class{constructor(t,e,i){this.executeMethod=t,this.vertoManager=e,this.deviceController=i}createSelfParticipant(t){return new Wo(t,this.executeMethod,this.vertoManager,this.deviceController)}createParticipant(t){return new jo(t,this.executeMethod,this.deviceController)}};const ff=93.2,vf=.024,bf=2.5,mf=0,yf=100,wf=1,Sf=5,Cf=4,Af=3.5,Tf=3,Ef=2;function kf(t,e,i){const r=ff-(t/2+e)*vf-i*bf,n=Math.min(yf,Math.max(mf,r)),s=1+.035*n+n*(n-60)*(100-n)*7e-6;return Math.min(Sf,Math.max(wf,s))}function xf(t){return t>=Cf?"excellent":t>=Af?"good":t>=Tf?"fair":t>=Ef?"poor":"critical"}const me=W(),Df=5/3,If=t=>{if(!t)return{};try{const e=new URL(`destination:${t}`),i={};return e.searchParams.forEach((r,n)=>{i[n]=r}),i}catch(e){return me.warn(`Failed to parse destination URI: ${t}`,e),{}}};var Mf=class extends ie{constructor(t,e,i,r){super(),this.clientSession=t,this.options=e,this.address=r,this._errors$=this.createReplaySubject(1),this._lastMergedStatus="new",this._answered$=this.createReplaySubject(),this._holdState=!1,this._userVariables$=this.createBehaviorSubject({...g.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=e.callId??Qr(),this.to=e.to,this._userVariables$.next({...this._userVariables$.value,...If(e.to),...e.userVariables}),this.subscribeTo(this.webrtcMessages$,o=>{const c=tt(o,"params.userVariables");c&&this._userVariables$.next({...this._userVariables$.value,...c})});const n=i.initializeManagers(this);this.vertoManager=n.vertoManager,this.callEventsManager=n.callEventsManager,e.initOffer?(this._status$=this.createBehaviorSubject("ringing"),this._lastMergedStatus="ringing"):this._status$=this.createBehaviorSubject("new");const{deviceController:s,networkChange$:a}=i;this._networkChange$=a,this.participantFactory=new gf(this.executeMethod.bind(this),this.vertoManager,s),this.subscribeTo(xi(this._status$.asObservable(),this.vertoManager.signalingStatus$).pipe(L(),S(this._destroyed$)),o=>{var c;this._lastMergedStatus=o,o==="connected"&&!this._statsMonitor?this.initResilienceSubsystems():o==="disconnected"?((c=this._statsMonitor)==null||c.destroy(),this._statsMonitor=void 0):(o==="destroyed"||o==="failed")&&this.stopResilienceSubsystems()})}get errors$(){return this.deferEmission(this._errors$.asObservable())}emitError(t){this._status$.value==="destroyed"||this._status$.value==="failed"||(this._errors$.next(t),t.fatal&&(this._status$.next("failed"),this.destroy()))}notifyModifyFailed(){var t;(t=this._recoveryManager)==null||t.notifyModifyFailed()}get direction(){return this.options.initOffer?"inbound":"outbound"}get address$(){return this.deferEmission(Ie([this.address])).pipe(S(this._destroyed$))}get fromName(){return this.options.fromName}get from(){return this.options.from}get toName(){return this.options.toName}async toggleIncomingVideo(){throw new ft}async toggleIncomingAudio(){throw new ft}addCallId(t){this.callEventsManager.addCallId(t)}get capabilities(){return this.callEventsManager.capabilities}get participants(){return this.callEventsManager.participants}get self(){return this.callEventsManager.self}async toggleLock(){const t=this.locked?"call.unlock":"call.lock";await this.executeMethod(this.selfId??"",t,{})}async toggleHold(){this._holdState?await this.vertoManager.unhold():await this.vertoManager.hold(),this._holdState=!this._holdState}async startRecording(){throw new ft}async startStreaming(){throw new ft}async setMeta(t){throw new ft}async updateMeta(t){throw new ft}get layoutLayers$(){return this.deferEmission(this.callEventsManager.layoutLayers$).pipe(S(this._destroyed$))}get layoutLayers(){return this.callEventsManager.layoutLayers}async executeMethod(t,e,i){var s,a,o;const r=this.buildMethodParams(t,i),n=Oi({method:e,params:r});try{const c=await this.clientSession.execute(n);if(lg(c))throw new _t(parseInt(((s=c.result)==null?void 0:s.code)??"0"),`Error response from method ${e}: ${(a=c.result)==null?void 0:a.code} ${(o=c.result)==null?void 0:o.message}`,void 0,void 0,n.id);return c}catch(c){throw me.error(`[Call] Error executing method ${e} with params`,r,c),c}}buildMethodParams(t,e){const i={node_id:this.nodeId??"",call_id:this.id,member_id:this.vertoManager.selfId??""};return typeof t=="object"?{...e,self:i,targets:[t]}:{...e,self:i,target:{node_id:this.nodeId??"",call_id:this.id,member_id:t}}}get status$(){return this.publicCachedObservable("status$",()=>xi(this._status$.asObservable(),this.vertoManager.signalingStatus$).pipe(L(),Se(t=>{this._lastMergedStatus=t})))}get participants$(){return this.deferEmission(this.callEventsManager.participants$).pipe(S(this._destroyed$))}get self$(){return this.deferEmission(this.callEventsManager.self$).pipe(S(this._destroyed$))}get recording$(){return this.deferEmission(this.callEventsManager.recording$).pipe(S(this._destroyed$))}get streaming$(){return this.deferEmission(this.callEventsManager.streaming$).pipe(S(this._destroyed$))}get raiseHandPriority$(){return this.deferEmission(this.callEventsManager.raiseHandPriority$).pipe(S(this._destroyed$))}get locked$(){return this.deferEmission(this.callEventsManager.locked$).pipe(S(this._destroyed$))}get meta$(){return this.deferEmission(this.callEventsManager.meta$).pipe(S(this._destroyed$))}get capabilities$(){return this.deferEmission(this.callEventsManager.capabilities$).pipe(S(this._destroyed$))}get layout$(){return this.deferEmission(this.callEventsManager.layout$).pipe(S(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(S(this._destroyed$))}get layouts(){return this.callEventsManager.layouts}get localStream$(){return this.deferEmission(this.vertoManager.localStream$).pipe(S(this._destroyed$))}get localStream(){return this.vertoManager.localStream}get remoteStream$(){return this.deferEmission(this.vertoManager.remoteStream$).pipe(S(this._destroyed$))}get remoteStream(){return this.vertoManager.remoteStream}get userVariables$(){return this.deferEmission(this._userVariables$.asObservable())}get userVariables(){return{...this._userVariables$.value}}set userVariables(t){this._userVariables$.next({...this._userVariables$.value,...t})}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(t){this._mediaParamsUpdated$.next(t)}requestKeyframe(){var t,e;(e=(t=this.vertoManager).requestKeyframe)==null||e.call(t)}async requestIceRestart(){var t,e;await((e=(t=this.vertoManager).requestIceRestart)==null?void 0:e.call(t))}initResilienceSubsystems(){const t=this.rtcPeerConnection;if(me.debug(`[Call] initResilienceSubsystems: pc=${t?"exists":"undefined"}, connectionState=${t==null?void 0:t.connectionState}`),!t){me.warn("[Call] No peer connection available, skipping resilience init");return}try{const e=g.instance;this._statsMonitor=new $g(t,{pollingIntervalMs:e.statsPollingInterval,baselineSamples:e.statsBaselineSamples,noAudioPacketThresholdMs:e.statsNoPacketThreshold,rttSpikeWarningMultiplier:e.statsRttSpikeMultiplier,rttSpikeCriticalMultiplier:e.statsRttSpikeMultiplier*Df,packetLossWarningPercent:e.statsPacketLossThreshold*100,packetLossCriticalPercent:e.statsPacketLossThreshold*200,jitterSpikeMultiplier:e.statsJitterSpikeMultiplier,historyWindowSeconds:e.statsHistorySize}),this._recoveryManager=new pf({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,n;try{this.vertoManager.requestIceRestartAll?await this.vertoManager.requestIceRestartAll(i):await((n=(r=this.vertoManager).requestIceRestart)==null?void 0:n.call(r,i))}catch{return!1}return this.waitForPeerConnectionConnected()},disableVideo:()=>{try{this.vertoManager.muteMainVideoInputDevice(),me.debug("[Call] Recovery manager disabled video")}catch{me.debug("[Call] Recovery manager failed to disable video")}},enableVideo:()=>{this.vertoManager.unmuteMainVideoInputDevice().catch(()=>{me.debug("[Call] Recovery manager failed to enable video")})},isNegotiating:()=>this.vertoManager.mainPeerConnection.isNegotiating,isCallConnected:()=>this._lastMergedStatus==="connected",getPeerConnectionState:()=>t.connectionState},{signalingReady$:this.clientSession.authenticated$},{debounceTimeMs:e.recoveryDebounceTime,cooldownMs:e.recoveryCooldown,iceGracePeriodMs:e.iceDisconnectedGracePeriod,iceRestartTimeoutMs:e.iceRestartTimeout,maxAttempts:e.maxRecoveryAttempts,enableRelayFallback:e.enableRelayFallback,keyframeMaxBurst:e.keyframeMaxBurst,keyframeBurstWindowMs:e.keyframeBurstWindow,keyframeCooldownMs:e.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 n=i[i.length-1],s=n.audio.packetsReceived+n.video.packetsReceived,a=n.audio.packetsLost+n.video.packetsLost,o=s+a>0?a/(s+a)*100:0,c=kf(n.roundTripTime,n.audio.jitter,o);this._qualityScore$.next(c),this._qualityLevel$.next(xf(c)),n.availableOutgoingBitrate!==void 0&&((r=this._recoveryManager)==null||r.reportBandwidth(n.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"&&(me.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,n;i.type==="offline"?(r=this._recoveryManager)==null||r.pushTrigger({source:"network",detail:"browser went offline"}):i.type==="online"&&((n=this._recoveryManager)==null||n.handleWebSocketReconnect())}),this.subscribeTo(this.clientSession.authenticated$.pipe(Wr(1),B(Boolean)),()=>{var i;me.debug("[Call] WebSocket reconnected — notifying recovery manager"),(i=this._recoveryManager)==null||i.handleWebSocketReconnect()}),this._statsMonitor.start(),me.debug("[Call] Resilience subsystems initialized for call",this.id)}catch(e){me.warn("[Call] Failed to initialize resilience subsystems:",e)}}async waitForPeerConnectionConnected(){const t=this.rtcPeerConnection;if(!t)return!1;const e=Date.now()+Xh;for(;;){const i=t.connectionState;if(i==="connected")return!0;if(i==="failed"||i==="closed"||Date.now()>=e)return!1;await new Promise(r=>setTimeout(r,Yh))}}stopResilienceSubsystems(){var t,e;try{(t=this._statsMonitor)==null||t.destroy(),(e=this._recoveryManager)==null||e.destroy()}catch{}this._statsMonitor=void 0,this._recoveryManager=void 0}createParticipant(t,e){return t===(e??this.vertoManager.selfId)?this.participantFactory.createSelfParticipant(t):this.participantFactory.createParticipant(t)}get mediaDirections$(){return this.deferEmission(this.vertoManager.mediaDirections$).pipe(S(this._destroyed$))}get mediaDirections(){return this.vertoManager.mediaDirections}get participantsId$(){return this.cachedObservable("participantsId$",()=>this.participants$.pipe(E(t=>t.map(e=>e.id))))}async execute(t,e){return this.clientSession.execute(t,e)}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(t){try{me.debug("[Call] Checking if event is for this call session:",t);const e=tt(t,"params.params.callID")??tt(t,"params.call_id"),i=tt(t,"params.room_session_id");return me.debug(`[Call] Extracted session identifiers callID: ${e} and roomSessionID: ${i} from event:`),e===this.id||!!e&&this.callEventsManager.isCallIdValid(e)||!!i&&this.callEventsManager.isRoomSessionIdValid(i)}catch(e){return me.error("[Call] Error checking if event is for this call session:",e),!1}}get callSessionEvents$(){return this.cachedObservable("callSessionEvents$",()=>this.clientSession.signalingEvent$.pipe(B(t=>this.isCallSessionEvent(t)),Se(t=>{me.debug("[Call] Received call session event:",t)}),S(this.destroyed$),Tt()))}get callUpdated$(){return this.publicCachedObservable("callUpdated$",()=>this.callSessionEvents$.pipe(fe(Xo,"params"),S(this.destroyed$)))}get memberJoined$(){return this.publicCachedObservable("memberJoined$",()=>this.callSessionEvents$.pipe(fe(Zo,"params"),S(this.destroyed$)))}get memberLeft$(){return this.publicCachedObservable("memberLeft$",()=>this.callSessionEvents$.pipe(fe(Qo,"params"),S(this.destroyed$)))}get memberUpdated$(){return this.publicCachedObservable("memberUpdated$",()=>this.callSessionEvents$.pipe(fe(Ko,"params"),S(this.destroyed$)))}get memberTalking$(){return this.publicCachedObservable("memberTalking$",()=>this.callSessionEvents$.pipe(fe(Jo,"params"),S(this.destroyed$)))}get callStates$(){return this.publicCachedObservable("callStates$",()=>this.callSessionEvents$.pipe(fe(Yo,"params"),S(this.destroyed$)))}get layoutUpdates$(){return this.publicCachedObservable("layoutUpdates$",()=>this.callSessionEvents$.pipe(fe(os,"params"),S(this.destroyed$)))}get rtcPeerConnection(){return this.vertoManager.mainPeerConnection.peerConnection}get signalingEvent$(){return this.publicCachedObservable("signalingEvent$",()=>this.callEvent$.pipe(E(t=>JSON.parse(JSON.stringify(t)))))}subscribe(t){const e=this._customSubscriptions.get(t);if(e)return e;const i=this.callSessionEvents$.pipe(B(r=>r.event_type===t),E(r=>JSON.parse(JSON.stringify(r))),S(this._destroyed$));return this._sendVertoSubscribe(t).then(()=>{this._customSubscriptions.set(t,i)},r=>{this._customSubscriptions.delete(t),me.warn(`[Call] verto.subscribe for '${t}' failed, not caching:`,r)}),this._customSubscriptions.set(t,i),i}get webrtcMessages$(){return this.cachedObservable("webrtcMessages$",()=>this.callSessionEvents$.pipe(fe(nn,"params"),Se(t=>me.debug("[Call] Event is a WebRTC message event:",t)),S(this.destroyed$),Tt()))}get callEvent$(){return this.cachedObservable("callEvent$",()=>this.callSessionEvents$.pipe(fe(ug,"params"),Se(t=>me.debug("[Call] Event is a call event:",t)),S(this.destroyed$),Tt()))}get layoutEvent$(){return this.cachedObservable("layoutEvent$",()=>this.callEvent$.pipe(fe(os,"params")))}async hangup(){this._status$.next("disconnecting");try{await this.vertoManager.bye()}finally{this.destroy()}}async sendDigits(t){return this.vertoManager.sendDigits(t)}answer(t){this._answerMediaOptions=t,this._answered$.next(!0)}get answerMediaOptions(){return this._answerMediaOptions}reject(){this._answered$.next(!1)}get answered$(){return this.deferEmission(this._answered$.asObservable())}async setLayout(t,e){if(!this.layouts.includes(t))throw new ro(`Layout ${t} is not available in the current call layouts: ${this.layouts.join(", ")}`);const i=await Ge(this.selfId$.pipe(B(r=>r!==null)));await this.executeMethod(i,"call.layout.set",{layout:t,positions:e})}async transfer(t){return this.vertoManager.transfer(t)}setLocalMicrophoneGain(t){const e=this.vertoManager.ensureLocalAudioPipeline();if(!e){me.warn("[Call] setLocalMicrophoneGain: audio pipeline unavailable");return}const i=Math.max(0,Math.min(200,t));e.setGain(i/100)}get localMicrophoneGain$(){const t=this.vertoManager.ensureLocalAudioPipeline();return t?this.publicCachedObservable("localMicrophoneGain$",()=>t.gain$.pipe(E(e=>e*100),S(this._destroyed$))):At(100).pipe(S(this._destroyed$))}get localAudioLevel$(){const t=this.vertoManager.ensureLocalAudioPipeline();return t?this.publicCachedObservable("localAudioLevel$",()=>t.level$.pipe(S(this._destroyed$),Tt())):At(0).pipe(S(this._destroyed$))}get localSpeaking$(){const t=this.vertoManager.ensureLocalAudioPipeline();return t?this.publicCachedObservable("localSpeaking$",()=>t.speaking$.pipe(S(this._destroyed$),Tt())):At(!1).pipe(S(this._destroyed$))}enablePushToTalk(){const t=this.vertoManager.ensureLocalAudioPipeline();if(!t){me.warn("[Call] enablePushToTalk: audio pipeline unavailable");return}t.setPTTActive(!1),this._pushToTalkEnabled=!0}disablePushToTalk(){var t;(t=this.vertoManager.localAudioPipeline)==null||t.setPTTActive(!0),this._pushToTalkEnabled=!1}setPushToTalkActive(t){var e;this._pushToTalkEnabled&&((e=this.vertoManager.localAudioPipeline)==null||e.setPTTActive(t))}async setEchoCancellation(t){await this.vertoManager.updateMediaConstraints({audio:{echoCancellation:t}})}async setNoiseSuppression(t){await this.vertoManager.updateMediaConstraints({audio:{noiseSuppression:t}})}async setAutoGainControl(t){await this.vertoManager.updateMediaConstraints({audio:{autoGainControl:t}})}get remoteAudioLevel$(){return this.publicCachedObservable("remoteAudioLevel$",()=>{this._remoteAudioMeter??(this._remoteAudioMeter=new Bg);const t=this._remoteAudioMeter;return this.subscribeTo(this.vertoManager.remoteStream$,e=>{t.setStream(e)}),t.level$.pipe(S(this._destroyed$),Tt())})}destroy(){var t;this._status$.value!=="destroyed"&&(this._status$.next("destroyed"),this.stopResilienceSubsystems(),(t=this._remoteAudioMeter)==null||t.destroy(),this._remoteAudioMeter=null,this.vertoManager.destroy(),this.callEventsManager.destroy(),super.destroy())}async _sendVertoSubscribe(t){const e=$p({sessid:this.id,eventChannel:[t]}),i={callID:this.id,node_id:this.vertoManager.nodeId??"",message:e};await this.clientSession.execute(Bo(i))}};function Rf(t){return t instanceof Xr?"timeout":t instanceof _t?"signaling":t instanceof Ii?"media":t instanceof $a||t instanceof eo?"network":"internal"}const Pf=new Set([wo,Co,So]);function Of(t){return!(t instanceof so||t instanceof Ii||t instanceof Xr||t instanceof _t&&Pf.has(t.code))}var _f=class{constructor(t,e,i,r,n){this.sessionManager=t,this.deviceController=e,this.attachManager=i,this.webRTCApiProvider=r,this.networkChange$=n}createCall(t,e){return new Mf(this.sessionManager,e,{initializeManagers:i=>({vertoManager:new Ng(i,this.attachManager,this.deviceController,this.webRTCApiProvider,{nodeId:e.nodeId,onError:r=>{const n={kind:Rf(r),fatal:Of(r),error:r,callId:i.id};i.emitError(n)},onModifyFailed:()=>{i.notifyModifyFailed()}}),callEventsManager:new yg(i)}),deviceController:this.deviceController,networkChange$:this.networkChange$},t)}};const ds=W();var lc=class{constructor(t,e,i){this.endpoint=t,this.http=i,this.filter=r=>!0,this.mapper=r=>r,this.nextUrl=`${this.endpoint}?${e}`}async next(){if(!this.nextUrl)return this.hasMore=!1,[];const t=await this.http.request({...$n,url:this.nextUrl});if(t.ok&&t.body){const e=JSON.parse(t.body);return this.nextUrl=e.links.next,this.hasMore=!!this.nextUrl,e.data.filter(this.filter).map(this.mapper)}return ds.error("Failed to fetch entity"),[]}async id(t){const e=await this.http.request({...$n,url:`${this.endpoint}/${String(t)}`});if(e.ok&&e.body)return JSON.parse(e.body)}},uc=class extends ie{constructor(t,e,i){super(),this.fetchController=t,this.update$=e,this.onError=i,this.collectionData=new Map,this.observablesRegistry=new Map,this.upsertData=r=>{var o;if(!r.id)return;const n=this.collectionData.get(r.id)??{},s={},a=new Set([...Object.keys(n),...Object.keys(r)]);for(const c of a){const u=n[c],h=r[c];h!==void 0&&u!==void 0&&typeof u=="object"&&u!==null&&!Array.isArray(u)&&typeof h=="object"&&h!==null&&!Array.isArray(h)?s[c]={...u,...h}:h!==void 0?s[c]=h:s[c]=u}this.collectionData.set(r.id,s),(o=this.observablesRegistry.get(r.id))==null||o.next(s),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$=$t(()=>Ie(this.init())).pipe(Ke(()=>this._hasMore$),L(),et(1),S(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(L(),Wr(1),B(t=>!t),E(()=>{}),S(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 t;try{this._loading$.next(!0),(await this.fetchController.next()).forEach(this.upsertData),this._hasMore$.next(this.fetchController.hasMore??!1),this._loading$.next(!1)}catch(e){ds.error("Failed to fetch initial collection data",e),this._hasMore$.next(this.fetchController.hasMore??!1),this._loading$.next(!1),(t=this.onError)==null||t.call(this,new ao("fetchMore",e))}}async tryFetch(t,e){var i,r,n;try{this._loading$.next(!0);const s=await((r=(i=this.fetchController)[t])==null?void 0:r.call(i,e));return this._loading$.next(!1),s&&this.upsertData(s),s}catch(s){ds.error(`Failed to fetch data for (${String(t)}:${String(e)}) :`,s),this._loading$.next(!1),(n=this.onError)==null||n.call(this,new ao(`tryFetch(${String(t)})`,s))}}get$(t){var e,i;if(!this.observablesRegistry.has(t)){this.observablesRegistry.set(t,new Bn(1));const r=this.collectionData.get(t);r?(e=this.observablesRegistry.get(t))==null||e.next(r):this.tryFetch("id",t)}return(i=this.observablesRegistry.get(t))==null?void 0:i.asObservable()}async find$(t,e){const i=Array.from(this.collectionData.values()).find(r=>r[t]===e)??await this.tryFetch(t,e);return i?this.get$(i.id):void 0}loadMore(){this.fetchController.hasMore!==!1&&this.fetchMore()}destroy(){this.observablesRegistry.forEach(t=>t.complete()),this.observablesRegistry.clear(),super.destroy()}},dc=class{constructor(t,e=r=>!!r,i=r=>r){this.originalCollection=t,this.filter=e,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(E(t=>t.filter(this.filter).map(this.mapper))))}get$(t){const e=this.originalCollection.get$(t);return e&&e.pipe(zr(B(this.filter),E(this.mapper)))}async find$(t,e){const i=await this.originalCollection.find$(t,e);return i&&i.pipe(zr(B(this.filter),E(this.mapper)))}loadMore(){this.originalCollection.loadMore()}destroy(){this.originalCollection.destroy()}},hc=class extends ie{constructor(t,e,i){super(),this.addressId=t,this.conversationManager=e,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$=$t(this.initConversationMessages).pipe(E(()=>this.textMessage),et(1),S(this.destroyed$)),this.history$=$t(this.initConversationMessages).pipe(E(()=>this.history),et(1),S(this.destroyed$)),this._state$=this.createBehaviorSubject(null)}upnext(t){const e={...this._state$.value,...t};this._state$.next(e)}get state(){return this._state$.value}get id(){return this.addressId}get name(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.name}get createdAt(){if(!this._state$.value)throw new Q("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(ue(),E(t=>t.display_name),S(this.destroyed$)))}get displayName(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.display_name}get previewUrl$(){return this.cachedObservable("previewUrl$",()=>this._state$.pipe(ue(),E(t=>t.preview_url),S(this.destroyed$)))}get previewUrl(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.preview_url}get coverUrl$(){return this.cachedObservable("coverUrl$",()=>this._state$.pipe(ue(),et(1),E(t=>t.cover_url),S(this.destroyed$)))}get coverUrl(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.cover_url}get resourceId$(){return this.cachedObservable("resourceId$",()=>this._state$.pipe(ue(),et(1),E(t=>t.resource_id),S(this.destroyed$)))}get resourceId(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.resource_id}get type$(){return this.cachedObservable("type$",()=>this._state$.pipe(ue(),et(1),E(t=>t.type),S(this.destroyed$)))}get type(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.type}get channels$(){return this.cachedObservable("channels$",()=>this._state$.pipe(ue(),et(1),E(t=>t.channels),S(this.destroyed$)))}get channels(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.channels}get locked(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.locked}get locked$(){return this.cachedObservable("locked$",()=>this._state$.pipe(ue(),et(1),E(t=>t.locked),S(this.destroyed$)))}async sendText(t){return this.conversationManager.sendText(t,this.id)}get textMessage(){if(this._conversationMessages)return this._textMessages$=this._textMessages$??new dc(this._conversationMessages,t=>t.subtype==="chat",t=>({id:t.id,text:t.text,created:t.ts,fromAddress$:this.addressProvider.get$(t.from_fabric_address_id)})),this._textMessages$}get history(){if(this._conversationMessages)return this._history$=this._history$??new dc(this._conversationMessages,t=>t.subtype==="log",t=>({id:t.id,kind:t.kind,status:t.details.status,started:t.details.start_time,ended:t.details.end_time,fromAddress$:this.addressProvider.get$(t.from_fabric_address_id)})),this._history$}get activity$(){throw new ft}get activity(){throw new ft}};const oi=W(),Lf=t=>{if(oi.debug("isRPCConnectResult check:",t),!t||typeof t!="object")return!1;const e=t,i=typeof e.identity=="string"&&typeof e.protocol=="string"&&typeof e.authorization=="object"&&typeof e.authorization.jti=="string"&&typeof e.authorization.project_id=="string"&&typeof e.authorization.fabric_subscriber=="object";return oi.debug("isRPCConnectResult check result:",i),i};var Ff=(pi=class{constructor(e,i,r){this.id=Qr(),oi.debug(`[PendingRPC(${this.id}) request:${e.id}: method:${e.method}] Creating PendingRPC`),this.request=e;const n=(r==null?void 0:r.timeoutMs)??pi.defaultTimeoutMs,s=r==null?void 0:r.signal;this.promise=new Promise((a,o)=>{if(s!=null&&s.aborted){o(new DOMException("The operation was aborted","AbortError"));return}let c=!1;const u=or(i.pipe(B(h=>h.id===e.id),Me(1)),new be(h=>{const p=setTimeout(()=>{h.error(new Xr(e.id,n))},n);return()=>clearTimeout(p)}),s?new be(h=>{const p=()=>{h.error(new DOMException("The operation was aborted","AbortError"))};return s.addEventListener("abort",p),()=>s.removeEventListener("abort",p)}):vd).subscribe({next:h=>{if(c=!0,h.error){const p=new _t(h.error.code,h.error.message,h.error.data,void 0,e.id);oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Rejecting promise with RPC error:`,p),o(p)}else oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Resolving promise with response:`,h),a(h);u.unsubscribe()},error:h=>{oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Rejecting promise with error:`,h),c=!0,o(h),u.unsubscribe()},complete:()=>{oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Observable completed`),c||o(new Xr(e.id,n)),u.unsubscribe()}})})}async then(e,i){return this.promise.then(e,i)}async catch(e){return this.promise.catch(e)}async finally(e){return this.promise.finally(e)}},pi.defaultTimeoutMs=5e3,pi);const X=W(),Uf=t=>{var n,s;const e=(n=t.to)==null?void 0:n.split("?")[0],i=(s=t.from)!=null&&s.startsWith("subscriber://")?t.from.replace("subscriber://",""):t.from,r=e??i;if(!r)throw new Di("Error building Address name");return r};var Nf=class extends ie{constructor(t,e,i,r,n,s,a,o,c){super(),this.getCredential=t,this.transport=e,this.storage=i,this.authorizationStateKey=r,this.attachManager=s,this.dpopManager=o,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._userInfo$=this.createBehaviorSubject(null),this._calls$=this.createBehaviorSubject({}),this._iceServers$=this.createBehaviorSubject([]),s.setSession(this),this.callFactory=new _f(this,n,s,a,c),this.initialized$=$t(()=>Ie(this.init())).pipe(et(1),S(this.destroyed$))}get incomingCalls$(){return this.cachedObservable("incomingCalls$",()=>this.calls$.pipe(E(t=>t.filter(e=>e.direction==="inbound"))))}get incomingCalls(){return Object.values(this._calls$.value).filter(t=>t.direction==="inbound")}get userInfo$(){return this._userInfo$.asObservable()}get userInfo(){return this._userInfo$.value}get calls$(){return this.cachedObservable("calls$",()=>this._calls$.pipe(E(t=>Object.values(t))))}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(E(t=>t.kind==="authenticated"),L())}get authenticated(){return this._authState$.value.kind==="authenticated"}get clientBound(){return this._wasClientBound}get authState(){return this._authState$.value}setDirectory(t){this._directory=t}async execute(t,e){try{return await this.transport.execute(t,e)}catch(i){throw X.debug("[Session] Execute Error",i),this._errors$.next(i instanceof Error?i:new Error(String(i),{cause:i})),i}}send(t){this.transport.send(t)}async init(){return await this.loadAuthorizationStateFromStorage(),this.setupMessageHandlers(),!0}setupMessageHandlers(){X.debug("[Session] Setting up message handlers"),this.subscribeTo(this.authStateEvent$,async t=>{X.debug("[Session] Authorization state event received:",t);try{await this.updateAuthorizationStateInStorage(t.authorization_state)}catch(e){X.error("[Session] Failed to handle authorization state update:",e),this._errors$.next(new Yn(e))}}),this.subscribeTo(this.transport.connectionStatus$.pipe(B(t=>t==="disconnected"||t==="reconnecting")),()=>{this._authState$.value.kind==="authenticated"&&this._authState$.next({kind:"unauthenticated"})}),this.subscribeTo(this.transport.connectionStatus$.pipe(B(t=>t==="connected"),qn(()=>(X.debug("[Session] Connection established, initiating authentication"),Ie(this.authenticate()).pipe(ei(t=>(this.handleAuthenticationError(t).catch(e=>{X.error("[Session] Error handling authentication failure:",e)}),Jt)))))),void 0),this.subscribeTo(this.vertoInvite$,async t=>{X.debug("[Session] Verto invite received:",t);try{await this.createInboundCall(t)}catch(e){X.error("[Session] Error handling Verto invite:",e),this._errors$.next(new zd(e))}}),this.subscribeTo(this.vertoAttach$,async t=>{X.debug("[Session] Verto attach received:",t);try{await this.handleVertoAttach(t)}catch(e){X.error("[Session] Error handling Verto attach:",e),this._errors$.next(new Vd(e))}})}async loadAuthorizationStateFromStorage(){try{const t=await this.storage.getItem(this.authorizationStateKey);this.authorizationState$.next(t??void 0)}catch(t){X.error("Failed to retrieve authorization state from storage:",t),this.authorizationState$.next(void 0)}}async updateAuthorizationStateInStorage(t){if(!t){X.debug("[Session] Removing authorization state from storage");try{await this.storage.removeItem(this.authorizationStateKey),this.authorizationState$.next(void 0)}catch(e){throw X.error("Failed to remove authorization state from storage:",e),e}return}try{X.debug("[Session] Updating authorization state in storage"),await this.storage.setItem(this.authorizationStateKey,t),this.authorizationState$.next(t)}catch(e){throw X.error("Failed to retrieve authorization state from storage:",e),e}}get authStateEvent$(){return this.cachedObservable("authStateEvent$",()=>this.signalingEvent$.pipe(Se(t=>{X.debug("[Session] Received incoming message:",t)}),fe(dg,"params"),Se(t=>{X.debug("[Session] Authorization state event received:",t.authorization_state)})))}get signalingEvent$(){return this.cachedObservable("signalingEvent$",()=>this.transport.incomingEvent$.pipe(fe(as,"params"),Tt()))}get vertoInvite$(){return this.cachedObservable("vertoInvite$",()=>this.signalingEvent$.pipe(B(nn),B(t=>ac(t.params)),E(t=>({node_id:t.node_id,...t.params.params}))))}get vertoAttach$(){return this.cachedObservable("vertoAttach$",()=>this.signalingEvent$.pipe(B(nn),B(t=>oc(t.params)),E(t=>({node_id:t.node_id,...t.params.params}))))}get contexts(){return[]}get eventing(){return[]}get topics(){return[]}get authentication(){const t=this.getCredential();if(!t.token)throw new Q("Credential token is undefined");return{jwt_token:t.token}}async connect(){await Ge(this.initialized$),await this.transport.connect(),await Ge(this.authenticated$.pipe(S(this.destroyed$),B(Boolean),Me(1),ar({first:15e3})))}async handleAuthenticationError(t){X.error("Authentication error:",t);const e=t instanceof _t&&(t.code===wo||t.code===So||t.code===Co),i=await Ge(this.authorizationState$.pipe(Me(1)))!==void 0;if(e&&i){X.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");try{await this.cleanupStoredConnectionParams()}catch(r){X.error("Failed to cleanup stored connection params:",r)}finally{this.transport.reconnect()}}else this._errors$.next(t)}async cleanupStoredConnectionParams(){await this.transport.setProtocol(void 0),await this.updateAuthorizationStateInStorage(void 0),this._authorization$.next(void 0)}async updateAuthState(t){try{await this.storage.setItem(this.authorizationStateKey,t)}catch(e){X.error("Failed to update authorization state in storage:",e),this._errors$.next(new Yn(e))}}async reauthenticate(t,e,i){var r,n;X.debug("[Session] Re-authenticating session");try{let s=e;if(!s&&((r=this.dpopManager)!=null&&r.initialized))try{s=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"})}catch(o){if(this.clientBound)throw o;X.warn("[Session] Failed to create DPoP proof for reauthenticate:",o)}const a=Wp({project:((n=this._authorization$.value)==null?void 0:n.project_id)??"",jwt_token:t,...s?{dpop_token:s}:{}});await Ba(Ie(this.transport.execute(a)).pipe(uo(),Me(1),ei(o=>{throw X.error("[Session] Re-authentication RPC failed:",o),o}))),i!=null&&i.clientBound&&(this._wasClientBound=!0),X.debug("[Session] Re-authentication successful, updating stored auth state")}catch(s){throw X.error("[Session] Re-authentication failed:",s),this._errors$.next(new Yn(s)),s}}async authenticate(){var o,c;X.debug("[Session] Starting authentication process");const t=await Ge(Ha({protocol:this.transport.protocol$,authorization_state:this.authorizationState$}).pipe(Me(1)));X.debug(`[Session] Persisted params:
|
|
73
|
-
`,{protocol:t.protocol,authStateLength:(o=t.authorization_state)==null?void 0:o.length});const e=t.authorization_state&&t.protocol,i=this.getCredential().token,r=e&&i;let n;if(r?X.debug("[Session] Reconnecting with stored jwt_token + authorization_state"):this.onBeforeReconnect&&this.clientBound&&(X.debug("[Session] Refreshing credentials before fresh connect"),await this.onBeforeReconnect()),(!r||this.clientBound)&&((c=this.dpopManager)!=null&&c.initialized))try{n=await this.dpopManager.createRpcProof({method:"signalwire.connect"})}catch(u){if(this.clientBound)throw u;X.warn("[Session] Failed to create DPoP proof for connect, proceeding without:",u)}const s=jp({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,...n?{dpop_token:n}:{},...r?{authorization_state:t.authorization_state,protocol:t.protocol}:{}}),a=await Ba(Ie(this.transport.execute(s)).pipe(uo(),E(u=>u.result),B(Lf),Se(()=>{X.debug("[Session] Response passed filter, processing authentication result")}),Me(1),ei(u=>{throw X.error("[Session] Authentication RPC failed:",u),u})));X.debug("[Session] Processing authentication result:",{hasProtocol:!!a.protocol,hasAuthorization:!!a.authorization,hasIceServers:!!a.ice_servers}),a.protocol&&await this.transport.setProtocol(a.protocol),this._authorization$.next(a.authorization),this._iceServers$.next(a.ice_servers??[]),this._authState$.next({kind:"authenticated"}),X.debug("[Session] Authentication completed successfully")}async disconnect(){this.transport.disconnect(),this._authState$.next({kind:"unauthenticated"}),await this.cleanupStoredConnectionParams()}async createInboundCall(t){const e=await this.createCall({nodeId:t.node_id,callId:t.callID,initOffer:t.sdp,toName:t.callee_id_name,to:t.callee_id_number,fromName:t.caller_id_name,from:t.caller_id_number,displayDirection:t.display_direction,userVariables:t.userVariables});this._calls$.next({[`${e.id}`]:e,...this._calls$.value})}async handleVertoAttach(t){const{callID:e}=t;if(e in this._calls$.value){X.debug(`[Session] Verto attach for existing call ${e}, deferring to per-call handler`);return}const i=await this.attachManager.consumePendingAttachment(e);X.debug(`[Session] Creating reattached call for callID: ${e}`);const r=await this.createCall({nodeId:t.node_id,callId:e,toName:t.callee_id_name,to:t.callee_id_number,fromName:t.caller_id_name,from:t.caller_id_number,reattach:!0,...i});this._calls$.next({[`${r.id}`]:r,...this._calls$.value})}async createOutboundCall(t,e={}){const i=t instanceof hc?t.defaultChannel:t;let r;try{return r=await this.createCall({to:i,...e}),await Ge(or(r.selfId$.pipe(B(n=>!!n),Me(1),ar(this.callCreateTimeout)),r.errors$.pipe(Me(1),Ke(n=>td(()=>n.error))))),this._calls$.next({[`${r.id}`]:r,...this._calls$.value}),r}catch(n){X.error("[Session] Error creating outbound call:",n),r==null||r.destroy();const s=new io(n instanceof Va?"Call create timeout":"Call creation failed",n,"outbound");throw this._errors$.next(s),s}}async createCall(t={}){try{const e=Uf(t);let i;try{if(!this._directory)throw new Q("Directory not initialized");const n=await this._directory.findAddressIdByURI(e);if(!n)throw new Q(`Address name: ${e} not found`);if(i=this._directory.get(n),!i)throw new Q(`Address ID: ${n} not found`)}catch{X.warn(`[Session] Directory lookup failed for ${e}, proceeding with raw URI`)}const r=this.callFactory.createCall(i,{...t});return this.subscribeTo(r.status$.pipe(B(n=>n==="destroyed"),Me(1)),()=>{const{[`${r.id}`]:n,...s}=this._calls$.value;this._calls$.next(s)}),r}catch(e){throw X.error("[Session] Error creating call session:",e),new io("Call create error",e,t.initOffer?"inbound":"outbound")}}destroy(){for(const t of Object.values(this._calls$.value))t.hangup();super.destroy()}},Bf=class{constructor(t){this.clientSessionManager=t}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(t,e){return this.clientSessionManager.execute(t,e)}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 zf=t=>typeof t=="string",hs=W();var Vf=class extends lc{constructor(t,e){super(`/api/fabric/conversations/${t}/messages`,"page_size=100",e),this.groupId=t}},Hf=class extends uc{constructor(t,e,i,r){super(new Vf(t,i),e,r)}},jf=class{constructor(t,e,i,r){this.clientSession=t,this.http=e,this.getUserAddressId=i,this.onError=r,this.groupIds=new Map}async join(t){const e=this.getUserAddressId();try{const i=await this.http.request({...Jr,url:"/api/fabric/conversations/join",body:JSON.stringify({from_fabric_address_id:e,fabric_address_ids:[t,e]})});if(i.ok&&i.body){const r=JSON.parse(i.body);if(zf(r.group_id))return this.groupIds.set(t,r.group_id),r.group_id}throw new no("Join Failed - Unexpected response")}catch(i){throw hs.error("[ConversationsManager] Failed to join conversation:",i),i}}async getConversationMessageCollection(t){const e=this.groupIds.get(t)??await this.join(t);return Promise.resolve(new Hf(e,this.clientSession.signalingEvent$.pipe(fe($o,"params"),Se(i=>hs.debug("[ConversationsManager ] Conversation Event:",i)),E(i=>({...i}))),this.http,this.onError))}async sendText(t,e){const i=this.groupIds.get(e)??await this.join(e),r=this.getUserAddressId();try{if((await this.http.request({...Jr,url:"/api/fabric/messages",body:JSON.stringify({group_id:i,from_fabric_address_id:r,text:t})})).ok)return;throw new no("Send Text Failed - Unexpected response")}catch(n){throw hs.error("[ConversationsManager] Failed to send text message:",n),n}}};const st=W();function Wf(t){return t.expires_at?t.expires_at:t.expires_in?Math.floor(Date.now()/1e3)+t.expires_in:(st.warn("[DeviceToken] Could not determine token expiry, using default"),Math.floor(Date.now()/1e3)+lr)}function pc(t){return t.expires_in?t.expires_in:t.expires_at?Math.max(t.expires_at-Math.floor(Date.now()/1e3),1):lr}var Gf=class extends ie{constructor(t,e,i,r){super(),this.dpopManager=t,this.http=e,this.errorHandler=i,this.getCredential=r,this._currentToken$=this.createBehaviorSubject(null),this._refreshInProgress=!1,this._effectiveExpireIn=lr,this.subscribeTo(this._currentToken$.pipe(B(Boolean),Ke(n=>{const s=Wf(n),a=Math.max(s*1e3-Date.now()-Ah,1e3);return st.debug(`[DeviceToken] Scheduling Client Bound SAT refresh in ${a}ms`),ki(a)})),()=>{this.executeRefresh()})}get effectiveExpireIn(){return this._effectiveExpireIn}async activate(t,e,i){var n;const{satClaims:r}=t;if(!((n=r==null?void 0:r.scope)!=null&&n.includes(Ch))){st.debug("[DeviceToken] No sat:refresh scope, skipping Client Bound SAT activation");return}this._session=e,this._updateCredential=i;try{const s=await this.obtainToken();!s.expires_at&&!s.expires_in&&r.expires_at&&(s.expires_at=r.expires_at),this._effectiveExpireIn=pc(s);const a=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"});await e.reauthenticate(s.token,a,{clientBound:!0}),i({token:s.token}),st.info("[DeviceToken] Client Bound SAT activated successfully"),this._currentToken$.next(s)}catch(s){st.error("[DeviceToken] Failed to activate Client Bound SAT:",s),this.errorHandler(new Kr(s,"Failed to activate Client Bound SAT"));const a=this.getCredential(),o=r.expires_at??(a.expiry_at?a.expiry_at/1e3:Date.now()/1e3+lr/1e3);this._currentToken$.next({token:a.token??"",expires_at:o})}}async obtainToken(){const t=await this.dpopManager.createHttpProof({method:"POST",uri:vo}),e=await this.http.request({url:vo,...Jr,body:JSON.stringify({dpop_token:t,expire_in:lr})});if(!e.ok||!e.body)throw new oo(`Failed to obtain device token: ${e.status} ${e.statusText}`);const i=JSON.parse(e.body);if(!i.token)throw new oo("Device token response missing token field");return i}async refreshToken(t,e,i){st.debug("[DeviceToken] Refreshing Client Bound SAT");const r=await this.dpopManager.createHttpProof({method:"POST",uri:bo,accessToken:e}),n=await this.http.request({url:bo,...Jr,body:JSON.stringify({dpop_token:r,expire_in:this._effectiveExpireIn})});if(!n.ok||!n.body)throw new ii(`Failed to refresh device token: ${n.status} ${n.statusText}`);const s=JSON.parse(n.body);if(!s.token)throw new ii("Device token refresh response missing token field");!s.expires_at&&!s.expires_in&&(s.expires_in=this._effectiveExpireIn),this._effectiveExpireIn=pc(s);const a=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"});return await t.reauthenticate(s.token,a),i({token:s.token}),st.info("[DeviceToken] Client Bound SAT refreshed successfully"),s}async executeRefresh(){if(this._refreshInProgress){st.debug("[DeviceToken] Refresh already in progress, skipping");return}const t=this._session,e=this._updateCredential;if(!t||!e){st.warn("[DeviceToken] Cannot refresh: session or updateCredential not set");return}if(!t.authenticated){st.debug("[DeviceToken] Session not authenticated, deferring refresh");return}this._refreshInProgress=!0;try{const i=this.getCredential().token;if(!i)throw new ii("No current token available for refresh");const r=await this.retryRefresh(t,i,e);this._currentToken$.next(r)}catch(i){st.error("[DeviceToken] Automatic Client Bound SAT refresh failed:",i),this.errorHandler(i instanceof ii?i:new ii("Automatic token refresh failed",i))}finally{this._refreshInProgress=!1}}async retryRefresh(t,e,i){let r;for(let n=0;n<mo;n++)try{return await this.refreshToken(t,e,i)}catch(s){if(r=s,n<mo-1){const a=Th*Math.pow(2,n);st.warn(`[DeviceToken] Refresh attempt ${n+1} failed, retrying in ${a}ms`),await new Promise(o=>setTimeout(o,a))}}throw r instanceof Error?r:new ii("All refresh retries exhausted",r)}destroy(){super.destroy()}};const ps=W(),qf=1e3;function Xf(){try{if(typeof navigator<"u"&&navigator.userAgent)return navigator.userAgent}catch{}return"unknown"}var Yf=class extends ie{constructor(t){super(),this._events=[],this._calls=[],this._deviceChanges=[],this._eventRecorded$=this.createSubject(),this._sdkVersion=t.sdkVersion,this._maxEvents=t.maxEvents??qf,ps.debug("DiagnosticsCollector initialized",{sdkVersion:this._sdkVersion,maxEvents:this._maxEvents})}get eventRecorded$(){return this._eventRecorded$.asObservable()}record(t,e,i){const r={timestamp:Date.now(),category:t,event:e,...i!==void 0?{details:i}:{}};this._events=this._appendToBuffer(this._events,r),this._eventRecorded$.next(r)}recordDeviceChange(t,e){const i={timestamp:Date.now(),category:"device",event:t,...e!==void 0?{details:e}:{}};this._deviceChanges=this._appendToBuffer(this._deviceChanges,i),this._events=this._appendToBuffer(this._events,i),this._eventRecorded$.next(i)}recordCallSummary(t){this._calls=this._appendCallToBuffer(this._calls,t),this.record("call","call_summary",{callId:t.callId,direction:t.direction,duration:t.duration,finalStatus:t.finalStatus})}export(){return{sdkVersion:this._sdkVersion,userAgent:Xf(),exportedAt:Date.now(),events:[...this._events],calls:[...this._calls],deviceChanges:[...this._deviceChanges]}}clear(){this._events=[],this._calls=[],this._deviceChanges=[],ps.debug("DiagnosticsCollector buffers cleared")}destroy(){ps.debug("DiagnosticsCollector destroyed"),super.destroy()}_appendToBuffer(t,e){const i=[...t,e];return i.length>this._maxEvents?i.slice(i.length-this._maxEvents):i}_appendCallToBuffer(t,e){const i=[...t,e];return i.length>this._maxEvents?i.slice(i.length-this._maxEvents):i}};const gc=t=>((t==null?void 0:t.length)??0)===0,Kf=t=>{t.pipe(Me(1)).subscribe()},Zf=W();var Qf=class extends lc{constructor(t){super("/api/fabric/addresses","sort_by=name&sort_order=asc",t)}async name(t){const e=await this.http.request({...$n,url:`${this.endpoint}?name=${encodeURIComponent(t)}`});if(e.ok&&e.body){const i=JSON.parse(e.body);if(!gc(i.data))return i.data[0]}Zf.error("Failed to fetch addresses")}},Jf=class extends uc{constructor(t,e,i){super(new Qf(e),t,i)}},$f=class extends ie{constructor(t,e,i,r){super(),this.http=t,this.conversationManager=i,this.onError=r,this.addNewAddress=n=>{var o;const s=new hc(n,this.conversationManager,this),a=(o=this._statesCollection.get$(n))==null?void 0:o.pipe(ue(),E(c=>(s.upnext(c),s)));a&&(Kf(a),this._observableRegistry.set(n,a)),this._addressesInstances.set(n,s)},this._addresses$=this.createBehaviorSubject([]),this._addressesInstances=new Map,this._observableRegistry=new Map,this._statesCollection=new Jf(e.signalingEvent$.pipe(fe(ec,"params"),E(n=>({}))),this.http,this.onError),this.initSubscriptions()}get loading(){return this._statesCollection.loading}initSubscriptions(){this.subscribeTo(this._statesCollection.updated$,()=>{const t=Array.from(this._addressesInstances.values().map(i=>i.id)),e=this._statesCollection.values.filter(i=>!t.includes(i.id));gc(e)||(e.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$(t){return this._observableRegistry.has(t)||this.addNewAddress(t),this._observableRegistry.get(t)}get(t){return this._addressesInstances.get(t)}async findAddressIdByURI(t){var i;let e=(i=this._addressesInstances.values().find(r=>r.name===t))==null?void 0:i.id;if(!e){const r=await this._statesCollection.find$("name",t);if(r){const n=await Ge(r);this.addNewAddress(n.id),e=n.id}}return e}};const fc=W();var ev=(mt=class extends ie{constructor(e,i,r,n={}){super(),this.WebSocketConstructor=e,this.endpoint=i,this.outgoingMessages$=r,this.messageQueue=[],this.shouldReconnect=!1,this.boundHandleOpen=()=>this.handleOpen(),this.boundHandleClose=s=>this.handleClose(s),this.boundHandleError=()=>this.handleError(),this.boundHandleMessage=s=>this.handleMessage(s),this._status$=this.createBehaviorSubject("disconnected"),this._incomingMessages$=this.createSubject(),this._errors$=this.createReplaySubject(1),this.reconnectDelayMin=n.reconnectDelayMin??mt.DEFAULT_RECONNECT_DELAY_MIN_MS,this.reconnectDelayMax=n.reconnectDelayMax??mt.DEFAULT_RECONNECT_DELAY_MAX_MS,this.connectionTimeout=n.connectionTimeout??mt.DEFAULT_CONNECTION_TIMEOUT_MS,this.currentReconnectDelay=this.reconnectDelayMin,this.subscriptions.push(this.outgoingMessages$.subscribe(s=>{this.send(s)}))}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 e=this._status$.value;e==="connected"||e==="connecting"||e==="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(e){var i;this._status$.value==="connected"&&((i=this.socket)==null?void 0:i.readyState)===1?(fc.wsTraffic({type:"send",raw:e}),this.socket.send(e)):this.messageQueue.push(e)}createWebSocket(){try{this.closeExistingSocket(),this.socket=new this.WebSocketConstructor(this.endpoint),this.setupWebSocketListeners(),this.startConnectionTimeout()}catch(e){const i=e instanceof Error?e:new Di("Failed to create WebSocket");this._errors$.next(i),this.handleConnectionError()}}closeExistingSocket(){if(!this.socket)return;const e=this.socket;this.socket=void 0,this.removeWebSocketListeners(e);try{e.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(e){try{e.removeEventListener("open",this.boundHandleOpen),e.removeEventListener("close",this.boundHandleClose),e.removeEventListener("error",this.boundHandleError),e.removeEventListener("message",this.boundHandleMessage)}catch{}}handleOpen(){this.clearConnectionTimeout(),this._status$.next("connected"),this.currentReconnectDelay=this.reconnectDelayMin,this.flushMessageQueue()}handleClose(e){this.clearConnectionTimeout(),this.shouldReconnect?(this._status$.next("reconnecting"),this.scheduleReconnection()):this._status$.next("disconnected")}handleError(){const e=new $a("WebSocket connection error");this._errors$.next(e),this.handleConnectionError()}handleMessage(e){fc.wsTraffic({type:"recv",raw:e.data}),this._incomingMessages$.next(e)}handleConnectionError(){this.reconnect()}scheduleReconnection(){this.clearReconnectTimer();const e=this.currentReconnectDelay*(.5+Math.random()*.5);this.reconnectTimer=setTimeout(()=>{this.shouldReconnect&&(this._status$.next("connecting"),this.createWebSocket(),this.increaseReconnectDelay())},e)}increaseReconnectDelay(){this.currentReconnectDelay=Math.min(this.currentReconnectDelay*2,this.reconnectDelayMax)}startConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeoutTimer=setTimeout(()=>{if(this._status$.value==="connecting"){const e=new Ld("WebSocket connection timeout");this._errors$.next(e),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 e;for(;this.messageQueue.length>0&&((e=this.socket)==null?void 0:e.readyState)===1;){const i=this.messageQueue.shift();i!==void 0&&this.socket.send(i)}}},mt.DEFAULT_RECONNECT_DELAY_MIN_MS=1e3,mt.DEFAULT_RECONNECT_DELAY_MAX_MS=3e4,mt.DEFAULT_CONNECTION_TIMEOUT_MS=1e4,mt);function tv(t){return ns(t)&&t.method==="signalwire.ping"}const Pe=W();var iv=class extends ie{constructor(t,e,i,r,n){super(),this.storage=t,this.protocolKey=e,this.onError=n,this.protocol$=this.createReplaySubject(1),this.isConnecting=!1,this.isConnected=!1,this.ackEvent=()=>Se(s=>{if(as(s))try{Pe.debug("[Transport] Sending event ack",{eventId:s.id}),this.send(ig(s.id))}catch(a){Pe.error("[Transport] Failed to send event acknowledgment:",a)}}),this.replySignalwirePing=()=>B(s=>{if(tv(s)){try{Pe.debug("[Transport] Received ping, sending pong",{pingId:s.id}),this.send(Gp(s.id))}catch(a){Pe.error("[Transport] Failed to send ping response:",a)}return!1}return!0}),this.discardStaleEvents=()=>B(s=>{if(!as(s))return!0;const a=s.params.event_channel;if(!a)return!0;const o=this._currentProtocol;if(!o)return!0;if(!a.includes(o)){const c=s.params.event_type;return Pe.warn(`[Transport] Discarding stale event: ${c} (event_channel does not match current protocol)`),!1}return!0}),this._outgoingMessages$=this.createSubject(),this._webSocketConnections=new ev(i,r,this._outgoingMessages$.asObservable(),{connectionTimeout:g.instance.connectionTimeout,reconnectDelayMin:g.instance.reconnectDelayMin,reconnectDelayMax:g.instance.reconnectDelayMax}),this.subscribeTo(this._webSocketConnections.errors$,s=>{var a;(a=this.onError)==null||a.call(this,s)}),this.initialized$=$t(()=>Ie(this._init())).pipe(et(1),S(this.destroyed$)),this._jsonRPCMessage$=this._webSocketConnections.incomingMessages$.pipe(E(s=>{var a;try{return JSON.parse(s.data)}catch(o){return Pe.error("[Transport] Failed to parse incoming message:",o),(a=this.onError)==null||a.call(this,new Hd(o)),null}}),B(s=>s!==null&&(ss(s)||ns(s))),ei(s=>{var a;return Pe.error("[Transport] Message processing error:",s),(a=this.onError)==null||a.call(this,s instanceof Error?s:new Error(String(s),{cause:s})),Jt}),Tt(),S(this.destroyed$)),this._jsonRPCResponse$=this._jsonRPCMessage$.pipe(B(ss)),this._incomingEvent$=this._jsonRPCMessage$.pipe(this.ackEvent(),this.replySignalwirePing(),B(s=>!ss(s)),this.discardStaleEvents(),Tt(),S(this.destroyed$))}async setProtocol(t){this._currentProtocol=t,this.protocol$.next(t),await this._updateProtocolInStorage(t)}get incomingEvent$(){return this._incomingEvent$}get connectionStatus$(){return this._webSocketConnections.status$}async connect(){return this.isConnecting||this.isConnected?(Pe.warn("[Transport] Already connecting or connected"),Promise.resolve()):new Promise((t,e)=>{this.isConnecting=!0,this.subscribeTo(this.initialized$,()=>{this._webSocketConnections.connect();const i=this._webSocketConnections.status$.pipe(B(r=>r==="connected"||r==="disconnected"),Me(1),ar(1e4)).subscribe({next:r=>{var n;if(r==="connected")this.isConnecting=!1,this.isConnected=!0,Pe.debug("[Transport] Connection established"),t();else{this.isConnecting=!1;const s=new eo("Failed to connect");Pe.error("[Transport] Connection failed"),(n=this.onError)==null||n.call(this,s),e(s)}},error:r=>{var n;this.isConnecting=!1,Pe.error("[Transport] Connection error:",r),(n=this.onError)==null||n.call(this,r instanceof Error?r:new Error(String(r),{cause:r})),e(r)}});this.subscriptions.push(i),this.subscribeTo(this._webSocketConnections.status$.pipe(B(r=>r==="disconnected")),()=>{Pe.debug("[Transport] Disconnected"),this.isConnected=!1})})})}reconnect(){this._webSocketConnections.reconnect()}async execute(t,e){return this.send(t),new Ff(t,this._jsonRPCResponse$,e).promise}send(t){const e=JSON.stringify(t);this._outgoingMessages$.next(e)}disconnect(){Pe.debug("[Transport] Disconnecting"),this.isConnected=!1,this.isConnecting=!1,this._webSocketConnections.disconnect()}destroy(){Pe.debug("[Transport] Destroying"),this.disconnect(),super.destroy(),this._webSocketConnections.destroy()}async _loadProtocolFromStorage(){try{const t=await this.storage.getItem(this.protocolKey);this._currentProtocol=t??void 0,this.protocol$.next(t??void 0)}catch(t){throw Pe.error("Failed to retrieve protocol from storage:",t),t}}async _updateProtocolInStorage(t){if(!t){try{await this.storage.removeItem(this.protocolKey)}catch(e){throw Pe.error("Failed to remove protocol from storage:",e),e}return}try{const e=await this.storage.getItem(this.protocolKey);(!e||e!==t)&&await this.storage.setItem(this.protocolKey,t)}catch(e){throw Pe.error("Failed to update protocol in storage:",e),e}}async _init(){return await this._loadProtocolFromStorage(),!0}};const Y=W(),rv=t=>{if(typeof t=="string"){const e=t.indexOf("?");if(e!==-1){const i=t.substring(e+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 vc=class extends ie{constructor(t,e={}){super(),this.preferences=new bp,this._user$=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 Sp,this._credentialProvider=t,this._options={...g.instance.defaultSignalWireOptions,...e},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&&Xd(this._options.logger),this._options.logLevel&&Kd(this._options.logLevel),this._options.debug&&Yd(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=>{Y.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=>{Y.error("[SignalWire] Initialization error:",i),this._errors$.next(i instanceof Error?i:new Error(String(i),{cause:i}))})}async initDPoP(){var t;if((t=this._dpopManager)!=null&&t.initialized)return this._dpopManager.fingerprint;try{this._dpopManager=new kp;const e=await this._dpopManager.init();return Y.debug("[SignalWire] DPoP initialized, fingerprint available"),e}catch(e){Y.warn("[SignalWire] DPoP initialization failed, proceeding without DPoP:",e),this._dpopManager=void 0;return}}async resolveCredentials(){const t=await this.initDPoP();if(this._credentialProvider)return this.validateCredentials(this._credentialProvider,void 0,t);for(const e of this._deps.persistSession?["local","session"]:["session"])try{const i=await this._deps.storage.getItem("sw:cached_credential",e);if(i!=null&&i.token)return Y.debug(`[SignalWire] Using cached credential from ${e}Storage`),await this.validateCredentials(void 0,i)}catch{}throw new ti("No credential provider and no cached session. Provide a CredentialProvider or enable persistSession with a prior login.")}async validateCredentials(t,e,i){var s;const r=i??((s=this._dpopManager)!=null&&s.initialized?this._dpopManager.fingerprint:void 0),n=e??(t?await t.authenticate(r?{fingerprint:r}:void 0):void 0);if(!n)throw new ti("No credentials available.");if(n.token)try{const a=th(n.token,{header:!0});this._deps.ch=a.ch}catch(a){throw Y.error("[SignalWire] Invalid JWT token provided in credentials:",a),new ti("Invalid JWT token provided in credentials.",{cause:a})}if(!n.token&&!n.authorizationState)throw Y.error("[SignalWire] No valid authentication credentials provided."),new ti("No valid authentication credentials provided.");if(!this._deps.persistSession&&n.expiry_at&&n.expiry_at<Date.now())throw Y.error("[SignalWire] Provided credentials have expired."),new ti("Provided credentials have expired.");if(n.expiry_at&&(t!=null&&t.refresh)&&this.scheduleCredentialRefresh(t,n.expiry_at),this._deps.credential=n,this.persistCredential(n),this.isConnected&&this._clientSession.authenticated&&n.token)try{await this._clientSession.reauthenticate(n.token),Y.info("[SignalWire] Session refreshed with new credentials.")}catch(a){Y.error("[SignalWire] Failed to refresh session with new credentials:",a),this._errors$.next(a instanceof Error?a:new Error(String(a),{cause:a}))}}scheduleCredentialRefresh(t,e,i=0){this._refreshTimerId!==void 0&&clearTimeout(this._refreshTimerId);const r=i===0?Math.max(e-Date.now()-xh,1e3):Math.min(Eh*Math.pow(2,i)*(.5+Math.random()*.5),kh);this._refreshTimerId=setTimeout(async()=>{try{if(!t.refresh)throw new ti("Credential provider does not support refresh");const n=await t.refresh();this._deps.credential=n,this.persistCredential(n),Y.info("[SignalWire] Credentials refreshed successfully."),n.expiry_at&&this.scheduleCredentialRefresh(t,n.expiry_at,0)}catch(n){const s=i+1;Y.error(`[SignalWire] Credential refresh failed (attempt ${s}/${yo}):`,n),this._errors$.next(n instanceof Error?n:new Error(String(n),{cause:n})),s<yo?this.scheduleCredentialRefresh(t,e,s):(Y.error("[SignalWire] Credential refresh exhausted all retries. Disconnecting."),this._errors$.next(new ii("Credential refresh failed after max retries")),this.disconnect())}},r)}persistCredential(t){t.token&&(this._deps.storage.setItem("sw:cached_credential",t),this._deps.persistSession&&this._deps.storage.setItem("sw:cached_credential",t,"local"))}async init(){if(this._user$.next(new Vp(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(t){Y.error("[SignalWire] Registration failed:",t),this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t}))}this.handleAttachments()}async handleAttachments(){if(!this._attachManager){Y.error("[SignalWire] AttachManager not initialized");return}if(this._options.reconnectAttachedCalls)try{await this._attachManager.reattachCalls()}catch(t){Y.error("[SignalWire] Failed to reattach calls:",t),this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t}))}}async connect(){var r,n,s;await this.teardownTransportAndSession();try{const a=this._user$.value;if(!a)throw new Di("User not initialized before connect");if(!await Ge(a.fetched$))throw new Di("Failed to fetch user information - fetched$ emitted false");this._deps.user=a}catch(a){throw Y.error(`[SignalWire] Failed to fetch user information: ${a instanceof Error?a.message:"Unknown error"}. This usually means the user token is invalid or expired.`),new Di("Error fetching user information",{cause:a})}const t=a=>{this._errors$.next(a)};this._transport=new iv(this._deps.storage,this._deps.protocolKey,this._deps.WebSocket,g.instance.relayHost??this._deps.relayHost,t),this._attachManager=new rg(this._deps.storage,this._deps.deviceController,g.instance.reconnectCallsTimeout,this._deps.attachedCallsKey),this._clientSession=new Nf(()=>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 Bf(this._clientSession),this._clientSession.onBeforeReconnect=async()=>{var a;if(this._credentialProvider)try{const o=(a=this._dpopManager)!=null&&a.initialized?this._dpopManager.fingerprint:void 0;Y.debug("[SignalWire] Credential expired, refreshing before reconnect");const c=await this._credentialProvider.authenticate(o?{fingerprint:o}:void 0);this._deps.credential=c,Y.debug("[SignalWire] Credential refreshed successfully for reconnect")}catch(o){throw Y.error("[SignalWire] Failed to refresh credentials for reconnect:",o),this._errors$.next(o instanceof Error?o:new Error(String(o),{cause:o})),o}},this.subscribeTo(this._clientSession.errors$,a=>{this._errors$.next(a)}),await this._clientSession.connect(),(n=this._dpopManager)!=null&&n.initialized&&(this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0,Y.debug("[SignalWire] Developer refresh disabled — Client Bound SAT activation starting")),this._deviceTokenManager=new Gf(this._dpopManager,this._deps.http,a=>this._errors$.next(a),()=>this._deps.credential),await this._deviceTokenManager.activate(this._deps.user,this._clientSession,a=>{this._deps.credential={...this._deps.credential,...a}})),this.subscribeTo(this._clientSession.authenticated$.pipe(Wr(1),B(Boolean)),async()=>{try{this._deviceTokenManager&&(await this._deviceTokenManager.activate(this._deps.user,this._clientSession,a=>{this._deps.credential={...this._deps.credential,...a}}),Y.debug("[SignalWire] Client Bound SAT re-activated after reconnect"))}catch(a){Y.error("[SignalWire] Client Bound SAT re-activation failed (non-fatal):",a),this._errors$.next(a instanceof Error?a:new Error(String(a),{cause:a}))}try{Y.debug("[SignalWire] Re-registering user after reconnect"),await this.register(),Y.debug("[SignalWire] User re-registered successfully after reconnect")}catch(a){Y.error("[SignalWire] Re-registration failed after reconnect:",a),this._errors$.next(a instanceof Error?a:new Error(String(a),{cause:a}))}});const e=new jf(this._clientSession,this._deps.http,()=>this._deps.getUserFromAddressId(),t),i=new $f(this._deps.http,this._clientSession,e,t);this._directory$.next(i),this._clientSession.setDirectory(i),this._isConnected$.next(!0),(s=this._diagnosticsCollector)==null||s.record("connection","connected"),this.subscribeTo(this._clientSession.authenticated$.pipe(Wr(2),B(Boolean)),()=>{var a;(a=this._diagnosticsCollector)==null||a.record("connection","reconnected")})}get user$(){return this.deferEmission(this._user$.asObservable())}get user(){return this._user$.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(Ke(t=>t?this._clientSession.authenticated$:At(!1))))}get errors$(){return this.deferEmission(this._errors$.asObservable())}get platformCapabilities(){return this._platformCapabilities??(this._platformCapabilities=Lo(this._options.webRTCApiProvider)),this._platformCapabilities}get deviceRecovered$(){return this.deferEmission(this._deviceController.deviceRecovered$)}exportDiagnostics(){const t={audioInput:this.audioInputDevices,audioOutput:this.audioOutputDevices,videoInput:this.videoInputDevices},e={sdkVersion:"unknown",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown",capabilities:this.platformCapabilities,events:[],calls:[],deviceChanges:[],devices:t};if(!this._diagnosticsCollector)return e;const i=this._diagnosticsCollector.export();return{...e,sdkVersion:i.sdkVersion,userAgent:i.userAgent,events:i.events,calls:i.calls,deviceChanges:i.deviceChanges,devices:t}}initResilienceSubsystems(){try{this._platformCapabilities=Lo(this._options.webRTCApiProvider)}catch(t){Y.warn("[SignalWire] Failed to detect platform capabilities:",t)}try{this._networkMonitor=new xp}catch(t){Y.warn("[SignalWire] Failed to initialize NetworkMonitor:",t)}try{this._visibilityController=new Bp,this.subscribeTo(this._visibilityController.visibilityChange$.pipe(B(t=>t.to==="visible"&&g.instance.refreshDevicesOnVisible)),()=>{Y.debug("[SignalWire] Page visible, re-enumerating devices");try{this._deviceController.disableDeviceMonitoring(),this._deviceController.enableDeviceMonitoring()}catch{}})}catch(t){Y.warn("[SignalWire] Failed to initialize VisibilityController:",t)}try{this._diagnosticsCollector=new Yf({sdkVersion:"3.30.0"})}catch(t){Y.warn("[SignalWire] Failed to initialize DiagnosticsCollector:",t)}}async disconnect(){var t;this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0),(t=this._diagnosticsCollector)==null||t.record("connection","disconnected"),await this.teardownTransportAndSession(),this._isConnected$.next(!1)}async teardownTransportAndSession(){const t=this._clientSession,e=this._transport;if(t){try{await t.disconnect()}catch(i){Y.warn("[SignalWire] Error disconnecting previous session:",i)}t.destroy()}e&&e.destroy(),this._clientSession=void 0,this._publicSession=void 0,this._transport=void 0,this._attachManager=void 0}async waitAuthentication(){await Ge(this.ready$.pipe(B(t=>t===!0)))}async register(){try{await this.waitAuthentication(),await this._transport.execute(is({method:"subscriber.online",params:{}})),this._isRegistered$.next(!0);return}catch(t){if(!this._deps.credential.token)throw this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t})),t;Y.debug("[SignalWire] Failed to register user, trying reauthentication...");try{await this._clientSession.reauthenticate(this._deps.credential.token),Y.debug("[SignalWire] Reauthentication successful, retrying register()"),await this._transport.execute(is({method:"subscriber.online",params:{}})),this._isRegistered$.next(!0)}catch(e){Y.error("[SignalWire] Reauthentication failed during register():",e);const i=new ti("Failed to register user, and reauthentication attempt also failed. Please check your credentials.",{cause:e instanceof Error?e:new Error(String(e),{cause:e})});throw this._errors$.next(i),i}}}async unregister(){try{await this._transport.execute(is({method:"subscriber.offline",params:{}})),this._isRegistered$.next(!1)}catch(t){throw Y.error("[SignalWire] Failed to unregister user:",t),this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t})),t}}async dial(t,e={}){const i={...g.instance.preferredMediaOptions,...rv(t),...e};return await this.waitAuthentication(),Y.debug("[SignalWire] Dialing with options:",i),this._clientSession.createOutboundCall(t,i)}async preflight(t,e){const i=this._clientSession.iceServers??g.instance.iceServers??[],r=this._isConnected$.value;return new Up(this._deviceController,i,r,0,async(n,s)=>this.dial(n,s),e).run(t)}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(t){return this._deviceController.deviceInfoToConstraints(t)}selectAudioInputDevice(t){this._deviceController.selectAudioInputDevice(t)}selectVideoInputDevice(t){this._deviceController.selectVideoInputDevice(t)}selectAudioOutputDevice(t){this._deviceController.selectAudioOutputDevice(t)}async applySelectedAudioOutputDevice(t){const e=this._deviceController.selectedAudioOutputDevice;if(!(e!=null&&e.deviceId))return!1;const i=t;if(typeof i.setSinkId!="function")return Y.warn("[SignalWire] setSinkId not supported on this element / browser"),!1;try{return await i.setSinkId(e.deviceId),!0}catch(r){return Y.warn("[SignalWire] Failed to apply audio output device:",r),!1}}enableDeviceMonitoring(){this._deviceController.enableDeviceMonitoring()}disableDeviceMonitoring(){this._deviceController.disableDeviceMonitoring()}async getDeviceCapabilities(t){return this._deviceController.getDeviceCapabilities(t)}async isValidDevice(t){return this._deviceController.isValidDevice(t)}setStorageManager(t){this._deviceController.setStorageManager(t)}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(t={audio:!0,video:!0}){const e={audio:t.audio??!1,video:t.video??!1};let i=!1,r=!1,n,s;try{const a=(await this._deps.webRTCApiProvider.mediaDevices.getUserMedia(e)).getTracks();for(const o of a){const c=o.getSettings();o.kind==="audio"?(i=!0,c.deviceId&&(n=this.audioInputDevices.find(u=>u.deviceId===c.deviceId))):o.kind==="video"&&(r=!0,c.deviceId&&(s=this.videoInputDevices.find(u=>u.deviceId===c.deviceId))),o.stop()}}catch(a){Y.warn("[SignalWire] Media permission request failed:",a)}if(await this._deviceController.enumerateDevices(),i&&n){const a=n.deviceId;n=this.audioInputDevices.find(o=>o.deviceId===a)??n}if(r&&s){const a=s.deviceId;s=this.videoInputDevices.find(o=>o.deviceId===a)??s}return i&&n&&!this.selectedAudioInputDevice&&this.selectAudioInputDevice(n),r&&s&&!this.selectedVideoInputDevice&&this.selectVideoInputDevice(s),{audio:i,video:r,selectedAudioDevice:n,selectedVideoDevice:s}}async resetToDefaults(){await this._deps.storage.clearAll();const t=g.instance;t.preferredAudioInput=null,t.preferredAudioOutput=null,t.preferredVideoInput=null,await this._deviceController.clearDeviceState()}destroy(){var t,e,i,r,n;this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0),(t=this._deviceTokenManager)==null||t.destroy(),(e=this._dpopManager)==null||e.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{(n=this._diagnosticsCollector)==null||n.destroy()}catch{}this._networkMonitor=void 0,this._visibilityController=void 0,this._diagnosticsCollector=void 0,super.destroy()}};const nv=W();var bc=class{constructor(t,e){this.host=t,this.embedToken=e}async fetchSAT(){const t=`https://${this.host}/api/fabric/embeds/tokens`,e=1e4,i=new AbortController,r=setTimeout(()=>i.abort(),e);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.embedToken}),signal:i.signal});if(clearTimeout(r),n.ok)return(await n.json()).token;throw new Fd(`Failed to fetch SAT using embed token: ${n.status} ${n.statusText}`)}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?new to(`Request timeout after ${e}ms`,{cause:n}):(nv.error("[EmbedCredentialProvider] Request failed:",n),n)}}async authenticate(){return{token:await this.fetchSAT(),expiry_at:Date.now()+3600*1e3}}async refresh(){return this.authenticate()}},mc=class{constructor(t){this.credentials=t}async authenticate(){return Promise.resolve(this.credentials)}};(()=>{if(typeof window<"u"){const t=new CustomEvent("signalwire:js:ready",{detail:{version:"3.30.0"}});window.dispatchEvent(t)}})();var sv=Object.defineProperty,av=Object.getOwnPropertyDescriptor,dr=(t,e,i,r)=>{for(var n=r>1?void 0:r?av(e,i):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(n=(r?a(e,i,n):a(n))||n);return r&&n&&sv(e,i,n),n};const ov=W();l.SwCallMedia=class extends Z{constructor(){super(...arguments),this.stream=null,this._remoteStreamValue=null,this._lastTrackSignature="",this._subscriptions=[]}connectedCallback(){super.connectedCallback(),!this.stream&&this.call&&this._setupDirectSubscriptions(),this.stream&&(this._remoteStreamValue=this.stream,this._lastTrackSignature=this._computeTrackSignature(this.stream))}updated(e){var i,r,n,s,a;if(super.updated(e),e.has("call")&&(this._cleanupDirectSubscriptions(),!this.stream&&this.call&&this._setupDirectSubscriptions()),e.has("stream")){this._cleanupDirectSubscriptions();const o=this.stream,c=this._computeTrackSignature(o);if(o!==this._remoteStreamValue||c!==this._lastTrackSignature){this._remoteStreamValue=o,this._lastTrackSignature=c;const u=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");u&&Lr(u,o)}}if(!this.stream&&!this.call&&e.has("_callState")){const o=((r=this._callState)==null?void 0:r.remoteStream)??null,c=this._computeTrackSignature(o);if(o!==this._remoteStreamValue||c!==this._lastTrackSignature){this._remoteStreamValue=o,this._lastTrackSignature=c;const u=(n=this.shadowRoot)==null?void 0:n.querySelector("video.mcu-video");u&&Lr(u,o)}}e.has("_devicesState")&&this._applySinkId(((a=(s=this._devicesState)==null?void 0:s.selectedAudioOutput)==null?void 0:a.deviceId)??"")}disconnectedCallback(){super.disconnectedCallback(),this._cleanupDirectSubscriptions(),this._cleanupResizeObserver(),this._cleanupVideoElement()}firstUpdated(){var i;const e=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");e&&bu(e).then(()=>{this.isConnected&&this._setupResizeObserver()})}_setupDirectSubscriptions(){this.call&&this._subscriptions.push(this.call.remoteStream$.subscribe(e=>{var n;const i=this._computeTrackSignature(e);if(e===this._remoteStreamValue&&i===this._lastTrackSignature)return;this._remoteStreamValue=e,this._lastTrackSignature=i,this.requestUpdate();const r=(n=this.shadowRoot)==null?void 0:n.querySelector("video.mcu-video");r&&Lr(r,e)}))}_computeTrackSignature(e){return e?e.getTracks().map(i=>`${i.kind}:${i.id}`).sort().join("|"):""}_cleanupDirectSubscriptions(){this._subscriptions.forEach(e=>e.unsubscribe()),this._subscriptions=[]}_applySinkId(e){var r;const i=(r=this.shadowRoot)==null?void 0:r.querySelector("video.mcu-video");i!=null&&i.setSinkId&&i.setSinkId(e).catch(n=>{ov.error("[SwCallMedia] Failed to set audio output device:",n)})}_setupResizeObserver(){var r,n;const e=(r=this.shadowRoot)==null?void 0:r.querySelector("video.mcu-video"),i=(n=this.shadowRoot)==null?void 0:n.querySelector(".padding-wrapper");!e||!i||(this._videoElement=e,this._paddingWrapper=i,this._resizeObserver=new ResizeObserver(fu(()=>this._recalculateDimensions(),50)),this._resizeObserver.observe(this),this._videoResizeHandler=()=>this._recalculateDimensions(),e.addEventListener("resize",this._videoResizeHandler),this._windowResizeHandler=()=>{requestAnimationFrame(()=>this._recalculateDimensions())},window.addEventListener("resize",this._windowResizeHandler),this._recalculateDimensions())}_recalculateDimensions(){const e=this._videoElement,i=this._paddingWrapper;if(!e||!i)return;if(!e.videoWidth||!e.videoHeight){i.style.width="100%",i.style.height="100%",i.style.paddingBottom="0",i.style.transform="none";return}const r=window.innerWidth,n=window.innerHeight,s=this.getBoundingClientRect(),a=s.width,o=s.height;if(a<=0||o<=0)return;const c=Math.min(1,(r-s.left)/a),u=Math.min(1,(n-s.top)/o),h=Math.min(c,u),p=a*h,f=o*h;if(p<=0||f<=0)return;const m=e.videoWidth/e.videoHeight,R=p/f;let y,I;m>R?(y=p,I=y/m):(I=f,y=I*m);const x=Math.max(0,s.left),v=Math.max(0,s.top),b=Math.min(r,s.right),w=Math.min(n,s.bottom),A=(x+b)/2,D=(v+w)/2,F=s.left+a/2,K=s.top+o/2,_=A-F,te=D-K;i.style.width=`${y}px`,i.style.height=`${I}px`,i.style.paddingBottom="0",i.style.transform=`translate(${_}px, ${te}px)`}_cleanupResizeObserver(){var i;this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=void 0);const e=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");e&&this._videoResizeHandler&&(e.removeEventListener("resize",this._videoResizeHandler),this._videoResizeHandler=void 0),this._windowResizeHandler&&(window.removeEventListener("resize",this._windowResizeHandler),this._windowResizeHandler=void 0)}_cleanupVideoElement(){var i;const e=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");e&&ca(e)}render(){return k`
|
|
72
|
+
`,(e=this.peerConnection.localDescription)==null?void 0:e.sdp)}handleICECandidateTimeout(){this.iceCandidateTimer&&this.removeTimer("iceCandidateTimer"),Ne.warn("[ICEGatheringController] ICE candidate timeout");const t=this.hasValidLocalDescriptionSDP;!t&&!this.relayOnly?this.restartICEGatheringWithRelayOnly():(Ne.debug("[ICEGatheringController] Using current SDP due to ICE candidate timeout"),this._iceCandidatesState.next({state:"timeout",validSDP:t}),this.stopGathering())}restartICEGatheringWithRelayOnly(){Ne.debug("[ICEGatheringController] Restarting ICE gathering with relay-only candidates"),this.relayOnly=!0,this.peerConnection.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:"relay"}),this.peerConnection.restartIce()}removeTimer(t){this[t]&&(clearTimeout(this[t]),this[t]=void 0)}clearAllTimers(){Ne.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(){Ne.debug("[ICEGatheringController] Destroying ICEGatheringController"),this.clearAllTimers(),this.removeEventListeners(),super.destroy()}};const cs=W();var Ig=class extends ie{constructor(t={}){super(),this._inputSource=null,this._inputStream=null,this._lastSpokeAt=0,this._gain$=this.createBehaviorSubject(1),this._pttMultiplier=1,this._audioContext=(t.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=t.speakingThreshold??Kh,this._speakingHoldMs=t.speakingHoldMs??Zh,this._pollIntervalMs=t.pollIntervalMs??Ao;const e=t.initialGain??1;this._gain$.next(e),this.applyEffectiveGain()}get gain$(){return this._gain$.asObservable()}get gain(){return this._gain$.value}get outputTrack(){const[t]=this._destination.stream.getAudioTracks();return t}get level$(){return this.deferEmission(jr(this._pollIntervalMs,Ta).pipe(E(()=>this.computeLevel())))}get speaking$(){return this.deferEmission(this.level$.pipe(E(t=>this.evaluateSpeaking(t)),L()))}setGain(t){const e=Math.max(0,Math.min(2,t));this._gain$.next(e),this.applyEffectiveGain()}setPTTActive(t){this._pttMultiplier=t?1:0,this.applyEffectiveGain()}applyEffectiveGain(){this._gainNode.gain.value=this._gain$.value*this._pttMultiplier}setInputTrack(t){if(this._inputSource){try{this._inputSource.disconnect()}catch(e){cs.debug("[LocalAudioPipeline] input disconnect warning:",e)}this._inputSource=null}this._inputStream&&(this._inputStream=null),t&&(this._inputStream=new MediaStream([t]),this._inputSource=this._audioContext.createMediaStreamSource(this._inputStream),this._inputSource.connect(this._gainNode),this._audioContext.state==="suspended"&&this._audioContext.resume().catch(e=>{cs.warn("[LocalAudioPipeline] AudioContext resume failed:",e)}))}destroy(){if(this._inputSource){try{this._inputSource.disconnect()}catch{}this._inputSource=null}try{this._gainNode.disconnect(),this._analyser.disconnect()}catch{}this._audioContext.close().catch(t=>{cs.debug("[LocalAudioPipeline] audio context close warning:",t)}),super.destroy()}computeLevel(){if(!this._inputSource)return 0;this._analyser.getByteTimeDomainData(this._analyserBuffer);let t=0;for(const e of this._analyserBuffer){const i=(e-128)/128;t+=i*i}return Math.sqrt(t/this._analyserBuffer.length)}evaluateSpeaking(t){const e=Date.now();return t>=this._speakingThreshold?(this._lastSpokeAt=e,!0):e-this._lastSpokeAt<this._speakingHoldMs}};const Lt=W();var Mg=class extends ie{constructor(t){super(),this.options=t,this.mediaTrackEndedHandler=e=>{this._mediaTrackEnded$.next(e)},this._localStream$=this.createBehaviorSubject(null),this._localAudioTracks$=this.createBehaviorSubject([]),this._localVideoTracks$=this.createBehaviorSubject([]),this._mediaTrackEnded$=this.createSubject()}get localStream$(){return this._localStream$.asObservable().pipe(S(this.destroyed$))}get localAudioTracks$(){return this._localAudioTracks$.asObservable().pipe(S(this.destroyed$))}get localVideoTracks$(){return this._localVideoTracks$.asObservable().pipe(S(this.destroyed$))}get mediaTrackEnded$(){return this._mediaTrackEnded$.asObservable().pipe(S(this.destroyed$))}get localStream(){return this._localStream$.value}get localAudioTracks(){return this._localAudioTracks$.value}get localVideoTracks(){return this._localVideoTracks$.value}async buildLocalStream(){var e,i;Lt.debug("[LocalStreamController] Building local media stream.");let t;if(this.options.inputAudioStream??this.options.inputVideoStream){const r=[...((e=this.options.inputAudioStream)==null?void 0:e.getTracks())??[],...((i=this.options.inputVideoStream)==null?void 0:i.getTracks())??[]];t=new MediaStream(r)}else if(this.options.propose==="screenshare")Lt.debug("[LocalStreamController] Requesting display media for screen sharing with audio:",!!this.options.inputAudioDeviceConstraints),t=await this.options.getDisplayMedia({video:!0,audio:!!this.options.inputAudioDeviceConstraints}),Lt.debug("[LocalStreamController] Screen share media obtained:",t);else{const r={audio:this.options.inputAudioDeviceConstraints,video:this.options.inputVideoDeviceConstraints};Lt.debug("[LocalStreamController] Requesting user media with constraints:",r),t=await this.options.getUserMedia(r),Lt.debug("[LocalStreamController] User media obtained:",t)}return this._localStream$.next(t),t}addTrack(t){const e=this._localStream$.value??new MediaStream;return t.addEventListener("ended",this.mediaTrackEndedHandler),e.addTrack(t),this._localStream$.next(e),t.kind==="video"?this._localVideoTracks$.next(e.getVideoTracks()):this._localAudioTracks$.next(e.getAudioTracks()),Lt.debug(`[LocalStreamController] ${t.kind} track added:`,t.id),e}removeTrack(t){const e=this._localStream$.value,i=e==null?void 0:e.getTracks().find(r=>r.id===t);if(!i){Lt.debug(`[LocalStreamController] track not found: ${t}`);return}return i.removeEventListener("ended",this.mediaTrackEndedHandler),e==null||e.removeTrack(i),i.stop(),this._localStream$.next(e),i.kind==="video"?this._localVideoTracks$.next((e==null?void 0:e.getVideoTracks())??[]):this._localAudioTracks$.next((e==null?void 0:e.getAudioTracks())??[]),Lt.debug(`[LocalStreamController] ${i.kind} track removed:`,t),i}getOrCreateLocalStream(){return this._localStream$.value??new MediaStream}setLocalStream(t){this._localStream$.next(t)}addTrackEndedListener(t){t.addEventListener("ended",this.mediaTrackEndedHandler)}updateOptions(t){this.options={...this.options,...t}}stopAllTracks(){var t;(t=this._localStream$.value)==null||t.getTracks().forEach(e=>{Lt.debug(`[LocalStreamController] Stopping local track: ${e.kind}`),e.removeEventListener("ended",this.mediaTrackEndedHandler),e.stop()})}destroy(){this.stopAllTracks(),super.destroy()}};const Be=W(),nc=(t,e)=>t&&e?"sendrecv":t&&!e?"sendonly":!t&&e?"recvonly":"inactive";var Rg=class extends ie{constructor(t){super(),this.peerConnection=t.peerConnection,this.options=t}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:t}=this,e=t==null?void 0:t.getAudioTracks().some(n=>n.enabled),i=!!this.inputAudioDeviceConstraints,r=!!this.receiveAudio;return nc(e||i,r)}get videoDirection(){if(this.isAdditionalDevice||this.isScreenShare)return"sendonly";if(this.isSFU)return"recvonly";const{localStream:t}=this,e=t==null?void 0:t.getVideoTracks().some(n=>n.enabled),i=!!this.inputVideoDeviceConstraints,r=!!this.receiveVideo;return nc(e||i,r)}get sendEncodings(){if(this.isSimulcast)return["0","1","2"].map(t=>({active:!0,rid:t,scaleResolutionDownBy:Number(t)*6||1}))}getConstraintsFor(t){const e=t==="audio"?this.inputAudioDeviceConstraints:this.inputVideoDeviceConstraints;return typeof e=="boolean"?{}:e}transceiverByKind(t){return this.peerConnection.getTransceivers().filter(e=>t==="both"||e.receiver.track.kind===t)}get audioTransceivers(){return this.transceiverByKind("audio")}get videoTransceivers(){return this.transceiverByKind("video")}async setupTransceiverSender(t,e,i){var a;const r=t.kind==="audio",n=r?this.audioDirection:this.videoDirection,s={direction:n,sendEncodings:r?void 0:this.sendEncodings,streams:n==="recvonly"?void 0:[e]};Be.debug(`[TransceiverController] Setting up transceiver sender for local ${t.kind} track:`,{transceiver:i,transceiverParams:s}),s.direction&&["sendonly","sendrecv"].includes(s.direction)&&(i?(await i.sender.replaceTrack(t),i.direction=s.direction,(a=s.streams)!=null&&a.some(o=>!!o)&&(Be.debug(`[TransceiverController] Setting streams for transceiver sender for local ${t.kind} track:`,s.streams),i.sender.setStreams(...s.streams))):(Be.debug(`[TransceiverController] Adding new transceiver for local ${t.kind} track:`,t.id),this.peerConnection.addTransceiver(t,s)))}stopTrackSender(t,e={updateTransceiverDirection:!1}){var i,r,n;try{const s=this.transceiverByKind(t);for(const a of s)if(((i=a.sender.track)==null?void 0:i.readyState)==="live"){const o=a.sender.track.id;a.sender.track.stop(),this.options.localStreamController.removeTrack(o),e.updateTransceiverDirection&&(a.direction="inactive")}}catch(s){Be.error("[TransceiverController] stopTrackSender error",t,s),(n=(r=this.options).onError)==null||n.call(r,new Ii("stopTrackSender",t,s))}}async restoreTrackSender(t){var e,i;try{Be.debug("[TransceiverController] restoreTrackSender called",t);const r={},n=this.transceiverByKind(t);for(const a of n){const{track:o}=a.sender;if(!o||o.readyState==="ended"){const c=(o==null?void 0:o.kind)??a.receiver.track.kind;(c==="audio"||c==="video")&&(r[c]=this.getConstraintsFor(c))}}if(Be.debug("[TransceiverController] restoreTrackSender constraints:",r),Object.keys(r).length===0){Be.warn("[TransceiverController] restoreTrackSender: no tracks need restoration",t);return}const s=(await this.options.getUserMedia(r)).getTracks();Be.debug("[TransceiverController] restoreTrackSender new tracks:",s);for(const a of s){this.options.localStreamController.addTrack(a);const o=a.kind,c=this.transceiverByKind(o)[0];c.direction=o==="audio"?this.audioDirection:this.videoDirection,Be.debug("[TransceiverController] restoreTrackSender setting direction for",o,c.direction),await c.sender.replaceTrack(a)}}catch(r){Be.error("[TransceiverController] restoreTrackSender error",t,r),(i=(e=this.options).onError)==null||i.call(e,new Ii("restoreTrackSender",t,r))}}async replaceSenderTrack(t,e){const i=t==="audio"?this.audioTransceivers:this.videoTransceivers;for(const r of i)await r.sender.replaceTrack(e)}async setupRemoteTransceivers(t){if(t!=="answer"){for(const e of["audio","video"]){const i=e==="audio"?this.audioTransceivers:this.videoTransceivers;for(const r of i){const n=e==="audio"?this.audioDirection:this.videoDirection;["inactive","recvonly"].includes(n)&&(r.direction=n,await r.sender.replaceTrack(null),r.sender.setStreams())}}if(this.videoDirection==="recvonly"&&this.isSFU&&this.useAddTransceivers){const{msStreamsNumber:e=5}=this.options;for(let i=0;i<Number(e);i++)this.peerConnection.addTransceiver("video",{direction:"recvonly"})}}}async updateSendersConstraints(t,e){var r,n;if(!e)return this.stopTrackSender(t),Promise.resolve();const i=this.peerConnection.getSenders().filter(s=>{var a;return((a=s.track)==null?void 0:a.kind)===t&&s.track.readyState==="live"});for(const s of i){const{track:a}=s;if(a){const o={...a.getConstraints(),...e};try{await a.applyConstraints(o),Be.debug(`[TransceiverController] Updated ${t} sender constraints:`,o),Be.debug(`[TransceiverController] Updated ${t} sender constraints:`,a.getConstraints())}catch(c){Be.warn(`[TransceiverController] applyConstraints failed for ${t} track ${a.id}, attempting track replacement fallback:`,c);try{await this.replaceTrackFallback(s,a,t,o)}catch(u){Be.warn(`[TransceiverController] Track replacement fallback also failed for ${t} track:`,u),(n=(r=this.options).onError)==null||n.call(r,new Ii("updateSendersConstraints",t,u))}}}}}async replaceTrackFallback(t,e,i,r){const{deviceId:n}=e.getSettings(),s={...r,...n?{deviceId:{exact:n}}:{}},a=e.id;e.stop(),this.options.localStreamController.removeTrack(a);const o=(await this.options.getUserMedia({[i]:s})).getTracks().find(c=>c.kind===i);if(!o)throw new Ii("replaceTrackFallback",i,new Error("getUserMedia returned no track of the requested kind"));await t.replaceTrack(o),this.options.localStreamController.addTrack(o),Be.debug(`[TransceiverController] Track replacement fallback succeeded for ${i}. New track: ${o.id}`)}getMediaDirections(){return this.peerConnection.connectionState==="connected"?this.peerConnection.getTransceivers().reduce((t,e)=>({...t,[e.receiver.track.kind]:e.direction}),{audio:"inactive",video:"inactive"}):{audio:this.audioDirection,video:this.videoDirection}}updatePeerConnection(t){this.peerConnection=t}updateOptions(t){this.options={...this.options,...t}}};const z=W();var sc=class extends ie{constructor(t={},e,i){super(),this.options=t,this.firstSDPExchangeCompleted=!1,this.negotiationNeeded$=this.createSubject(),this.localDescription$=$t(()=>Ie(this.init())).pipe(Ke(()=>this.iceGatheringController.iceCandidatesState$.pipe(B(n=>!["new","gathering"].includes(n)),Se(()=>{this.negotiationEnded()}),B(()=>this.shouldEmitLocalDescription),E(()=>{var n;return(n=this.peerConnection)==null?void 0:n.localDescription}),ue(),Se(n=>{n.type==="answer"&&(this._type="offer")}))),et(1),S(this.destroyed$)),this.connectionTimeout=3e3,this.oniceconnectionstatechangeHandler=()=>{if(this.peerConnection){const{iceConnectionState:n}=this.peerConnection;z.debug(`[RTCPeerConnectionController] ICE connection state changed to: ${n}`),this._iceConnectionState$.next(this.peerConnection.iceConnectionState)}},this.onconnectionstatechangeHandler=()=>{if(this.peerConnection){const{connectionState:n}=this.peerConnection;z.debug(`[RTCPeerConnectionController] Connection state changed to: ${n}`),n==="connected"&&this.removeConnectionTimer(),this._connectionState$.next(this.peerConnection.connectionState)}},this.onsignalingstatechangeHandler=()=>{var n;z.debug(`[RTCPeerConnectionController] Signaling state changed to: ${(n=this.peerConnection)==null?void 0:n.signalingState}`)},this.onicegatheringstatechangeHandler=()=>{this.peerConnection&&this._iceGatheringState$.next(this.peerConnection.iceGatheringState)},this.onnegotiationneededHandler=n=>{z.debug("[RTCPeerConnectionController] Negotiation needed event received.",n),this.negotiationNeeded$.next()},this.updateSelectedInputDevice=async(n,s)=>{var a,o,c;try{const{localStream:u}=this;if(!u){z.warn("[RTCPeerConnectionController] No local stream available to update input device.");return}z.debug(`[RTCPeerConnectionController] Updating selected ${n} input device:`,u.getTracks());const h=u.getTracks().find(p=>p.kind===n);if(h){if((a=this.transceiverController)==null||a.stopTrackSender(n),this.localStreamController.removeTrack(h.id),z.debug(`[RTCPeerConnectionController] Stopped existing ${n} track: ${h.id}`,u.getTracks()),!s){z.debug(`[RTCPeerConnectionController] ${n} input device selected: none`);return}const p=(await this.getUserMedia({[n]:{...h.getConstraints(),...this.deviceController.deviceInfoToConstraints(s)}})).getTracks().find(f=>f.kind===n);p&&(z.debug(`[RTCPeerConnectionController] Adding new ${n} track: ${p.id}`),this.localStreamController.addTrack(p),await((o=this.transceiverController)==null?void 0:o.replaceSenderTrack(n,p)),z.debug(`[RTCPeerConnectionController] Added new ${n} track: ${p.id}`,(c=this.localStream)==null?void 0:c.getTracks()))}z.debug(`[RTCPeerConnectionController] ${n} input device selected:`,s==null?void 0:s.label)}catch(u){throw z.error(`[RTCPeerConnectionController] Failed to select ${n} input device:`,u),this._errors$.next(vt(u)),u}},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=t.callId??Qr(),this._type=e?"answer":"offer",this.sdpInit=e?{type:"offer",sdp:e}:void 0,this._remoteOfferMediaDirections=e?Sg(e):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={...t,audio:t.audio??r.audio,video:t.video??r.video,receiveAudio:t.receiveAudio??r.receiveAudio??g.instance.receiveAudio,receiveVideo:t.receiveVideo??r.receiveVideo??g.instance.receiveVideo},this.localStreamController=new Mg({propose:this.propose,inputAudioStream:this.options.inputAudioStream,inputVideoStream:this.options.inputVideoStream,inputAudioDeviceConstraints:this.inputAudioDeviceConstraints,inputVideoDeviceConstraints:this.inputVideoDeviceConstraints,getUserMedia:async n=>this.getUserMedia(n),getDisplayMedia:async n=>this.getDisplayMedia(n)})}get iceGatheringController(){if(!this._iceGatheringController)throw new Q("ICEGatheringController is not initialized");return this._iceGatheringController}get shouldEmitLocalDescription(){if(!this.peerConnection)return!1;const{localDescription:t,signalingState:e}=this.peerConnection;return!t||!ic(t.sdp)?!1:t.type==="offer"&&e==="have-local-offer"||t.type==="answer"&&e==="stable"}removeConnectionTimer(){this.connectionTimer&&(clearTimeout(this.connectionTimer),this.connectionTimer=void 0)}setMemberId(t){this._memberId=t}get memberId(){return this._memberId}stopTrackSender(t,e={updateTransceiverDirection:!1}){var r,n,s;const i=t==="audio"||t==="both";i&&this._localAudioPipeline&&this.stopRawAudioInputForPipeline(),i?t==="both"?(n=this.transceiverController)==null||n.stopTrackSender("video",e):this._localAudioPipeline||(s=this.transceiverController)==null||s.stopTrackSender(t,e):(r=this.transceiverController)==null||r.stopTrackSender(t,e)}stopRawAudioInputForPipeline(){var e;const t=this.localStreamController.localAudioTracks;for(const i of t)i.readyState==="live"&&(i.stop(),this.localStreamController.removeTrack(i.id));(e=this._localAudioPipeline)==null||e.setInputTrack(null)}get isNegotiating$(){return this._isNegotiating$.asObservable()}get isNegotiating(){return this._isNegotiating$.value}updateMediaDevicesOptions(t){this.options={...this.options,...t}}get iceGatheringState$(){return this.cachedObservable("iceGatheringState$",()=>this._iceGatheringState$.asObservable().pipe(S(this.destroyed$)))}get mediaTrackEnded$(){return this.cachedObservable("mediaTrackEnded$",()=>this.localStreamController.mediaTrackEnded$.pipe(S(this.destroyed$)))}get errors$(){return this.cachedObservable("errors$",()=>this._errors$.asObservable().pipe(S(this.destroyed$)))}get iceCandidates$(){return this.cachedObservable("iceCandidates$",()=>this._iceCandidates$.asObservable().pipe(S(this.destroyed$)))}get initialized$(){return this.cachedObservable("initialized$",()=>this._initialized$.asObservable().pipe(B(t=>t),S(this.destroyed$)))}get remoteDescription$(){return this.cachedObservable("remoteDescription$",()=>this._remoteDescription$.asObservable().pipe(S(this.destroyed$)))}get localStream$(){return this.cachedObservable("localStream$",()=>this.localStreamController.localStream$.pipe(S(this.destroyed$)))}get remoteStream$(){return this.cachedObservable("remoteStream$",()=>this._remoteStream$.asObservable().pipe(S(this.destroyed$)))}get localAudioTracks$(){return this.cachedObservable("localAudioTracks$",()=>this.localStreamController.localAudioTracks$.pipe(S(this.destroyed$)))}get localVideoTracks$(){return this.cachedObservable("localVideoTracks$",()=>this.localStreamController.localVideoTracks$.pipe(S(this.destroyed$)))}get iceConnectionState$(){return this.cachedObservable("iceConnectionState$",()=>this._iceConnectionState$.asObservable().pipe(S(this.destroyed$)))}get connectionState$(){return this.cachedObservable("connectionState$",()=>this._connectionState$.asObservable().pipe(S(this.destroyed$)))}get signalingState$(){return this.cachedObservable("signalingState$",()=>this._signalingState$.asObservable().pipe(S(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 t="transport=tcp";return(this.options.iceServers??[]).map(e=>{const i=Array.isArray(e.urls)?e.urls:[e.urls];return{...e,urls:i.filter(r=>r.includes(t))}})}get rtcConfiguration(){const{iceServers:t,...e}=this.options;return{bundlePolicy:"max-compat",iceCandidatePoolSize:10,iceServers:this.iceServers,iceTransportPolicy:this.options.relayOnly?"relay":"all",sdpSemantics:"unified-plan",...e}}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 t=this.deviceController.selectedAudioInputDeviceConstraints;return t===!1?!1:{...typeof this.options.inputAudioDeviceConstraints=="object"?this.options.inputAudioDeviceConstraints:{},...typeof t=="object"?t:{}}}get inputVideoDeviceConstraints(){if(!this.options.video&&!this.options.inputVideoDeviceConstraints)return!1;const t=this.deviceController.selectedVideoInputDeviceConstraints;return t===!1?!1:{...typeof this.options.inputVideoDeviceConstraints=="object"?this.options.inputVideoDeviceConstraints:{},...typeof t=="object"?t:{}}}get WebRTCPeerConnectionConstructor(){var t;return((t=this.options.webRTCApiProvider)==null?void 0:t.RTCPeerConnection)??RTCPeerConnection}get offerOptions(){const t={iceRestart:this.firstSDPExchangeCompleted?!0:void 0};switch(this.propose){case"screenshare":case"additional-device":return{...t,offerToReceiveAudio:!1,offerToReceiveVideo:!1};case"main":default:return{...t,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(Sd(0),qn(async()=>this.startNegotiation())),{next:()=>{z.debug("[RTCPeerConnectionController] Start Negotiation completed successfully")},error:t=>{z.error("[RTCPeerConnectionController] Start Negotiation error:",t),this._errors$.next(vt(t))}}),this.subscribeTo(xi(this.deviceController.selectedAudioInputDevice$.pipe(E(t=>["audio",t])),this.deviceController.selectedVideoInputDevice$.pipe(E(t=>["video",t]))).pipe(Id(()=>!this.localStreamController.localStream)),async([t,e])=>{z.debug("[RTCPeerConnectionController] Selected input device changed for:",{kind:t,deviceInfo:e}),await this.updateSelectedInputDevice(t,e)}),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(t){z.error("[RTCPeerConnectionController] Initialization error:",t),this._errors$.next(vt(t)),this.destroy()}}setupPeerConnection(){this.peerConnection=new this.WebRTCPeerConnectionConstructor(this.rtcConfiguration),this.peerConnection.addEventListener("negotiationneeded",this.onnegotiationneededHandler),this._iceGatheringController=new Dg(this.peerConnection,this.isNegotiating$,{iceCandidateTimeout:this.options.iceCandidateTimeout,iceGatheringTimeout:this.options.iceGatheringTimeout,relayOnly:this.options.relayOnly}),this.transceiverController=new Rg({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 t=>this.getUserMedia(t),onError:t=>{this._errors$.next(t)}})}async startNegotiation(){if(this.isNegotiating){z.debug("[RTCPeerConnectionController] Negotiation already in progress, skipping.");return}if(this.setupEventListeners(),this.type==="answer"){z.debug("[RTCPeerConnectionController] This is an answer type still, skipping offer creation.");return}this._isNegotiating$.next(!0),z.debug("[RTCPeerConnectionController] Starting negotiation.");try{const{offerOptions:t}=this;z.debug("[RTCPeerConnectionController] Creating offer with options:",t),await this.createOffer(t)}catch(t){z.error("[RTCPeerConnectionController] Error during negotiation:",t),this._errors$.next(vt(t))}}async createOffer(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=await this.peerConnection.createOffer(t);await this.setLocalDescription(e)}async updateAnswerStatus({status:t,sdp:e}){let i=t!=="failed";try{t==="received"&&e&&(z.debug("[RTCPeerConnectionController] Received answer SDP:",e),await this._setRemoteDescription({type:"answer",sdp:e}))}catch(r){z.error("[RTCPeerConnectionController] Error updating answer status:",r),this._errors$.next(vt(r)),i=!1}finally{i?this.readyToConnect():this.iceGatheringController.restartICEGatheringWithRelayOnly()}}async updateOfferStatus({status:t,sdp:e}){switch(t){case"received":this._type="answer",this.sdpInit={type:"offer",sdp:e},await this.handleOfferReceived();break;case"failed":z.error("[RTCPeerConnectionController] Offer failed to be processed by remote.");break}}async acceptInbound(t){var i;if(t){const{audio:r,video:n,receiveAudio:s,receiveVideo:a}=t;this.options={...this.options,...r!==void 0?{audio:r}:{},...n!==void 0?{video:n}:{},...s!==void 0?{receiveAudio:s}:{},...a!==void 0?{receiveVideo:a}:{}},(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:e}=this;z.debug("[RTCPeerConnectionController] Creating inbound answer with options:",e),await this.createAnswer(e)}async handleOfferReceived(){if(!this.sdpInit)throw new Q("SDP initialization parameters are not set");this._isNegotiating$.next(!0),await this._setRemoteDescription(this.sdpInit);const{answerOptions:t}=this;z.debug("[RTCPeerConnectionController] Creating answer with options:",t),await this.createAnswer(t)}readyToConnect(){this.firstSDPExchangeCompleted=!0,this.connectionTimer=setTimeout(()=>{var t;this.removeConnectionTimer(),((t=this.peerConnection)==null?void 0:t.connectionState)!=="connected"&&(z.debug("[RTCPeerConnectionController] Connection timeout, restarting ICE gathering with relay only."),this.iceGatheringController.restartICEGatheringWithRelayOnly())},this.connectionTimeout)}async setRemoteDescriptionBefore(t=""){return Promise.resolve(t)}async setLocalDescription(t){var i;const e=await this.setLocalDescriptionBefore(t.sdp);return(i=this.peerConnection)==null?void 0:i.setLocalDescription({...t,sdp:e})}async setLocalDescriptionBefore(t=""){let e=t;const i=this.options.preferredAudioCodecs??g.instance.preferredAudioCodecs,r=this.options.preferredVideoCodecs??g.instance.preferredVideoCodecs,n=this.options.stereo??g.instance.stereoAudio;return(i.length>0||r.length>0)&&(e=Tg(e,i,r),z.debug("[RTCPeerConnectionController] Applied codec preferences to SDP",{preferredAudioCodecs:i,preferredVideoCodecs:r})),n&&(e=Ag(e),z.debug("[RTCPeerConnectionController] Applied stereo Opus to SDP")),Promise.resolve(e)}async createAnswer(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=await this.peerConnection.createAnswer(t);await this.setLocalDescription(e)}setupEventListeners(){if(!this.peerConnection)throw new Q("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(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=t&&!this.options.relayOnly;if(e)try{this.peerConnection.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:"relay"}),z.debug("[RTCPeerConnectionController] ICE transport policy set to relay-only")}catch(i){z.warn("[RTCPeerConnectionController] Failed to set relay-only policy:",i)}this.setupEventListeners(),this._isNegotiating$.next(!0),z.debug(`[RTCPeerConnectionController] Triggering ICE restart${t?" (relay-only)":""}.`);try{const i=await this.peerConnection.createOffer({iceRestart:!0});await this.setLocalDescription(i)}catch(i){throw z.error("[RTCPeerConnectionController] ICE restart offer failed:",i),this._errors$.next(vt(i)),this.negotiationEnded(),e&&this.restoreIceTransportPolicy(),i}e&&Ge(or(this._iceGatheringState$.pipe(B(i=>i==="complete"),Me(1)),ki(qh).pipe(E(()=>"timeout")))).then(()=>this.restoreIceTransportPolicy()).catch(i=>{z.warn("[RTCPeerConnectionController] Error waiting for ICE gathering to complete:",i),this.restoreIceTransportPolicy()})}restoreIceTransportPolicy(){var t;try{(t=this.peerConnection)==null||t.setConfiguration({...this.peerConnection.getConfiguration(),iceTransportPolicy:this.options.relayOnly?"relay":"all"}),z.debug("[RTCPeerConnectionController] ICE transport policy restored")}catch(e){z.warn("[RTCPeerConnectionController] Failed to restore ICE transport policy:",e)}}async setupTrackHandling(){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");await this.setupLocalTracks(),await this.setupRemoteTracks()}async setupLocalTracks(){var e,i,r,n,s,a,o;z.debug("[RTCPeerConnectionController] Setting up local tracks/transceivers.");const t=this.localStream??await this.localStreamController.buildLocalStream();if(((e=this.transceiverController)==null?void 0:e.useAddStream)??!1){z.warn("[RTCPeerConnectionController] Using deprecated addStream API to add local stream."),(i=this.peerConnection)==null||i.addStream(t),this.isNegotiating||(z.debug("[RTCPeerConnectionController] Forcing negotiationneeded after local tracks setup."),this.negotiationNeeded$.next());return}for(const c of["audio","video"]){const u=(c==="audio"?t.getAudioTracks():t.getVideoTracks()).map((h,p)=>({index:p,track:h}));for(const{index:h,track:p}of u)if(this.localStreamController.addTrackEndedListener(p),((r=this.transceiverController)==null?void 0:r.useAddTransceivers)??!1){const f=(c==="audio"?(n=this.transceiverController)==null?void 0:n.audioTransceivers:(s=this.transceiverController)==null?void 0:s.videoTransceivers)??[];await((a=this.transceiverController)==null?void 0:a.setupTransceiverSender(p,t,f[h]))}else z.debug(`[RTCPeerConnectionController] Using addTrack for local ${c} track:`,p.id),(o=this.peerConnection)==null||o.addTrack(p,t)}}async getUserMedia(t){var e;return(((e=this.options.webRTCApiProvider)==null?void 0:e.mediaDevices)??navigator.mediaDevices).getUserMedia(t)}async getDisplayMedia(t){var i;const e=((i=this.options.webRTCApiProvider)==null?void 0:i.mediaDevices)??navigator.mediaDevices;if(!e.getDisplayMedia)throw new Q("getDisplayMedia is not supported by the current WebRTC provider");return e.getDisplayMedia(t)}async setupRemoteTracks(){var t;if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");this.peerConnection.ontrack=e=>{var i;if(z.debug("[RTCPeerConnectionController] Remote track received:",e.track.kind),e.streams[0])this._remoteStream$.next(e.streams[0]);else{const r=((i=this._remoteStream$.value)==null?void 0:i.getTracks())??[],n=new MediaStream([...r,e.track]);this._remoteStream$.next(n)}},await((t=this.transceiverController)==null?void 0:t.setupRemoteTransceivers(this.type))}async restoreTrackSender(t){var i,r,n;const e=t==="audio"||t==="both";e&&this._localAudioPipeline&&await this.restoreRawAudioInputForPipeline(),e?t==="both"?await((r=this.transceiverController)==null?void 0:r.restoreTrackSender("video")):this._localAudioPipeline||await((n=this.transceiverController)==null?void 0:n.restoreTrackSender(t)):await((i=this.transceiverController)==null?void 0:i.restoreTrackSender(t))}async restoreRawAudioInputForPipeline(){var r;if(!this._localAudioPipeline)return;const t=((r=this.transceiverController)==null?void 0:r.getConstraintsFor("audio"))??{};let e;try{e=await this.getUserMedia({audio:t})}catch(n){z.error("[RTCPeerConnectionController] Failed to re-acquire mic for pipeline restore:",n),this._errors$.next(vt(n));return}const i=e.getAudioTracks().at(0);i&&(this.localStreamController.addTrack(i),this._localAudioPipeline.setInputTrack(i))}ensureLocalAudioPipeline(){if(this._localAudioPipeline)return this._localAudioPipeline;if(!this.peerConnection)return null;try{this._localAudioPipeline=new Ig}catch(t){return z.warn("[RTCPeerConnectionController] Failed to create LocalAudioPipeline:",t),null}return this.subscribeTo(this.localStreamController.localAudioTracks$,()=>{this.applyLocalAudioPipelineToSender()}),this.applyLocalAudioPipelineToSender(),this._localAudioPipeline}get localAudioPipeline(){return this._localAudioPipeline}async applyLocalAudioPipelineToSender(){var i,r;if(!this._localAudioPipeline||!this.peerConnection)return;const t=this.localStreamController.localAudioTracks.at(0);this._localAudioPipeline.setInputTrack(t??null);const e=((r=(i=this.transceiverController)==null?void 0:i.audioTransceivers.at(0))==null?void 0:r.sender)??this.peerConnection.getSenders().find(n=>{var s;return((s=n.track)==null?void 0:s.kind)==="audio"});if(!(!e||!t))try{await e.replaceTrack(this._localAudioPipeline.outputTrack)}catch(n){z.warn("[RTCPeerConnectionController] Failed to route audio sender through pipeline:",n)}}addLocalTrack(t){if(!this.peerConnection){const e=new Q("RTCPeerConnection is not initialized");throw this._errors$.next(e),e}try{const e=this.localStreamController.addTrack(t);this.peerConnection.addTrack(t,e),z.debug(`[RTCPeerConnectionController] ${t.kind} track added:`,t.id)}catch(e){throw z.error(`[RTCPeerConnectionController] Failed to add ${t.kind} track:`,e),this._errors$.next(vt(e)),e}}removeLocalTrack(t){var i,r;if(!this.peerConnection){const n=new Q("RTCPeerConnection is not initialized");throw this._errors$.next(n),n}const e=this.peerConnection.getSenders().find(n=>{var s;return((s=n.track)==null?void 0:s.id)===t});if(!e){z.debug(`[RTCPeerConnectionController] track not found: ${t}`);return}try{this.peerConnection.removeTrack(e),this.localStreamController.removeTrack(t),z.debug(`[RTCPeerConnectionController] ${(i=e.track)==null?void 0:i.kind} track removed:`,t)}catch(n){throw z.error(`[RTCPeerConnectionController] Failed to remove ${(r=e.track)==null?void 0:r.kind} track:`,n),this._errors$.next(vt(n)),n}}setLocalTrack(t){const e=[...t.kind==="audio"?this.localStreamController.localAudioTracks:this.localStreamController.localVideoTracks];for(const i of e)this.removeLocalTrack(i.id);this.addLocalTrack(t)}async updateSendersConstraints(t,e){var i;await((i=this.transceiverController)==null?void 0:i.updateSendersConstraints(t,e))}async replaceAudioTrackWithConstraints(t){var i;const e=(i=this.peerConnection)==null?void 0:i.getSenders().filter(r=>{var n;return((n=r.track)==null?void 0:n.kind)==="audio"&&r.track.readyState==="live"});if(!e||e.length===0){z.warn("[RTCPeerConnectionController] No live audio sender to replace");return}for(const r of e){const n=r.track;if(!n)continue;const{deviceId:s}=n.getSettings(),a={...n.getConstraints(),...t,...s?{deviceId:{exact:s}}:{}},o=n.id;n.stop(),this.localStreamController.removeTrack(o);const c=(await this.getUserMedia({audio:a})).getAudioTracks()[0];await r.replaceTrack(c),this.localStreamController.addTrack(c),z.debug(`[RTCPeerConnectionController] Audio track replaced for server-pushed params. New track: ${c.id}`)}}destroy(){var t,e,i;z.debug(`[RTCPeerConnectionController] Destroying RTCPeerConnectionController. ${this.propose}`),this.removeConnectionTimer(),(t=this._iceGatheringController)==null||t.destroy(),(e=this._localAudioPipeline)==null||e.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 t;(t=this._remoteStream$.value)==null||t.getTracks().forEach(e=>{z.debug(`[RTCPeerConnectionController] Stopping remote track: ${e.kind}`),e.stop()})}get mediaDirections(){var t;return((t=this.transceiverController)==null?void 0:t.getMediaDirections())??this._remoteOfferMediaDirections??{audio:"inactive",video:"inactive"}}async _setRemoteDescription(t){if(!this.peerConnection)throw new Q("RTCPeerConnection is not initialized");const e=await this.setRemoteDescriptionBefore(t.sdp),i={...t,sdp:e};return z.debug("[RTCPeerConnectionController] Setting remote description:",i),this.peerConnection.setRemoteDescription(i)}};function ls(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"id")}function ac(t){if(!ls(t))return!1;const e=t;return e.method==="verto.invite"&&ke(e.params)&&G(e.params,"sdp")&&G(e.params,"callID")}function us(t){return ls(t)?t.method==="verto.bye":!1}function oc(t){return ls(t)?t.method==="verto.attach":!1}function Pg(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.answer"&&ke(t.params)&&G(t.params,"callID")}function Og(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.media"&&ke(t.params)&&G(t.params,"callID")&&G(t.params,"sdp")}function _g(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.mediaParams"&&ke(t.params)&&G(t.params,"mediaParams")}function Lg(t){return ke(t)&&G(t,"jsonrpc")&&t.jsonrpc==="2.0"&&G(t,"method")&&t.method==="verto.ping"}const V=W();function Fg(t){return t.isInvite&&!t.reattach&&!t.explicitNodeId?"":t.currentNodeId??""}var Ug=class extends ie{constructor(t){super(),this.callSession=t}destroy(){this.callSession=void 0,super.destroy()}},Ng=class extends Ug{constructor(t,e,i,r,n={}){super(t),this.webRtcCallSession=t,this.attachManager=e,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(n.nodeId??null),this.onError=n.onError,this.onModifyFailed=n.onModifyFailed,this.initSubscriptions(),this.initMainPeerConnection()}async hold(){const t=rn({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},action:"hold"});try{await this.executeVerto(t)}catch(e){throw V.warn("[WebRTCManager] Call might already be disconnected, error sending Verto hold:",e),e}}async unhold(){const t=rn({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},action:"unhold"});try{await this.executeVerto(t)}catch(e){throw V.warn("[WebRTCManager] Call might already be disconnected, error sending Verto unhold:",e),e}}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 t;return((t=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id))==null?void 0:t.localStream)??null}get remoteStream(){var t;return((t=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id))==null?void 0:t.remoteStream)??null}get nodeId(){return this._nodeId$.value}get screenShareStatus(){return this._screenShareStatus$.value}get screenShareStatus$(){return this._screenShareStatus$.asObservable()}get mainPeerConnection(){const t=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id);if(!t)throw new Q("Main peer connection not found");return t}get signalingStatus$(){return this.cachedObservable("signalingStatus$",()=>xi(this._signalingStatus$.asObservable(),this.mainPeerConnection.connectionState$.pipe(B(t=>["connected","disconnected","failed"].includes(t)))))}initSubscriptions(){this.subscribeTo(this.callJoinedEvent$,t=>{var i;const e=(i=t.room_session.members.find(r=>r.call_id===t.call_id))==null?void 0:i.node_id;e&&this.setNodeIdIfNull(e),t.member_id&&this.setSelfIdIfNull(t.member_id)}),this.subscribeTo(this.vertoMedia$,t=>{var r;V.debug("[WebRTCManager] Received Verto media event (early media SDP):",t),this._signalingStatus$.next("ringing");const{sdp:e,callID:i}=t;(r=this._rtcPeerConnectionsMap.get(i))==null||r.updateAnswerStatus({status:"received",sdp:e})}),this.subscribeTo(this.vertoAnswer$,t=>{var r;V.debug("[WebRTCManager] Received Verto answer event:",t),this._signalingStatus$.next("connecting");const{sdp:e,callID:i}=t;(r=this._rtcPeerConnectionsMap.get(i))==null||r.updateAnswerStatus({status:"received",sdp:e})}),this.subscribeTo(this.vertoMediaParams$,t=>{V.debug("[WebRTCManager] Received Verto mediaParams event:",t);const{mediaParams:e,callID:i}=t,r=this._rtcPeerConnectionsMap.get(i),{audio:n,video:s}=e;(async()=>{var a;try{n&&r&&await r.replaceAudioTrackWithConstraints(n),s&&await(r==null?void 0:r.updateSendersConstraints("video",s)),this.webRtcCallSession.emitMediaParamsUpdated({audio:n,video:s,timestamp:Date.now()})}catch(o){V.warn("[WebRTCManager] Error applying server-pushed media params:",o),(a=this.onError)==null||a.call(this,o instanceof Error?o:new Error(String(o),{cause:o}))}})()}),this.subscribeTo(this.vertoPing$,t=>{this.attachManager.attach(this.buildAttachableCall()),this.sendVertoPong(t)})}setNodeIdIfNull(t){!this._nodeId$.value&&t&&(V.debug(`[WebRTCManager] Early node_id set: ${t}`),this._nodeId$.next(t))}setSelfIdIfNull(t){!this._selfId$.value&&t&&(V.debug(`[WebRTCManager] Early selfId set: ${t}`),this._selfId$.next(t))}async sendVertoPong(t){var e;try{const i=eg({...t});await this.executeVerto(i)}catch(i){V.warn("[WebRTCManager] Call might disconnect, error sending Verto pong:",i),(e=this.onError)==null||e.call(this,new so(i))}}async updateMediaConstraints(t={}){var r;const{audio:e,video:i}=t;try{e&&await this.mainPeerConnection.updateSendersConstraints("audio",e),i&&await this.mainPeerConnection.updateSendersConstraints("video",i)}catch(n){throw V.warn("[WebRTCManager] Error updating media constraints:",n),(r=this.onError)==null||r.call(this,n instanceof Error?n:new Error(String(n),{cause:n})),n}}get selfId(){return this._selfId$.value}buildAttachableCall(t){return{nodeId:this.nodeId??void 0,id:t??this.webRtcCallSession.id,to:this.webRtcCallSession.to,mediaDirections:this.webRtcCallSession.mediaDirections}}requestKeyframe(){try{const t=this.mainPeerConnection.peerConnection;if(!t){V.warn("[WebRTCManager] No peer connection for keyframe request");return}const e=t.getReceivers().find(i=>i.track.kind==="video");if(!e){V.warn("[WebRTCManager] No video receiver for keyframe request");return}typeof e.requestKeyFrame=="function"?(e.requestKeyFrame(),V.debug("[WebRTCManager] Keyframe requested via RTCRtpReceiver.requestKeyFrame()")):V.debug("[WebRTCManager] requestKeyFrame() not supported, skipping")}catch(t){V.warn("[WebRTCManager] Keyframe request failed (non-fatal):",t)}}async requestIceRestart(t){try{const e=this.mainPeerConnection;if(!e.peerConnection){V.warn("[WebRTCManager] No peer connection for ICE restart");return}await e.triggerIceRestart(t),V.info(`[WebRTCManager] ICE restart initiated${t?" (relay-only)":""}`)}catch(e){throw V.error("[WebRTCManager] ICE restart failed:",e),e}}async requestIceRestartAll(t){const e=Array.from(this._rtcPeerConnectionsMap.entries());for(const[i,r]of e)try{if(!r.peerConnection){V.debug(`[WebRTCManager] No peer connection for leg ${i}, skipping ICE restart`);continue}await r.triggerIceRestart(t),V.info(`[WebRTCManager] ICE restart initiated for leg ${i}${t?" (relay-only)":""}`)}catch(n){V.warn(`[WebRTCManager] ICE restart failed for leg ${i}:`,n)}}requestKeyframeAll(){for(const[t,e]of this._rtcPeerConnectionsMap){if(e.isScreenShare){V.debug(`[WebRTCManager] Skipping keyframe for send-only screen share leg ${t}`);continue}try{const i=e.peerConnection;if(!i)continue;const r=i.getReceivers().find(n=>n.track.kind==="video");if(!r)continue;typeof r.requestKeyFrame=="function"&&(r.requestKeyFrame(),V.debug(`[WebRTCManager] Keyframe requested for leg ${t}`))}catch(i){V.warn(`[WebRTCManager] Keyframe request failed for leg ${t} (non-fatal):`,i)}}}get callJoinedEvent$(){return this.webRtcCallSession.callEvent$.pipe(B(tc),S(this.destroyed$))}get vertoMedia$(){return this.webRtcCallSession.webrtcMessages$.pipe(fe(Og,"params"),S(this.destroyed$))}get vertoAnswer$(){return this.cachedObservable("vertoAnswer$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(Pg,"params"),S(this.destroyed$)))}get vertoMediaParams$(){return this.cachedObservable("vertoMediaParams$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(_g,"params"),S(this.destroyed$)))}get vertoBye$(){return this.cachedObservable("vertoBye$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(us,"params"),S(this.destroyed$)))}get vertoAttach$(){return this.cachedObservable("vertoAttach$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(oc,"params"),S(this.destroyed$)))}get vertoPing$(){return this.cachedObservable("vertoPing$",()=>this.webRtcCallSession.webrtcMessages$.pipe(fe(Lg,"params"),S(this.destroyed$)))}async executeVerto(t,e={}){var s,a;const i=Bo({callID:e.callID??this.webRtcCallSession.id,node_id:e.node_id??this._nodeId$.value??"",message:t,subscribe:e.subscribe}),r=await this.webRtcCallSession.execute(i);if(r.error){const o=new _t(r.error.code,r.error.message,r.error.data);return(s=this.onError)==null||s.call(this,o),r}const n=tt(r,"result.result");if(n!=null&&n.error){const o=new _t(n.error.code,n.error.message,n.error.data);return(a=this.onError)==null||a.call(this,o),r}return r}async sendLocalDescription(t,e){var n,s;const i=t.method,r=this.getSendLocalSDPOptionalParams(e,t);try{const a=await this.executeVerto(t,r);switch(i){case"verto.invite":this.processInviteResponse(a,e);break;case"verto.modify":await this.processModifyResponse(a,e);break;default:}}catch(a){V.error(`[WebRTCManager] Error sending Verto ${i}:`,a),(n=this.onError)==null||n.call(this,a instanceof Error?a:new Error(String(a),{cause:a})),i==="verto.modify"&&((s=this.onModifyFailed)==null||s.call(this))}}async processModifyResponse(t,e){var i;if(!t.error){const r=tt(t,"result.result.result.action"),n=tt(t,"result.result.result.sdp");if(r==="updateMedia"&&n)try{await e.updateAnswerStatus({status:"received",sdp:n})}catch(s){V.warn("[WebRTCManager] Error processing modify response:",s);const a=s instanceof Error?s:new Error(String(s),{cause:s});(i=this.onError)==null||i.call(this,a)}}}processInviteResponse(t,e){var i;if(!t.error&&tt(t,"result.result.result.message")==="CALL CREATED"){this._signalingStatus$.next("trying"),this._nodeId$.next(tt(t,"result.node_id")??null);const r=tt(t,"result.result.result.memberID")??null,n=tt(t,"result.result.result.callID")??null;V.debug("[WebRTCManager] Verto invite response:",{callId:n,memberId:r,response:t}),this._selfId$.next(r),e.setMemberId(r),n?(this.webRtcCallSession.addCallId(n),this.attachManager.attach(this.buildAttachableCall(n))):V.warn("[WebRTCManager] Cannot attach call, missing callId:",{nodeId:this.nodeId,callId:n}),V.info("[WebRTCManager] Verto invite successful"),V.debug(`[WebRTCManager] nodeid: ${this._nodeId$.value}, selfId: ${this._selfId$.value}`)}else{V.error("[WebRTCManager] Verto invite failed:",t);const r=t.error?new _t(t.error.code,t.error.message,t.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??g.instance.iceServers,relayOnly:g.instance.relayOnly||g.instance.disableUdpIceServers,disableUdpIceServers:g.instance.disableUdpIceServers,iceCandidateTimeout:g.instance.iceCandidateTimeout,iceGatheringTimeout:g.instance.iceGatheringTimeout}}initMainPeerConnection(){const{options:t}=this.webRtcCallSession,e=new sc({propose:"main",callId:this.webRtcCallSession.id,audio:t.audio,video:t.video,inputAudioDeviceConstraints:t.inputAudioDeviceConstraints,inputVideoDeviceConstraints:t.inputVideoDeviceConstraints,inputAudioStream:t.inputAudioStream,inputVideoStream:t.inputVideoStream,receiveAudio:t.receiveAudio,receiveVideo:t.receiveVideo,webRTCApiProvider:this.webRTCApiProvider,preferredVideoCodecs:t.preferredVideoCodecs,preferredAudioCodecs:t.preferredAudioCodecs,stereo:t.stereo,...this.RTCPeerConnectionConfig},t.initOffer,this.deviceController);this.setupLocalDescriptionHandler(e),this.setupVertoByeHandler(),this.setupVertoAttachHandler(),this.initObservables(e),this._rtcPeerConnectionsMap.set(e.id,e),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values())),this.subscribeTo(e.errors$,i=>{var r;(r=this.onError)==null||r.call(this,i)}),t.initOffer&&this.handleInboundAnswer(e)}async handleInboundAnswer(t){var i,r,n;V.debug("[WebRTCManager] Waiting for inbound call to be accepted or rejected");const e=await Ge(or(this.vertoBye$,this.webRtcCallSession.answered$).pipe(S(this.destroyed$))).catch(()=>null);if(e===null){V.debug("[WebRTCManager] Inbound answer handler aborted (destroyed).");return}if(us(e))V.info("[WebRTCManager] Inbound call ended by remote before answer."),(i=this.callSession)==null||i.destroy();else if(e){V.debug("[WebRTCManager] Inbound call accepted, creating SDP answer");const s=this.webRtcCallSession.answerMediaOptions;try{await t.acceptInbound(s)}catch(a){V.error("[WebRTCManager] Error creating inbound answer:",a),(n=this.onError)==null||n.call(this,a instanceof Error?a:new Error(String(a),{cause:a}))}}else{V.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 t=>{V.debug("[WebRTCManager] Received Verto attach event for existing call:",t);const{callID:e}=t;await this.attachManager.attach({nodeId:this.nodeId??void 0,id:e,to:t.callee_id_number,mediaDirections:{audio:"sendrecv",video:"inactive"}})})}initObservables(t){this.mediaDirections$=t.connectionState$.pipe(B(e=>e==="connected"),E(()=>t.mediaDirections),Md(t.mediaDirections),S(this.destroyed$)),this.localStream$=t.localStream$.pipe(ue(),S(this.destroyed$)),this.remoteStream$=t.remoteStream$.pipe(ue(),S(this.destroyed$))}setupLocalDescriptionHandler(t){this.subscribeTo(t.localDescription$.pipe(B(e=>e!==null),S(this.destroyed$)),e=>{const{type:i,sdp:r}=e,n=this.dialogParams(t),s=!t.firstSDPExchangeCompleted;if(i==="answer"){const a=Jp({dialogParams:n,sdp:r});this.sendLocalDescriptionOnceAccepted(a,t)}else if(s){const a=Kp({dialogParams:n,sdp:r});this.sendLocalDescription(a,t)}else{const a=rn({dialogParams:n,sdp:r,action:"updateMedia"});this.sendLocalDescription(a,t)}})}setupVertoByeHandler(){this.subscribeTo(this.vertoBye$,()=>{var t;this._signalingStatus$.next("disconnected"),this.attachManager.detach(this.buildAttachableCall()),(t=this.callSession)==null||t.destroy()})}getSendLocalSDPOptionalParams(t,e){let i;return t.firstSDPExchangeCompleted||(i=[],t.isMainDevice?i.push(...g.instance.inviteSubscribeMainDevice):t.isAdditionalDevice?i.push(...g.instance.inviteSubscribeAdditionalDevice):t.isScreenShare&&i.push(...g.instance.inviteSubscribeScreenshare)),{callID:t.id,node_id:Fg({isInvite:ac(e),reattach:this.webRtcCallSession.options.reattach===!0,explicitNodeId:this.webRtcCallSession.options.nodeId,currentNodeId:this._nodeId$.value}),subscribe:i}}async sendLocalDescriptionOnceAccepted(t,e){var r,n,s;V.debug("[WebRTCManager] Waiting for call to be accepted or ended before sending answer");const i=await Ge(or(this.vertoBye$,this.webRtcCallSession.answered$).pipe(S(this.destroyed$))).catch(()=>null);if(i===null){V.debug("[WebRTCManager] Destroyed while waiting for call acceptance");return}if(us(i))V.info("[WebRTCManager] Call ended before answer was sent."),(r=this.callSession)==null||r.destroy();else if(i){V.debug("[WebRTCManager] Call accepted, sending answer");try{this._signalingStatus$.next("connecting"),await this.sendLocalDescription(t,e),await e.updateAnswerStatus({status:"sent"}),await this.attachManager.attach(this.buildAttachableCall())}catch(a){V.error("[WebRTCManager] Error sending Verto answer:",a),(s=this.onError)==null||s.call(this,a instanceof Error?a:new Error(String(a),{cause:a})),await e.updateAnswerStatus({status:"failed"})}}else{V.info("[WebRTCManager] Call was not accepted, sending verto.bye.");try{await this.bye("USER_BUSY")}finally{this._signalingStatus$.next("disconnected"),(n=this.callSession)==null||n.destroy()}}}dialogParams(t){const e=t.memberId??this._selfId$.value??void 0,i=t.propose==="main"&&!t.firstSDPExchangeCompleted&&this.webRtcCallSession.options.reattach;return{id:t.isMainDevice?this.webRtcCallSession.id:t.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:e,...this.webRtcCallSession.userVariables},screenShare:t.isScreenShare,additionalDevice:t.isAdditionalDevice,pingSupported:!0,version:fh}}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(t={audio:!1,video:!0}){return this.initAdditionalPeerConnection("additional-device",t)}async addMainInputDevices(t={audio:!0}){var r;let e;const{mediaDirections:i}=this.mainPeerConnection;if((t.audio??t.inputAudioDeviceConstraints??(t.inputAudioStream&&i.audio.startsWith("send")))&&(e="audio"),(t.video??t.inputVideoDeviceConstraints??(t.inputVideoStream&&!i.video.startsWith("send")))&&(e=e==="audio"?"both":"video"),e)this.mainPeerConnection.updateMediaDevicesOptions(t),await this.mainPeerConnection.restoreTrackSender(e);else{const n=new ro("No valid device to be added");throw(r=this.onError)==null||r.call(this,n),n}}async addScreenMedia(t={audio:!1}){await this.initAdditionalPeerConnection("screenshare",t)}async initAdditionalPeerConnection(t,e){var r;let i=null;try{return this._screenShareStatus$.next("starting"),i=new sc({...e,...this.RTCPeerConnectionConfig,propose:t,webRTCApiProvider:this.webRTCApiProvider},void 0,this.deviceController),this.setupLocalDescriptionHandler(i),t==="screenshare"&&(this._screenShareId=i.id),this._rtcPeerConnectionsMap.set(i.id,i),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values())),this.subscribeTo(i.errors$,n=>{var s;(s=this.onError)==null||s.call(this,n)}),await Ge(i.connectionState$.pipe(B(n=>n==="connected"),Me(1),ar(this._screenShareTimeoutMs),S(this.destroyed$))),this._screenShareStatus$.next("started"),V.info("[WebRTCManager] Screen share started successfully."),i.id}catch(n){V.warn("[WebRTCManager] Error initializing additional peer connection:",n),(r=this.onError)==null||r.call(this,n instanceof Error?n:new Error(String(n),{cause:n})),i&&i.destroy(),this._screenShareStatus$.next("none")}}async removeInputDevices(t){return this.removeAdditionalPeerConnection(t)}removeMainInputDevice(t={removeAudio:!1,removeVideo:!0}){let e;if(t.removeAudio&&(e="audio"),t.removeVideo&&(e=e==="audio"?"both":"video"),e)return this.mainPeerConnection.stopTrackSender(e,{updateTransceiverDirection:!0})}async removeScreenMedia(){if(["starting","started"].includes(this._screenShareStatus$.value)||V.warn("[WebRTCManager] No active screen share to stop."),!this._screenShareId){V.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(t){const e=this._rtcPeerConnectionsMap.get(t);try{e&&await this.executeVertoBye(e)}finally{e==null||e.destroy(),this._rtcPeerConnectionsMap.delete(t),this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values()))}}async executeVertoBye(t,e){try{const i=e?{cause:e,causeCode:tg[e]}:{};await this.executeVerto(Zp({...i,dialogParams:this.dialogParams(t)}))}catch(i){throw V.warn("[WebRTCManager] Call might already be disconnected, error sending Verto bye:",i),i}}async bye(t){this.attachManager.detach(this.buildAttachableCall());const e=this._rtcPeerConnectionsMap.get(this.webRtcCallSession.id);e&&await this.executeVertoBye(e,t)}async sendDigits(t){const e=Qp({sessid:this.webRtcCallSession.id,dialogParams:{callID:this.webRtcCallSession.id},dtmf:t});try{await this.executeVerto(e)}catch(i){throw V.warn("[WebRTCManager] Error sending DTMF digits:",i),i}}async transfer(t){const e=rn({...t,dialogParams:this.dialogParams(this.mainPeerConnection),action:"transfer"});try{V.debug("[WebRTCManager] Transferring call with options:",t),await this.executeVerto(e)}catch(i){throw V.error("[WebRTCManager] Error transferring call:",i),i}}destroy(){this._rtcPeerConnectionsMap.forEach(t=>{t.destroy()}),this._rtcPeerConnectionsMap.clear(),this._rtcPeerConnections$.complete(),super.destroy()}};const cc=W();var Bg=class extends ie{constructor(t={}){super(),this._source=null,this._stream=null,this._audioContext=(t.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=t.pollIntervalMs??Ao}get level$(){return this.deferEmission(jr(this._pollIntervalMs,Ta).pipe(E(()=>this.computeLevel())))}setStream(t){if(this._source){try{this._source.disconnect()}catch(e){cc.debug("[RemoteAudioMeter] source disconnect warning:",e)}this._source=null,this._stream=null}!t||t.getAudioTracks().length===0||(this._stream=new MediaStream(t.getAudioTracks()),this._source=this._audioContext.createMediaStreamSource(this._stream))}destroy(){if(this._source){try{this._source.disconnect()}catch{}this._source=null}this._audioContext.close().catch(t=>{cc.debug("[RemoteAudioMeter] audio context close warning:",t)}),super.destroy()}computeLevel(){if(!this._source)return 0;this._analyser.getByteTimeDomainData(this._analyserBuffer);let t=0;for(const e of this._analyserBuffer){const i=(e-128)/128;t+=i*i}return Math.sqrt(t/this._analyserBuffer.length)}};const ur=W(),zg=1e3,Vg=10,Hg=2e3,jg=3e3,Wg=3,Gg=5,qg=5,Xg=10,Yg=4,Kg=30;function Zg(t,e){const i=t+e;return i===0?0:t/i*100}function Qg(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="inbound-rtp"}function Jg(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="candidate-pair"}var $g=class extends ie{constructor(t,e={}){super(),this.peerConnection=t,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=e.pollingIntervalMs??zg,this.baselineSampleCount=e.baselineSamples??Vg,this.noAudioPacketThresholdMs=e.noAudioPacketThresholdMs??Hg,this.noVideoPacketThresholdMs=e.noVideoPacketThresholdMs??jg,this.rttSpikeWarningMultiplier=e.rttSpikeWarningMultiplier??Wg,this.rttSpikeCriticalMultiplier=e.rttSpikeCriticalMultiplier??Gg,this.packetLossWarningPercent=e.packetLossWarningPercent??qg,this.packetLossCriticalPercent=e.packetLossCriticalPercent??Xg,this.jitterSpikeMultiplier=e.jitterSpikeMultiplier??Yg,this.historyWindowSeconds=e.historyWindowSeconds??Kg}get networkIssues$(){return this._networkIssues$.asObservable()}get networkIssues(){return[...this._networkIssues$.value]}get isNetworkHealthy$(){return this.cachedObservable("isNetworkHealthy$",()=>this._networkIssues$.pipe(E(t=>t.length===0),L(),S(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(Gn(t=>Ie(t.filter(e=>e.severity==="critical"))),S(this.destroyed$)))}get sample$(){return this._sample$.asObservable()}start(){if(this.running)return;this.running=!0;const t=Date.now();this.lastAudioPacketChangeTime=t,this.lastVideoPacketChangeTime=t,ur.debug("[RTCStatsMonitor] Starting stats monitoring"),this.subscribeTo(jr(this.pollingIntervalMs).pipe(B(()=>this.running),Ke(()=>Ie(this.peerConnection.getStats()).pipe(ei(e=>(ur.warn("[RTCStatsMonitor] Failed to get stats:",e),Jt)))),B(()=>this.running),E(e=>this.extractSample(e))),e=>this._sample$.next(e)),this.subscribeTo(this._sample$.pipe(Me(this.baselineSampleCount),Td(),E(e=>({rtt:e.reduce((i,r)=>i+r.roundTripTime,0)/e.length,jitter:e.reduce((i,r)=>i+r.audioJitter,0)/e.length,ready:!0}))),e=>{ur.debug(`[RTCStatsMonitor] Baseline established: rtt=${e.rtt.toFixed(1)}ms, jitter=${e.jitter.toFixed(1)}ms`),this._baseline$.next(e)}),this.subscribeTo(this._sample$.pipe(Ka((e,i)=>({prev:e.current,current:i}),{prev:null,current:null}),B(e=>e.current!==null)),({prev:e,current:i})=>{const r=i.timestamp;this.updatePacketTracking(i,r);const n=this.detectIssues(i,e,r);this._networkIssues$.next(n)}),this.subscribeTo(this._sample$.pipe(Ka((e,i)=>{const r=i.timestamp-this.historyWindowSeconds*1e3,n={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[...e.filter(s=>s.timestamp>r),n]},[])),e=>this._networkMetrics$.next(e))}stop(){this.running&&(this.running=!1,ur.debug("[RTCStatsMonitor] Stopping stats monitoring"))}destroy(){ur.debug("[RTCStatsMonitor] Destroying RTCStatsMonitor"),this.stop(),super.destroy()}extractSample(t){let e=0,i=0,r=0,n=0,s=0,a=0,o;return t.forEach(c=>{Qg(c)&&(c.kind==="audio"?(e+=c.packetsReceived??0,i+=c.packetsLost??0,r=Math.max(r,(c.jitter??0)*1e3)):(n+=c.packetsReceived??0,s+=c.packetsLost??0)),Jg(c)&&c.state==="succeeded"&&c.nominated&&(a=c.currentRoundTripTime?c.currentRoundTripTime*1e3:this.lastRoundTripTime,o=c.availableOutgoingBitrate??this.lastAvailableOutgoingBitrate)}),{audioPacketsReceived:e,audioPacketsLost:i,audioJitter:r,videoPacketsReceived:n,videoPacketsLost:s,roundTripTime:a,availableOutgoingBitrate:o,timestamp:Date.now()}}updatePacketTracking(t,e){t.audioPacketsReceived!==this.lastAudioPacketsReceived&&(this.lastAudioPacketsReceived=t.audioPacketsReceived,this.lastAudioPacketChangeTime=e),t.videoPacketsReceived!==this.lastVideoPacketsReceived&&(this.lastVideoPacketsReceived=t.videoPacketsReceived,this.lastVideoPacketChangeTime=e),t.roundTripTime>0&&(this.lastRoundTripTime=t.roundTripTime),t.availableOutgoingBitrate!==void 0&&(this.lastAvailableOutgoingBitrate=t.availableOutgoingBitrate)}detectIssues(t,e,i){const r=[],n=this._baseline$.value,s=i-this.lastAudioPacketChangeTime;s>this.noAudioPacketThresholdMs&&r.push({type:"no_inbound_audio",severity:"critical",timestamp:i,value:s,threshold:this.noAudioPacketThresholdMs});const a=i-this.lastVideoPacketChangeTime;if(a>this.noVideoPacketThresholdMs&&r.push({type:"no_inbound_video",severity:"warning",timestamp:i,value:a,threshold:this.noVideoPacketThresholdMs}),n.ready){const o=t.roundTripTime,c=n.rtt;if(c>0){const p=o/c;p>this.rttSpikeCriticalMultiplier?r.push({type:"high_rtt",severity:"critical",timestamp:i,value:o,threshold:c*this.rttSpikeCriticalMultiplier}):p>this.rttSpikeWarningMultiplier&&r.push({type:"high_rtt",severity:"warning",timestamp:i,value:o,threshold:c*this.rttSpikeWarningMultiplier})}const u=t.audioJitter,h=n.jitter;h>0&&u/h>this.jitterSpikeMultiplier&&r.push({type:"high_jitter",severity:"warning",timestamp:i,value:u,threshold:h*this.jitterSpikeMultiplier})}if(e){const o=Math.max(0,t.audioPacketsReceived-e.audioPacketsReceived),c=Math.max(0,t.audioPacketsLost-e.audioPacketsLost),u=Math.max(0,t.videoPacketsReceived-e.videoPacketsReceived),h=Math.max(0,t.videoPacketsLost-e.videoPacketsLost),p=o+u,f=Zg(c+h,p);f>this.packetLossCriticalPercent?r.push({type:"high_packet_loss",severity:"critical",timestamp:i,value:f,threshold:this.packetLossCriticalPercent}):f>this.packetLossWarningPercent&&r.push({type:"high_packet_loss",severity:"warning",timestamp:i,value:f,threshold:this.packetLossWarningPercent})}return r}};const oe=W(),ef=2e3,tf=1e4,rf=3e3,nf=5e3,sf=3,af=3,of=3e3,cf=1e4,lf=150,uf=300,df=5,hf=new Set(["high_rtt","high_jitter","high_packet_loss"]);var pf=class extends ie{constructor(t,e,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=t,this._inputs=e,this._config={debounceTimeMs:i.debounceTimeMs??ef,cooldownMs:i.cooldownMs??tf,iceGracePeriodMs:i.iceGracePeriodMs??rf,iceRestartTimeoutMs:i.iceRestartTimeoutMs??nf,maxAttempts:i.maxAttempts??sf,enableRelayFallback:i.enableRelayFallback??!0,keyframeMaxBurst:i.keyframeMaxBurst??af,keyframeBurstWindowMs:i.keyframeBurstWindowMs??of,keyframeCooldownMs:i.keyframeCooldownMs??cf,degradationBitrateThreshold:i.degradationBitrateThreshold??lf,degradationRecoveryThreshold:i.degradationRecoveryThreshold??uf,enableAutoDegradation:i.enableAutoDegradation??!0,packetLossRecoveryDelaySec:i.packetLossRecoveryDelaySec??df},this.initPipeline(),this.initDegradationRecoveryPipeline()}get recoveryState$(){return this._recoveryState$.asObservable().pipe(S(this._destroyed$))}get recoveryState(){return this._recoveryState$.value}get recoveryEvent$(){return this._recoveryEvent$.asObservable().pipe(S(this._destroyed$))}get bandwidthConstrained$(){return this._bandwidthConstrained$.asObservable().pipe(S(this._destroyed$))}get bandwidthConstrained(){return this._bandwidthConstrained$.value}pushTrigger(t){this._trigger$.next(t)}async requestIceRestart(){if(this._recoveryState$.value==="recovering"){oe.info("CallRecoveryManager: manual ICE restart skipped — recovery already in progress");return}oe.info("CallRecoveryManager: manual ICE restart requested"),this.transitionTo("recovering"),await this.executeIceRestart(!1),this.startCooldown()}requestKeyframe(){this.executeKeyframe("manual request")}reset(){oe.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")&&(oe.info("CallRecoveryManager: verto.modify failed — re-entering recovery"),this._cooldownUntil=0,this.transitionTo("idle"),this.pushTrigger({source:"network",detail:"modify_failed_during_recovery"}))}reportBandwidth(t){if(!this._config.enableAutoDegradation)return;const e=this._bandwidthConstrained$.value;!e&&t<this._config.degradationBitrateThreshold?(this._bandwidthConstrained$.next(!0),this._callbacks.disableVideo(),this.emitEvent({action:"video_disabled",reason:`bandwidth ${t}kbps below threshold ${this._config.degradationBitrateThreshold}kbps`,timestamp:Date.now()}),oe.warn(`CallRecoveryManager: disabling video — bandwidth ${t}kbps < ${this._config.degradationBitrateThreshold}kbps`)):e&&t>=this._config.degradationRecoveryThreshold&&(this._bandwidthConstrained$.next(!1),this._callbacks.enableVideo(),this.emitEvent({action:"video_restored",reason:`bandwidth ${t}kbps recovered above ${this._config.degradationRecoveryThreshold}kbps`,timestamp:Date.now()}),oe.info(`CallRecoveryManager: restoring video — bandwidth ${t}kbps >= ${this._config.degradationRecoveryThreshold}kbps`))}reportNetworkIssues(t){const e=t.some(i=>i.type==="high_packet_loss");e!==this._hasPacketLoss$.value&&this._hasPacketLoss$.next(e)}handleWebSocketReconnect(){const t=this._callbacks.getPeerConnectionState();t==="connected"||t==="completed"?(oe.info("CallRecoveryManager: signal-only reconnect — peer connection still alive"),this.emitEvent({action:"signal_reconnect",reason:"WebSocket reconnected, peer connection still connected",timestamp:Date.now()})):(oe.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(Se(()=>{this._recoveryState$.value==="idle"&&this.transitionTo("debouncing")}),Xa(this._config.debounceTimeMs),Za(this._inputs.signalingReady$),B(([,t])=>this.passGateChecks(t)),E(([t])=>t),qn(t=>this.executeTieredRecovery(t)),S(xi(this._destroyed$,this._pipelineStop$))),{next:()=>{},error:t=>{oe.error("CallRecoveryManager: pipeline error",t),this.transitionTo("idle")}})}initDegradationRecoveryPipeline(){if(!this._config.enableAutoDegradation)return;const t=this._config.packetLossRecoveryDelaySec*1e3;this.subscribeTo(Ha([this._bandwidthConstrained$,this._hasPacketLoss$]).pipe(Ke(([e,i])=>e&&!i?ki(t):Jt),S(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()}),oe.info(`CallRecoveryManager: restoring video — no packet loss for ${this._config.packetLossRecoveryDelaySec}s`)})}passGateChecks(t){return this._callbacks.isNegotiating()?(oe.debug("CallRecoveryManager: gate blocked — negotiation in progress"),this.transitionTo("idle"),!1):t?this._callbacks.isCallConnected()?this.isCooldownActive()?(oe.debug("CallRecoveryManager: gate blocked — cooldown active"),this.transitionTo("cooldown"),!1):!0:(oe.debug("CallRecoveryManager: gate blocked — call not connected"),this.transitionTo("idle"),!1):(oe.debug("CallRecoveryManager: gate blocked — signaling not ready"),this.transitionTo("idle"),!1)}isCooldownActive(){return Date.now()<this._cooldownUntil}executeTieredRecovery(t){return this.transitionTo("recovering"),oe.info(`CallRecoveryManager: starting tiered recovery — source=${t.source} detail=${t.detail}`),Ie(this.runTiers(t)).pipe(Se(()=>this.startCooldown()),ei(e=>(oe.error("CallRecoveryManager: tiered recovery failed",e),this.startCooldown(),Jt)))}async runTiers(t){if(this.executeKeyframe(t.detail),t.issueType&&hf.has(t.issueType)){oe.debug(`CallRecoveryManager: degradation-only issue (${t.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()}),oe.warn("CallRecoveryManager: max recovery attempts reached"))}executeKeyframe(t){const e=Date.now();if(e<this._keyframeCooldownUntil){oe.debug("CallRecoveryManager: keyframe request skipped — cooldown active");return}if(e-this._keyframeBurstStart>this._config.keyframeBurstWindowMs&&(this._keyframeBurstCount=0,this._keyframeBurstStart=e),this._keyframeBurstCount>=this._config.keyframeMaxBurst){this._keyframeCooldownUntil=e+this._config.keyframeCooldownMs,oe.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:t,timestamp:e}),oe.debug(`CallRecoveryManager: keyframe requested (burst ${this._keyframeBurstCount}/${this._config.keyframeMaxBurst})`)}async executeIceRestart(t){this._attemptCount+=1;const e=t?"Tier 3 (relay-only)":"Tier 2 (standard)";oe.info(`CallRecoveryManager: ${e} ICE restart — attempt ${this._attemptCount}/${this._config.maxAttempts}`),this.emitEvent({action:"reinvite_started",reason:`${e} ICE restart`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()});try{return await this.withTimeout(this._callbacks.requestIceRestart(t),this._config.iceRestartTimeoutMs)?(this.emitEvent({action:"reinvite_succeeded",reason:`${e} ICE restart succeeded`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),oe.info(`CallRecoveryManager: ${e} ICE restart succeeded`),this._attemptCount=0,!0):(this.emitEvent({action:"reinvite_failed",reason:`${e} ICE restart returned false`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),oe.warn(`CallRecoveryManager: ${e} ICE restart failed`),!1)}catch{return this.emitEvent({action:"reinvite_timeout",reason:`${e} ICE restart timed out after ${this._config.iceRestartTimeoutMs}ms`,attempt:this._attemptCount,maxAttempts:this._config.maxAttempts,timestamp:Date.now()}),oe.warn(`CallRecoveryManager: ${e} ICE restart timed out`),!1}}async withTimeout(t,e){return new Promise((i,r)=>{const n=setTimeout(()=>{r(new Error(`Timeout after ${e}ms`))},e);t.then(s=>{clearTimeout(n),i(s)},s=>{clearTimeout(n),r(s instanceof Error?s:new Error(String(s)))})})}transitionTo(t){const e=this._recoveryState$.value;e!==t&&(oe.debug(`CallRecoveryManager: state ${e} -> ${t}`),this._recoveryState$.next(t))}startCooldown(){this._cooldownUntil=Date.now()+this._config.cooldownMs,this.transitionTo("cooldown"),this._cooldownSubscription&&this._cooldownSubscription.unsubscribe(),this._cooldownSubscription=ki(this._config.cooldownMs).pipe(Me(1),S(this._destroyed$),B(()=>this._recoveryState$.value==="cooldown")).subscribe(()=>this.transitionTo("idle"))}emitEvent(t){this._recoveryEvent$.next(t)}},gf=class{constructor(t,e,i){this.executeMethod=t,this.vertoManager=e,this.deviceController=i}createSelfParticipant(t){return new Wo(t,this.executeMethod,this.vertoManager,this.deviceController)}createParticipant(t){return new jo(t,this.executeMethod,this.deviceController)}};const ff=93.2,vf=.024,bf=2.5,mf=0,yf=100,wf=1,Sf=5,Cf=4,Af=3.5,Tf=3,Ef=2;function kf(t,e,i){const r=ff-(t/2+e)*vf-i*bf,n=Math.min(yf,Math.max(mf,r)),s=1+.035*n+n*(n-60)*(100-n)*7e-6;return Math.min(Sf,Math.max(wf,s))}function xf(t){return t>=Cf?"excellent":t>=Af?"good":t>=Tf?"fair":t>=Ef?"poor":"critical"}const me=W(),Df=5/3,If=t=>{if(!t)return{};try{const e=new URL(`destination:${t}`),i={};return e.searchParams.forEach((r,n)=>{i[n]=r}),i}catch(e){return me.warn(`Failed to parse destination URI: ${t}`,e),{}}};var Mf=class extends ie{constructor(t,e,i,r){super(),this.clientSession=t,this.options=e,this.address=r,this._errors$=this.createReplaySubject(1),this._lastMergedStatus="new",this._answered$=this.createReplaySubject(),this._holdState=!1,this._userVariables$=this.createBehaviorSubject({...g.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=e.callId??Qr(),this.to=e.to,this._userVariables$.next({...this._userVariables$.value,...If(e.to),...e.userVariables}),this.subscribeTo(this.webrtcMessages$,o=>{const c=tt(o,"params.userVariables");c&&this._userVariables$.next({...this._userVariables$.value,...c})});const n=i.initializeManagers(this);this.vertoManager=n.vertoManager,this.callEventsManager=n.callEventsManager,e.initOffer?(this._status$=this.createBehaviorSubject("ringing"),this._lastMergedStatus="ringing"):this._status$=this.createBehaviorSubject("new");const{deviceController:s,networkChange$:a}=i;this._networkChange$=a,this.participantFactory=new gf(this.executeMethod.bind(this),this.vertoManager,s),this.subscribeTo(xi(this._status$.asObservable(),this.vertoManager.signalingStatus$).pipe(L(),S(this._destroyed$)),o=>{var c;this._lastMergedStatus=o,o==="connected"&&!this._statsMonitor?this.initResilienceSubsystems():o==="disconnected"?((c=this._statsMonitor)==null||c.destroy(),this._statsMonitor=void 0):(o==="destroyed"||o==="failed")&&this.stopResilienceSubsystems()})}get errors$(){return this.deferEmission(this._errors$.asObservable())}emitError(t){this._status$.value==="destroyed"||this._status$.value==="failed"||(this._errors$.next(t),t.fatal&&(this._status$.next("failed"),this.destroy()))}notifyModifyFailed(){var t;(t=this._recoveryManager)==null||t.notifyModifyFailed()}get direction(){return this.options.initOffer?"inbound":"outbound"}get address$(){return this.deferEmission(Ie([this.address])).pipe(S(this._destroyed$))}get fromName(){return this.options.fromName}get from(){return this.options.from}get toName(){return this.options.toName}async toggleIncomingVideo(){throw new ft}async toggleIncomingAudio(){throw new ft}addCallId(t){this.callEventsManager.addCallId(t)}get capabilities(){return this.callEventsManager.capabilities}get participants(){return this.callEventsManager.participants}get self(){return this.callEventsManager.self}async toggleLock(){const t=this.locked?"call.unlock":"call.lock";await this.executeMethod(this.selfId??"",t,{})}async toggleHold(){this._holdState?await this.vertoManager.unhold():await this.vertoManager.hold(),this._holdState=!this._holdState}async startRecording(){throw new ft}async startStreaming(){throw new ft}async setMeta(t){throw new ft}async updateMeta(t){throw new ft}get layoutLayers$(){return this.deferEmission(this.callEventsManager.layoutLayers$).pipe(S(this._destroyed$))}get layoutLayers(){return this.callEventsManager.layoutLayers}async executeMethod(t,e,i){var s,a,o;const r=this.buildMethodParams(t,i),n=Oi({method:e,params:r});try{const c=await this.clientSession.execute(n);if(lg(c))throw new _t(parseInt(((s=c.result)==null?void 0:s.code)??"0"),`Error response from method ${e}: ${(a=c.result)==null?void 0:a.code} ${(o=c.result)==null?void 0:o.message}`,void 0,void 0,n.id);return c}catch(c){throw me.error(`[Call] Error executing method ${e} with params`,r,c),c}}buildMethodParams(t,e){const i={node_id:this.nodeId??"",call_id:this.id,member_id:this.vertoManager.selfId??""};return typeof t=="object"?{...e,self:i,targets:[t]}:{...e,self:i,target:{node_id:this.nodeId??"",call_id:this.id,member_id:t}}}get status$(){return this.publicCachedObservable("status$",()=>xi(this._status$.asObservable(),this.vertoManager.signalingStatus$).pipe(L(),Se(t=>{this._lastMergedStatus=t})))}get participants$(){return this.deferEmission(this.callEventsManager.participants$).pipe(S(this._destroyed$))}get self$(){return this.deferEmission(this.callEventsManager.self$).pipe(S(this._destroyed$))}get recording$(){return this.deferEmission(this.callEventsManager.recording$).pipe(S(this._destroyed$))}get streaming$(){return this.deferEmission(this.callEventsManager.streaming$).pipe(S(this._destroyed$))}get raiseHandPriority$(){return this.deferEmission(this.callEventsManager.raiseHandPriority$).pipe(S(this._destroyed$))}get locked$(){return this.deferEmission(this.callEventsManager.locked$).pipe(S(this._destroyed$))}get meta$(){return this.deferEmission(this.callEventsManager.meta$).pipe(S(this._destroyed$))}get capabilities$(){return this.deferEmission(this.callEventsManager.capabilities$).pipe(S(this._destroyed$))}get layout$(){return this.deferEmission(this.callEventsManager.layout$).pipe(S(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(S(this._destroyed$))}get layouts(){return this.callEventsManager.layouts}get localStream$(){return this.deferEmission(this.vertoManager.localStream$).pipe(S(this._destroyed$))}get localStream(){return this.vertoManager.localStream}get remoteStream$(){return this.deferEmission(this.vertoManager.remoteStream$).pipe(S(this._destroyed$))}get remoteStream(){return this.vertoManager.remoteStream}get userVariables$(){return this.deferEmission(this._userVariables$.asObservable())}get userVariables(){return{...this._userVariables$.value}}set userVariables(t){this._userVariables$.next({...this._userVariables$.value,...t})}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(t){this._mediaParamsUpdated$.next(t)}requestKeyframe(){var t,e;(e=(t=this.vertoManager).requestKeyframe)==null||e.call(t)}async requestIceRestart(){var t,e;await((e=(t=this.vertoManager).requestIceRestart)==null?void 0:e.call(t))}initResilienceSubsystems(){const t=this.rtcPeerConnection;if(me.debug(`[Call] initResilienceSubsystems: pc=${t?"exists":"undefined"}, connectionState=${t==null?void 0:t.connectionState}`),!t){me.warn("[Call] No peer connection available, skipping resilience init");return}try{const e=g.instance;this._statsMonitor=new $g(t,{pollingIntervalMs:e.statsPollingInterval,baselineSamples:e.statsBaselineSamples,noAudioPacketThresholdMs:e.statsNoPacketThreshold,rttSpikeWarningMultiplier:e.statsRttSpikeMultiplier,rttSpikeCriticalMultiplier:e.statsRttSpikeMultiplier*Df,packetLossWarningPercent:e.statsPacketLossThreshold*100,packetLossCriticalPercent:e.statsPacketLossThreshold*200,jitterSpikeMultiplier:e.statsJitterSpikeMultiplier,historyWindowSeconds:e.statsHistorySize}),this._recoveryManager=new pf({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,n;try{this.vertoManager.requestIceRestartAll?await this.vertoManager.requestIceRestartAll(i):await((n=(r=this.vertoManager).requestIceRestart)==null?void 0:n.call(r,i))}catch{return!1}return this.waitForPeerConnectionConnected()},disableVideo:()=>{try{this.vertoManager.muteMainVideoInputDevice(),me.debug("[Call] Recovery manager disabled video")}catch{me.debug("[Call] Recovery manager failed to disable video")}},enableVideo:()=>{this.vertoManager.unmuteMainVideoInputDevice().catch(()=>{me.debug("[Call] Recovery manager failed to enable video")})},isNegotiating:()=>this.vertoManager.mainPeerConnection.isNegotiating,isCallConnected:()=>this._lastMergedStatus==="connected",getPeerConnectionState:()=>t.connectionState},{signalingReady$:this.clientSession.authenticated$},{debounceTimeMs:e.recoveryDebounceTime,cooldownMs:e.recoveryCooldown,iceGracePeriodMs:e.iceDisconnectedGracePeriod,iceRestartTimeoutMs:e.iceRestartTimeout,maxAttempts:e.maxRecoveryAttempts,enableRelayFallback:e.enableRelayFallback,keyframeMaxBurst:e.keyframeMaxBurst,keyframeBurstWindowMs:e.keyframeBurstWindow,keyframeCooldownMs:e.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 n=i[i.length-1],s=n.audio.packetsReceived+n.video.packetsReceived,a=n.audio.packetsLost+n.video.packetsLost,o=s+a>0?a/(s+a)*100:0,c=kf(n.roundTripTime,n.audio.jitter,o);this._qualityScore$.next(c),this._qualityLevel$.next(xf(c)),n.availableOutgoingBitrate!==void 0&&((r=this._recoveryManager)==null||r.reportBandwidth(n.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"&&(me.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,n;i.type==="offline"?(r=this._recoveryManager)==null||r.pushTrigger({source:"network",detail:"browser went offline"}):i.type==="online"&&((n=this._recoveryManager)==null||n.handleWebSocketReconnect())}),this.subscribeTo(this.clientSession.authenticated$.pipe(Wr(1),B(Boolean)),()=>{var i;me.debug("[Call] WebSocket reconnected — notifying recovery manager"),(i=this._recoveryManager)==null||i.handleWebSocketReconnect()}),this._statsMonitor.start(),me.debug("[Call] Resilience subsystems initialized for call",this.id)}catch(e){me.warn("[Call] Failed to initialize resilience subsystems:",e)}}async waitForPeerConnectionConnected(){const t=this.rtcPeerConnection;if(!t)return!1;const e=Date.now()+Xh;for(;;){const i=t.connectionState;if(i==="connected")return!0;if(i==="failed"||i==="closed"||Date.now()>=e)return!1;await new Promise(r=>setTimeout(r,Yh))}}stopResilienceSubsystems(){var t,e;try{(t=this._statsMonitor)==null||t.destroy(),(e=this._recoveryManager)==null||e.destroy()}catch{}this._statsMonitor=void 0,this._recoveryManager=void 0}createParticipant(t,e){return t===(e??this.vertoManager.selfId)?this.participantFactory.createSelfParticipant(t):this.participantFactory.createParticipant(t)}get mediaDirections$(){return this.deferEmission(this.vertoManager.mediaDirections$).pipe(S(this._destroyed$))}get mediaDirections(){return this.vertoManager.mediaDirections}get participantsId$(){return this.cachedObservable("participantsId$",()=>this.participants$.pipe(E(t=>t.map(e=>e.id))))}async execute(t,e){return this.clientSession.execute(t,e)}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(t){try{me.debug("[Call] Checking if event is for this call session:",t);const e=tt(t,"params.params.callID")??tt(t,"params.call_id"),i=tt(t,"params.room_session_id");return me.debug(`[Call] Extracted session identifiers callID: ${e} and roomSessionID: ${i} from event:`),e===this.id||!!e&&this.callEventsManager.isCallIdValid(e)||!!i&&this.callEventsManager.isRoomSessionIdValid(i)}catch(e){return me.error("[Call] Error checking if event is for this call session:",e),!1}}get callSessionEvents$(){return this.cachedObservable("callSessionEvents$",()=>this.clientSession.signalingEvent$.pipe(B(t=>this.isCallSessionEvent(t)),Se(t=>{me.debug("[Call] Received call session event:",t)}),S(this.destroyed$),Et()))}get callUpdated$(){return this.publicCachedObservable("callUpdated$",()=>this.callSessionEvents$.pipe(fe(Xo,"params"),S(this.destroyed$)))}get memberJoined$(){return this.publicCachedObservable("memberJoined$",()=>this.callSessionEvents$.pipe(fe(Zo,"params"),S(this.destroyed$)))}get memberLeft$(){return this.publicCachedObservable("memberLeft$",()=>this.callSessionEvents$.pipe(fe(Qo,"params"),S(this.destroyed$)))}get memberUpdated$(){return this.publicCachedObservable("memberUpdated$",()=>this.callSessionEvents$.pipe(fe(Ko,"params"),S(this.destroyed$)))}get memberTalking$(){return this.publicCachedObservable("memberTalking$",()=>this.callSessionEvents$.pipe(fe(Jo,"params"),S(this.destroyed$)))}get callStates$(){return this.publicCachedObservable("callStates$",()=>this.callSessionEvents$.pipe(fe(Yo,"params"),S(this.destroyed$)))}get layoutUpdates$(){return this.publicCachedObservable("layoutUpdates$",()=>this.callSessionEvents$.pipe(fe(os,"params"),S(this.destroyed$)))}get rtcPeerConnection(){return this.vertoManager.mainPeerConnection.peerConnection}get signalingEvent$(){return this.publicCachedObservable("signalingEvent$",()=>this.callEvent$.pipe(E(t=>JSON.parse(JSON.stringify(t)))))}subscribe(t){const e=this._customSubscriptions.get(t);if(e)return e;const i=this.callSessionEvents$.pipe(B(r=>r.event_type===t),E(r=>JSON.parse(JSON.stringify(r))),S(this._destroyed$));return this._sendVertoSubscribe(t).then(()=>{this._customSubscriptions.set(t,i)},r=>{this._customSubscriptions.delete(t),me.warn(`[Call] verto.subscribe for '${t}' failed, not caching:`,r)}),this._customSubscriptions.set(t,i),i}get webrtcMessages$(){return this.cachedObservable("webrtcMessages$",()=>this.callSessionEvents$.pipe(fe(nn,"params"),Se(t=>me.debug("[Call] Event is a WebRTC message event:",t)),S(this.destroyed$),Et()))}get callEvent$(){return this.cachedObservable("callEvent$",()=>this.callSessionEvents$.pipe(fe(ug,"params"),Se(t=>me.debug("[Call] Event is a call event:",t)),S(this.destroyed$),Et()))}get layoutEvent$(){return this.cachedObservable("layoutEvent$",()=>this.callEvent$.pipe(fe(os,"params")))}async hangup(){this._status$.next("disconnecting");try{await this.vertoManager.bye()}finally{this.destroy()}}async sendDigits(t){return this.vertoManager.sendDigits(t)}answer(t){this._answerMediaOptions=t,this._answered$.next(!0)}get answerMediaOptions(){return this._answerMediaOptions}reject(){this._answered$.next(!1)}get answered$(){return this.deferEmission(this._answered$.asObservable())}async setLayout(t,e){if(!this.layouts.includes(t))throw new ro(`Layout ${t} is not available in the current call layouts: ${this.layouts.join(", ")}`);const i=await Ge(this.selfId$.pipe(B(r=>r!==null)));await this.executeMethod(i,"call.layout.set",{layout:t,positions:e})}async transfer(t){return this.vertoManager.transfer(t)}setLocalMicrophoneGain(t){const e=this.vertoManager.ensureLocalAudioPipeline();if(!e){me.warn("[Call] setLocalMicrophoneGain: audio pipeline unavailable");return}const i=Math.max(0,Math.min(200,t));e.setGain(i/100)}get localMicrophoneGain$(){const t=this.vertoManager.ensureLocalAudioPipeline();return t?this.publicCachedObservable("localMicrophoneGain$",()=>t.gain$.pipe(E(e=>e*100),S(this._destroyed$))):Tt(100).pipe(S(this._destroyed$))}get localAudioLevel$(){const t=this.vertoManager.ensureLocalAudioPipeline();return t?this.publicCachedObservable("localAudioLevel$",()=>t.level$.pipe(S(this._destroyed$),Et())):Tt(0).pipe(S(this._destroyed$))}get localSpeaking$(){const t=this.vertoManager.ensureLocalAudioPipeline();return t?this.publicCachedObservable("localSpeaking$",()=>t.speaking$.pipe(S(this._destroyed$),Et())):Tt(!1).pipe(S(this._destroyed$))}enablePushToTalk(){const t=this.vertoManager.ensureLocalAudioPipeline();if(!t){me.warn("[Call] enablePushToTalk: audio pipeline unavailable");return}t.setPTTActive(!1),this._pushToTalkEnabled=!0}disablePushToTalk(){var t;(t=this.vertoManager.localAudioPipeline)==null||t.setPTTActive(!0),this._pushToTalkEnabled=!1}setPushToTalkActive(t){var e;this._pushToTalkEnabled&&((e=this.vertoManager.localAudioPipeline)==null||e.setPTTActive(t))}async setEchoCancellation(t){await this.vertoManager.updateMediaConstraints({audio:{echoCancellation:t}})}async setNoiseSuppression(t){await this.vertoManager.updateMediaConstraints({audio:{noiseSuppression:t}})}async setAutoGainControl(t){await this.vertoManager.updateMediaConstraints({audio:{autoGainControl:t}})}get remoteAudioLevel$(){return this.publicCachedObservable("remoteAudioLevel$",()=>{this._remoteAudioMeter??(this._remoteAudioMeter=new Bg);const t=this._remoteAudioMeter;return this.subscribeTo(this.vertoManager.remoteStream$,e=>{t.setStream(e)}),t.level$.pipe(S(this._destroyed$),Et())})}destroy(){var t;this._status$.value!=="destroyed"&&(this._status$.next("destroyed"),this.stopResilienceSubsystems(),(t=this._remoteAudioMeter)==null||t.destroy(),this._remoteAudioMeter=null,this.vertoManager.destroy(),this.callEventsManager.destroy(),super.destroy())}async _sendVertoSubscribe(t){const e=$p({sessid:this.id,eventChannel:[t]}),i={callID:this.id,node_id:this.vertoManager.nodeId??"",message:e};await this.clientSession.execute(Bo(i))}};function Rf(t){return t instanceof Xr?"timeout":t instanceof _t?"signaling":t instanceof Ii?"media":t instanceof $a||t instanceof eo?"network":"internal"}const Pf=new Set([wo,Co,So]);function Of(t){return!(t instanceof so||t instanceof Ii||t instanceof Xr||t instanceof _t&&Pf.has(t.code))}var _f=class{constructor(t,e,i,r,n){this.sessionManager=t,this.deviceController=e,this.attachManager=i,this.webRTCApiProvider=r,this.networkChange$=n}createCall(t,e){return new Mf(this.sessionManager,e,{initializeManagers:i=>({vertoManager:new Ng(i,this.attachManager,this.deviceController,this.webRTCApiProvider,{nodeId:e.nodeId,onError:r=>{const n={kind:Rf(r),fatal:Of(r),error:r,callId:i.id};i.emitError(n)},onModifyFailed:()=>{i.notifyModifyFailed()}}),callEventsManager:new yg(i)}),deviceController:this.deviceController,networkChange$:this.networkChange$},t)}};const ds=W();var lc=class{constructor(t,e,i){this.endpoint=t,this.http=i,this.filter=r=>!0,this.mapper=r=>r,this.nextUrl=`${this.endpoint}?${e}`}async next(){if(!this.nextUrl)return this.hasMore=!1,[];const t=await this.http.request({...$n,url:this.nextUrl});if(t.ok&&t.body){const e=JSON.parse(t.body);return this.nextUrl=e.links.next,this.hasMore=!!this.nextUrl,e.data.filter(this.filter).map(this.mapper)}return ds.error("Failed to fetch entity"),[]}async id(t){const e=await this.http.request({...$n,url:`${this.endpoint}/${String(t)}`});if(e.ok&&e.body)return JSON.parse(e.body)}},uc=class extends ie{constructor(t,e,i){super(),this.fetchController=t,this.update$=e,this.onError=i,this.collectionData=new Map,this.observablesRegistry=new Map,this.upsertData=r=>{var o;if(!r.id)return;const n=this.collectionData.get(r.id)??{},s={},a=new Set([...Object.keys(n),...Object.keys(r)]);for(const c of a){const u=n[c],h=r[c];h!==void 0&&u!==void 0&&typeof u=="object"&&u!==null&&!Array.isArray(u)&&typeof h=="object"&&h!==null&&!Array.isArray(h)?s[c]={...u,...h}:h!==void 0?s[c]=h:s[c]=u}this.collectionData.set(r.id,s),(o=this.observablesRegistry.get(r.id))==null||o.next(s),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$=$t(()=>Ie(this.init())).pipe(Ke(()=>this._hasMore$),L(),et(1),S(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(L(),Wr(1),B(t=>!t),E(()=>{}),S(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 t;try{this._loading$.next(!0),(await this.fetchController.next()).forEach(this.upsertData),this._hasMore$.next(this.fetchController.hasMore??!1),this._loading$.next(!1)}catch(e){ds.error("Failed to fetch initial collection data",e),this._hasMore$.next(this.fetchController.hasMore??!1),this._loading$.next(!1),(t=this.onError)==null||t.call(this,new ao("fetchMore",e))}}async tryFetch(t,e){var i,r,n;try{this._loading$.next(!0);const s=await((r=(i=this.fetchController)[t])==null?void 0:r.call(i,e));return this._loading$.next(!1),s&&this.upsertData(s),s}catch(s){ds.error(`Failed to fetch data for (${String(t)}:${String(e)}) :`,s),this._loading$.next(!1),(n=this.onError)==null||n.call(this,new ao(`tryFetch(${String(t)})`,s))}}get$(t){var e,i;if(!this.observablesRegistry.has(t)){this.observablesRegistry.set(t,new Bn(1));const r=this.collectionData.get(t);r?(e=this.observablesRegistry.get(t))==null||e.next(r):this.tryFetch("id",t)}return(i=this.observablesRegistry.get(t))==null?void 0:i.asObservable()}async find$(t,e){const i=Array.from(this.collectionData.values()).find(r=>r[t]===e)??await this.tryFetch(t,e);return i?this.get$(i.id):void 0}loadMore(){this.fetchController.hasMore!==!1&&this.fetchMore()}destroy(){this.observablesRegistry.forEach(t=>t.complete()),this.observablesRegistry.clear(),super.destroy()}},dc=class{constructor(t,e=r=>!!r,i=r=>r){this.originalCollection=t,this.filter=e,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(E(t=>t.filter(this.filter).map(this.mapper))))}get$(t){const e=this.originalCollection.get$(t);return e&&e.pipe(zr(B(this.filter),E(this.mapper)))}async find$(t,e){const i=await this.originalCollection.find$(t,e);return i&&i.pipe(zr(B(this.filter),E(this.mapper)))}loadMore(){this.originalCollection.loadMore()}destroy(){this.originalCollection.destroy()}},hc=class extends ie{constructor(t,e,i){super(),this.addressId=t,this.conversationManager=e,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$=$t(this.initConversationMessages).pipe(E(()=>this.textMessage),et(1),S(this.destroyed$)),this.history$=$t(this.initConversationMessages).pipe(E(()=>this.history),et(1),S(this.destroyed$)),this._state$=this.createBehaviorSubject(null)}upnext(t){const e={...this._state$.value,...t};this._state$.next(e)}get state(){return this._state$.value}get id(){return this.addressId}get name(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.name}get createdAt(){if(!this._state$.value)throw new Q("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(ue(),E(t=>t.display_name),S(this.destroyed$)))}get displayName(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.display_name}get previewUrl$(){return this.cachedObservable("previewUrl$",()=>this._state$.pipe(ue(),E(t=>t.preview_url),S(this.destroyed$)))}get previewUrl(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.preview_url}get coverUrl$(){return this.cachedObservable("coverUrl$",()=>this._state$.pipe(ue(),et(1),E(t=>t.cover_url),S(this.destroyed$)))}get coverUrl(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.cover_url}get resourceId$(){return this.cachedObservable("resourceId$",()=>this._state$.pipe(ue(),et(1),E(t=>t.resource_id),S(this.destroyed$)))}get resourceId(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.resource_id}get type$(){return this.cachedObservable("type$",()=>this._state$.pipe(ue(),et(1),E(t=>t.type),S(this.destroyed$)))}get type(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.type}get channels$(){return this.cachedObservable("channels$",()=>this._state$.pipe(ue(),et(1),E(t=>t.channels),S(this.destroyed$)))}get channels(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.channels}get locked(){if(!this._state$.value)throw new Q("state not initialized");return this._state$.value.locked}get locked$(){return this.cachedObservable("locked$",()=>this._state$.pipe(ue(),et(1),E(t=>t.locked),S(this.destroyed$)))}async sendText(t){return this.conversationManager.sendText(t,this.id)}get textMessage(){if(this._conversationMessages)return this._textMessages$=this._textMessages$??new dc(this._conversationMessages,t=>t.subtype==="chat",t=>({id:t.id,text:t.text,created:t.ts,fromAddress$:this.addressProvider.get$(t.from_fabric_address_id)})),this._textMessages$}get history(){if(this._conversationMessages)return this._history$=this._history$??new dc(this._conversationMessages,t=>t.subtype==="log",t=>({id:t.id,kind:t.kind,status:t.details.status,started:t.details.start_time,ended:t.details.end_time,fromAddress$:this.addressProvider.get$(t.from_fabric_address_id)})),this._history$}get activity$(){throw new ft}get activity(){throw new ft}};const oi=W(),Lf=t=>{if(oi.debug("isRPCConnectResult check:",t),!t||typeof t!="object")return!1;const e=t,i=typeof e.identity=="string"&&typeof e.protocol=="string"&&typeof e.authorization=="object"&&typeof e.authorization.jti=="string"&&typeof e.authorization.project_id=="string"&&typeof e.authorization.fabric_subscriber=="object";return oi.debug("isRPCConnectResult check result:",i),i};var Ff=(pi=class{constructor(e,i,r){this.id=Qr(),oi.debug(`[PendingRPC(${this.id}) request:${e.id}: method:${e.method}] Creating PendingRPC`),this.request=e;const n=(r==null?void 0:r.timeoutMs)??pi.defaultTimeoutMs,s=r==null?void 0:r.signal;this.promise=new Promise((a,o)=>{if(s!=null&&s.aborted){o(new DOMException("The operation was aborted","AbortError"));return}let c=!1;const u=or(i.pipe(B(h=>h.id===e.id),Me(1)),new be(h=>{const p=setTimeout(()=>{h.error(new Xr(e.id,n))},n);return()=>clearTimeout(p)}),s?new be(h=>{const p=()=>{h.error(new DOMException("The operation was aborted","AbortError"))};return s.addEventListener("abort",p),()=>s.removeEventListener("abort",p)}):vd).subscribe({next:h=>{if(c=!0,h.error){const p=new _t(h.error.code,h.error.message,h.error.data,void 0,e.id);oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Rejecting promise with RPC error:`,p),o(p)}else oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Resolving promise with response:`,h),a(h);u.unsubscribe()},error:h=>{oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Rejecting promise with error:`,h),c=!0,o(h),u.unsubscribe()},complete:()=>{oi.debug(`[PendingRPC(${this.id}) request:${e.id}] Observable completed`),c||o(new Xr(e.id,n)),u.unsubscribe()}})})}async then(e,i){return this.promise.then(e,i)}async catch(e){return this.promise.catch(e)}async finally(e){return this.promise.finally(e)}},pi.defaultTimeoutMs=5e3,pi);const X=W(),Uf=t=>{var n,s;const e=(n=t.to)==null?void 0:n.split("?")[0],i=(s=t.from)!=null&&s.startsWith("subscriber://")?t.from.replace("subscriber://",""):t.from,r=e??i;if(!r)throw new Di("Error building Address name");return r};var Nf=class extends ie{constructor(t,e,i,r,n,s,a,o,c){super(),this.getCredential=t,this.transport=e,this.storage=i,this.authorizationStateKey=r,this.attachManager=s,this.dpopManager=o,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._userInfo$=this.createBehaviorSubject(null),this._calls$=this.createBehaviorSubject({}),this._iceServers$=this.createBehaviorSubject([]),s.setSession(this),this.callFactory=new _f(this,n,s,a,c),this.initialized$=$t(()=>Ie(this.init())).pipe(et(1),S(this.destroyed$))}get incomingCalls$(){return this.cachedObservable("incomingCalls$",()=>this.calls$.pipe(E(t=>t.filter(e=>e.direction==="inbound"))))}get incomingCalls(){return Object.values(this._calls$.value).filter(t=>t.direction==="inbound")}get userInfo$(){return this._userInfo$.asObservable()}get userInfo(){return this._userInfo$.value}get calls$(){return this.cachedObservable("calls$",()=>this._calls$.pipe(E(t=>Object.values(t))))}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(E(t=>t.kind==="authenticated"),L())}get authenticated(){return this._authState$.value.kind==="authenticated"}get clientBound(){return this._wasClientBound}get authState(){return this._authState$.value}setDirectory(t){this._directory=t}async execute(t,e){try{return await this.transport.execute(t,e)}catch(i){throw X.debug("[Session] Execute Error",i),this._errors$.next(i instanceof Error?i:new Error(String(i),{cause:i})),i}}send(t){this.transport.send(t)}async init(){return await this.loadAuthorizationStateFromStorage(),this.setupMessageHandlers(),!0}setupMessageHandlers(){X.debug("[Session] Setting up message handlers"),this.subscribeTo(this.authStateEvent$,async t=>{X.debug("[Session] Authorization state event received:",t);try{await this.updateAuthorizationStateInStorage(t.authorization_state)}catch(e){X.error("[Session] Failed to handle authorization state update:",e),this._errors$.next(new Yn(e))}}),this.subscribeTo(this.transport.connectionStatus$.pipe(B(t=>t==="disconnected"||t==="reconnecting")),()=>{this._authState$.value.kind==="authenticated"&&this._authState$.next({kind:"unauthenticated"})}),this.subscribeTo(this.transport.connectionStatus$.pipe(B(t=>t==="connected"),qn(()=>(X.debug("[Session] Connection established, initiating authentication"),Ie(this.authenticate()).pipe(ei(t=>(this.handleAuthenticationError(t).catch(e=>{X.error("[Session] Error handling authentication failure:",e)}),Jt)))))),void 0),this.subscribeTo(this.vertoInvite$,async t=>{X.debug("[Session] Verto invite received:",t);try{await this.createInboundCall(t)}catch(e){X.error("[Session] Error handling Verto invite:",e),this._errors$.next(new zd(e))}}),this.subscribeTo(this.vertoAttach$,async t=>{X.debug("[Session] Verto attach received:",t);try{await this.handleVertoAttach(t)}catch(e){X.error("[Session] Error handling Verto attach:",e),this._errors$.next(new Vd(e))}})}async loadAuthorizationStateFromStorage(){try{const t=await this.storage.getItem(this.authorizationStateKey);this.authorizationState$.next(t??void 0)}catch(t){X.error("Failed to retrieve authorization state from storage:",t),this.authorizationState$.next(void 0)}}async updateAuthorizationStateInStorage(t){if(!t){X.debug("[Session] Removing authorization state from storage");try{await this.storage.removeItem(this.authorizationStateKey),this.authorizationState$.next(void 0)}catch(e){throw X.error("Failed to remove authorization state from storage:",e),e}return}try{X.debug("[Session] Updating authorization state in storage"),await this.storage.setItem(this.authorizationStateKey,t),this.authorizationState$.next(t)}catch(e){throw X.error("Failed to retrieve authorization state from storage:",e),e}}get authStateEvent$(){return this.cachedObservable("authStateEvent$",()=>this.signalingEvent$.pipe(Se(t=>{X.debug("[Session] Received incoming message:",t)}),fe(dg,"params"),Se(t=>{X.debug("[Session] Authorization state event received:",t.authorization_state)})))}get signalingEvent$(){return this.cachedObservable("signalingEvent$",()=>this.transport.incomingEvent$.pipe(fe(as,"params"),Et()))}get vertoInvite$(){return this.cachedObservable("vertoInvite$",()=>this.signalingEvent$.pipe(B(nn),B(t=>ac(t.params)),E(t=>({node_id:t.node_id,...t.params.params}))))}get vertoAttach$(){return this.cachedObservable("vertoAttach$",()=>this.signalingEvent$.pipe(B(nn),B(t=>oc(t.params)),E(t=>({node_id:t.node_id,...t.params.params}))))}get contexts(){return[]}get eventing(){return[]}get topics(){return[]}get authentication(){const t=this.getCredential();if(!t.token)throw new Q("Credential token is undefined");return{jwt_token:t.token}}async connect(){await Ge(this.initialized$),await this.transport.connect(),await Ge(this.authenticated$.pipe(S(this.destroyed$),B(Boolean),Me(1),ar({first:15e3})))}async handleAuthenticationError(t){X.error("Authentication error:",t);const e=t instanceof _t&&(t.code===wo||t.code===So||t.code===Co),i=await Ge(this.authorizationState$.pipe(Me(1)))!==void 0;if(e&&i){X.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");try{await this.cleanupStoredConnectionParams()}catch(r){X.error("Failed to cleanup stored connection params:",r)}finally{this.transport.reconnect()}}else this._errors$.next(t)}async cleanupStoredConnectionParams(){await this.transport.setProtocol(void 0),await this.updateAuthorizationStateInStorage(void 0),this._authorization$.next(void 0)}async updateAuthState(t){try{await this.storage.setItem(this.authorizationStateKey,t)}catch(e){X.error("Failed to update authorization state in storage:",e),this._errors$.next(new Yn(e))}}async reauthenticate(t,e,i){var r,n;X.debug("[Session] Re-authenticating session");try{let s=e;if(!s&&((r=this.dpopManager)!=null&&r.initialized))try{s=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"})}catch(o){if(this.clientBound)throw o;X.warn("[Session] Failed to create DPoP proof for reauthenticate:",o)}const a=Wp({project:((n=this._authorization$.value)==null?void 0:n.project_id)??"",jwt_token:t,...s?{dpop_token:s}:{}});await Ba(Ie(this.transport.execute(a)).pipe(uo(),Me(1),ei(o=>{throw X.error("[Session] Re-authentication RPC failed:",o),o}))),i!=null&&i.clientBound&&(this._wasClientBound=!0),X.debug("[Session] Re-authentication successful, updating stored auth state")}catch(s){throw X.error("[Session] Re-authentication failed:",s),this._errors$.next(new Yn(s)),s}}async authenticate(){var o,c;X.debug("[Session] Starting authentication process");const t=await Ge(Ha({protocol:this.transport.protocol$,authorization_state:this.authorizationState$}).pipe(Me(1)));X.debug(`[Session] Persisted params:
|
|
73
|
+
`,{protocol:t.protocol,authStateLength:(o=t.authorization_state)==null?void 0:o.length});const e=t.authorization_state&&t.protocol,i=this.getCredential().token,r=e&&i;let n;if(r?X.debug("[Session] Reconnecting with stored jwt_token + authorization_state"):this.onBeforeReconnect&&this.clientBound&&(X.debug("[Session] Refreshing credentials before fresh connect"),await this.onBeforeReconnect()),(!r||this.clientBound)&&((c=this.dpopManager)!=null&&c.initialized))try{n=await this.dpopManager.createRpcProof({method:"signalwire.connect"})}catch(u){if(this.clientBound)throw u;X.warn("[Session] Failed to create DPoP proof for connect, proceeding without:",u)}const s=jp({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,...n?{dpop_token:n}:{},...r?{authorization_state:t.authorization_state,protocol:t.protocol}:{}}),a=await Ba(Ie(this.transport.execute(s)).pipe(uo(),E(u=>u.result),B(Lf),Se(()=>{X.debug("[Session] Response passed filter, processing authentication result")}),Me(1),ei(u=>{throw X.error("[Session] Authentication RPC failed:",u),u})));X.debug("[Session] Processing authentication result:",{hasProtocol:!!a.protocol,hasAuthorization:!!a.authorization,hasIceServers:!!a.ice_servers}),a.protocol&&await this.transport.setProtocol(a.protocol),this._authorization$.next(a.authorization),this._iceServers$.next(a.ice_servers??[]),this._authState$.next({kind:"authenticated"}),X.debug("[Session] Authentication completed successfully")}async disconnect(){this.transport.disconnect(),this._authState$.next({kind:"unauthenticated"}),await this.cleanupStoredConnectionParams()}async createInboundCall(t){const e=await this.createCall({nodeId:t.node_id,callId:t.callID,initOffer:t.sdp,toName:t.callee_id_name,to:t.callee_id_number,fromName:t.caller_id_name,from:t.caller_id_number,displayDirection:t.display_direction,userVariables:t.userVariables});this._calls$.next({[`${e.id}`]:e,...this._calls$.value})}async handleVertoAttach(t){const{callID:e}=t;if(e in this._calls$.value){X.debug(`[Session] Verto attach for existing call ${e}, deferring to per-call handler`);return}const i=await this.attachManager.consumePendingAttachment(e);X.debug(`[Session] Creating reattached call for callID: ${e}`);const r=await this.createCall({nodeId:t.node_id,callId:e,toName:t.callee_id_name,to:t.callee_id_number,fromName:t.caller_id_name,from:t.caller_id_number,reattach:!0,...i});this._calls$.next({[`${r.id}`]:r,...this._calls$.value})}async createOutboundCall(t,e={}){const i=t instanceof hc?t.defaultChannel:t;let r;try{return r=await this.createCall({to:i,...e}),await Ge(or(r.selfId$.pipe(B(n=>!!n),Me(1),ar(this.callCreateTimeout)),r.errors$.pipe(Me(1),Ke(n=>td(()=>n.error))))),this._calls$.next({[`${r.id}`]:r,...this._calls$.value}),r}catch(n){X.error("[Session] Error creating outbound call:",n),r==null||r.destroy();const s=new io(n instanceof Va?"Call create timeout":"Call creation failed",n,"outbound");throw this._errors$.next(s),s}}async createCall(t={}){try{const e=Uf(t);let i;try{if(!this._directory)throw new Q("Directory not initialized");const n=await this._directory.findAddressIdByURI(e);if(!n)throw new Q(`Address name: ${e} not found`);if(i=this._directory.get(n),!i)throw new Q(`Address ID: ${n} not found`)}catch{X.warn(`[Session] Directory lookup failed for ${e}, proceeding with raw URI`)}const r=this.callFactory.createCall(i,{...t});return this.subscribeTo(r.status$.pipe(B(n=>n==="destroyed"),Me(1)),()=>{const{[`${r.id}`]:n,...s}=this._calls$.value;this._calls$.next(s)}),r}catch(e){throw X.error("[Session] Error creating call session:",e),new io("Call create error",e,t.initOffer?"inbound":"outbound")}}destroy(){for(const t of Object.values(this._calls$.value))t.hangup();super.destroy()}},Bf=class{constructor(t){this.clientSessionManager=t}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(t,e){return this.clientSessionManager.execute(t,e)}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 zf=t=>typeof t=="string",hs=W();var Vf=class extends lc{constructor(t,e){super(`/api/fabric/conversations/${t}/messages`,"page_size=100",e),this.groupId=t}},Hf=class extends uc{constructor(t,e,i,r){super(new Vf(t,i),e,r)}},jf=class{constructor(t,e,i,r){this.clientSession=t,this.http=e,this.getUserAddressId=i,this.onError=r,this.groupIds=new Map}async join(t){const e=this.getUserAddressId();try{const i=await this.http.request({...Jr,url:"/api/fabric/conversations/join",body:JSON.stringify({from_fabric_address_id:e,fabric_address_ids:[t,e]})});if(i.ok&&i.body){const r=JSON.parse(i.body);if(zf(r.group_id))return this.groupIds.set(t,r.group_id),r.group_id}throw new no("Join Failed - Unexpected response")}catch(i){throw hs.error("[ConversationsManager] Failed to join conversation:",i),i}}async getConversationMessageCollection(t){const e=this.groupIds.get(t)??await this.join(t);return Promise.resolve(new Hf(e,this.clientSession.signalingEvent$.pipe(fe($o,"params"),Se(i=>hs.debug("[ConversationsManager ] Conversation Event:",i)),E(i=>({...i}))),this.http,this.onError))}async sendText(t,e){const i=this.groupIds.get(e)??await this.join(e),r=this.getUserAddressId();try{if((await this.http.request({...Jr,url:"/api/fabric/messages",body:JSON.stringify({group_id:i,from_fabric_address_id:r,text:t})})).ok)return;throw new no("Send Text Failed - Unexpected response")}catch(n){throw hs.error("[ConversationsManager] Failed to send text message:",n),n}}};const st=W();function Wf(t){return t.expires_at?t.expires_at:t.expires_in?Math.floor(Date.now()/1e3)+t.expires_in:(st.warn("[DeviceToken] Could not determine token expiry, using default"),Math.floor(Date.now()/1e3)+lr)}function pc(t){return t.expires_in?t.expires_in:t.expires_at?Math.max(t.expires_at-Math.floor(Date.now()/1e3),1):lr}var Gf=class extends ie{constructor(t,e,i,r){super(),this.dpopManager=t,this.http=e,this.errorHandler=i,this.getCredential=r,this._currentToken$=this.createBehaviorSubject(null),this._refreshInProgress=!1,this._effectiveExpireIn=lr,this.subscribeTo(this._currentToken$.pipe(B(Boolean),Ke(n=>{const s=Wf(n),a=Math.max(s*1e3-Date.now()-Ah,1e3);return st.debug(`[DeviceToken] Scheduling Client Bound SAT refresh in ${a}ms`),ki(a)})),()=>{this.executeRefresh()})}get effectiveExpireIn(){return this._effectiveExpireIn}async activate(t,e,i){var n;const{satClaims:r}=t;if(!((n=r==null?void 0:r.scope)!=null&&n.includes(Ch))){st.debug("[DeviceToken] No sat:refresh scope, skipping Client Bound SAT activation");return}this._session=e,this._updateCredential=i;try{const s=await this.obtainToken();!s.expires_at&&!s.expires_in&&r.expires_at&&(s.expires_at=r.expires_at),this._effectiveExpireIn=pc(s);const a=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"});await e.reauthenticate(s.token,a,{clientBound:!0}),i({token:s.token}),st.info("[DeviceToken] Client Bound SAT activated successfully"),this._currentToken$.next(s)}catch(s){st.error("[DeviceToken] Failed to activate Client Bound SAT:",s),this.errorHandler(new Kr(s,"Failed to activate Client Bound SAT"));const a=this.getCredential(),o=r.expires_at??(a.expiry_at?a.expiry_at/1e3:Date.now()/1e3+lr/1e3);this._currentToken$.next({token:a.token??"",expires_at:o})}}async obtainToken(){const t=await this.dpopManager.createHttpProof({method:"POST",uri:vo}),e=await this.http.request({url:vo,...Jr,body:JSON.stringify({dpop_token:t,expire_in:lr})});if(!e.ok||!e.body)throw new oo(`Failed to obtain device token: ${e.status} ${e.statusText}`);const i=JSON.parse(e.body);if(!i.token)throw new oo("Device token response missing token field");return i}async refreshToken(t,e,i){st.debug("[DeviceToken] Refreshing Client Bound SAT");const r=await this.dpopManager.createHttpProof({method:"POST",uri:bo,accessToken:e}),n=await this.http.request({url:bo,...Jr,body:JSON.stringify({dpop_token:r,expire_in:this._effectiveExpireIn})});if(!n.ok||!n.body)throw new ii(`Failed to refresh device token: ${n.status} ${n.statusText}`);const s=JSON.parse(n.body);if(!s.token)throw new ii("Device token refresh response missing token field");!s.expires_at&&!s.expires_in&&(s.expires_in=this._effectiveExpireIn),this._effectiveExpireIn=pc(s);const a=await this.dpopManager.createRpcProof({method:"signalwire.reauthenticate"});return await t.reauthenticate(s.token,a),i({token:s.token}),st.info("[DeviceToken] Client Bound SAT refreshed successfully"),s}async executeRefresh(){if(this._refreshInProgress){st.debug("[DeviceToken] Refresh already in progress, skipping");return}const t=this._session,e=this._updateCredential;if(!t||!e){st.warn("[DeviceToken] Cannot refresh: session or updateCredential not set");return}if(!t.authenticated){st.debug("[DeviceToken] Session not authenticated, deferring refresh");return}this._refreshInProgress=!0;try{const i=this.getCredential().token;if(!i)throw new ii("No current token available for refresh");const r=await this.retryRefresh(t,i,e);this._currentToken$.next(r)}catch(i){st.error("[DeviceToken] Automatic Client Bound SAT refresh failed:",i),this.errorHandler(i instanceof ii?i:new ii("Automatic token refresh failed",i))}finally{this._refreshInProgress=!1}}async retryRefresh(t,e,i){let r;for(let n=0;n<mo;n++)try{return await this.refreshToken(t,e,i)}catch(s){if(r=s,n<mo-1){const a=Th*Math.pow(2,n);st.warn(`[DeviceToken] Refresh attempt ${n+1} failed, retrying in ${a}ms`),await new Promise(o=>setTimeout(o,a))}}throw r instanceof Error?r:new ii("All refresh retries exhausted",r)}destroy(){super.destroy()}};const ps=W(),qf=1e3;function Xf(){try{if(typeof navigator<"u"&&navigator.userAgent)return navigator.userAgent}catch{}return"unknown"}var Yf=class extends ie{constructor(t){super(),this._events=[],this._calls=[],this._deviceChanges=[],this._eventRecorded$=this.createSubject(),this._sdkVersion=t.sdkVersion,this._maxEvents=t.maxEvents??qf,ps.debug("DiagnosticsCollector initialized",{sdkVersion:this._sdkVersion,maxEvents:this._maxEvents})}get eventRecorded$(){return this._eventRecorded$.asObservable()}record(t,e,i){const r={timestamp:Date.now(),category:t,event:e,...i!==void 0?{details:i}:{}};this._events=this._appendToBuffer(this._events,r),this._eventRecorded$.next(r)}recordDeviceChange(t,e){const i={timestamp:Date.now(),category:"device",event:t,...e!==void 0?{details:e}:{}};this._deviceChanges=this._appendToBuffer(this._deviceChanges,i),this._events=this._appendToBuffer(this._events,i),this._eventRecorded$.next(i)}recordCallSummary(t){this._calls=this._appendCallToBuffer(this._calls,t),this.record("call","call_summary",{callId:t.callId,direction:t.direction,duration:t.duration,finalStatus:t.finalStatus})}export(){return{sdkVersion:this._sdkVersion,userAgent:Xf(),exportedAt:Date.now(),events:[...this._events],calls:[...this._calls],deviceChanges:[...this._deviceChanges]}}clear(){this._events=[],this._calls=[],this._deviceChanges=[],ps.debug("DiagnosticsCollector buffers cleared")}destroy(){ps.debug("DiagnosticsCollector destroyed"),super.destroy()}_appendToBuffer(t,e){const i=[...t,e];return i.length>this._maxEvents?i.slice(i.length-this._maxEvents):i}_appendCallToBuffer(t,e){const i=[...t,e];return i.length>this._maxEvents?i.slice(i.length-this._maxEvents):i}};const gc=t=>((t==null?void 0:t.length)??0)===0,Kf=t=>{t.pipe(Me(1)).subscribe()},Zf=W();var Qf=class extends lc{constructor(t){super("/api/fabric/addresses","sort_by=name&sort_order=asc",t)}async name(t){const e=await this.http.request({...$n,url:`${this.endpoint}?name=${encodeURIComponent(t)}`});if(e.ok&&e.body){const i=JSON.parse(e.body);if(!gc(i.data))return i.data[0]}Zf.error("Failed to fetch addresses")}},Jf=class extends uc{constructor(t,e,i){super(new Qf(e),t,i)}},$f=class extends ie{constructor(t,e,i,r){super(),this.http=t,this.conversationManager=i,this.onError=r,this.addNewAddress=n=>{var o;const s=new hc(n,this.conversationManager,this),a=(o=this._statesCollection.get$(n))==null?void 0:o.pipe(ue(),E(c=>(s.upnext(c),s)));a&&(Kf(a),this._observableRegistry.set(n,a)),this._addressesInstances.set(n,s)},this._addresses$=this.createBehaviorSubject([]),this._addressesInstances=new Map,this._observableRegistry=new Map,this._statesCollection=new Jf(e.signalingEvent$.pipe(fe(ec,"params"),E(n=>({}))),this.http,this.onError),this.initSubscriptions()}get loading(){return this._statesCollection.loading}initSubscriptions(){this.subscribeTo(this._statesCollection.updated$,()=>{const t=Array.from(this._addressesInstances.values().map(i=>i.id)),e=this._statesCollection.values.filter(i=>!t.includes(i.id));gc(e)||(e.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$(t){return this._observableRegistry.has(t)||this.addNewAddress(t),this._observableRegistry.get(t)}get(t){return this._addressesInstances.get(t)}async findAddressIdByURI(t){var i;let e=(i=this._addressesInstances.values().find(r=>r.name===t))==null?void 0:i.id;if(!e){const r=await this._statesCollection.find$("name",t);if(r){const n=await Ge(r);this.addNewAddress(n.id),e=n.id}}return e}};const fc=W();var ev=(yt=class extends ie{constructor(e,i,r,n={}){super(),this.WebSocketConstructor=e,this.endpoint=i,this.outgoingMessages$=r,this.messageQueue=[],this.shouldReconnect=!1,this.boundHandleOpen=()=>this.handleOpen(),this.boundHandleClose=s=>this.handleClose(s),this.boundHandleError=()=>this.handleError(),this.boundHandleMessage=s=>this.handleMessage(s),this._status$=this.createBehaviorSubject("disconnected"),this._incomingMessages$=this.createSubject(),this._errors$=this.createReplaySubject(1),this.reconnectDelayMin=n.reconnectDelayMin??yt.DEFAULT_RECONNECT_DELAY_MIN_MS,this.reconnectDelayMax=n.reconnectDelayMax??yt.DEFAULT_RECONNECT_DELAY_MAX_MS,this.connectionTimeout=n.connectionTimeout??yt.DEFAULT_CONNECTION_TIMEOUT_MS,this.currentReconnectDelay=this.reconnectDelayMin,this.subscriptions.push(this.outgoingMessages$.subscribe(s=>{this.send(s)}))}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 e=this._status$.value;e==="connected"||e==="connecting"||e==="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(e){var i;this._status$.value==="connected"&&((i=this.socket)==null?void 0:i.readyState)===1?(fc.wsTraffic({type:"send",raw:e}),this.socket.send(e)):this.messageQueue.push(e)}createWebSocket(){try{this.closeExistingSocket(),this.socket=new this.WebSocketConstructor(this.endpoint),this.setupWebSocketListeners(),this.startConnectionTimeout()}catch(e){const i=e instanceof Error?e:new Di("Failed to create WebSocket");this._errors$.next(i),this.handleConnectionError()}}closeExistingSocket(){if(!this.socket)return;const e=this.socket;this.socket=void 0,this.removeWebSocketListeners(e);try{e.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(e){try{e.removeEventListener("open",this.boundHandleOpen),e.removeEventListener("close",this.boundHandleClose),e.removeEventListener("error",this.boundHandleError),e.removeEventListener("message",this.boundHandleMessage)}catch{}}handleOpen(){this.clearConnectionTimeout(),this._status$.next("connected"),this.currentReconnectDelay=this.reconnectDelayMin,this.flushMessageQueue()}handleClose(e){this.clearConnectionTimeout(),this.shouldReconnect?(this._status$.next("reconnecting"),this.scheduleReconnection()):this._status$.next("disconnected")}handleError(){const e=new $a("WebSocket connection error");this._errors$.next(e),this.handleConnectionError()}handleMessage(e){fc.wsTraffic({type:"recv",raw:e.data}),this._incomingMessages$.next(e)}handleConnectionError(){this.reconnect()}scheduleReconnection(){this.clearReconnectTimer();const e=this.currentReconnectDelay*(.5+Math.random()*.5);this.reconnectTimer=setTimeout(()=>{this.shouldReconnect&&(this._status$.next("connecting"),this.createWebSocket(),this.increaseReconnectDelay())},e)}increaseReconnectDelay(){this.currentReconnectDelay=Math.min(this.currentReconnectDelay*2,this.reconnectDelayMax)}startConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeoutTimer=setTimeout(()=>{if(this._status$.value==="connecting"){const e=new Ld("WebSocket connection timeout");this._errors$.next(e),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 e;for(;this.messageQueue.length>0&&((e=this.socket)==null?void 0:e.readyState)===1;){const i=this.messageQueue.shift();i!==void 0&&this.socket.send(i)}}},yt.DEFAULT_RECONNECT_DELAY_MIN_MS=1e3,yt.DEFAULT_RECONNECT_DELAY_MAX_MS=3e4,yt.DEFAULT_CONNECTION_TIMEOUT_MS=1e4,yt);function tv(t){return ns(t)&&t.method==="signalwire.ping"}const Pe=W();var iv=class extends ie{constructor(t,e,i,r,n){super(),this.storage=t,this.protocolKey=e,this.onError=n,this.protocol$=this.createReplaySubject(1),this.isConnecting=!1,this.isConnected=!1,this.ackEvent=()=>Se(s=>{if(as(s))try{Pe.debug("[Transport] Sending event ack",{eventId:s.id}),this.send(ig(s.id))}catch(a){Pe.error("[Transport] Failed to send event acknowledgment:",a)}}),this.replySignalwirePing=()=>B(s=>{if(tv(s)){try{Pe.debug("[Transport] Received ping, sending pong",{pingId:s.id}),this.send(Gp(s.id))}catch(a){Pe.error("[Transport] Failed to send ping response:",a)}return!1}return!0}),this.discardStaleEvents=()=>B(s=>{if(!as(s))return!0;const a=s.params.event_channel;if(!a)return!0;const o=this._currentProtocol;if(!o)return!0;if(!a.includes(o)){const c=s.params.event_type;return Pe.warn(`[Transport] Discarding stale event: ${c} (event_channel does not match current protocol)`),!1}return!0}),this._outgoingMessages$=this.createSubject(),this._webSocketConnections=new ev(i,r,this._outgoingMessages$.asObservable(),{connectionTimeout:g.instance.connectionTimeout,reconnectDelayMin:g.instance.reconnectDelayMin,reconnectDelayMax:g.instance.reconnectDelayMax}),this.subscribeTo(this._webSocketConnections.errors$,s=>{var a;(a=this.onError)==null||a.call(this,s)}),this.initialized$=$t(()=>Ie(this._init())).pipe(et(1),S(this.destroyed$)),this._jsonRPCMessage$=this._webSocketConnections.incomingMessages$.pipe(E(s=>{var a;try{return JSON.parse(s.data)}catch(o){return Pe.error("[Transport] Failed to parse incoming message:",o),(a=this.onError)==null||a.call(this,new Hd(o)),null}}),B(s=>s!==null&&(ss(s)||ns(s))),ei(s=>{var a;return Pe.error("[Transport] Message processing error:",s),(a=this.onError)==null||a.call(this,s instanceof Error?s:new Error(String(s),{cause:s})),Jt}),Et(),S(this.destroyed$)),this._jsonRPCResponse$=this._jsonRPCMessage$.pipe(B(ss)),this._incomingEvent$=this._jsonRPCMessage$.pipe(this.ackEvent(),this.replySignalwirePing(),B(s=>!ss(s)),this.discardStaleEvents(),Et(),S(this.destroyed$))}async setProtocol(t){this._currentProtocol=t,this.protocol$.next(t),await this._updateProtocolInStorage(t)}get incomingEvent$(){return this._incomingEvent$}get connectionStatus$(){return this._webSocketConnections.status$}async connect(){return this.isConnecting||this.isConnected?(Pe.warn("[Transport] Already connecting or connected"),Promise.resolve()):new Promise((t,e)=>{this.isConnecting=!0,this.subscribeTo(this.initialized$,()=>{this._webSocketConnections.connect();const i=this._webSocketConnections.status$.pipe(B(r=>r==="connected"||r==="disconnected"),Me(1),ar(1e4)).subscribe({next:r=>{var n;if(r==="connected")this.isConnecting=!1,this.isConnected=!0,Pe.debug("[Transport] Connection established"),t();else{this.isConnecting=!1;const s=new eo("Failed to connect");Pe.error("[Transport] Connection failed"),(n=this.onError)==null||n.call(this,s),e(s)}},error:r=>{var n;this.isConnecting=!1,Pe.error("[Transport] Connection error:",r),(n=this.onError)==null||n.call(this,r instanceof Error?r:new Error(String(r),{cause:r})),e(r)}});this.subscriptions.push(i),this.subscribeTo(this._webSocketConnections.status$.pipe(B(r=>r==="disconnected")),()=>{Pe.debug("[Transport] Disconnected"),this.isConnected=!1})})})}reconnect(){this._webSocketConnections.reconnect()}async execute(t,e){return this.send(t),new Ff(t,this._jsonRPCResponse$,e).promise}send(t){const e=JSON.stringify(t);this._outgoingMessages$.next(e)}disconnect(){Pe.debug("[Transport] Disconnecting"),this.isConnected=!1,this.isConnecting=!1,this._webSocketConnections.disconnect()}destroy(){Pe.debug("[Transport] Destroying"),this.disconnect(),super.destroy(),this._webSocketConnections.destroy()}async _loadProtocolFromStorage(){try{const t=await this.storage.getItem(this.protocolKey);this._currentProtocol=t??void 0,this.protocol$.next(t??void 0)}catch(t){throw Pe.error("Failed to retrieve protocol from storage:",t),t}}async _updateProtocolInStorage(t){if(!t){try{await this.storage.removeItem(this.protocolKey)}catch(e){throw Pe.error("Failed to remove protocol from storage:",e),e}return}try{const e=await this.storage.getItem(this.protocolKey);(!e||e!==t)&&await this.storage.setItem(this.protocolKey,t)}catch(e){throw Pe.error("Failed to update protocol in storage:",e),e}}async _init(){return await this._loadProtocolFromStorage(),!0}};const Y=W(),rv=t=>{if(typeof t=="string"){const e=t.indexOf("?");if(e!==-1){const i=t.substring(e+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 vc=class extends ie{constructor(t,e={}){super(),this.preferences=new bp,this._user$=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 Sp,this._credentialProvider=t,this._options={...g.instance.defaultSignalWireOptions,...e},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&&Xd(this._options.logger),this._options.logLevel&&Kd(this._options.logLevel),this._options.debug&&Yd(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=>{Y.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=>{Y.error("[SignalWire] Initialization error:",i),this._errors$.next(i instanceof Error?i:new Error(String(i),{cause:i}))})}async initDPoP(){var t;if((t=this._dpopManager)!=null&&t.initialized)return this._dpopManager.fingerprint;try{this._dpopManager=new kp;const e=await this._dpopManager.init();return Y.debug("[SignalWire] DPoP initialized, fingerprint available"),e}catch(e){Y.warn("[SignalWire] DPoP initialization failed, proceeding without DPoP:",e),this._dpopManager=void 0;return}}async resolveCredentials(){const t=await this.initDPoP();if(this._credentialProvider)return this.validateCredentials(this._credentialProvider,void 0,t);for(const e of this._deps.persistSession?["local","session"]:["session"])try{const i=await this._deps.storage.getItem("sw:cached_credential",e);if(i!=null&&i.token)return Y.debug(`[SignalWire] Using cached credential from ${e}Storage`),await this.validateCredentials(void 0,i)}catch{}throw new ti("No credential provider and no cached session. Provide a CredentialProvider or enable persistSession with a prior login.")}async validateCredentials(t,e,i){var s;const r=i??((s=this._dpopManager)!=null&&s.initialized?this._dpopManager.fingerprint:void 0),n=e??(t?await t.authenticate(r?{fingerprint:r}:void 0):void 0);if(!n)throw new ti("No credentials available.");if(n.token)try{const a=th(n.token,{header:!0});this._deps.ch=a.ch}catch(a){throw Y.error("[SignalWire] Invalid JWT token provided in credentials:",a),new ti("Invalid JWT token provided in credentials.",{cause:a})}if(!n.token&&!n.authorizationState)throw Y.error("[SignalWire] No valid authentication credentials provided."),new ti("No valid authentication credentials provided.");if(!this._deps.persistSession&&n.expiry_at&&n.expiry_at<Date.now())throw Y.error("[SignalWire] Provided credentials have expired."),new ti("Provided credentials have expired.");if(n.expiry_at&&(t!=null&&t.refresh)&&this.scheduleCredentialRefresh(t,n.expiry_at),this._deps.credential=n,this.persistCredential(n),this.isConnected&&this._clientSession.authenticated&&n.token)try{await this._clientSession.reauthenticate(n.token),Y.info("[SignalWire] Session refreshed with new credentials.")}catch(a){Y.error("[SignalWire] Failed to refresh session with new credentials:",a),this._errors$.next(a instanceof Error?a:new Error(String(a),{cause:a}))}}scheduleCredentialRefresh(t,e,i=0){this._refreshTimerId!==void 0&&clearTimeout(this._refreshTimerId);const r=i===0?Math.max(e-Date.now()-xh,1e3):Math.min(Eh*Math.pow(2,i)*(.5+Math.random()*.5),kh);this._refreshTimerId=setTimeout(async()=>{try{if(!t.refresh)throw new ti("Credential provider does not support refresh");const n=await t.refresh();this._deps.credential=n,this.persistCredential(n),Y.info("[SignalWire] Credentials refreshed successfully."),n.expiry_at&&this.scheduleCredentialRefresh(t,n.expiry_at,0)}catch(n){const s=i+1;Y.error(`[SignalWire] Credential refresh failed (attempt ${s}/${yo}):`,n),this._errors$.next(n instanceof Error?n:new Error(String(n),{cause:n})),s<yo?this.scheduleCredentialRefresh(t,e,s):(Y.error("[SignalWire] Credential refresh exhausted all retries. Disconnecting."),this._errors$.next(new ii("Credential refresh failed after max retries")),this.disconnect())}},r)}persistCredential(t){t.token&&(this._deps.storage.setItem("sw:cached_credential",t),this._deps.persistSession&&this._deps.storage.setItem("sw:cached_credential",t,"local"))}async init(){if(this._user$.next(new Vp(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(t){Y.error("[SignalWire] Registration failed:",t),this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t}))}this.handleAttachments()}async handleAttachments(){if(!this._attachManager){Y.error("[SignalWire] AttachManager not initialized");return}if(this._options.reconnectAttachedCalls)try{await this._attachManager.reattachCalls()}catch(t){Y.error("[SignalWire] Failed to reattach calls:",t),this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t}))}}async connect(){var r,n,s;await this.teardownTransportAndSession();try{const a=this._user$.value;if(!a)throw new Di("User not initialized before connect");if(!await Ge(a.fetched$))throw new Di("Failed to fetch user information - fetched$ emitted false");this._deps.user=a}catch(a){throw Y.error(`[SignalWire] Failed to fetch user information: ${a instanceof Error?a.message:"Unknown error"}. This usually means the user token is invalid or expired.`),new Di("Error fetching user information",{cause:a})}const t=a=>{this._errors$.next(a)};this._transport=new iv(this._deps.storage,this._deps.protocolKey,this._deps.WebSocket,g.instance.relayHost??this._deps.relayHost,t),this._attachManager=new rg(this._deps.storage,this._deps.deviceController,g.instance.reconnectCallsTimeout,this._deps.attachedCallsKey),this._clientSession=new Nf(()=>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 Bf(this._clientSession),this._clientSession.onBeforeReconnect=async()=>{var a;if(this._credentialProvider)try{const o=(a=this._dpopManager)!=null&&a.initialized?this._dpopManager.fingerprint:void 0;Y.debug("[SignalWire] Credential expired, refreshing before reconnect");const c=await this._credentialProvider.authenticate(o?{fingerprint:o}:void 0);this._deps.credential=c,Y.debug("[SignalWire] Credential refreshed successfully for reconnect")}catch(o){throw Y.error("[SignalWire] Failed to refresh credentials for reconnect:",o),this._errors$.next(o instanceof Error?o:new Error(String(o),{cause:o})),o}},this.subscribeTo(this._clientSession.errors$,a=>{this._errors$.next(a)}),await this._clientSession.connect(),(n=this._dpopManager)!=null&&n.initialized&&(this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0,Y.debug("[SignalWire] Developer refresh disabled — Client Bound SAT activation starting")),this._deviceTokenManager=new Gf(this._dpopManager,this._deps.http,a=>this._errors$.next(a),()=>this._deps.credential),await this._deviceTokenManager.activate(this._deps.user,this._clientSession,a=>{this._deps.credential={...this._deps.credential,...a}})),this.subscribeTo(this._clientSession.authenticated$.pipe(Wr(1),B(Boolean)),async()=>{try{this._deviceTokenManager&&(await this._deviceTokenManager.activate(this._deps.user,this._clientSession,a=>{this._deps.credential={...this._deps.credential,...a}}),Y.debug("[SignalWire] Client Bound SAT re-activated after reconnect"))}catch(a){Y.error("[SignalWire] Client Bound SAT re-activation failed (non-fatal):",a),this._errors$.next(a instanceof Error?a:new Error(String(a),{cause:a}))}try{Y.debug("[SignalWire] Re-registering user after reconnect"),await this.register(),Y.debug("[SignalWire] User re-registered successfully after reconnect")}catch(a){Y.error("[SignalWire] Re-registration failed after reconnect:",a),this._errors$.next(a instanceof Error?a:new Error(String(a),{cause:a}))}});const e=new jf(this._clientSession,this._deps.http,()=>this._deps.getUserFromAddressId(),t),i=new $f(this._deps.http,this._clientSession,e,t);this._directory$.next(i),this._clientSession.setDirectory(i),this._isConnected$.next(!0),(s=this._diagnosticsCollector)==null||s.record("connection","connected"),this.subscribeTo(this._clientSession.authenticated$.pipe(Wr(2),B(Boolean)),()=>{var a;(a=this._diagnosticsCollector)==null||a.record("connection","reconnected")})}get user$(){return this.deferEmission(this._user$.asObservable())}get user(){return this._user$.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(Ke(t=>t?this._clientSession.authenticated$:Tt(!1))))}get errors$(){return this.deferEmission(this._errors$.asObservable())}get platformCapabilities(){return this._platformCapabilities??(this._platformCapabilities=Lo(this._options.webRTCApiProvider)),this._platformCapabilities}get deviceRecovered$(){return this.deferEmission(this._deviceController.deviceRecovered$)}exportDiagnostics(){const t={audioInput:this.audioInputDevices,audioOutput:this.audioOutputDevices,videoInput:this.videoInputDevices},e={sdkVersion:"unknown",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown",capabilities:this.platformCapabilities,events:[],calls:[],deviceChanges:[],devices:t};if(!this._diagnosticsCollector)return e;const i=this._diagnosticsCollector.export();return{...e,sdkVersion:i.sdkVersion,userAgent:i.userAgent,events:i.events,calls:i.calls,deviceChanges:i.deviceChanges,devices:t}}initResilienceSubsystems(){try{this._platformCapabilities=Lo(this._options.webRTCApiProvider)}catch(t){Y.warn("[SignalWire] Failed to detect platform capabilities:",t)}try{this._networkMonitor=new xp}catch(t){Y.warn("[SignalWire] Failed to initialize NetworkMonitor:",t)}try{this._visibilityController=new Bp,this.subscribeTo(this._visibilityController.visibilityChange$.pipe(B(t=>t.to==="visible"&&g.instance.refreshDevicesOnVisible)),()=>{Y.debug("[SignalWire] Page visible, re-enumerating devices");try{this._deviceController.disableDeviceMonitoring(),this._deviceController.enableDeviceMonitoring()}catch{}})}catch(t){Y.warn("[SignalWire] Failed to initialize VisibilityController:",t)}try{this._diagnosticsCollector=new Yf({sdkVersion:"3.30.0"})}catch(t){Y.warn("[SignalWire] Failed to initialize DiagnosticsCollector:",t)}}async disconnect(){var t;this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0),(t=this._diagnosticsCollector)==null||t.record("connection","disconnected"),await this.teardownTransportAndSession(),this._isConnected$.next(!1)}async teardownTransportAndSession(){const t=this._clientSession,e=this._transport;if(t){try{await t.disconnect()}catch(i){Y.warn("[SignalWire] Error disconnecting previous session:",i)}t.destroy()}e&&e.destroy(),this._clientSession=void 0,this._publicSession=void 0,this._transport=void 0,this._attachManager=void 0}async waitAuthentication(){await Ge(this.ready$.pipe(B(t=>t===!0)))}async register(){try{await this.waitAuthentication(),await this._transport.execute(is({method:"subscriber.online",params:{}})),this._isRegistered$.next(!0);return}catch(t){if(!this._deps.credential.token)throw this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t})),t;Y.debug("[SignalWire] Failed to register user, trying reauthentication...");try{await this._clientSession.reauthenticate(this._deps.credential.token),Y.debug("[SignalWire] Reauthentication successful, retrying register()"),await this._transport.execute(is({method:"subscriber.online",params:{}})),this._isRegistered$.next(!0)}catch(e){Y.error("[SignalWire] Reauthentication failed during register():",e);const i=new ti("Failed to register user, and reauthentication attempt also failed. Please check your credentials.",{cause:e instanceof Error?e:new Error(String(e),{cause:e})});throw this._errors$.next(i),i}}}async unregister(){try{await this._transport.execute(is({method:"subscriber.offline",params:{}})),this._isRegistered$.next(!1)}catch(t){throw Y.error("[SignalWire] Failed to unregister user:",t),this._errors$.next(t instanceof Error?t:new Error(String(t),{cause:t})),t}}async dial(t,e={}){const i={...g.instance.preferredMediaOptions,...rv(t),...e};return await this.waitAuthentication(),Y.debug("[SignalWire] Dialing with options:",i),this._clientSession.createOutboundCall(t,i)}async preflight(t,e){const i=this._clientSession.iceServers??g.instance.iceServers??[],r=this._isConnected$.value;return new Up(this._deviceController,i,r,0,async(n,s)=>this.dial(n,s),e).run(t)}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(t){return this._deviceController.deviceInfoToConstraints(t)}selectAudioInputDevice(t){this._deviceController.selectAudioInputDevice(t)}selectVideoInputDevice(t){this._deviceController.selectVideoInputDevice(t)}selectAudioOutputDevice(t){this._deviceController.selectAudioOutputDevice(t)}async applySelectedAudioOutputDevice(t){const e=this._deviceController.selectedAudioOutputDevice;if(!(e!=null&&e.deviceId))return!1;const i=t;if(typeof i.setSinkId!="function")return Y.warn("[SignalWire] setSinkId not supported on this element / browser"),!1;try{return await i.setSinkId(e.deviceId),!0}catch(r){return Y.warn("[SignalWire] Failed to apply audio output device:",r),!1}}enableDeviceMonitoring(){this._deviceController.enableDeviceMonitoring()}disableDeviceMonitoring(){this._deviceController.disableDeviceMonitoring()}async getDeviceCapabilities(t){return this._deviceController.getDeviceCapabilities(t)}async isValidDevice(t){return this._deviceController.isValidDevice(t)}setStorageManager(t){this._deviceController.setStorageManager(t)}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(t={audio:!0,video:!0}){const e={audio:t.audio??!1,video:t.video??!1};let i=!1,r=!1,n,s;try{const a=(await this._deps.webRTCApiProvider.mediaDevices.getUserMedia(e)).getTracks();for(const o of a){const c=o.getSettings();o.kind==="audio"?(i=!0,c.deviceId&&(n=this.audioInputDevices.find(u=>u.deviceId===c.deviceId))):o.kind==="video"&&(r=!0,c.deviceId&&(s=this.videoInputDevices.find(u=>u.deviceId===c.deviceId))),o.stop()}}catch(a){Y.warn("[SignalWire] Media permission request failed:",a)}if(await this._deviceController.enumerateDevices(),i&&n){const a=n.deviceId;n=this.audioInputDevices.find(o=>o.deviceId===a)??n}if(r&&s){const a=s.deviceId;s=this.videoInputDevices.find(o=>o.deviceId===a)??s}return i&&n&&!this.selectedAudioInputDevice&&this.selectAudioInputDevice(n),r&&s&&!this.selectedVideoInputDevice&&this.selectVideoInputDevice(s),{audio:i,video:r,selectedAudioDevice:n,selectedVideoDevice:s}}async resetToDefaults(){await this._deps.storage.clearAll();const t=g.instance;t.preferredAudioInput=null,t.preferredAudioOutput=null,t.preferredVideoInput=null,await this._deviceController.clearDeviceState()}destroy(){var t,e,i,r,n;this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=void 0),(t=this._deviceTokenManager)==null||t.destroy(),(e=this._dpopManager)==null||e.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{(n=this._diagnosticsCollector)==null||n.destroy()}catch{}this._networkMonitor=void 0,this._visibilityController=void 0,this._diagnosticsCollector=void 0,super.destroy()}};const nv=W();var bc=class{constructor(t,e){this.host=t,this.embedToken=e}async fetchSAT(){const t=`https://${this.host}/api/fabric/embeds/tokens`,e=1e4,i=new AbortController,r=setTimeout(()=>i.abort(),e);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.embedToken}),signal:i.signal});if(clearTimeout(r),n.ok)return(await n.json()).token;throw new Fd(`Failed to fetch SAT using embed token: ${n.status} ${n.statusText}`)}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?new to(`Request timeout after ${e}ms`,{cause:n}):(nv.error("[EmbedCredentialProvider] Request failed:",n),n)}}async authenticate(){return{token:await this.fetchSAT(),expiry_at:Date.now()+3600*1e3}}async refresh(){return this.authenticate()}},mc=class{constructor(t){this.credentials=t}async authenticate(){return Promise.resolve(this.credentials)}};(()=>{if(typeof window<"u"){const t=new CustomEvent("signalwire:js:ready",{detail:{version:"3.30.0"}});window.dispatchEvent(t)}})();var sv=Object.defineProperty,av=Object.getOwnPropertyDescriptor,dr=(t,e,i,r)=>{for(var n=r>1?void 0:r?av(e,i):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(n=(r?a(e,i,n):a(n))||n);return r&&n&&sv(e,i,n),n};const ov=W();l.SwCallMedia=class extends Z{constructor(){super(...arguments),this.stream=null,this._remoteStreamValue=null,this._lastTrackSignature="",this._subscriptions=[]}connectedCallback(){super.connectedCallback(),!this.stream&&this.call&&this._setupDirectSubscriptions(),this.stream&&(this._remoteStreamValue=this.stream,this._lastTrackSignature=this._computeTrackSignature(this.stream))}updated(e){var i,r,n,s,a;if(super.updated(e),e.has("call")&&(this._cleanupDirectSubscriptions(),!this.stream&&this.call&&this._setupDirectSubscriptions()),e.has("stream")){this._cleanupDirectSubscriptions();const o=this.stream,c=this._computeTrackSignature(o);if(o!==this._remoteStreamValue||c!==this._lastTrackSignature){this._remoteStreamValue=o,this._lastTrackSignature=c;const u=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");u&&Lr(u,o)}}if(!this.stream&&!this.call&&e.has("_callState")){const o=((r=this._callState)==null?void 0:r.remoteStream)??null,c=this._computeTrackSignature(o);if(o!==this._remoteStreamValue||c!==this._lastTrackSignature){this._remoteStreamValue=o,this._lastTrackSignature=c;const u=(n=this.shadowRoot)==null?void 0:n.querySelector("video.mcu-video");u&&Lr(u,o)}}e.has("_devicesState")&&this._applySinkId(((a=(s=this._devicesState)==null?void 0:s.selectedAudioOutput)==null?void 0:a.deviceId)??"")}disconnectedCallback(){super.disconnectedCallback(),this._cleanupDirectSubscriptions(),this._cleanupResizeObserver(),this._cleanupVideoElement()}firstUpdated(){var i;const e=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");e&&bu(e).then(()=>{this.isConnected&&this._setupResizeObserver()})}_setupDirectSubscriptions(){this.call&&this._subscriptions.push(this.call.remoteStream$.subscribe(e=>{var n;const i=this._computeTrackSignature(e);if(e===this._remoteStreamValue&&i===this._lastTrackSignature)return;this._remoteStreamValue=e,this._lastTrackSignature=i,this.requestUpdate();const r=(n=this.shadowRoot)==null?void 0:n.querySelector("video.mcu-video");r&&Lr(r,e)}))}_computeTrackSignature(e){return e?e.getTracks().map(i=>`${i.kind}:${i.id}`).sort().join("|"):""}_cleanupDirectSubscriptions(){this._subscriptions.forEach(e=>e.unsubscribe()),this._subscriptions=[]}_applySinkId(e){var r;const i=(r=this.shadowRoot)==null?void 0:r.querySelector("video.mcu-video");i!=null&&i.setSinkId&&i.setSinkId(e).catch(n=>{ov.error("[SwCallMedia] Failed to set audio output device:",n)})}_setupResizeObserver(){var r,n;const e=(r=this.shadowRoot)==null?void 0:r.querySelector("video.mcu-video"),i=(n=this.shadowRoot)==null?void 0:n.querySelector(".padding-wrapper");!e||!i||(this._videoElement=e,this._paddingWrapper=i,this._resizeObserver=new ResizeObserver(fu(()=>this._recalculateDimensions(),50)),this._resizeObserver.observe(this),this._videoResizeHandler=()=>this._recalculateDimensions(),e.addEventListener("resize",this._videoResizeHandler),this._windowResizeHandler=()=>{requestAnimationFrame(()=>this._recalculateDimensions())},window.addEventListener("resize",this._windowResizeHandler),this._recalculateDimensions())}_recalculateDimensions(){const e=this._videoElement,i=this._paddingWrapper;if(!e||!i)return;if(!e.videoWidth||!e.videoHeight){i.style.width="100%",i.style.height="100%",i.style.paddingBottom="0",i.style.transform="none";return}const r=window.innerWidth,n=window.innerHeight,s=this.getBoundingClientRect(),a=s.width,o=s.height;if(a<=0||o<=0)return;const c=Math.min(1,(r-s.left)/a),u=Math.min(1,(n-s.top)/o),h=Math.min(c,u),p=a*h,f=o*h;if(p<=0||f<=0)return;const m=e.videoWidth/e.videoHeight,R=p/f;let y,I;m>R?(y=p,I=y/m):(I=f,y=I*m);const x=Math.max(0,s.left),v=Math.max(0,s.top),b=Math.min(r,s.right),w=Math.min(n,s.bottom),A=(x+b)/2,D=(v+w)/2,F=s.left+a/2,K=s.top+o/2,_=A-F,te=D-K;i.style.width=`${y}px`,i.style.height=`${I}px`,i.style.paddingBottom="0",i.style.transform=`translate(${_}px, ${te}px)`}_cleanupResizeObserver(){var i;this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=void 0);const e=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");e&&this._videoResizeHandler&&(e.removeEventListener("resize",this._videoResizeHandler),this._videoResizeHandler=void 0),this._windowResizeHandler&&(window.removeEventListener("resize",this._windowResizeHandler),this._windowResizeHandler=void 0)}_cleanupVideoElement(){var i;const e=(i=this.shadowRoot)==null?void 0:i.querySelector("video.mcu-video");e&&ca(e)}render(){return k`
|
|
74
74
|
<div class="mcu-content" part="container">
|
|
75
75
|
<div class="padding-wrapper">
|
|
76
76
|
<div class="mcu-wrapper">
|
|
@@ -887,7 +887,7 @@ var SignalWireUI=(function(l){"use strict";var Km=Object.defineProperty;var Vl=l
|
|
|
887
887
|
opacity: 0.6;
|
|
888
888
|
font-size: 0.85em;
|
|
889
889
|
}
|
|
890
|
-
`,Fi([T({type:Object})],l.SwCallStatus.prototype,"call",2),Fi([$e({context:ht,subscribe:!0}),P()],l.SwCallStatus.prototype,"_callState",2),Fi([P()],l.SwCallStatus.prototype,"_directStatus",2),Fi([P()],l.SwCallStatus.prototype,"_callStartTime",2),Fi([P()],l.SwCallStatus.prototype,"_duration",2),l.SwCallStatus=Fi([se("sw-call-status")],l.SwCallStatus);const ui=()=>Promise.resolve(),Cc=()=>{},Ac=Object.freeze({id:"",direction:"outbound",to:void 0,status:"new",recording:!1,streaming:!1,locked:!1,raiseHandPriority:!1,meta:Object.freeze({}),participants:Object.freeze([]),self:null,remoteStream:null,localStream:null,mediaDirections:Object.freeze({audio:"inactive",video:"inactive"}),layout:void 0,layouts:Object.freeze([]),layoutLayers:Object.freeze([]),address:void 0,capabilities:Object.freeze([]),hangup:ui,toggleLock:ui,toggleHold:ui,setLayout:ui,startRecording:ui,startStreaming:ui,sendDigits:ui,answer:Cc,reject:Cc});class bs{constructor(e){this._subscriptions=[],this._state={...Ac},this._batching=!1,this._provider=new On(e,{context:ht,initialValue:this._state}),e.addController(this)}hostConnected(){}hostDisconnected(){this.disconnect()}connect(e){this.disconnect(),this._batching=!0,this._patch({id:e.id,direction:e.direction,to:e.to}),this._patch({hangup:()=>e.hangup(),toggleLock:()=>e.toggleLock(),toggleHold:()=>e.toggleHold(),setLayout:(i,r={})=>e.setLayout(i,r),startRecording:()=>e.startRecording(),startStreaming:()=>e.startStreaming(),sendDigits:i=>e.sendDigits(i),answer:()=>e.answer(),reject:()=>e.reject()}),this._subscriptions=[e.status$.subscribe(i=>this._patch({status:i})),e.recording$.subscribe(i=>this._patch({recording:i})),e.streaming$.subscribe(i=>this._patch({streaming:i})),e.locked$.subscribe(i=>this._patch({locked:i})),e.raiseHandPriority$.subscribe(i=>this._patch({raiseHandPriority:i})),e.meta$.subscribe(i=>this._patch({meta:i})),e.participants$.subscribe(i=>this._patch({participants:i})),e.self$.subscribe(i=>this._patch({self:i})),e.remoteStream$.subscribe(i=>this._patch({remoteStream:i})),e.localStream$.subscribe(i=>this._patch({localStream:i})),e.mediaDirections$.subscribe(i=>this._patch({mediaDirections:i})),e.layout$.subscribe(i=>this._patch({layout:i})),e.layouts$.subscribe(i=>this._patch({layouts:i})),e.layoutLayers$.subscribe(i=>this._patch({layoutLayers:i})),e.address$.subscribe(i=>this._patch({address:i})),e.capabilities$.subscribe(i=>this._patch({capabilities:i}))],this._batching=!1,this._publish()}disconnect(){this._subscriptions.forEach(e=>e.unsubscribe()),this._subscriptions=[],this._patch({...Ac})}_patch(e){this._state={...this._state,...e},this._batching||this._publish()}_publish(){this._provider.setValue(this._state)}}const xe=()=>Promise.resolve(),Tc=Object.freeze({audioInputDevices:Object.freeze([]),audioOutputDevices:Object.freeze([]),videoInputDevices:Object.freeze([]),selectedAudioInput:null,selectedAudioOutput:null,selectedVideoInput:null,audioMuted:!1,videoMuted:!1,speakerMuted:!1,selectAudioInput:()=>{},selectAudioOutput:()=>{},selectVideoInput:()=>{},toggleAudioMute:xe,toggleVideoMute:xe,toggleSpeakerMute:xe,echoCancellation:!0,autoGain:!0,noiseSuppression:!0,toggleEchoCancellation:xe,toggleAutoGain:xe,toggleNoiseSuppression:xe});class ms{constructor(e){this._dc=null,this._deviceSubs=[],this._callSubs=[],this._state={...Tc},this._provider=new On(e,{context:ir,initialValue:this._state}),e.addController(this)}hostConnected(){}hostDisconnected(){this.disconnect()}connectDevices(e){this._dc=e,this._deviceSubs.forEach(i=>i.unsubscribe()),this._patch({selectAudioInput:i=>e.selectAudioInputDevice(i),selectAudioOutput:i=>e.selectAudioOutputDevice(i),selectVideoInput:i=>e.selectVideoInputDevice(i)}),this._deviceSubs=[e.audioInputDevices$.subscribe(i=>this._patch({audioInputDevices:i})),e.audioOutputDevices$.subscribe(i=>this._patch({audioOutputDevices:i})),e.videoInputDevices$.subscribe(i=>this._patch({videoInputDevices:i})),e.selectedAudioInputDevice$.subscribe(i=>this._patch({selectedAudioInput:i})),e.selectedAudioOutputDevice$.subscribe(i=>this._patch({selectedAudioOutput:i})),e.selectedVideoInputDevice$.subscribe(i=>this._patch({selectedVideoInput:i}))],e.enableDeviceMonitoring()}refreshDevices(){this._dc&&this._dc.enableDeviceMonitoring()}connectCall(e){this.disconnectCall();const i=e.self$.subscribe(u=>{this._patch({toggleAudioMute:u?()=>u.toggleMute():xe,toggleVideoMute:u?()=>u.toggleMuteVideo():xe,toggleSpeakerMute:u?()=>u.toggleDeaf():xe,toggleEchoCancellation:u?()=>u.toggleEchoCancellation():xe,toggleAutoGain:u?()=>u.toggleAudioInputAutoGain():xe,toggleNoiseSuppression:u?()=>u.toggleNoiseSuppression():xe})}),r=e.self$.pipe(Ke(u=>u?u.audioMuted$:
|
|
890
|
+
`,Fi([T({type:Object})],l.SwCallStatus.prototype,"call",2),Fi([$e({context:ht,subscribe:!0}),P()],l.SwCallStatus.prototype,"_callState",2),Fi([P()],l.SwCallStatus.prototype,"_directStatus",2),Fi([P()],l.SwCallStatus.prototype,"_callStartTime",2),Fi([P()],l.SwCallStatus.prototype,"_duration",2),l.SwCallStatus=Fi([se("sw-call-status")],l.SwCallStatus);const ui=()=>Promise.resolve(),Cc=()=>{},Ac=Object.freeze({id:"",direction:"outbound",to:void 0,status:"new",recording:!1,streaming:!1,locked:!1,raiseHandPriority:!1,meta:Object.freeze({}),participants:Object.freeze([]),self:null,remoteStream:null,localStream:null,mediaDirections:Object.freeze({audio:"inactive",video:"inactive"}),layout:void 0,layouts:Object.freeze([]),layoutLayers:Object.freeze([]),address:void 0,capabilities:Object.freeze([]),hangup:ui,toggleLock:ui,toggleHold:ui,setLayout:ui,startRecording:ui,startStreaming:ui,sendDigits:ui,answer:Cc,reject:Cc});class bs{constructor(e){this._subscriptions=[],this._state={...Ac},this._batching=!1,this._provider=new On(e,{context:ht,initialValue:this._state}),e.addController(this)}hostConnected(){}hostDisconnected(){this.disconnect()}connect(e){this.disconnect(),this._batching=!0,this._patch({id:e.id,direction:e.direction,to:e.to}),this._patch({hangup:()=>e.hangup(),toggleLock:()=>e.toggleLock(),toggleHold:()=>e.toggleHold(),setLayout:(i,r={})=>e.setLayout(i,r),startRecording:()=>e.startRecording(),startStreaming:()=>e.startStreaming(),sendDigits:i=>e.sendDigits(i),answer:()=>e.answer(),reject:()=>e.reject()}),this._subscriptions=[e.status$.subscribe(i=>this._patch({status:i})),e.recording$.subscribe(i=>this._patch({recording:i})),e.streaming$.subscribe(i=>this._patch({streaming:i})),e.locked$.subscribe(i=>this._patch({locked:i})),e.raiseHandPriority$.subscribe(i=>this._patch({raiseHandPriority:i})),e.meta$.subscribe(i=>this._patch({meta:i})),e.participants$.subscribe(i=>this._patch({participants:i})),e.self$.subscribe(i=>this._patch({self:i})),e.remoteStream$.subscribe(i=>this._patch({remoteStream:i})),e.localStream$.subscribe(i=>this._patch({localStream:i})),e.mediaDirections$.subscribe(i=>this._patch({mediaDirections:i})),e.layout$.subscribe(i=>this._patch({layout:i})),e.layouts$.subscribe(i=>this._patch({layouts:i})),e.layoutLayers$.subscribe(i=>this._patch({layoutLayers:i})),e.address$.subscribe(i=>this._patch({address:i})),e.capabilities$.subscribe(i=>this._patch({capabilities:i}))],this._batching=!1,this._publish()}disconnect(){this._subscriptions.forEach(e=>e.unsubscribe()),this._subscriptions=[],this._patch({...Ac})}_patch(e){this._state={...this._state,...e},this._batching||this._publish()}_publish(){this._provider.setValue(this._state)}}const xe=()=>Promise.resolve(),Tc=Object.freeze({audioInputDevices:Object.freeze([]),audioOutputDevices:Object.freeze([]),videoInputDevices:Object.freeze([]),selectedAudioInput:null,selectedAudioOutput:null,selectedVideoInput:null,audioMuted:!1,videoMuted:!1,speakerMuted:!1,selectAudioInput:()=>{},selectAudioOutput:()=>{},selectVideoInput:()=>{},toggleAudioMute:xe,toggleVideoMute:xe,toggleSpeakerMute:xe,echoCancellation:!0,autoGain:!0,noiseSuppression:!0,toggleEchoCancellation:xe,toggleAutoGain:xe,toggleNoiseSuppression:xe});class ms{constructor(e){this._dc=null,this._deviceSubs=[],this._callSubs=[],this._state={...Tc},this._provider=new On(e,{context:ir,initialValue:this._state}),e.addController(this)}hostConnected(){}hostDisconnected(){this.disconnect()}connectDevices(e){this._dc=e,this._deviceSubs.forEach(i=>i.unsubscribe()),this._patch({selectAudioInput:i=>e.selectAudioInputDevice(i),selectAudioOutput:i=>e.selectAudioOutputDevice(i),selectVideoInput:i=>e.selectVideoInputDevice(i)}),this._deviceSubs=[e.audioInputDevices$.subscribe(i=>this._patch({audioInputDevices:i})),e.audioOutputDevices$.subscribe(i=>this._patch({audioOutputDevices:i})),e.videoInputDevices$.subscribe(i=>this._patch({videoInputDevices:i})),e.selectedAudioInputDevice$.subscribe(i=>this._patch({selectedAudioInput:i})),e.selectedAudioOutputDevice$.subscribe(i=>this._patch({selectedAudioOutput:i})),e.selectedVideoInputDevice$.subscribe(i=>this._patch({selectedVideoInput:i}))],e.enableDeviceMonitoring()}refreshDevices(){this._dc&&this._dc.enableDeviceMonitoring()}connectCall(e){this.disconnectCall();const i=e.self$.subscribe(u=>{this._patch({toggleAudioMute:u?()=>u.toggleMute():xe,toggleVideoMute:u?()=>u.toggleMuteVideo():xe,toggleSpeakerMute:u?()=>u.toggleDeaf():xe,toggleEchoCancellation:u?()=>u.toggleEchoCancellation():xe,toggleAutoGain:u?()=>u.toggleAudioInputAutoGain():xe,toggleNoiseSuppression:u?()=>u.toggleNoiseSuppression():xe})}),r=e.self$.pipe(Ke(u=>u?u.audioMuted$:Tt(!1))).subscribe(u=>this._patch({audioMuted:u})),n=e.self$.pipe(Ke(u=>u?u.videoMuted$:Tt(!1))).subscribe(u=>this._patch({videoMuted:u})),s=e.self$.pipe(Ke(u=>u?u.deaf$:Tt(!1))).subscribe(u=>this._patch({speakerMuted:u})),a=e.self$.pipe(Ke(u=>u?u.echoCancellation$:Tt(!0))).subscribe(u=>this._patch({echoCancellation:u})),o=e.self$.pipe(Ke(u=>u?u.autoGain$:Tt(!0))).subscribe(u=>this._patch({autoGain:u})),c=e.self$.pipe(Ke(u=>u?u.noiseSuppression$:Tt(!0))).subscribe(u=>this._patch({noiseSuppression:u}));this._callSubs=[i,r,n,s,a,o,c]}disconnectCall(){this._callSubs.forEach(e=>e.unsubscribe()),this._callSubs=[],this._patch({audioMuted:!1,videoMuted:!1,speakerMuted:!1,toggleAudioMute:xe,toggleVideoMute:xe,toggleSpeakerMute:xe,echoCancellation:!0,autoGain:!0,noiseSuppression:!0,toggleEchoCancellation:xe,toggleAutoGain:xe,toggleNoiseSuppression:xe})}disconnect(){this._deviceSubs.forEach(e=>e.unsubscribe()),this._deviceSubs=[],this.disconnectCall(),this._patch({...Tc})}_patch(e){this._state={...this._state,...e},this._provider.setValue(this._state)}}var kv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,ys=(t,e,i,r)=>{for(var n=r>1?void 0:r?xv(e,i):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(n=(r?a(e,i,n):a(n))||n);return r&&n&&kv(e,i,n),n};l.SwCallProvider=class extends Z{constructor(){super(...arguments),this.call=void 0,this.deviceController=void 0,this._callState=new bs(this),this._devices=new ms(this)}updated(e){super.updated(e),e.has("call")&&(this.call?(this._callState.connect(this.call),this._devices.connectCall(this.call)):(this._callState.disconnect(),this._devices.disconnectCall())),e.has("deviceController")&&this.deviceController&&this._devices.connectDevices(this.deviceController)}disconnectedCallback(){super.disconnectedCallback(),this._callState.disconnect(),this._devices.disconnect()}render(){return k`<slot></slot>`}},l.SwCallProvider.styles=ne`:host { display: contents; }`,ys([T({attribute:!1})],l.SwCallProvider.prototype,"call",2),ys([T({attribute:!1})],l.SwCallProvider.prototype,"deviceController",2),l.SwCallProvider=ys([se("sw-call-provider")],l.SwCallProvider);var Dv=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,Ui=(t,e,i,r)=>{for(var n=r>1?void 0:r?Iv(e,i):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(n=(r?a(e,i,n):a(n))||n);return r&&n&&Dv(e,i,n),n};const Mv=/^[0-9*#]$/,Rv=500,Pv=[{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:""}];l.SwUiDialpad=class extends Z{constructor(){super(...arguments),this.showCallButton=!1,this.allowText=!1,this.placeholder="Enter number",this.digits="",this.pressedKey=null,this._longPressTimer=null,this._longPressFired=!1}_startLongPress(e){this._cancelLongPress(),this._longPressFired=!1,this._longPressTimer=setTimeout(()=>{this._longPressFired=!0,this._longPressTimer=null,e()},Rv)}_cancelLongPress(){this._longPressTimer!==null&&(clearTimeout(this._longPressTimer),this._longPressTimer=null)}disconnectedCallback(){this._cancelLongPress(),super.disconnectedCallback()}_clearAll(){this.digits.length!==0&&(this.digits="",this.dispatchEvent(new CustomEvent("sw-dialpad-backspace",{detail:{digits:this.digits},bubbles:!0,composed:!0})))}_pressDigit(e){this.digits+=e,this.pressedKey=e,this.dispatchEvent(new CustomEvent("sw-digit-press",{detail:{digit:e,digits:this.digits},bubbles:!0,composed:!0})),setTimeout(()=>{this.pressedKey=null},100)}_backspace(){this.digits.length!==0&&(this.digits=this.digits.slice(0,-1),this.dispatchEvent(new CustomEvent("sw-dialpad-backspace",{detail:{digits:this.digits},bubbles:!0,composed:!0})))}_dial(){this.digits.length!==0&&this.dispatchEvent(new CustomEvent("sw-dial",{detail:{digits:this.digits},bubbles:!0,composed:!0}))}_onKeyDown(e){const{key:i}=e;if(this.allowText){i==="Enter"&&this.showCallButton&&(e.preventDefault(),this._dial());return}Mv.test(i)?(e.preventDefault(),this._pressDigit(i)):i==="Backspace"?(e.preventDefault(),this._backspace()):i==="Enter"&&this.showCallButton?(e.preventDefault(),this._dial()):i!=="Tab"&&!e.ctrlKey&&!e.metaKey&&e.preventDefault()}_onInput(e){if(!this.allowText)return;const i=e.target.value;this.digits=i,this.dispatchEvent(new CustomEvent("sw-dialpad-input",{detail:{digits:this.digits},bubbles:!0,composed:!0}))}render(){return k`
|
|
891
891
|
<div class="container" part="container">
|
|
892
892
|
<div class="display" part="display">
|
|
893
893
|
<input
|
|
@@ -3175,7 +3175,7 @@ var SignalWireUI=(function(l){"use strict";var Km=Object.defineProperty;var Vl=l
|
|
|
3175
3175
|
* @author Lea Verou <https://lea.verou.me>
|
|
3176
3176
|
* @namespace
|
|
3177
3177
|
* @public
|
|
3178
|
-
*/var i=(function(r){var n=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,s=0,a={},o={manual:r.Prism&&r.Prism.manual,disableWorkerMessageHandler:r.Prism&&r.Prism.disableWorkerMessageHandler,util:{encode:function v(b){return b instanceof c?new c(b.type,v(b.content),b.alias):Array.isArray(b)?b.map(v):b.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(v){return Object.prototype.toString.call(v).slice(8,-1)},objId:function(v){return v.__id||Object.defineProperty(v,"__id",{value:++s}),v.__id},clone:function v(b,w){w=w||{};var A,D;switch(o.util.type(b)){case"Object":if(D=o.util.objId(b),w[D])return w[D];A={},w[D]=A;for(var F in b)b.hasOwnProperty(F)&&(A[F]=v(b[F],w));return A;case"Array":return D=o.util.objId(b),w[D]?w[D]:(A=[],w[D]=A,b.forEach(function(K,_){A[_]=v(K,w)}),A);default:return b}},getLanguage:function(v){for(;v;){var b=n.exec(v.className);if(b)return b[1].toLowerCase();v=v.parentElement}return"none"},setLanguage:function(v,b){v.className=v.className.replace(RegExp(n,"gi"),""),v.classList.add("language-"+b)},currentScript:function(){if(typeof document>"u")return null;if(document.currentScript&&document.currentScript.tagName==="SCRIPT")return document.currentScript;try{throw new Error}catch(A){var v=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(A.stack)||[])[1];if(v){var b=document.getElementsByTagName("script");for(var w in b)if(b[w].src==v)return b[w]}return null}},isActive:function(v,b,w){for(var A="no-"+b;v;){var D=v.classList;if(D.contains(b))return!0;if(D.contains(A))return!1;v=v.parentElement}return!!w}},languages:{plain:a,plaintext:a,text:a,txt:a,extend:function(v,b){var w=o.util.clone(o.languages[v]);for(var A in b)w[A]=b[A];return w},insertBefore:function(v,b,w,A){A=A||o.languages;var D=A[v],F={};for(var K in D)if(D.hasOwnProperty(K)){if(K==b)for(var _ in w)w.hasOwnProperty(_)&&(F[_]=w[_]);w.hasOwnProperty(K)||(F[K]=D[K])}var te=A[v];return A[v]=F,o.languages.DFS(o.languages,function(U,ee){ee===te&&U!=v&&(this[U]=F)}),F},DFS:function v(b,w,A,D){D=D||{};var F=o.util.objId;for(var K in b)if(b.hasOwnProperty(K)){w.call(b,K,b[K],A||K);var _=b[K],te=o.util.type(_);te==="Object"&&!D[F(_)]?(D[F(_)]=!0,v(_,w,null,D)):te==="Array"&&!D[F(_)]&&(D[F(_)]=!0,v(_,w,K,D))}}},plugins:{},highlightAll:function(v,b){o.highlightAllUnder(document,v,b)},highlightAllUnder:function(v,b,w){var A={callback:w,container:v,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};o.hooks.run("before-highlightall",A),A.elements=Array.prototype.slice.apply(A.container.querySelectorAll(A.selector)),o.hooks.run("before-all-elements-highlight",A);for(var D=0,F;F=A.elements[D++];)o.highlightElement(F,b===!0,A.callback)},highlightElement:function(v,b,w){var A=o.util.getLanguage(v),D=o.languages[A];o.util.setLanguage(v,A);var F=v.parentElement;F&&F.nodeName.toLowerCase()==="pre"&&o.util.setLanguage(F,A);var K=v.textContent,_={element:v,language:A,grammar:D,code:K};function te(ee){_.highlightedCode=ee,o.hooks.run("before-insert",_),_.element.innerHTML=_.highlightedCode,o.hooks.run("after-highlight",_),o.hooks.run("complete",_),w&&w.call(_.element)}if(o.hooks.run("before-sanity-check",_),F=_.element.parentElement,F&&F.nodeName.toLowerCase()==="pre"&&!F.hasAttribute("tabindex")&&F.setAttribute("tabindex","0"),!_.code){o.hooks.run("complete",_),w&&w.call(_.element);return}if(o.hooks.run("before-highlight",_),!_.grammar){te(o.util.encode(_.code));return}if(b&&r.Worker){var U=new Worker(o.filename);U.onmessage=function(ee){te(ee.data)},U.postMessage(JSON.stringify({language:_.language,code:_.code,immediateClose:!0}))}else te(o.highlight(_.code,_.grammar,_.language))},highlight:function(v,b,w){var A={code:v,grammar:b,language:w};if(o.hooks.run("before-tokenize",A),!A.grammar)throw new Error('The language "'+A.language+'" has no grammar.');return A.tokens=o.tokenize(A.code,A.grammar),o.hooks.run("after-tokenize",A),c.stringify(o.util.encode(A.tokens),A.language)},tokenize:function(v,b){var w=b.rest;if(w){for(var A in w)b[A]=w[A];delete b.rest}var D=new p;return f(D,D.head,v),h(v,D,b,D.head,0),R(D)},hooks:{all:{},add:function(v,b){var w=o.hooks.all;w[v]=w[v]||[],w[v].push(b)},run:function(v,b){var w=o.hooks.all[v];if(!(!w||!w.length))for(var A=0,D;D=w[A++];)D(b)}},Token:c};r.Prism=o;function c(v,b,w,A){this.type=v,this.content=b,this.alias=w,this.length=(A||"").length|0}c.stringify=function v(b,w){if(typeof b=="string")return b;if(Array.isArray(b)){var A="";return b.forEach(function(te){A+=v(te,w)}),A}var D={type:b.type,content:v(b.content,w),tag:"span",classes:["token",b.type],attributes:{},language:w},F=b.alias;F&&(Array.isArray(F)?Array.prototype.push.apply(D.classes,F):D.classes.push(F)),o.hooks.run("wrap",D);var K="";for(var _ in D.attributes)K+=" "+_+'="'+(D.attributes[_]||"").replace(/"/g,""")+'"';return"<"+D.tag+' class="'+D.classes.join(" ")+'"'+K+">"+D.content+"</"+D.tag+">"};function u(v,b,w,A){v.lastIndex=b;var D=v.exec(w);if(D&&A&&D[1]){var F=D[1].length;D.index+=F,D[0]=D[0].slice(F)}return D}function h(v,b,w,A,D,F){for(var K in w)if(!(!w.hasOwnProperty(K)||!w[K])){var _=w[K];_=Array.isArray(_)?_:[_];for(var te=0;te<_.length;++te){if(F&&F.cause==K+","+te)return;var U=_[te],ee=U.inside,ct=!!U.lookbehind,It=!!U.greedy,kr=U.alias;if(It&&!U.pattern.global){var Is=U.pattern.toString().match(/[imsuy]*$/)[0];U.pattern=RegExp(U.pattern.source,Is+"g")}for(var mn=U.pattern||U,Ce=A.next,lt=D;Ce!==b.tail&&!(F&<>=F.reach);lt+=Ce.value.length,Ce=Ce.next){var Ut=Ce.value;if(b.length>v.length)return;if(!(Ut instanceof c)){var he=1,Xe;if(It){if(Xe=u(mn,lt,v,ct),!Xe||Xe.index>=v.length)break;var Mt=Xe.index,Ae=Xe.index+Xe[0].length,yt=lt;for(yt+=Ce.value.length;Mt>=yt;)Ce=Ce.next,yt+=Ce.value.length;if(yt-=Ce.value.length,lt=yt,Ce.value instanceof c)continue;for(var re=Ce;re!==b.tail&&(yt<Ae||typeof re.value=="string");re=re.next)he++,yt+=re.value.length;he--,Ut=v.slice(lt,yt),Xe.index-=lt}else if(Xe=u(mn,0,Ut,ct),!Xe)continue;var Mt=Xe.index,Nt=Xe[0],ut=Ut.slice(0,Mt),xr=Ut.slice(Mt+Nt.length),fi=lt+Ut.length;F&&fi>F.reach&&(F.reach=fi);var vi=Ce.prev;ut&&(vi=f(b,vi,ut),lt+=ut.length),m(b,vi,he);var yn=new c(K,ee?o.tokenize(Nt,ee):Nt,kr,Nt);if(Ce=f(b,vi,yn),xr&&f(b,Ce,xr),he>1){var wt={cause:K+","+te,reach:fi};h(v,b,w,Ce.prev,lt,wt),F&&wt.reach>F.reach&&(F.reach=wt.reach)}}}}}}function p(){var v={value:null,prev:null,next:null},b={value:null,prev:v,next:null};v.next=b,this.head=v,this.tail=b,this.length=0}function f(v,b,w){var A=b.next,D={value:w,prev:b,next:A};return b.next=D,A.prev=D,v.length++,D}function m(v,b,w){for(var A=b.next,D=0;D<w&&A!==v.tail;D++)A=A.next;b.next=A,A.prev=b,v.length-=D}function R(v){for(var b=[],w=v.head.next;w!==v.tail;)b.push(w.value),w=w.next;return b}if(!r.document)return r.addEventListener&&(o.disableWorkerMessageHandler||r.addEventListener("message",function(v){var b=JSON.parse(v.data),w=b.language,A=b.code,D=b.immediateClose;r.postMessage(o.highlight(A,o.languages[w],w)),D&&r.close()},!1)),o;var y=o.util.currentScript();y&&(o.filename=y.src,y.hasAttribute("data-manual")&&(o.manual=!0));function I(){o.manual||o.highlightAll()}if(!o.manual){var x=document.readyState;x==="loading"||x==="interactive"&&y&&y.defer?document.addEventListener("DOMContentLoaded",I):window.requestAnimationFrame?window.requestAnimationFrame(I):window.setTimeout(I,16)}return o})(e);t.exports&&(t.exports=i),typeof Qa<"u"&&(Qa.Prism=i),i.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},i.languages.markup.tag.inside["attr-value"].inside.entity=i.languages.markup.entity,i.languages.markup.doctype.inside["internal-subset"].inside=i.languages.markup,i.hooks.add("wrap",function(r){r.type==="entity"&&(r.attributes.title=r.content.replace(/&/,"&"))}),Object.defineProperty(i.languages.markup.tag,"addInlined",{value:function(n,s){var a={};a["language-"+s]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:i.languages[s]},a.cdata=/^<!\[CDATA\[|\]\]>$/i;var o={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:a}};o["language-"+s]={pattern:/[\s\S]+/,inside:i.languages[s]};var c={};c[n]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return n}),"i"),lookbehind:!0,greedy:!0,inside:o},i.languages.insertBefore("markup","cdata",c)}}),Object.defineProperty(i.languages.markup.tag,"addAttribute",{value:function(r,n){i.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+r+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[n,"language-"+n],inside:i.languages[n]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),i.languages.html=i.languages.markup,i.languages.mathml=i.languages.markup,i.languages.svg=i.languages.markup,i.languages.xml=i.languages.extend("markup",{}),i.languages.ssml=i.languages.xml,i.languages.atom=i.languages.xml,i.languages.rss=i.languages.xml,(function(r){var n=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;r.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+n.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+n.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+n.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+n.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:n,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},r.languages.css.atrule.inside.rest=r.languages.css;var s=r.languages.markup;s&&(s.tag.addInlined("style","css"),s.tag.addAttribute("style","css"))})(i),i.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},i.languages.javascript=i.languages.extend("clike",{"class-name":[i.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+(/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source)+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),i.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,i.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:i.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:i.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:i.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:i.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:i.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),i.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:i.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),i.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),i.languages.markup&&(i.languages.markup.tag.addInlined("script","javascript"),i.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript")),i.languages.js=i.languages.javascript,(function(){if(typeof i>"u"||typeof document>"u")return;Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector);var r="Loading…",n=function(y,I){return"✖ Error "+y+" while fetching file: "+I},s="✖ Error: File does not exist or is empty",a={js:"javascript",py:"python",rb:"ruby",ps1:"powershell",psm1:"powershell",sh:"bash",bat:"batch",h:"c",tex:"latex"},o="data-src-status",c="loading",u="loaded",h="failed",p="pre[data-src]:not(["+o+'="'+u+'"]):not(['+o+'="'+c+'"])';function f(y,I,x){var v=new XMLHttpRequest;v.open("GET",y,!0),v.onreadystatechange=function(){v.readyState==4&&(v.status<400&&v.responseText?I(v.responseText):v.status>=400?x(n(v.status,v.statusText)):x(s))},v.send(null)}function m(y){var I=/^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(y||"");if(I){var x=Number(I[1]),v=I[2],b=I[3];return v?b?[x,Number(b)]:[x,void 0]:[x,x]}}i.hooks.add("before-highlightall",function(y){y.selector+=", "+p}),i.hooks.add("before-sanity-check",function(y){var I=y.element;if(I.matches(p)){y.code="",I.setAttribute(o,c);var x=I.appendChild(document.createElement("CODE"));x.textContent=r;var v=I.getAttribute("data-src"),b=y.language;if(b==="none"){var w=(/\.(\w+)$/.exec(v)||[,"none"])[1];b=a[w]||w}i.util.setLanguage(x,b),i.util.setLanguage(I,b);var A=i.plugins.autoloader;A&&A.loadLanguages(b),f(v,function(D){I.setAttribute(o,u);var F=m(I.getAttribute("data-range"));if(F){var K=D.split(/\r\n?|\n/g),_=F[0],te=F[1]==null?K.length:F[1];_<0&&(_+=K.length),_=Math.max(0,Math.min(_-1,K.length)),te<0&&(te+=K.length),te=Math.max(0,Math.min(te,K.length)),D=K.slice(_,te).join(`
|
|
3178
|
+
*/var i=(function(r){var n=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,s=0,a={},o={manual:r.Prism&&r.Prism.manual,disableWorkerMessageHandler:r.Prism&&r.Prism.disableWorkerMessageHandler,util:{encode:function v(b){return b instanceof c?new c(b.type,v(b.content),b.alias):Array.isArray(b)?b.map(v):b.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(v){return Object.prototype.toString.call(v).slice(8,-1)},objId:function(v){return v.__id||Object.defineProperty(v,"__id",{value:++s}),v.__id},clone:function v(b,w){w=w||{};var A,D;switch(o.util.type(b)){case"Object":if(D=o.util.objId(b),w[D])return w[D];A={},w[D]=A;for(var F in b)b.hasOwnProperty(F)&&(A[F]=v(b[F],w));return A;case"Array":return D=o.util.objId(b),w[D]?w[D]:(A=[],w[D]=A,b.forEach(function(K,_){A[_]=v(K,w)}),A);default:return b}},getLanguage:function(v){for(;v;){var b=n.exec(v.className);if(b)return b[1].toLowerCase();v=v.parentElement}return"none"},setLanguage:function(v,b){v.className=v.className.replace(RegExp(n,"gi"),""),v.classList.add("language-"+b)},currentScript:function(){if(typeof document>"u")return null;if(document.currentScript&&document.currentScript.tagName==="SCRIPT")return document.currentScript;try{throw new Error}catch(A){var v=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(A.stack)||[])[1];if(v){var b=document.getElementsByTagName("script");for(var w in b)if(b[w].src==v)return b[w]}return null}},isActive:function(v,b,w){for(var A="no-"+b;v;){var D=v.classList;if(D.contains(b))return!0;if(D.contains(A))return!1;v=v.parentElement}return!!w}},languages:{plain:a,plaintext:a,text:a,txt:a,extend:function(v,b){var w=o.util.clone(o.languages[v]);for(var A in b)w[A]=b[A];return w},insertBefore:function(v,b,w,A){A=A||o.languages;var D=A[v],F={};for(var K in D)if(D.hasOwnProperty(K)){if(K==b)for(var _ in w)w.hasOwnProperty(_)&&(F[_]=w[_]);w.hasOwnProperty(K)||(F[K]=D[K])}var te=A[v];return A[v]=F,o.languages.DFS(o.languages,function(U,ee){ee===te&&U!=v&&(this[U]=F)}),F},DFS:function v(b,w,A,D){D=D||{};var F=o.util.objId;for(var K in b)if(b.hasOwnProperty(K)){w.call(b,K,b[K],A||K);var _=b[K],te=o.util.type(_);te==="Object"&&!D[F(_)]?(D[F(_)]=!0,v(_,w,null,D)):te==="Array"&&!D[F(_)]&&(D[F(_)]=!0,v(_,w,K,D))}}},plugins:{},highlightAll:function(v,b){o.highlightAllUnder(document,v,b)},highlightAllUnder:function(v,b,w){var A={callback:w,container:v,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};o.hooks.run("before-highlightall",A),A.elements=Array.prototype.slice.apply(A.container.querySelectorAll(A.selector)),o.hooks.run("before-all-elements-highlight",A);for(var D=0,F;F=A.elements[D++];)o.highlightElement(F,b===!0,A.callback)},highlightElement:function(v,b,w){var A=o.util.getLanguage(v),D=o.languages[A];o.util.setLanguage(v,A);var F=v.parentElement;F&&F.nodeName.toLowerCase()==="pre"&&o.util.setLanguage(F,A);var K=v.textContent,_={element:v,language:A,grammar:D,code:K};function te(ee){_.highlightedCode=ee,o.hooks.run("before-insert",_),_.element.innerHTML=_.highlightedCode,o.hooks.run("after-highlight",_),o.hooks.run("complete",_),w&&w.call(_.element)}if(o.hooks.run("before-sanity-check",_),F=_.element.parentElement,F&&F.nodeName.toLowerCase()==="pre"&&!F.hasAttribute("tabindex")&&F.setAttribute("tabindex","0"),!_.code){o.hooks.run("complete",_),w&&w.call(_.element);return}if(o.hooks.run("before-highlight",_),!_.grammar){te(o.util.encode(_.code));return}if(b&&r.Worker){var U=new Worker(o.filename);U.onmessage=function(ee){te(ee.data)},U.postMessage(JSON.stringify({language:_.language,code:_.code,immediateClose:!0}))}else te(o.highlight(_.code,_.grammar,_.language))},highlight:function(v,b,w){var A={code:v,grammar:b,language:w};if(o.hooks.run("before-tokenize",A),!A.grammar)throw new Error('The language "'+A.language+'" has no grammar.');return A.tokens=o.tokenize(A.code,A.grammar),o.hooks.run("after-tokenize",A),c.stringify(o.util.encode(A.tokens),A.language)},tokenize:function(v,b){var w=b.rest;if(w){for(var A in w)b[A]=w[A];delete b.rest}var D=new p;return f(D,D.head,v),h(v,D,b,D.head,0),R(D)},hooks:{all:{},add:function(v,b){var w=o.hooks.all;w[v]=w[v]||[],w[v].push(b)},run:function(v,b){var w=o.hooks.all[v];if(!(!w||!w.length))for(var A=0,D;D=w[A++];)D(b)}},Token:c};r.Prism=o;function c(v,b,w,A){this.type=v,this.content=b,this.alias=w,this.length=(A||"").length|0}c.stringify=function v(b,w){if(typeof b=="string")return b;if(Array.isArray(b)){var A="";return b.forEach(function(te){A+=v(te,w)}),A}var D={type:b.type,content:v(b.content,w),tag:"span",classes:["token",b.type],attributes:{},language:w},F=b.alias;F&&(Array.isArray(F)?Array.prototype.push.apply(D.classes,F):D.classes.push(F)),o.hooks.run("wrap",D);var K="";for(var _ in D.attributes)K+=" "+_+'="'+(D.attributes[_]||"").replace(/"/g,""")+'"';return"<"+D.tag+' class="'+D.classes.join(" ")+'"'+K+">"+D.content+"</"+D.tag+">"};function u(v,b,w,A){v.lastIndex=b;var D=v.exec(w);if(D&&A&&D[1]){var F=D[1].length;D.index+=F,D[0]=D[0].slice(F)}return D}function h(v,b,w,A,D,F){for(var K in w)if(!(!w.hasOwnProperty(K)||!w[K])){var _=w[K];_=Array.isArray(_)?_:[_];for(var te=0;te<_.length;++te){if(F&&F.cause==K+","+te)return;var U=_[te],ee=U.inside,ct=!!U.lookbehind,It=!!U.greedy,kr=U.alias;if(It&&!U.pattern.global){var Is=U.pattern.toString().match(/[imsuy]*$/)[0];U.pattern=RegExp(U.pattern.source,Is+"g")}for(var mn=U.pattern||U,Ce=A.next,lt=D;Ce!==b.tail&&!(F&<>=F.reach);lt+=Ce.value.length,Ce=Ce.next){var Ut=Ce.value;if(b.length>v.length)return;if(!(Ut instanceof c)){var he=1,Xe;if(It){if(Xe=u(mn,lt,v,ct),!Xe||Xe.index>=v.length)break;var Mt=Xe.index,Ae=Xe.index+Xe[0].length,wt=lt;for(wt+=Ce.value.length;Mt>=wt;)Ce=Ce.next,wt+=Ce.value.length;if(wt-=Ce.value.length,lt=wt,Ce.value instanceof c)continue;for(var re=Ce;re!==b.tail&&(wt<Ae||typeof re.value=="string");re=re.next)he++,wt+=re.value.length;he--,Ut=v.slice(lt,wt),Xe.index-=lt}else if(Xe=u(mn,0,Ut,ct),!Xe)continue;var Mt=Xe.index,Nt=Xe[0],ut=Ut.slice(0,Mt),xr=Ut.slice(Mt+Nt.length),fi=lt+Ut.length;F&&fi>F.reach&&(F.reach=fi);var vi=Ce.prev;ut&&(vi=f(b,vi,ut),lt+=ut.length),m(b,vi,he);var yn=new c(K,ee?o.tokenize(Nt,ee):Nt,kr,Nt);if(Ce=f(b,vi,yn),xr&&f(b,Ce,xr),he>1){var St={cause:K+","+te,reach:fi};h(v,b,w,Ce.prev,lt,St),F&&St.reach>F.reach&&(F.reach=St.reach)}}}}}}function p(){var v={value:null,prev:null,next:null},b={value:null,prev:v,next:null};v.next=b,this.head=v,this.tail=b,this.length=0}function f(v,b,w){var A=b.next,D={value:w,prev:b,next:A};return b.next=D,A.prev=D,v.length++,D}function m(v,b,w){for(var A=b.next,D=0;D<w&&A!==v.tail;D++)A=A.next;b.next=A,A.prev=b,v.length-=D}function R(v){for(var b=[],w=v.head.next;w!==v.tail;)b.push(w.value),w=w.next;return b}if(!r.document)return r.addEventListener&&(o.disableWorkerMessageHandler||r.addEventListener("message",function(v){var b=JSON.parse(v.data),w=b.language,A=b.code,D=b.immediateClose;r.postMessage(o.highlight(A,o.languages[w],w)),D&&r.close()},!1)),o;var y=o.util.currentScript();y&&(o.filename=y.src,y.hasAttribute("data-manual")&&(o.manual=!0));function I(){o.manual||o.highlightAll()}if(!o.manual){var x=document.readyState;x==="loading"||x==="interactive"&&y&&y.defer?document.addEventListener("DOMContentLoaded",I):window.requestAnimationFrame?window.requestAnimationFrame(I):window.setTimeout(I,16)}return o})(e);t.exports&&(t.exports=i),typeof Qa<"u"&&(Qa.Prism=i),i.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},i.languages.markup.tag.inside["attr-value"].inside.entity=i.languages.markup.entity,i.languages.markup.doctype.inside["internal-subset"].inside=i.languages.markup,i.hooks.add("wrap",function(r){r.type==="entity"&&(r.attributes.title=r.content.replace(/&/,"&"))}),Object.defineProperty(i.languages.markup.tag,"addInlined",{value:function(n,s){var a={};a["language-"+s]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:i.languages[s]},a.cdata=/^<!\[CDATA\[|\]\]>$/i;var o={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:a}};o["language-"+s]={pattern:/[\s\S]+/,inside:i.languages[s]};var c={};c[n]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return n}),"i"),lookbehind:!0,greedy:!0,inside:o},i.languages.insertBefore("markup","cdata",c)}}),Object.defineProperty(i.languages.markup.tag,"addAttribute",{value:function(r,n){i.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+r+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[n,"language-"+n],inside:i.languages[n]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),i.languages.html=i.languages.markup,i.languages.mathml=i.languages.markup,i.languages.svg=i.languages.markup,i.languages.xml=i.languages.extend("markup",{}),i.languages.ssml=i.languages.xml,i.languages.atom=i.languages.xml,i.languages.rss=i.languages.xml,(function(r){var n=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;r.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+n.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+n.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+n.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+n.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:n,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},r.languages.css.atrule.inside.rest=r.languages.css;var s=r.languages.markup;s&&(s.tag.addInlined("style","css"),s.tag.addAttribute("style","css"))})(i),i.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},i.languages.javascript=i.languages.extend("clike",{"class-name":[i.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+(/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source)+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),i.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,i.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:i.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:i.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:i.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:i.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:i.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),i.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:i.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),i.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),i.languages.markup&&(i.languages.markup.tag.addInlined("script","javascript"),i.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript")),i.languages.js=i.languages.javascript,(function(){if(typeof i>"u"||typeof document>"u")return;Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector);var r="Loading…",n=function(y,I){return"✖ Error "+y+" while fetching file: "+I},s="✖ Error: File does not exist or is empty",a={js:"javascript",py:"python",rb:"ruby",ps1:"powershell",psm1:"powershell",sh:"bash",bat:"batch",h:"c",tex:"latex"},o="data-src-status",c="loading",u="loaded",h="failed",p="pre[data-src]:not(["+o+'="'+u+'"]):not(['+o+'="'+c+'"])';function f(y,I,x){var v=new XMLHttpRequest;v.open("GET",y,!0),v.onreadystatechange=function(){v.readyState==4&&(v.status<400&&v.responseText?I(v.responseText):v.status>=400?x(n(v.status,v.statusText)):x(s))},v.send(null)}function m(y){var I=/^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(y||"");if(I){var x=Number(I[1]),v=I[2],b=I[3];return v?b?[x,Number(b)]:[x,void 0]:[x,x]}}i.hooks.add("before-highlightall",function(y){y.selector+=", "+p}),i.hooks.add("before-sanity-check",function(y){var I=y.element;if(I.matches(p)){y.code="",I.setAttribute(o,c);var x=I.appendChild(document.createElement("CODE"));x.textContent=r;var v=I.getAttribute("data-src"),b=y.language;if(b==="none"){var w=(/\.(\w+)$/.exec(v)||[,"none"])[1];b=a[w]||w}i.util.setLanguage(x,b),i.util.setLanguage(I,b);var A=i.plugins.autoloader;A&&A.loadLanguages(b),f(v,function(D){I.setAttribute(o,u);var F=m(I.getAttribute("data-range"));if(F){var K=D.split(/\r\n?|\n/g),_=F[0],te=F[1]==null?K.length:F[1];_<0&&(_+=K.length),_=Math.max(0,Math.min(_-1,K.length)),te<0&&(te+=K.length),te=Math.max(0,Math.min(te,K.length)),D=K.slice(_,te).join(`
|
|
3179
3179
|
`),I.hasAttribute("data-start")||I.setAttribute("data-start",String(_+1))}x.textContent=D,i.highlightElement(x)},function(D){I.setAttribute(o,h),x.textContent=D})}}),i.plugins.fileHighlight={highlight:function(I){for(var x=(I||document).querySelectorAll(p),v=0,b;b=x[v++];)i.highlightElement(b)}};var R=!1;i.fileHighlight=function(){R||(console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead."),R=!0),i.plugins.fileHighlight.highlight.apply(this,arguments)}})()})(Ss)),Ss.exports}var jc=Hb();const jb=ve({__proto__:null,default:Gr(jc)},[jc]);Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+(/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source)+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),Prism.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),Prism.languages.markup&&(Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript")),Prism.languages.js=Prism.languages.javascript;const Wb=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));var Wc={},Gc;function Gb(){return Gc||(Gc=1,(function(t){t.languages.typescript=t.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),t.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete t.languages.typescript.parameter,delete t.languages.typescript["literal-property"];var e=t.languages.extend("typescript",{});delete e["class-name"],t.languages.typescript["class-name"].inside=e,t.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:e}}}}),t.languages.ts=t.languages.typescript})(Prism)),Wc}var qc=Gb();const qb=ve({__proto__:null,default:Gr(qc)},[qc]);var Xc={},Yc;function Xb(){return Yc||(Yc=1,Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern://,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python),Xc}var Kc=Xb();const Yb=ve({__proto__:null,default:Gr(Kc)},[Kc]);(function(t){var e="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",i={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:"punctuation",inside:null},r={bash:i,environment:{pattern:RegExp("\\$"+e),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+e),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};t.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+e),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:r},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:i}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:r},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:r.entity}}],environment:{pattern:RegExp("\\$?"+e),alias:"constant"},variable:r.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},i.inside=t.languages.bash;for(var n=["comment","function-name","for-or-select","assign-left","parameter","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],s=r.variable[1].inside,a=0;a<n.length;a++)s[n[a]]=t.languages.bash[n[a]];t.languages.sh=t.languages.bash,t.languages.shell=t.languages.bash})(Prism);const Zc=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}},Prism.languages.webmanifest=Prism.languages.json;const Kb=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));(function(t){var e=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;t.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+e.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+e.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+e.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+e.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:e,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},t.languages.css.atrule.inside.rest=t.languages.css;var i=t.languages.markup;i&&(i.tag.addInlined("style","css"),i.tag.addAttribute("style","css"))})(Prism);const Zb=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));(function(t){var e=/[*&][^\s[\]{},]+/,i=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,r="(?:"+i.source+"(?:[ ]+"+e.source+")?|"+e.source+"(?:[ ]+"+i.source+")?)",n=/(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g,function(){return/[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source}),s=/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;function a(o,c){c=(c||"").replace(/m/g,"")+"m";var u=/([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g,function(){return r}).replace(/<<value>>/g,function(){return o});return RegExp(u,c)}t.languages.yaml={scalar:{pattern:RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g,function(){return r})),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g,function(){return r}).replace(/<<key>>/g,function(){return"(?:"+n+"|"+s+")"})),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:a(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),lookbehind:!0,alias:"number"},boolean:{pattern:a(/false|true/.source,"i"),lookbehind:!0,alias:"important"},null:{pattern:a(/null|~/.source,"i"),lookbehind:!0,alias:"important"},string:{pattern:a(s),lookbehind:!0,greedy:!0},number:{pattern:a(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source,"i"),lookbehind:!0},tag:i,important:e,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},t.languages.yml=t.languages.yaml})(Prism);const Qb=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));Prism.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/};const Jb=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));(function(t){var e=/(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?![\r\n]))/.source;function i(h){return h=h.replace(/<inner>/g,function(){return e}),RegExp(/((?:^|[^\\])(?:\\{2})*)/.source+"(?:"+h+")")}var r=/(?:\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\|\r\n`])+/.source,n=/\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|(?![\s\S]))/.source.replace(/__/g,function(){return r}),s=/\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source;t.languages.markdown=t.languages.extend("markup",{}),t.languages.insertBefore("markdown","prolog",{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:["yaml","language-yaml"],inside:t.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+n+s+"(?:"+n+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+n+s+")(?:"+n+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(r),inside:t.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+n+")"+s+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+n+"$"),inside:{"table-header":{pattern:RegExp(r),alias:"important",inside:t.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:i(/\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\b|\*\*(?:(?!\*)<inner>|\*(?:(?!\*)<inner>)+\*)+\*\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:i(/\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\b|\*(?:(?!\*)<inner>|\*\*(?:(?!\*)<inner>)+\*\*)+\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:i(/(~~?)(?:(?!~)<inner>)+\2/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:["code","keyword"]},url:{pattern:i(/!?\[(?:(?!\])<inner>)+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)|[ \t]?\[(?:(?!\])<inner>)+\])/.source),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),["url","bold","italic","strike"].forEach(function(h){["url","bold","italic","strike","code-snippet"].forEach(function(p){h!==p&&(t.languages.markdown[h].inside.content.inside[p]=t.languages.markdown[p])})}),t.hooks.add("after-tokenize",function(h){if(h.language!=="markdown"&&h.language!=="md")return;function p(f){if(!(!f||typeof f=="string"))for(var m=0,R=f.length;m<R;m++){var y=f[m];if(y.type!=="code"){p(y.content);continue}var I=y.content[1],x=y.content[3];if(I&&x&&I.type==="code-language"&&x.type==="code-block"&&typeof I.content=="string"){var v=I.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp");v=(/[a-z][\w-]*/i.exec(v)||[""])[0].toLowerCase();var b="language-"+v;x.alias?typeof x.alias=="string"?x.alias=[x.alias,b]:x.alias.push(b):x.alias=[b]}}}p(h.tokens)}),t.hooks.add("wrap",function(h){if(h.type==="code-block"){for(var p="",f=0,m=h.classes.length;f<m;f++){var R=h.classes[f],y=/language-(.+)/.exec(R);if(y){p=y[1];break}}var I=t.languages[p];if(I)h.content=t.highlight(u(h.content),I,p);else if(p&&p!=="none"&&t.plugins.autoloader){var x="md-"+new Date().valueOf()+"-"+Math.floor(Math.random()*1e16);h.attributes.id=x,t.plugins.autoloader.loadLanguages(p,function(){var v=document.getElementById(x);v&&(v.innerHTML=t.highlight(v.textContent,t.languages[p],p))})}}});var a=RegExp(t.languages.markup.tag.pattern.source,"gi"),o={amp:"&",lt:"<",gt:">",quot:'"'},c=String.fromCodePoint||String.fromCharCode;function u(h){var p=h.replace(a,"");return p=p.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(f,m){if(m=m.toLowerCase(),m[0]==="#"){var R;return m[1]==="x"?R=parseInt(m.slice(2),16):R=Number(m.slice(1)),c(R)}else{var y=o[m];return y||f}}),p}t.languages.md=t.languages.markdown})(Prism);const $b=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function hn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let Xt=hn();function Qc(t){Xt=t}const Jc=/[&<>"']/,em=new RegExp(Jc.source,"g"),$c=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,tm=new RegExp($c.source,"g"),im={"&":"&","<":"<",">":">",'"':""","'":"'"},el=t=>im[t];function Je(t,e){if(e){if(Jc.test(t))return t.replace(em,el)}else if($c.test(t))return t.replace(tm,el);return t}const rm=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function nm(t){return t.replace(rm,(e,i)=>(i=i.toLowerCase(),i==="colon"?":":i.charAt(0)==="#"?i.charAt(1)==="x"?String.fromCharCode(parseInt(i.substring(2),16)):String.fromCharCode(+i.substring(1)):""))}const sm=/(^|[^\[])\^/g;function J(t,e){t=typeof t=="string"?t:t.source,e=e||"";const i={replace:(r,n)=>(n=typeof n=="object"&&"source"in n?n.source:n,n=n.replace(sm,"$1"),t=t.replace(r,n),i),getRegex:()=>new RegExp(t,e)};return i}function tl(t){try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}const pn={exec:()=>null};function il(t,e){const i=t.replace(/\|/g,(s,a,o)=>{let c=!1,u=a;for(;--u>=0&&o[u]==="\\";)c=!c;return c?"|":" |"}),r=i.split(/ \|/);let n=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;n<r.length;n++)r[n]=r[n].trim().replace(/\\\|/g,"|");return r}function gn(t,e,i){const r=t.length;if(r===0)return"";let n=0;for(;n<r&&t.charAt(r-n-1)===e;)n++;return t.slice(0,r-n)}function am(t,e){if(t.indexOf(e[1])===-1)return-1;let i=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])i++;else if(t[r]===e[1]&&(i--,i<0))return r;return-1}function rl(t,e,i,r){const n=e.href,s=e.title?Je(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");if(t[0].charAt(0)!=="!"){r.state.inLink=!0;const o={type:"link",raw:i,href:n,title:s,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,o}return{type:"image",raw:i,href:n,title:s,text:Je(a)}}function om(t,e){const i=t.match(/^(\s+)(?:```)/);if(i===null)return e;const r=i[1];return e.split(`
|
|
3180
3180
|
`).map(n=>{const s=n.match(/^\s+/);if(s===null)return n;const[a]=s;return a.length>=r.length?n.slice(r.length):n}).join(`
|
|
3181
3181
|
`)}class yr{constructor(e){ce(this,"options");ce(this,"rules");ce(this,"lexer");this.options=e||Xt}space(e){const i=this.rules.block.newline.exec(e);if(i&&i[0].length>0)return{type:"space",raw:i[0]}}code(e){const i=this.rules.block.code.exec(e);if(i){const r=i[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:i[0],codeBlockStyle:"indented",text:this.options.pedantic?r:gn(r,`
|
|
@@ -3190,7 +3190,7 @@ var SignalWireUI=(function(l){"use strict";var Km=Object.defineProperty;var Vl=l
|
|
|
3190
3190
|
`,e=e.substring(A.length+1),p=f.slice(m)}}s.loose||(u?s.loose=!0:/\n *\n *$/.test(o)&&(u=!0));let y=null,I;this.options.gfm&&(y=/^\[[ xX]\] /.exec(c),y&&(I=y[0]!=="[ ] ",c=c.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:o,task:!!y,checked:I,loose:!1,text:c,tokens:[]}),s.raw+=o}s.items[s.items.length-1].raw=o.trimEnd(),s.items[s.items.length-1].text=c.trimEnd(),s.raw=s.raw.trimEnd();for(let h=0;h<s.items.length;h++)if(this.lexer.state.top=!1,s.items[h].tokens=this.lexer.blockTokens(s.items[h].text,[]),!s.loose){const p=s.items[h].tokens.filter(m=>m.type==="space"),f=p.length>0&&p.some(m=>/\n.*\n/.test(m.raw));s.loose=f}if(s.loose)for(let h=0;h<s.items.length;h++)s.items[h].loose=!0;return s}}html(e){const i=this.rules.block.html.exec(e);if(i)return{type:"html",block:!0,raw:i[0],pre:i[1]==="pre"||i[1]==="script"||i[1]==="style",text:i[0]}}def(e){const i=this.rules.block.def.exec(e);if(i){const r=i[1].toLowerCase().replace(/\s+/g," "),n=i[2]?i[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=i[3]?i[3].substring(1,i[3].length-1).replace(this.rules.inline._escapes,"$1"):i[3];return{type:"def",tag:r,raw:i[0],href:n,title:s}}}table(e){const i=this.rules.block.table.exec(e);if(i){if(!/[:|]/.test(i[2]))return;const r={type:"table",raw:i[0],header:il(i[1]).map(n=>({text:n,tokens:[]})),align:i[2].replace(/^\||\| *$/g,"").split("|"),rows:i[3]&&i[3].trim()?i[3].replace(/\n[ \t]*$/,"").split(`
|
|
3191
3191
|
`):[]};if(r.header.length===r.align.length){let n=r.align.length,s,a,o,c;for(s=0;s<n;s++){const u=r.align[s];u&&(/^ *-+: *$/.test(u)?r.align[s]="right":/^ *:-+: *$/.test(u)?r.align[s]="center":/^ *:-+ *$/.test(u)?r.align[s]="left":r.align[s]=null)}for(n=r.rows.length,s=0;s<n;s++)r.rows[s]=il(r.rows[s],r.header.length).map(u=>({text:u,tokens:[]}));for(n=r.header.length,a=0;a<n;a++)r.header[a].tokens=this.lexer.inline(r.header[a].text);for(n=r.rows.length,a=0;a<n;a++)for(c=r.rows[a],o=0;o<c.length;o++)c[o].tokens=this.lexer.inline(c[o].text);return r}}}lheading(e){const i=this.rules.block.lheading.exec(e);if(i)return{type:"heading",raw:i[0],depth:i[2].charAt(0)==="="?1:2,text:i[1],tokens:this.lexer.inline(i[1])}}paragraph(e){const i=this.rules.block.paragraph.exec(e);if(i){const r=i[1].charAt(i[1].length-1)===`
|
|
3192
3192
|
`?i[1].slice(0,-1):i[1];return{type:"paragraph",raw:i[0],text:r,tokens:this.lexer.inline(r)}}}text(e){const i=this.rules.block.text.exec(e);if(i)return{type:"text",raw:i[0],text:i[0],tokens:this.lexer.inline(i[0])}}escape(e){const i=this.rules.inline.escape.exec(e);if(i)return{type:"escape",raw:i[0],text:Je(i[1])}}tag(e){const i=this.rules.inline.tag.exec(e);if(i)return!this.lexer.state.inLink&&/^<a /i.test(i[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(i[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(i[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(i[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:i[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:i[0]}}link(e){const i=this.rules.inline.link.exec(e);if(i){const r=i[2].trim();if(!this.options.pedantic&&/^</.test(r)){if(!/>$/.test(r))return;const a=gn(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{const a=am(i[2],"()");if(a>-1){const c=(i[0].indexOf("!")===0?5:4)+i[1].length+a;i[2]=i[2].substring(0,a),i[0]=i[0].substring(0,c).trim(),i[3]=""}}let n=i[2],s="";if(this.options.pedantic){const a=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);a&&(n=a[1],s=a[3])}else s=i[3]?i[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(this.options.pedantic&&!/>$/.test(r)?n=n.slice(1):n=n.slice(1,-1)),rl(i,{href:n&&n.replace(this.rules.inline._escapes,"$1"),title:s&&s.replace(this.rules.inline._escapes,"$1")},i[0],this.lexer)}}reflink(e,i){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(/\s+/g," ");if(n=i[n.toLowerCase()],!n){const s=r[0].charAt(0);return{type:"text",raw:s,text:s}}return rl(r,n,r[0],this.lexer)}}emStrong(e,i,r=""){let n=this.rules.inline.emStrong.lDelim.exec(e);if(!n||n[3]&&r.match(/[\p{L}\p{N}]/u))return;if(!(n[1]||n[2]||"")||!r||this.rules.inline.punctuation.exec(r)){const a=[...n[0]].length-1;let o,c,u=a,h=0;const p=n[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(p.lastIndex=0,i=i.slice(-1*e.length+a);(n=p.exec(i))!=null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o)continue;if(c=[...o].length,n[3]||n[4]){u+=c;continue}else if((n[5]||n[6])&&a%3&&!((a+c)%3)){h+=c;continue}if(u-=c,u>0)continue;c=Math.min(c,c+u+h);const f=[...n[0]][0].length,m=e.slice(0,a+n.index+f+c);if(Math.min(a,c)%2){const y=m.slice(1,-1);return{type:"em",raw:m,text:y,tokens:this.lexer.inlineTokens(y)}}const R=m.slice(2,-2);return{type:"strong",raw:m,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){const i=this.rules.inline.code.exec(e);if(i){let r=i[2].replace(/\n/g," ");const n=/[^ ]/.test(r),s=/^ /.test(r)&&/ $/.test(r);return n&&s&&(r=r.substring(1,r.length-1)),r=Je(r,!0),{type:"codespan",raw:i[0],text:r}}}br(e){const i=this.rules.inline.br.exec(e);if(i)return{type:"br",raw:i[0]}}del(e){const i=this.rules.inline.del.exec(e);if(i)return{type:"del",raw:i[0],text:i[2],tokens:this.lexer.inlineTokens(i[2])}}autolink(e){const i=this.rules.inline.autolink.exec(e);if(i){let r,n;return i[2]==="@"?(r=Je(i[1]),n="mailto:"+r):(r=Je(i[1]),n=r),{type:"link",raw:i[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let i;if(i=this.rules.inline.url.exec(e)){let r,n;if(i[2]==="@")r=Je(i[0]),n="mailto:"+r;else{let s;do s=i[0],i[0]=this.rules.inline._backpedal.exec(i[0])[0];while(s!==i[0]);r=Je(i[0]),i[1]==="www."?n="http://"+i[0]:n=i[0]}return{type:"link",raw:i[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){const i=this.rules.inline.text.exec(e);if(i){let r;return this.lexer.state.inRawBlock?r=i[0]:r=Je(i[0]),{type:"text",raw:i[0],text:r}}}}const N={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:pn,lheading:/^(?!bull )((?:.|\n(?!\s*?\n|bull ))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};N._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/,N._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,N.def=J(N.def).replace("label",N._label).replace("title",N._title).getRegex(),N.bullet=/(?:[*+-]|\d{1,9}[.)])/,N.listItemStart=J(/^( *)(bull) */).replace("bull",N.bullet).getRegex(),N.list=J(N.list).replace(/bull/g,N.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+N.def.source+")").getRegex(),N._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",N._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,N.html=J(N.html,"i").replace("comment",N._comment).replace("tag",N._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),N.lheading=J(N.lheading).replace(/bull/g,N.bullet).getRegex(),N.paragraph=J(N._paragraph).replace("hr",N.hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",N._tag).getRegex(),N.blockquote=J(N.blockquote).replace("paragraph",N.paragraph).getRegex(),N.normal={...N},N.gfm={...N.normal,table:"^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},N.gfm.table=J(N.gfm.table).replace("hr",N.hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",N._tag).getRegex(),N.gfm.paragraph=J(N._paragraph).replace("hr",N.hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",N.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",N._tag).getRegex(),N.pedantic={...N.normal,html:J(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",N._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:pn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:J(N.normal._paragraph).replace("hr",N.hr).replace("heading",` *#{1,6} *[^
|
|
3193
|
-
]`).replace("lheading",N.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const M={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:pn,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,rDelimAst:/^[^_*]*?__[^_*]*?\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\*)[punct](\*+)(?=[\s]|$)|[^punct\s](\*+)(?!\*)(?=[punct\s]|$)|(?!\*)[punct\s](\*+)(?=[^punct\s])|[\s](\*+)(?!\*)(?=[punct])|(?!\*)[punct](\*+)(?!\*)(?=[punct])|[^punct\s](\*+)(?=[^punct\s])/,rDelimUnd:/^[^_*]*?\*\*[^_*]*?_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\s]|$)|[^punct\s](_+)(?!_)(?=[punct\s]|$)|(?!_)[punct\s](_+)(?=[^punct\s])|[\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:pn,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^((?![*_])[\spunctuation])/};M._punctuation="\\p{P}$+<=>`^|~",M.punctuation=J(M.punctuation,"u").replace(/punctuation/g,M._punctuation).getRegex(),M.blockSkip=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,M.anyPunctuation=/\\[punct]/g,M._escapes=/\\([punct])/g,M._comment=J(N._comment).replace("(?:-->|$)","-->").getRegex(),M.emStrong.lDelim=J(M.emStrong.lDelim,"u").replace(/punct/g,M._punctuation).getRegex(),M.emStrong.rDelimAst=J(M.emStrong.rDelimAst,"gu").replace(/punct/g,M._punctuation).getRegex(),M.emStrong.rDelimUnd=J(M.emStrong.rDelimUnd,"gu").replace(/punct/g,M._punctuation).getRegex(),M.anyPunctuation=J(M.anyPunctuation,"gu").replace(/punct/g,M._punctuation).getRegex(),M._escapes=J(M._escapes,"gu").replace(/punct/g,M._punctuation).getRegex(),M._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,M._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,M.autolink=J(M.autolink).replace("scheme",M._scheme).replace("email",M._email).getRegex(),M._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,M.tag=J(M.tag).replace("comment",M._comment).replace("attribute",M._attribute).getRegex(),M._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,M._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,M._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,M.link=J(M.link).replace("label",M._label).replace("href",M._href).replace("title",M._title).getRegex(),M.reflink=J(M.reflink).replace("label",M._label).replace("ref",N._label).getRegex(),M.nolink=J(M.nolink).replace("ref",N._label).getRegex(),M.reflinkSearch=J(M.reflinkSearch,"g").replace("reflink",M.reflink).replace("nolink",M.nolink).getRegex(),M.normal={...M},M.pedantic={...M.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:J(/^!?\[(label)\]\((.*?)\)/).replace("label",M._label).getRegex(),reflink:J(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",M._label).getRegex()},M.gfm={...M.normal,escape:J(M.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},M.gfm.url=J(M.gfm.url,"i").replace("email",M.gfm._extended_email).getRegex(),M.breaks={...M.gfm,br:J(M.br).replace("{2,}","*").getRegex(),text:J(M.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};class
|
|
3193
|
+
]`).replace("lheading",N.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const M={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:pn,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,rDelimAst:/^[^_*]*?__[^_*]*?\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\*)[punct](\*+)(?=[\s]|$)|[^punct\s](\*+)(?!\*)(?=[punct\s]|$)|(?!\*)[punct\s](\*+)(?=[^punct\s])|[\s](\*+)(?!\*)(?=[punct])|(?!\*)[punct](\*+)(?!\*)(?=[punct])|[^punct\s](\*+)(?=[^punct\s])/,rDelimUnd:/^[^_*]*?\*\*[^_*]*?_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\s]|$)|[^punct\s](_+)(?!_)(?=[punct\s]|$)|(?!_)[punct\s](_+)(?=[^punct\s])|[\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:pn,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^((?![*_])[\spunctuation])/};M._punctuation="\\p{P}$+<=>`^|~",M.punctuation=J(M.punctuation,"u").replace(/punctuation/g,M._punctuation).getRegex(),M.blockSkip=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,M.anyPunctuation=/\\[punct]/g,M._escapes=/\\([punct])/g,M._comment=J(N._comment).replace("(?:-->|$)","-->").getRegex(),M.emStrong.lDelim=J(M.emStrong.lDelim,"u").replace(/punct/g,M._punctuation).getRegex(),M.emStrong.rDelimAst=J(M.emStrong.rDelimAst,"gu").replace(/punct/g,M._punctuation).getRegex(),M.emStrong.rDelimUnd=J(M.emStrong.rDelimUnd,"gu").replace(/punct/g,M._punctuation).getRegex(),M.anyPunctuation=J(M.anyPunctuation,"gu").replace(/punct/g,M._punctuation).getRegex(),M._escapes=J(M._escapes,"gu").replace(/punct/g,M._punctuation).getRegex(),M._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,M._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,M.autolink=J(M.autolink).replace("scheme",M._scheme).replace("email",M._email).getRegex(),M._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,M.tag=J(M.tag).replace("comment",M._comment).replace("attribute",M._attribute).getRegex(),M._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,M._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,M._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,M.link=J(M.link).replace("label",M._label).replace("href",M._href).replace("title",M._title).getRegex(),M.reflink=J(M.reflink).replace("label",M._label).replace("ref",N._label).getRegex(),M.nolink=J(M.nolink).replace("ref",N._label).getRegex(),M.reflinkSearch=J(M.reflinkSearch,"g").replace("reflink",M.reflink).replace("nolink",M.nolink).getRegex(),M.normal={...M},M.pedantic={...M.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:J(/^!?\[(label)\]\((.*?)\)/).replace("label",M._label).getRegex(),reflink:J(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",M._label).getRegex()},M.gfm={...M.normal,escape:J(M.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},M.gfm.url=J(M.gfm.url,"i").replace("email",M.gfm._extended_email).getRegex(),M.breaks={...M.gfm,br:J(M.br).replace("{2,}","*").getRegex(),text:J(M.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};class bt{constructor(e){ce(this,"tokens");ce(this,"options");ce(this,"state");ce(this,"tokenizer");ce(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Xt,this.options.tokenizer=this.options.tokenizer||new yr,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const i={block:N.normal,inline:M.normal};this.options.pedantic?(i.block=N.pedantic,i.inline=M.pedantic):this.options.gfm&&(i.block=N.gfm,this.options.breaks?i.inline=M.breaks:i.inline=M.gfm),this.tokenizer.rules=i}static get rules(){return{block:N,inline:M}}static lex(e,i){return new bt(i).lex(e)}static lexInline(e,i){return new bt(i).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
|
|
3194
3194
|
`),this.blockTokens(e,this.tokens);let i;for(;i=this.inlineQueue.shift();)this.inlineTokens(i.src,i.tokens);return this.tokens}blockTokens(e,i=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(o,c,u)=>c+" ".repeat(u.length));let r,n,s,a;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(o=>(r=o.call({lexer:this},e,i))?(e=e.substring(r.raw.length),i.push(r),!0):!1))){if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length),r.raw.length===1&&i.length>0?i[i.length-1].raw+=`
|
|
3195
3195
|
`:i.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length),n=i[i.length-1],n&&(n.type==="paragraph"||n.type==="text")?(n.raw+=`
|
|
3196
3196
|
`+r.raw,n.text+=`
|
|
@@ -3218,8 +3218,8 @@ ${e}</blockquote>
|
|
|
3218
3218
|
`}tablerow(e){return`<tr>
|
|
3219
3219
|
${e}</tr>
|
|
3220
3220
|
`}tablecell(e,i){const r=i.header?"th":"td";return(i.align?`<${r} align="${i.align}">`:`<${r}>`)+e+`</${r}>
|
|
3221
|
-
`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,i,r){const n=tl(e);if(n===null)return r;e=n;let s='<a href="'+e+'"';return i&&(s+=' title="'+i+'"'),s+=">"+r+"</a>",s}image(e,i,r){const n=tl(e);if(n===null)return r;e=n;let s=`<img src="${e}" alt="${r}"`;return i&&(s+=` title="${i}"`),s+=">",s}text(e){return e}}class fn{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,i,r){return""+r}image(e,i,r){return""+r}br(){return""}}class
|
|
3222
|
-
`+(a.tokens?this.parseInline(a.tokens):a.text);r+=i?this.renderer.paragraph(o):o;continue}default:{const a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}parseInline(e,i){i=i||this.renderer;let r="";for(let n=0;n<e.length;n++){const s=e[n];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){const a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=a||"";continue}}switch(s.type){case"escape":{const a=s;r+=i.text(a.text);break}case"html":{const a=s;r+=i.html(a.text);break}case"link":{const a=s;r+=i.link(a.href,a.title,this.parseInline(a.tokens,i));break}case"image":{const a=s;r+=i.image(a.href,a.title,a.text);break}case"strong":{const a=s;r+=i.strong(this.parseInline(a.tokens,i));break}case"em":{const a=s;r+=i.em(this.parseInline(a.tokens,i));break}case"codespan":{const a=s;r+=i.codespan(a.text);break}case"br":{r+=i.br();break}case"del":{const a=s;r+=i.del(this.parseInline(a.tokens,i));break}case"text":{const a=s;r+=i.text(a.text);break}default:{const a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}}class Vi{constructor(e){ce(this,"options");this.options=e||Xt}preprocess(e){return e}postprocess(e){return e}}ce(Vi,"passThroughHooks",new Set(["preprocess","postprocess"]));class nl{constructor(...e){Hl(this,gi);ce(this,"defaults",hn());ce(this,"options",this.setOptions);ce(this,"parse",Tn(this,gi,js).call(this,
|
|
3223
|
-
Please report this to https://github.com/markedjs/marked.`,e){const n="<p>An error occurred:</p><pre>"+Je(r.message+"",!0)+"</pre>";return i?Promise.resolve(n):n}if(i)return Promise.reject(r);throw r}};const hi=new nl;function $(t,e){return hi.parse(t,e)}$.options=$.setOptions=function(t){return hi.setOptions(t),$.defaults=hi.defaults,Qc($.defaults),$},$.getDefaults=hn,$.defaults=Xt,$.use=function(...t){return hi.use(...t),$.defaults=hi.defaults,Qc($.defaults),$},$.walkTokens=function(t,e){return hi.walkTokens(t,e)},$.parseInline=hi.parseInline,$.Parser=bt,$.parser=bt.parse,$.Renderer=wr,$.TextRenderer=fn,$.Lexer=vt,$.lexer=vt.lex,$.Tokenizer=yr,$.Hooks=Vi,$.parse=$;const cm=$.options,lm=$.setOptions,um=$.use,dm=$.walkTokens,hm=$.parseInline,pm=$,gm=bt.parse,fm=vt.lex,vm=Object.freeze(Object.defineProperty({__proto__:null,Hooks:Vi,Lexer:vt,Marked:nl,Parser:bt,Renderer:wr,TextRenderer:fn,Tokenizer:yr,get defaults(){return Xt},getDefaults:hn,lexer:fm,marked:$,options:cm,parse:pm,parseInline:hm,parser:gm,setOptions:lm,use:um,walkTokens:dm},Symbol.toStringTag,{value:"Module"}));/*! @license DOMPurify 3.4.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.1/LICENSE */const{entries:sl,setPrototypeOf:al,isFrozen:bm,getPrototypeOf:mm,getOwnPropertyDescriptor:ym}=Object;let{freeze:Ve,seal:ot,create:Hi}=Object,{apply:Cs,construct:As}=typeof Reflect<"u"&&Reflect;Ve||(Ve=function(e){return e}),ot||(ot=function(e){return e}),Cs||(Cs=function(e,i){for(var r=arguments.length,n=new Array(r>2?r-2:0),s=2;s<r;s++)n[s-2]=arguments[s];return e.apply(i,n)}),As||(As=function(e){for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return new e(...r)});const Sr=ye(Array.prototype.forEach),wm=ye(Array.prototype.lastIndexOf),ol=ye(Array.prototype.pop),Cr=ye(Array.prototype.push),Sm=ye(Array.prototype.splice),He=Array.isArray,Ar=ye(String.prototype.toLowerCase),Ts=ye(String.prototype.toString),cl=ye(String.prototype.match),ji=ye(String.prototype.replace),ll=ye(String.prototype.indexOf),Cm=ye(String.prototype.trim),Am=ye(Number.prototype.toString),Tm=ye(Boolean.prototype.toString),ul=typeof BigInt>"u"?null:ye(BigInt.prototype.toString),dl=typeof Symbol>"u"?null:ye(Symbol.prototype.toString),ge=ye(Object.prototype.hasOwnProperty),Tr=ye(Object.prototype.toString),_e=ye(RegExp.prototype.test),vn=Em(TypeError);function ye(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return Cs(t,e,r)}}function Em(t){return function(){for(var e=arguments.length,i=new Array(e),r=0;r<e;r++)i[r]=arguments[r];return As(t,i)}}function q(t,e){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ar;if(al&&al(t,null),!He(e))return t;let r=e.length;for(;r--;){let n=e[r];if(typeof n=="string"){const s=i(n);s!==n&&(bm(e)||(e[r]=s),n=s)}t[n]=!0}return t}function km(t){for(let e=0;e<t.length;e++)ge(t,e)||(t[e]=null);return t}function qe(t){const e=Hi(null);for(const[i,r]of sl(t))ge(t,i)&&(He(r)?e[i]=km(r):r&&typeof r=="object"&&r.constructor===Object?e[i]=qe(r):e[i]=r);return e}function xm(t){switch(typeof t){case"string":return t;case"number":return Am(t);case"boolean":return Tm(t);case"bigint":return ul?ul(t):"0";case"symbol":return dl?dl(t):"Symbol()";case"undefined":return Tr(t);case"function":case"object":{if(t===null)return Tr(t);const e=t,i=Wi(e,"toString");if(typeof i=="function"){const r=i(e);return typeof r=="string"?r:Tr(r)}return Tr(t)}default:return Tr(t)}}function Wi(t,e){for(;t!==null;){const r=ym(t,e);if(r){if(r.get)return ye(r.get);if(typeof r.value=="function")return ye(r.value)}t=mm(t)}function i(){return null}return i}function Dm(t){try{return _e(t,""),!0}catch{return!1}}const hl=Ve(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Es=Ve(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ks=Ve(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Im=Ve(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),xs=Ve(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Mm=Ve(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),pl=Ve(["#text"]),gl=Ve(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Ds=Ve(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),fl=Ve(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),bn=Ve(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Rm=ot(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Pm=ot(/<%[\w\W]*|[\w\W]*%>/gm),Om=ot(/\$\{[\w\W]*/gm),_m=ot(/^data-[\-\w.\u00B7-\uFFFF]+$/),Lm=ot(/^aria-[\-\w]+$/),vl=ot(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Fm=ot(/^(?:\w+script|data):/i),Um=ot(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),bl=ot(/^html$/i),Nm=ot(/^[a-z][.\w]*(-[.\w]+)+$/i);var ml=Object.freeze({__proto__:null,ARIA_ATTR:Lm,ATTR_WHITESPACE:Um,CUSTOM_ELEMENT:Nm,DATA_ATTR:_m,DOCTYPE_NAME:bl,ERB_EXPR:Pm,IS_ALLOWED_URI:vl,IS_SCRIPT_OR_DATA:Fm,MUSTACHE_EXPR:Rm,TMPLIT_EXPR:Om});const Er={element:1,text:3,progressingInstruction:7,comment:8,document:9},Bm=function(){return typeof window>"u"?null:window},zm=function(e,i){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const n="data-tt-policy-suffix";i&&i.hasAttribute(n)&&(r=i.getAttribute(n));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},yl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function wl(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Bm();const e=H=>wl(H);if(e.version="3.4.1",e.removed=[],!t||!t.document||t.document.nodeType!==Er.document||!t.Element)return e.isSupported=!1,e;let{document:i}=t;const r=i,n=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:o,Element:c,NodeFilter:u,NamedNodeMap:h=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:f,trustedTypes:m}=t,R=c.prototype,y=Wi(R,"cloneNode"),I=Wi(R,"remove"),x=Wi(R,"nextSibling"),v=Wi(R,"childNodes"),b=Wi(R,"parentNode");if(typeof a=="function"){const H=i.createElement("template");H.content&&H.content.ownerDocument&&(i=H.content.ownerDocument)}let w,A="";const{implementation:D,createNodeIterator:F,createDocumentFragment:K,getElementsByTagName:_}=i,{importNode:te}=r;let U=yl();e.isSupported=typeof sl=="function"&&typeof b=="function"&&D&&D.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ee,ERB_EXPR:ct,TMPLIT_EXPR:It,DATA_ATTR:kr,ARIA_ATTR:Is,IS_SCRIPT_OR_DATA:mn,ATTR_WHITESPACE:Ce,CUSTOM_ELEMENT:lt}=ml;let{IS_ALLOWED_URI:Ut}=ml,he=null;const Xe=q({},[...hl,...Es,...ks,...xs,...pl]);let Ae=null;const yt=q({},[...gl,...Ds,...fl,...bn]);let re=Object.seal(Hi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Mt=null,Nt=null;const ut=Object.seal(Hi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let xr=!0,fi=!0,vi=!1,yn=!0,wt=!1,Dr=!0,bi=!1,Ms=!1,Rs=!1,Gi=!1,wn=!1,Sn=!1,Al=!0,Tl=!1;const El="user-content-";let Ps=!0,Ir=!1,qi={},Rt=null;const Os=q({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let kl=null;const xl=q({},["audio","video","img","source","image","track"]);let _s=null;const Dl=q({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cn="http://www.w3.org/1998/Math/MathML",An="http://www.w3.org/2000/svg",Pt="http://www.w3.org/1999/xhtml";let Xi=Pt,Ls=!1,Fs=null;const Hm=q({},[Cn,An,Pt],Ts);let Us=q({},["mi","mo","mn","ms","mtext"]),Ns=q({},["annotation-xml"]);const jm=q({},["title","style","font","a","script"]);let Mr=null;const Wm=["application/xhtml+xml","text/html"],Gm="text/html";let Te=null,Yi=null;const qm=i.createElement("form"),Il=function(d){return d instanceof RegExp||d instanceof Function},Bs=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Yi&&Yi===d)return;(!d||typeof d!="object")&&(d={}),d=qe(d),Mr=Wm.indexOf(d.PARSER_MEDIA_TYPE)===-1?Gm:d.PARSER_MEDIA_TYPE,Te=Mr==="application/xhtml+xml"?Ts:Ar,he=ge(d,"ALLOWED_TAGS")&&He(d.ALLOWED_TAGS)?q({},d.ALLOWED_TAGS,Te):Xe,Ae=ge(d,"ALLOWED_ATTR")&&He(d.ALLOWED_ATTR)?q({},d.ALLOWED_ATTR,Te):yt,Fs=ge(d,"ALLOWED_NAMESPACES")&&He(d.ALLOWED_NAMESPACES)?q({},d.ALLOWED_NAMESPACES,Ts):Hm,_s=ge(d,"ADD_URI_SAFE_ATTR")&&He(d.ADD_URI_SAFE_ATTR)?q(qe(Dl),d.ADD_URI_SAFE_ATTR,Te):Dl,kl=ge(d,"ADD_DATA_URI_TAGS")&&He(d.ADD_DATA_URI_TAGS)?q(qe(xl),d.ADD_DATA_URI_TAGS,Te):xl,Rt=ge(d,"FORBID_CONTENTS")&&He(d.FORBID_CONTENTS)?q({},d.FORBID_CONTENTS,Te):Os,Mt=ge(d,"FORBID_TAGS")&&He(d.FORBID_TAGS)?q({},d.FORBID_TAGS,Te):qe({}),Nt=ge(d,"FORBID_ATTR")&&He(d.FORBID_ATTR)?q({},d.FORBID_ATTR,Te):qe({}),qi=ge(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?qe(d.USE_PROFILES):d.USE_PROFILES:!1,xr=d.ALLOW_ARIA_ATTR!==!1,fi=d.ALLOW_DATA_ATTR!==!1,vi=d.ALLOW_UNKNOWN_PROTOCOLS||!1,yn=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,wt=d.SAFE_FOR_TEMPLATES||!1,Dr=d.SAFE_FOR_XML!==!1,bi=d.WHOLE_DOCUMENT||!1,Gi=d.RETURN_DOM||!1,wn=d.RETURN_DOM_FRAGMENT||!1,Sn=d.RETURN_TRUSTED_TYPE||!1,Rs=d.FORCE_BODY||!1,Al=d.SANITIZE_DOM!==!1,Tl=d.SANITIZE_NAMED_PROPS||!1,Ps=d.KEEP_CONTENT!==!1,Ir=d.IN_PLACE||!1,Ut=Dm(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:vl,Xi=typeof d.NAMESPACE=="string"?d.NAMESPACE:Pt,Us=ge(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?qe(d.MATHML_TEXT_INTEGRATION_POINTS):q({},["mi","mo","mn","ms","mtext"]),Ns=ge(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?qe(d.HTML_INTEGRATION_POINTS):q({},["annotation-xml"]);const C=ge(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?qe(d.CUSTOM_ELEMENT_HANDLING):Hi(null);if(re=Hi(null),ge(C,"tagNameCheck")&&Il(C.tagNameCheck)&&(re.tagNameCheck=C.tagNameCheck),ge(C,"attributeNameCheck")&&Il(C.attributeNameCheck)&&(re.attributeNameCheck=C.attributeNameCheck),ge(C,"allowCustomizedBuiltInElements")&&typeof C.allowCustomizedBuiltInElements=="boolean"&&(re.allowCustomizedBuiltInElements=C.allowCustomizedBuiltInElements),wt&&(fi=!1),wn&&(Gi=!0),qi&&(he=q({},pl),Ae=Hi(null),qi.html===!0&&(q(he,hl),q(Ae,gl)),qi.svg===!0&&(q(he,Es),q(Ae,Ds),q(Ae,bn)),qi.svgFilters===!0&&(q(he,ks),q(Ae,Ds),q(Ae,bn)),qi.mathMl===!0&&(q(he,xs),q(Ae,fl),q(Ae,bn))),ut.tagCheck=null,ut.attributeCheck=null,ge(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?ut.tagCheck=d.ADD_TAGS:He(d.ADD_TAGS)&&(he===Xe&&(he=qe(he)),q(he,d.ADD_TAGS,Te))),ge(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?ut.attributeCheck=d.ADD_ATTR:He(d.ADD_ATTR)&&(Ae===yt&&(Ae=qe(Ae)),q(Ae,d.ADD_ATTR,Te))),ge(d,"ADD_URI_SAFE_ATTR")&&He(d.ADD_URI_SAFE_ATTR)&&q(_s,d.ADD_URI_SAFE_ATTR,Te),ge(d,"FORBID_CONTENTS")&&He(d.FORBID_CONTENTS)&&(Rt===Os&&(Rt=qe(Rt)),q(Rt,d.FORBID_CONTENTS,Te)),ge(d,"ADD_FORBID_CONTENTS")&&He(d.ADD_FORBID_CONTENTS)&&(Rt===Os&&(Rt=qe(Rt)),q(Rt,d.ADD_FORBID_CONTENTS,Te)),Ps&&(he["#text"]=!0),bi&&q(he,["html","head","body"]),he.table&&(q(he,["tbody"]),delete Mt.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');w=d.TRUSTED_TYPES_POLICY,A=w.createHTML("")}else w===void 0&&(w=zm(m,n)),w!==null&&typeof A=="string"&&(A=w.createHTML(""));Ve&&Ve(d),Yi=d},Ml=q({},[...Es,...ks,...Im]),Rl=q({},[...xs,...Mm]),Xm=function(d){let C=b(d);(!C||!C.tagName)&&(C={namespaceURI:Xi,tagName:"template"});const O=Ar(d.tagName),de=Ar(C.tagName);return Fs[d.namespaceURI]?d.namespaceURI===An?C.namespaceURI===Pt?O==="svg":C.namespaceURI===Cn?O==="svg"&&(de==="annotation-xml"||Us[de]):!!Ml[O]:d.namespaceURI===Cn?C.namespaceURI===Pt?O==="math":C.namespaceURI===An?O==="math"&&Ns[de]:!!Rl[O]:d.namespaceURI===Pt?C.namespaceURI===An&&!Ns[de]||C.namespaceURI===Cn&&!Us[de]?!1:!Rl[O]&&(jm[O]||!Ml[O]):!!(Mr==="application/xhtml+xml"&&Fs[d.namespaceURI]):!1},St=function(d){Cr(e.removed,{element:d});try{b(d).removeChild(d)}catch{I(d)}},mi=function(d,C){try{Cr(e.removed,{attribute:C.getAttributeNode(d),from:C})}catch{Cr(e.removed,{attribute:null,from:C})}if(C.removeAttribute(d),d==="is")if(Gi||wn)try{St(C)}catch{}else try{C.setAttribute(d,"")}catch{}},Pl=function(d){let C=null,O=null;if(Rs)d="<remove></remove>"+d;else{const we=cl(d,/^[\r\n\t ]+/);O=we&&we[0]}Mr==="application/xhtml+xml"&&Xi===Pt&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");const de=w?w.createHTML(d):d;if(Xi===Pt)try{C=new f().parseFromString(de,Mr)}catch{}if(!C||!C.documentElement){C=D.createDocument(Xi,"template",null);try{C.documentElement.innerHTML=Ls?A:de}catch{}}const Fe=C.body||C.documentElement;return d&&O&&Fe.insertBefore(i.createTextNode(O),Fe.childNodes[0]||null),Xi===Pt?_.call(C,bi?"html":"body")[0]:bi?C.documentElement:Fe},Ol=function(d){return F.call(d.ownerDocument||d,d,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},zs=function(d){return d instanceof p&&(typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||!(d.attributes instanceof h)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function")},Vs=function(d){return typeof o=="function"&&d instanceof o};function Bt(H,d,C){Sr(H,O=>{O.call(e,d,C,Yi)})}const _l=function(d){let C=null;if(Bt(U.beforeSanitizeElements,d,null),zs(d))return St(d),!0;const O=Te(d.nodeName);if(Bt(U.uponSanitizeElement,d,{tagName:O,allowedTags:he}),Dr&&d.hasChildNodes()&&!Vs(d.firstElementChild)&&_e(/<[/\w!]/g,d.innerHTML)&&_e(/<[/\w!]/g,d.textContent)||Dr&&d.namespaceURI===Pt&&O==="style"&&Vs(d.firstElementChild)||d.nodeType===Er.progressingInstruction||Dr&&d.nodeType===Er.comment&&_e(/<[/\w]/g,d.data))return St(d),!0;if(Mt[O]||!(ut.tagCheck instanceof Function&&ut.tagCheck(O))&&!he[O]){if(!Mt[O]&&Fl(O)&&(re.tagNameCheck instanceof RegExp&&_e(re.tagNameCheck,O)||re.tagNameCheck instanceof Function&&re.tagNameCheck(O)))return!1;if(Ps&&!Rt[O]){const de=b(d)||d.parentNode,Fe=v(d)||d.childNodes;if(Fe&&de){const we=Fe.length;for(let Ye=we-1;Ye>=0;--Ye){const dt=y(Fe[Ye],!0);de.insertBefore(dt,x(d))}}}return St(d),!0}return d instanceof c&&!Xm(d)||(O==="noscript"||O==="noembed"||O==="noframes")&&_e(/<\/no(script|embed|frames)/i,d.innerHTML)?(St(d),!0):(wt&&d.nodeType===Er.text&&(C=d.textContent,Sr([ee,ct,It],de=>{C=ji(C,de," ")}),d.textContent!==C&&(Cr(e.removed,{element:d.cloneNode()}),d.textContent=C)),Bt(U.afterSanitizeElements,d,null),!1)},Ll=function(d,C,O){if(Nt[C]||Al&&(C==="id"||C==="name")&&(O in i||O in qm))return!1;if(!(fi&&!Nt[C]&&_e(kr,C))){if(!(xr&&_e(Is,C))){if(!(ut.attributeCheck instanceof Function&&ut.attributeCheck(C,d))){if(!Ae[C]||Nt[C]){if(!(Fl(d)&&(re.tagNameCheck instanceof RegExp&&_e(re.tagNameCheck,d)||re.tagNameCheck instanceof Function&&re.tagNameCheck(d))&&(re.attributeNameCheck instanceof RegExp&&_e(re.attributeNameCheck,C)||re.attributeNameCheck instanceof Function&&re.attributeNameCheck(C,d))||C==="is"&&re.allowCustomizedBuiltInElements&&(re.tagNameCheck instanceof RegExp&&_e(re.tagNameCheck,O)||re.tagNameCheck instanceof Function&&re.tagNameCheck(O))))return!1}else if(!_s[C]){if(!_e(Ut,ji(O,Ce,""))){if(!((C==="src"||C==="xlink:href"||C==="href")&&d!=="script"&&ll(O,"data:")===0&&kl[d])){if(!(vi&&!_e(mn,ji(O,Ce,"")))){if(O)return!1}}}}}}}return!0},Ym=q({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Fl=function(d){return!Ym[Ar(d)]&&_e(lt,d)},Ul=function(d){Bt(U.beforeSanitizeAttributes,d,null);const{attributes:C}=d;if(!C||zs(d))return;const O={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ae,forceKeepAttr:void 0};let de=C.length;for(;de--;){const Fe=C[de],{name:we,namespaceURI:Ye,value:dt}=Fe,Ct=Te(we),Hs=dt;let De=we==="value"?Hs:Cm(Hs);if(O.attrName=Ct,O.attrValue=De,O.keepAttr=!0,O.forceKeepAttr=void 0,Bt(U.uponSanitizeAttribute,d,O),De=O.attrValue,Tl&&(Ct==="id"||Ct==="name")&&ll(De,El)!==0&&(mi(we,d),De=El+De),Dr&&_e(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,De)){mi(we,d);continue}if(Ct==="attributename"&&cl(De,"href")){mi(we,d);continue}if(O.forceKeepAttr)continue;if(!O.keepAttr){mi(we,d);continue}if(!yn&&_e(/\/>/i,De)){mi(we,d);continue}wt&&Sr([ee,ct,It],zl=>{De=ji(De,zl," ")});const Bl=Te(d.nodeName);if(!Ll(Bl,Ct,De)){mi(we,d);continue}if(w&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Ye)switch(m.getAttributeType(Bl,Ct)){case"TrustedHTML":{De=w.createHTML(De);break}case"TrustedScriptURL":{De=w.createScriptURL(De);break}}if(De!==Hs)try{Ye?d.setAttributeNS(Ye,we,De):d.setAttribute(we,De),zs(d)?St(d):ol(e.removed)}catch{mi(we,d)}}Bt(U.afterSanitizeAttributes,d,null)},Nl=function(d){let C=null;const O=Ol(d);for(Bt(U.beforeSanitizeShadowDOM,d,null);C=O.nextNode();)Bt(U.uponSanitizeShadowNode,C,null),_l(C),Ul(C),C.content instanceof s&&Nl(C.content);Bt(U.afterSanitizeShadowDOM,d,null)};return e.sanitize=function(H){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C=null,O=null,de=null,Fe=null;if(Ls=!H,Ls&&(H="<!-->"),typeof H!="string"&&!Vs(H)&&(H=xm(H),typeof H!="string"))throw vn("dirty is not a string, aborting");if(!e.isSupported)return H;if(Ms||Bs(d),e.removed=[],typeof H=="string"&&(Ir=!1),Ir){const dt=H.nodeName;if(typeof dt=="string"){const Ct=Te(dt);if(!he[Ct]||Mt[Ct])throw vn("root node is forbidden and cannot be sanitized in-place")}}else if(H instanceof o)C=Pl("<!---->"),O=C.ownerDocument.importNode(H,!0),O.nodeType===Er.element&&O.nodeName==="BODY"||O.nodeName==="HTML"?C=O:C.appendChild(O);else{if(!Gi&&!wt&&!bi&&H.indexOf("<")===-1)return w&&Sn?w.createHTML(H):H;if(C=Pl(H),!C)return Gi?null:Sn?A:""}C&&Rs&&St(C.firstChild);const we=Ol(Ir?H:C);for(;de=we.nextNode();)_l(de),Ul(de),de.content instanceof s&&Nl(de.content);if(Ir)return H;if(Gi){if(wt){C.normalize();let dt=C.innerHTML;Sr([ee,ct,It],Ct=>{dt=ji(dt,Ct," ")}),C.innerHTML=dt}if(wn)for(Fe=K.call(C.ownerDocument);C.firstChild;)Fe.appendChild(C.firstChild);else Fe=C;return(Ae.shadowroot||Ae.shadowrootmode)&&(Fe=te.call(r,Fe,!0)),Fe}let Ye=bi?C.outerHTML:C.innerHTML;return bi&&he["!doctype"]&&C.ownerDocument&&C.ownerDocument.doctype&&C.ownerDocument.doctype.name&&_e(bl,C.ownerDocument.doctype.name)&&(Ye="<!DOCTYPE "+C.ownerDocument.doctype.name+`>
|
|
3224
|
-
`+Ye),
|
|
3221
|
+
`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,i,r){const n=tl(e);if(n===null)return r;e=n;let s='<a href="'+e+'"';return i&&(s+=' title="'+i+'"'),s+=">"+r+"</a>",s}image(e,i,r){const n=tl(e);if(n===null)return r;e=n;let s=`<img src="${e}" alt="${r}"`;return i&&(s+=` title="${i}"`),s+=">",s}text(e){return e}}class fn{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,i,r){return""+r}image(e,i,r){return""+r}br(){return""}}class mt{constructor(e){ce(this,"options");ce(this,"renderer");ce(this,"textRenderer");this.options=e||Xt,this.options.renderer=this.options.renderer||new wr,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new fn}static parse(e,i){return new mt(i).parse(e)}static parseInline(e,i){return new mt(i).parseInline(e)}parse(e,i=!0){let r="";for(let n=0;n<e.length;n++){const s=e[n];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){const a=s,o=this.options.extensions.renderers[a.type].call({parser:this},a);if(o!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(a.type)){r+=o||"";continue}}switch(s.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{const a=s;r+=this.renderer.heading(this.parseInline(a.tokens),a.depth,nm(this.parseInline(a.tokens,this.textRenderer)));continue}case"code":{const a=s;r+=this.renderer.code(a.text,a.lang,!!a.escaped);continue}case"table":{const a=s;let o="",c="";for(let h=0;h<a.header.length;h++)c+=this.renderer.tablecell(this.parseInline(a.header[h].tokens),{header:!0,align:a.align[h]});o+=this.renderer.tablerow(c);let u="";for(let h=0;h<a.rows.length;h++){const p=a.rows[h];c="";for(let f=0;f<p.length;f++)c+=this.renderer.tablecell(this.parseInline(p[f].tokens),{header:!1,align:a.align[f]});u+=this.renderer.tablerow(c)}r+=this.renderer.table(o,u);continue}case"blockquote":{const a=s,o=this.parse(a.tokens);r+=this.renderer.blockquote(o);continue}case"list":{const a=s,o=a.ordered,c=a.start,u=a.loose;let h="";for(let p=0;p<a.items.length;p++){const f=a.items[p],m=f.checked,R=f.task;let y="";if(f.task){const I=this.renderer.checkbox(!!m);u?f.tokens.length>0&&f.tokens[0].type==="paragraph"?(f.tokens[0].text=I+" "+f.tokens[0].text,f.tokens[0].tokens&&f.tokens[0].tokens.length>0&&f.tokens[0].tokens[0].type==="text"&&(f.tokens[0].tokens[0].text=I+" "+f.tokens[0].tokens[0].text)):f.tokens.unshift({type:"text",text:I+" "}):y+=I+" "}y+=this.parse(f.tokens,u),h+=this.renderer.listitem(y,R,!!m)}r+=this.renderer.list(h,o,c);continue}case"html":{const a=s;r+=this.renderer.html(a.text,a.block);continue}case"paragraph":{const a=s;r+=this.renderer.paragraph(this.parseInline(a.tokens));continue}case"text":{let a=s,o=a.tokens?this.parseInline(a.tokens):a.text;for(;n+1<e.length&&e[n+1].type==="text";)a=e[++n],o+=`
|
|
3222
|
+
`+(a.tokens?this.parseInline(a.tokens):a.text);r+=i?this.renderer.paragraph(o):o;continue}default:{const a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}parseInline(e,i){i=i||this.renderer;let r="";for(let n=0;n<e.length;n++){const s=e[n];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){const a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=a||"";continue}}switch(s.type){case"escape":{const a=s;r+=i.text(a.text);break}case"html":{const a=s;r+=i.html(a.text);break}case"link":{const a=s;r+=i.link(a.href,a.title,this.parseInline(a.tokens,i));break}case"image":{const a=s;r+=i.image(a.href,a.title,a.text);break}case"strong":{const a=s;r+=i.strong(this.parseInline(a.tokens,i));break}case"em":{const a=s;r+=i.em(this.parseInline(a.tokens,i));break}case"codespan":{const a=s;r+=i.codespan(a.text);break}case"br":{r+=i.br();break}case"del":{const a=s;r+=i.del(this.parseInline(a.tokens,i));break}case"text":{const a=s;r+=i.text(a.text);break}default:{const a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}}class Vi{constructor(e){ce(this,"options");this.options=e||Xt}preprocess(e){return e}postprocess(e){return e}}ce(Vi,"passThroughHooks",new Set(["preprocess","postprocess"]));class nl{constructor(...e){Hl(this,gi);ce(this,"defaults",hn());ce(this,"options",this.setOptions);ce(this,"parse",Tn(this,gi,js).call(this,bt.lex,mt.parse));ce(this,"parseInline",Tn(this,gi,js).call(this,bt.lexInline,mt.parseInline));ce(this,"Parser",mt);ce(this,"Renderer",wr);ce(this,"TextRenderer",fn);ce(this,"Lexer",bt);ce(this,"Tokenizer",yr);ce(this,"Hooks",Vi);this.use(...e)}walkTokens(e,i){var n,s;let r=[];for(const a of e)switch(r=r.concat(i.call(this,a)),a.type){case"table":{const o=a;for(const c of o.header)r=r.concat(this.walkTokens(c.tokens,i));for(const c of o.rows)for(const u of c)r=r.concat(this.walkTokens(u.tokens,i));break}case"list":{const o=a;r=r.concat(this.walkTokens(o.items,i));break}default:{const o=a;(s=(n=this.defaults.extensions)==null?void 0:n.childTokens)!=null&&s[o.type]?this.defaults.extensions.childTokens[o.type].forEach(c=>{r=r.concat(this.walkTokens(o[c],i))}):o.tokens&&(r=r.concat(this.walkTokens(o.tokens,i)))}}return r}use(...e){const i=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{const n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){const a=i.renderers[s.name];a?i.renderers[s.name]=function(...o){let c=s.renderer.apply(this,o);return c===!1&&(c=a.apply(this,o)),c}:i.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const a=i[s.level];a?a.unshift(s.tokenizer):i[s.level]=[s.tokenizer],s.start&&(s.level==="block"?i.startBlock?i.startBlock.push(s.start):i.startBlock=[s.start]:s.level==="inline"&&(i.startInline?i.startInline.push(s.start):i.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(i.childTokens[s.name]=s.childTokens)}),n.extensions=i),r.renderer){const s=this.defaults.renderer||new wr(this.defaults);for(const a in r.renderer){const o=r.renderer[a],c=a,u=s[c];s[c]=(...h)=>{let p=o.apply(s,h);return p===!1&&(p=u.apply(s,h)),p||""}}n.renderer=s}if(r.tokenizer){const s=this.defaults.tokenizer||new yr(this.defaults);for(const a in r.tokenizer){const o=r.tokenizer[a],c=a,u=s[c];s[c]=(...h)=>{let p=o.apply(s,h);return p===!1&&(p=u.apply(s,h)),p}}n.tokenizer=s}if(r.hooks){const s=this.defaults.hooks||new Vi;for(const a in r.hooks){const o=r.hooks[a],c=a,u=s[c];Vi.passThroughHooks.has(a)?s[c]=h=>{if(this.defaults.async)return Promise.resolve(o.call(s,h)).then(f=>u.call(s,f));const p=o.call(s,h);return u.call(s,p)}:s[c]=(...h)=>{let p=o.apply(s,h);return p===!1&&(p=u.apply(s,h)),p}}n.hooks=s}if(r.walkTokens){const s=this.defaults.walkTokens,a=r.walkTokens;n.walkTokens=function(o){let c=[];return c.push(a.call(this,o)),s&&(c=c.concat(s.call(this,o))),c}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,i){return bt.lex(e,i??this.defaults)}parser(e,i){return mt.parse(e,i??this.defaults)}}gi=new WeakSet,js=function(e,i){return(r,n)=>{const s={...n},a={...this.defaults,...s};this.defaults.async===!0&&s.async===!1&&(a.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),a.async=!0);const o=Tn(this,gi,Wl).call(this,!!a.silent,!!a.async);if(typeof r>"u"||r===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof r!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(r)+", string expected"));if(a.hooks&&(a.hooks.options=a),a.async)return Promise.resolve(a.hooks?a.hooks.preprocess(r):r).then(c=>e(c,a)).then(c=>a.walkTokens?Promise.all(this.walkTokens(c,a.walkTokens)).then(()=>c):c).then(c=>i(c,a)).then(c=>a.hooks?a.hooks.postprocess(c):c).catch(o);try{a.hooks&&(r=a.hooks.preprocess(r));const c=e(r,a);a.walkTokens&&this.walkTokens(c,a.walkTokens);let u=i(c,a);return a.hooks&&(u=a.hooks.postprocess(u)),u}catch(c){return o(c)}}},Wl=function(e,i){return r=>{if(r.message+=`
|
|
3223
|
+
Please report this to https://github.com/markedjs/marked.`,e){const n="<p>An error occurred:</p><pre>"+Je(r.message+"",!0)+"</pre>";return i?Promise.resolve(n):n}if(i)return Promise.reject(r);throw r}};const hi=new nl;function $(t,e){return hi.parse(t,e)}$.options=$.setOptions=function(t){return hi.setOptions(t),$.defaults=hi.defaults,Qc($.defaults),$},$.getDefaults=hn,$.defaults=Xt,$.use=function(...t){return hi.use(...t),$.defaults=hi.defaults,Qc($.defaults),$},$.walkTokens=function(t,e){return hi.walkTokens(t,e)},$.parseInline=hi.parseInline,$.Parser=mt,$.parser=mt.parse,$.Renderer=wr,$.TextRenderer=fn,$.Lexer=bt,$.lexer=bt.lex,$.Tokenizer=yr,$.Hooks=Vi,$.parse=$;const cm=$.options,lm=$.setOptions,um=$.use,dm=$.walkTokens,hm=$.parseInline,pm=$,gm=mt.parse,fm=bt.lex,vm=Object.freeze(Object.defineProperty({__proto__:null,Hooks:Vi,Lexer:bt,Marked:nl,Parser:mt,Renderer:wr,TextRenderer:fn,Tokenizer:yr,get defaults(){return Xt},getDefaults:hn,lexer:fm,marked:$,options:cm,parse:pm,parseInline:hm,parser:gm,setOptions:lm,use:um,walkTokens:dm},Symbol.toStringTag,{value:"Module"}));/*! @license DOMPurify 3.4.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.1/LICENSE */const{entries:sl,setPrototypeOf:al,isFrozen:bm,getPrototypeOf:mm,getOwnPropertyDescriptor:ym}=Object;let{freeze:Ve,seal:ot,create:Hi}=Object,{apply:Cs,construct:As}=typeof Reflect<"u"&&Reflect;Ve||(Ve=function(e){return e}),ot||(ot=function(e){return e}),Cs||(Cs=function(e,i){for(var r=arguments.length,n=new Array(r>2?r-2:0),s=2;s<r;s++)n[s-2]=arguments[s];return e.apply(i,n)}),As||(As=function(e){for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return new e(...r)});const Sr=ye(Array.prototype.forEach),wm=ye(Array.prototype.lastIndexOf),ol=ye(Array.prototype.pop),Cr=ye(Array.prototype.push),Sm=ye(Array.prototype.splice),He=Array.isArray,Ar=ye(String.prototype.toLowerCase),Ts=ye(String.prototype.toString),cl=ye(String.prototype.match),ji=ye(String.prototype.replace),ll=ye(String.prototype.indexOf),Cm=ye(String.prototype.trim),Am=ye(Number.prototype.toString),Tm=ye(Boolean.prototype.toString),ul=typeof BigInt>"u"?null:ye(BigInt.prototype.toString),dl=typeof Symbol>"u"?null:ye(Symbol.prototype.toString),ge=ye(Object.prototype.hasOwnProperty),Tr=ye(Object.prototype.toString),_e=ye(RegExp.prototype.test),vn=Em(TypeError);function ye(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return Cs(t,e,r)}}function Em(t){return function(){for(var e=arguments.length,i=new Array(e),r=0;r<e;r++)i[r]=arguments[r];return As(t,i)}}function q(t,e){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ar;if(al&&al(t,null),!He(e))return t;let r=e.length;for(;r--;){let n=e[r];if(typeof n=="string"){const s=i(n);s!==n&&(bm(e)||(e[r]=s),n=s)}t[n]=!0}return t}function km(t){for(let e=0;e<t.length;e++)ge(t,e)||(t[e]=null);return t}function qe(t){const e=Hi(null);for(const[i,r]of sl(t))ge(t,i)&&(He(r)?e[i]=km(r):r&&typeof r=="object"&&r.constructor===Object?e[i]=qe(r):e[i]=r);return e}function xm(t){switch(typeof t){case"string":return t;case"number":return Am(t);case"boolean":return Tm(t);case"bigint":return ul?ul(t):"0";case"symbol":return dl?dl(t):"Symbol()";case"undefined":return Tr(t);case"function":case"object":{if(t===null)return Tr(t);const e=t,i=Wi(e,"toString");if(typeof i=="function"){const r=i(e);return typeof r=="string"?r:Tr(r)}return Tr(t)}default:return Tr(t)}}function Wi(t,e){for(;t!==null;){const r=ym(t,e);if(r){if(r.get)return ye(r.get);if(typeof r.value=="function")return ye(r.value)}t=mm(t)}function i(){return null}return i}function Dm(t){try{return _e(t,""),!0}catch{return!1}}const hl=Ve(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Es=Ve(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ks=Ve(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Im=Ve(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),xs=Ve(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Mm=Ve(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),pl=Ve(["#text"]),gl=Ve(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Ds=Ve(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),fl=Ve(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),bn=Ve(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Rm=ot(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Pm=ot(/<%[\w\W]*|[\w\W]*%>/gm),Om=ot(/\$\{[\w\W]*/gm),_m=ot(/^data-[\-\w.\u00B7-\uFFFF]+$/),Lm=ot(/^aria-[\-\w]+$/),vl=ot(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Fm=ot(/^(?:\w+script|data):/i),Um=ot(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),bl=ot(/^html$/i),Nm=ot(/^[a-z][.\w]*(-[.\w]+)+$/i);var ml=Object.freeze({__proto__:null,ARIA_ATTR:Lm,ATTR_WHITESPACE:Um,CUSTOM_ELEMENT:Nm,DATA_ATTR:_m,DOCTYPE_NAME:bl,ERB_EXPR:Pm,IS_ALLOWED_URI:vl,IS_SCRIPT_OR_DATA:Fm,MUSTACHE_EXPR:Rm,TMPLIT_EXPR:Om});const Er={element:1,text:3,progressingInstruction:7,comment:8,document:9},Bm=function(){return typeof window>"u"?null:window},zm=function(e,i){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const n="data-tt-policy-suffix";i&&i.hasAttribute(n)&&(r=i.getAttribute(n));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},yl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function wl(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Bm();const e=H=>wl(H);if(e.version="3.4.1",e.removed=[],!t||!t.document||t.document.nodeType!==Er.document||!t.Element)return e.isSupported=!1,e;let{document:i}=t;const r=i,n=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:o,Element:c,NodeFilter:u,NamedNodeMap:h=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:f,trustedTypes:m}=t,R=c.prototype,y=Wi(R,"cloneNode"),I=Wi(R,"remove"),x=Wi(R,"nextSibling"),v=Wi(R,"childNodes"),b=Wi(R,"parentNode");if(typeof a=="function"){const H=i.createElement("template");H.content&&H.content.ownerDocument&&(i=H.content.ownerDocument)}let w,A="";const{implementation:D,createNodeIterator:F,createDocumentFragment:K,getElementsByTagName:_}=i,{importNode:te}=r;let U=yl();e.isSupported=typeof sl=="function"&&typeof b=="function"&&D&&D.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ee,ERB_EXPR:ct,TMPLIT_EXPR:It,DATA_ATTR:kr,ARIA_ATTR:Is,IS_SCRIPT_OR_DATA:mn,ATTR_WHITESPACE:Ce,CUSTOM_ELEMENT:lt}=ml;let{IS_ALLOWED_URI:Ut}=ml,he=null;const Xe=q({},[...hl,...Es,...ks,...xs,...pl]);let Ae=null;const wt=q({},[...gl,...Ds,...fl,...bn]);let re=Object.seal(Hi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Mt=null,Nt=null;const ut=Object.seal(Hi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let xr=!0,fi=!0,vi=!1,yn=!0,St=!1,Dr=!0,bi=!1,Ms=!1,Rs=!1,Gi=!1,wn=!1,Sn=!1,Al=!0,Tl=!1;const El="user-content-";let Ps=!0,Ir=!1,qi={},Rt=null;const Os=q({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let kl=null;const xl=q({},["audio","video","img","source","image","track"]);let _s=null;const Dl=q({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cn="http://www.w3.org/1998/Math/MathML",An="http://www.w3.org/2000/svg",Pt="http://www.w3.org/1999/xhtml";let Xi=Pt,Ls=!1,Fs=null;const Hm=q({},[Cn,An,Pt],Ts);let Us=q({},["mi","mo","mn","ms","mtext"]),Ns=q({},["annotation-xml"]);const jm=q({},["title","style","font","a","script"]);let Mr=null;const Wm=["application/xhtml+xml","text/html"],Gm="text/html";let Te=null,Yi=null;const qm=i.createElement("form"),Il=function(d){return d instanceof RegExp||d instanceof Function},Bs=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Yi&&Yi===d)return;(!d||typeof d!="object")&&(d={}),d=qe(d),Mr=Wm.indexOf(d.PARSER_MEDIA_TYPE)===-1?Gm:d.PARSER_MEDIA_TYPE,Te=Mr==="application/xhtml+xml"?Ts:Ar,he=ge(d,"ALLOWED_TAGS")&&He(d.ALLOWED_TAGS)?q({},d.ALLOWED_TAGS,Te):Xe,Ae=ge(d,"ALLOWED_ATTR")&&He(d.ALLOWED_ATTR)?q({},d.ALLOWED_ATTR,Te):wt,Fs=ge(d,"ALLOWED_NAMESPACES")&&He(d.ALLOWED_NAMESPACES)?q({},d.ALLOWED_NAMESPACES,Ts):Hm,_s=ge(d,"ADD_URI_SAFE_ATTR")&&He(d.ADD_URI_SAFE_ATTR)?q(qe(Dl),d.ADD_URI_SAFE_ATTR,Te):Dl,kl=ge(d,"ADD_DATA_URI_TAGS")&&He(d.ADD_DATA_URI_TAGS)?q(qe(xl),d.ADD_DATA_URI_TAGS,Te):xl,Rt=ge(d,"FORBID_CONTENTS")&&He(d.FORBID_CONTENTS)?q({},d.FORBID_CONTENTS,Te):Os,Mt=ge(d,"FORBID_TAGS")&&He(d.FORBID_TAGS)?q({},d.FORBID_TAGS,Te):qe({}),Nt=ge(d,"FORBID_ATTR")&&He(d.FORBID_ATTR)?q({},d.FORBID_ATTR,Te):qe({}),qi=ge(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?qe(d.USE_PROFILES):d.USE_PROFILES:!1,xr=d.ALLOW_ARIA_ATTR!==!1,fi=d.ALLOW_DATA_ATTR!==!1,vi=d.ALLOW_UNKNOWN_PROTOCOLS||!1,yn=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,St=d.SAFE_FOR_TEMPLATES||!1,Dr=d.SAFE_FOR_XML!==!1,bi=d.WHOLE_DOCUMENT||!1,Gi=d.RETURN_DOM||!1,wn=d.RETURN_DOM_FRAGMENT||!1,Sn=d.RETURN_TRUSTED_TYPE||!1,Rs=d.FORCE_BODY||!1,Al=d.SANITIZE_DOM!==!1,Tl=d.SANITIZE_NAMED_PROPS||!1,Ps=d.KEEP_CONTENT!==!1,Ir=d.IN_PLACE||!1,Ut=Dm(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:vl,Xi=typeof d.NAMESPACE=="string"?d.NAMESPACE:Pt,Us=ge(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?qe(d.MATHML_TEXT_INTEGRATION_POINTS):q({},["mi","mo","mn","ms","mtext"]),Ns=ge(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?qe(d.HTML_INTEGRATION_POINTS):q({},["annotation-xml"]);const C=ge(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?qe(d.CUSTOM_ELEMENT_HANDLING):Hi(null);if(re=Hi(null),ge(C,"tagNameCheck")&&Il(C.tagNameCheck)&&(re.tagNameCheck=C.tagNameCheck),ge(C,"attributeNameCheck")&&Il(C.attributeNameCheck)&&(re.attributeNameCheck=C.attributeNameCheck),ge(C,"allowCustomizedBuiltInElements")&&typeof C.allowCustomizedBuiltInElements=="boolean"&&(re.allowCustomizedBuiltInElements=C.allowCustomizedBuiltInElements),St&&(fi=!1),wn&&(Gi=!0),qi&&(he=q({},pl),Ae=Hi(null),qi.html===!0&&(q(he,hl),q(Ae,gl)),qi.svg===!0&&(q(he,Es),q(Ae,Ds),q(Ae,bn)),qi.svgFilters===!0&&(q(he,ks),q(Ae,Ds),q(Ae,bn)),qi.mathMl===!0&&(q(he,xs),q(Ae,fl),q(Ae,bn))),ut.tagCheck=null,ut.attributeCheck=null,ge(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?ut.tagCheck=d.ADD_TAGS:He(d.ADD_TAGS)&&(he===Xe&&(he=qe(he)),q(he,d.ADD_TAGS,Te))),ge(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?ut.attributeCheck=d.ADD_ATTR:He(d.ADD_ATTR)&&(Ae===wt&&(Ae=qe(Ae)),q(Ae,d.ADD_ATTR,Te))),ge(d,"ADD_URI_SAFE_ATTR")&&He(d.ADD_URI_SAFE_ATTR)&&q(_s,d.ADD_URI_SAFE_ATTR,Te),ge(d,"FORBID_CONTENTS")&&He(d.FORBID_CONTENTS)&&(Rt===Os&&(Rt=qe(Rt)),q(Rt,d.FORBID_CONTENTS,Te)),ge(d,"ADD_FORBID_CONTENTS")&&He(d.ADD_FORBID_CONTENTS)&&(Rt===Os&&(Rt=qe(Rt)),q(Rt,d.ADD_FORBID_CONTENTS,Te)),Ps&&(he["#text"]=!0),bi&&q(he,["html","head","body"]),he.table&&(q(he,["tbody"]),delete Mt.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');w=d.TRUSTED_TYPES_POLICY,A=w.createHTML("")}else w===void 0&&(w=zm(m,n)),w!==null&&typeof A=="string"&&(A=w.createHTML(""));Ve&&Ve(d),Yi=d},Ml=q({},[...Es,...ks,...Im]),Rl=q({},[...xs,...Mm]),Xm=function(d){let C=b(d);(!C||!C.tagName)&&(C={namespaceURI:Xi,tagName:"template"});const O=Ar(d.tagName),de=Ar(C.tagName);return Fs[d.namespaceURI]?d.namespaceURI===An?C.namespaceURI===Pt?O==="svg":C.namespaceURI===Cn?O==="svg"&&(de==="annotation-xml"||Us[de]):!!Ml[O]:d.namespaceURI===Cn?C.namespaceURI===Pt?O==="math":C.namespaceURI===An?O==="math"&&Ns[de]:!!Rl[O]:d.namespaceURI===Pt?C.namespaceURI===An&&!Ns[de]||C.namespaceURI===Cn&&!Us[de]?!1:!Rl[O]&&(jm[O]||!Ml[O]):!!(Mr==="application/xhtml+xml"&&Fs[d.namespaceURI]):!1},Ct=function(d){Cr(e.removed,{element:d});try{b(d).removeChild(d)}catch{I(d)}},mi=function(d,C){try{Cr(e.removed,{attribute:C.getAttributeNode(d),from:C})}catch{Cr(e.removed,{attribute:null,from:C})}if(C.removeAttribute(d),d==="is")if(Gi||wn)try{Ct(C)}catch{}else try{C.setAttribute(d,"")}catch{}},Pl=function(d){let C=null,O=null;if(Rs)d="<remove></remove>"+d;else{const we=cl(d,/^[\r\n\t ]+/);O=we&&we[0]}Mr==="application/xhtml+xml"&&Xi===Pt&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");const de=w?w.createHTML(d):d;if(Xi===Pt)try{C=new f().parseFromString(de,Mr)}catch{}if(!C||!C.documentElement){C=D.createDocument(Xi,"template",null);try{C.documentElement.innerHTML=Ls?A:de}catch{}}const Fe=C.body||C.documentElement;return d&&O&&Fe.insertBefore(i.createTextNode(O),Fe.childNodes[0]||null),Xi===Pt?_.call(C,bi?"html":"body")[0]:bi?C.documentElement:Fe},Ol=function(d){return F.call(d.ownerDocument||d,d,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},zs=function(d){return d instanceof p&&(typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||!(d.attributes instanceof h)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function")},Vs=function(d){return typeof o=="function"&&d instanceof o};function Bt(H,d,C){Sr(H,O=>{O.call(e,d,C,Yi)})}const _l=function(d){let C=null;if(Bt(U.beforeSanitizeElements,d,null),zs(d))return Ct(d),!0;const O=Te(d.nodeName);if(Bt(U.uponSanitizeElement,d,{tagName:O,allowedTags:he}),Dr&&d.hasChildNodes()&&!Vs(d.firstElementChild)&&_e(/<[/\w!]/g,d.innerHTML)&&_e(/<[/\w!]/g,d.textContent)||Dr&&d.namespaceURI===Pt&&O==="style"&&Vs(d.firstElementChild)||d.nodeType===Er.progressingInstruction||Dr&&d.nodeType===Er.comment&&_e(/<[/\w]/g,d.data))return Ct(d),!0;if(Mt[O]||!(ut.tagCheck instanceof Function&&ut.tagCheck(O))&&!he[O]){if(!Mt[O]&&Fl(O)&&(re.tagNameCheck instanceof RegExp&&_e(re.tagNameCheck,O)||re.tagNameCheck instanceof Function&&re.tagNameCheck(O)))return!1;if(Ps&&!Rt[O]){const de=b(d)||d.parentNode,Fe=v(d)||d.childNodes;if(Fe&&de){const we=Fe.length;for(let Ye=we-1;Ye>=0;--Ye){const dt=y(Fe[Ye],!0);de.insertBefore(dt,x(d))}}}return Ct(d),!0}return d instanceof c&&!Xm(d)||(O==="noscript"||O==="noembed"||O==="noframes")&&_e(/<\/no(script|embed|frames)/i,d.innerHTML)?(Ct(d),!0):(St&&d.nodeType===Er.text&&(C=d.textContent,Sr([ee,ct,It],de=>{C=ji(C,de," ")}),d.textContent!==C&&(Cr(e.removed,{element:d.cloneNode()}),d.textContent=C)),Bt(U.afterSanitizeElements,d,null),!1)},Ll=function(d,C,O){if(Nt[C]||Al&&(C==="id"||C==="name")&&(O in i||O in qm))return!1;if(!(fi&&!Nt[C]&&_e(kr,C))){if(!(xr&&_e(Is,C))){if(!(ut.attributeCheck instanceof Function&&ut.attributeCheck(C,d))){if(!Ae[C]||Nt[C]){if(!(Fl(d)&&(re.tagNameCheck instanceof RegExp&&_e(re.tagNameCheck,d)||re.tagNameCheck instanceof Function&&re.tagNameCheck(d))&&(re.attributeNameCheck instanceof RegExp&&_e(re.attributeNameCheck,C)||re.attributeNameCheck instanceof Function&&re.attributeNameCheck(C,d))||C==="is"&&re.allowCustomizedBuiltInElements&&(re.tagNameCheck instanceof RegExp&&_e(re.tagNameCheck,O)||re.tagNameCheck instanceof Function&&re.tagNameCheck(O))))return!1}else if(!_s[C]){if(!_e(Ut,ji(O,Ce,""))){if(!((C==="src"||C==="xlink:href"||C==="href")&&d!=="script"&&ll(O,"data:")===0&&kl[d])){if(!(vi&&!_e(mn,ji(O,Ce,"")))){if(O)return!1}}}}}}}return!0},Ym=q({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Fl=function(d){return!Ym[Ar(d)]&&_e(lt,d)},Ul=function(d){Bt(U.beforeSanitizeAttributes,d,null);const{attributes:C}=d;if(!C||zs(d))return;const O={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ae,forceKeepAttr:void 0};let de=C.length;for(;de--;){const Fe=C[de],{name:we,namespaceURI:Ye,value:dt}=Fe,At=Te(we),Hs=dt;let De=we==="value"?Hs:Cm(Hs);if(O.attrName=At,O.attrValue=De,O.keepAttr=!0,O.forceKeepAttr=void 0,Bt(U.uponSanitizeAttribute,d,O),De=O.attrValue,Tl&&(At==="id"||At==="name")&&ll(De,El)!==0&&(mi(we,d),De=El+De),Dr&&_e(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,De)){mi(we,d);continue}if(At==="attributename"&&cl(De,"href")){mi(we,d);continue}if(O.forceKeepAttr)continue;if(!O.keepAttr){mi(we,d);continue}if(!yn&&_e(/\/>/i,De)){mi(we,d);continue}St&&Sr([ee,ct,It],zl=>{De=ji(De,zl," ")});const Bl=Te(d.nodeName);if(!Ll(Bl,At,De)){mi(we,d);continue}if(w&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Ye)switch(m.getAttributeType(Bl,At)){case"TrustedHTML":{De=w.createHTML(De);break}case"TrustedScriptURL":{De=w.createScriptURL(De);break}}if(De!==Hs)try{Ye?d.setAttributeNS(Ye,we,De):d.setAttribute(we,De),zs(d)?Ct(d):ol(e.removed)}catch{mi(we,d)}}Bt(U.afterSanitizeAttributes,d,null)},Nl=function(d){let C=null;const O=Ol(d);for(Bt(U.beforeSanitizeShadowDOM,d,null);C=O.nextNode();)Bt(U.uponSanitizeShadowNode,C,null),_l(C),Ul(C),C.content instanceof s&&Nl(C.content);Bt(U.afterSanitizeShadowDOM,d,null)};return e.sanitize=function(H){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C=null,O=null,de=null,Fe=null;if(Ls=!H,Ls&&(H="<!-->"),typeof H!="string"&&!Vs(H)&&(H=xm(H),typeof H!="string"))throw vn("dirty is not a string, aborting");if(!e.isSupported)return H;if(Ms||Bs(d),e.removed=[],typeof H=="string"&&(Ir=!1),Ir){const dt=H.nodeName;if(typeof dt=="string"){const At=Te(dt);if(!he[At]||Mt[At])throw vn("root node is forbidden and cannot be sanitized in-place")}}else if(H instanceof o)C=Pl("<!---->"),O=C.ownerDocument.importNode(H,!0),O.nodeType===Er.element&&O.nodeName==="BODY"||O.nodeName==="HTML"?C=O:C.appendChild(O);else{if(!Gi&&!St&&!bi&&H.indexOf("<")===-1)return w&&Sn?w.createHTML(H):H;if(C=Pl(H),!C)return Gi?null:Sn?A:""}C&&Rs&&Ct(C.firstChild);const we=Ol(Ir?H:C);for(;de=we.nextNode();)_l(de),Ul(de),de.content instanceof s&&Nl(de.content);if(Ir)return H;if(Gi){if(St){C.normalize();let dt=C.innerHTML;Sr([ee,ct,It],At=>{dt=ji(dt,At," ")}),C.innerHTML=dt}if(wn)for(Fe=K.call(C.ownerDocument);C.firstChild;)Fe.appendChild(C.firstChild);else Fe=C;return(Ae.shadowroot||Ae.shadowrootmode)&&(Fe=te.call(r,Fe,!0)),Fe}let Ye=bi?C.outerHTML:C.innerHTML;return bi&&he["!doctype"]&&C.ownerDocument&&C.ownerDocument.doctype&&C.ownerDocument.doctype.name&&_e(bl,C.ownerDocument.doctype.name)&&(Ye="<!DOCTYPE "+C.ownerDocument.doctype.name+`>
|
|
3224
|
+
`+Ye),St&&Sr([ee,ct,It],dt=>{Ye=ji(Ye,dt," ")}),w&&Sn?w.createHTML(Ye):Ye},e.setConfig=function(){let H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Bs(H),Ms=!0},e.clearConfig=function(){Yi=null,Ms=!1},e.isValidAttribute=function(H,d,C){Yi||Bs({});const O=Te(H),de=Te(d);return Ll(O,de,C)},e.addHook=function(H,d){typeof d=="function"&&Cr(U[H],d)},e.removeHook=function(H,d){if(d!==void 0){const C=wm(U[H],d);return C===-1?void 0:Sm(U[H],C,1)[0]}return ol(U[H])},e.removeHooks=function(H){U[H]=[]},e.removeAllHooks=function(){U=yl()},e}var Vm=wl();const Sl=Object.freeze(Object.defineProperty({__proto__:null,default:Vm},Symbol.toStringTag,{value:"Module"}));return l.CallStateContextController=bs,l.ChatState=kc,l.DevicesContextController=ms,l.EmbedTokenCredentialProvider=bc,l.IncomingCallController=oa,l.LitElement=Z,l.SignalWire=vc,l.StaticCredentialProvider=mc,l.TranscriptController=pr,l.UserEventController=Dc,l.callStateContext=ht,l.css=ne,l.devicesContext=ir,l.ensureSignalWireFonts=zc,l.ensureSignalWireTheme=Bc,l.html=k,l.ready=Vb,l.showPrompt=br,l.transcriptContext=Ec,l.useGoogleFont=cn,l.version=zb,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),l})({});
|
|
3225
3225
|
//# sourceMappingURL=signalwire-web-components-embed.iife.js.map
|