hanc-webrtc-widgets 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hanc-webrtc-widgets.es.js +8791 -0
- package/dist/hanc-webrtc-widgets.umd.js +506 -0
- package/dist/index.d.ts +2 -0
- package/dist/src/components/call-control/call-control.d.ts +14 -0
- package/dist/src/components/call-control/index.d.ts +1 -0
- package/dist/src/components/call-control/styles.d.ts +1 -0
- package/dist/src/components/floating-call/floating-call.d.ts +14 -0
- package/dist/src/components/floating-call/index.d.ts +1 -0
- package/dist/src/components/floating-call/styles.d.ts +1 -0
- package/dist/src/components/index.d.ts +2 -0
- package/dist/src/core/global-styles.d.ts +1 -0
- package/dist/src/core/twilio-call-manager.d.ts +22 -0
- package/dist/src/icons/index.d.ts +2 -0
- package/dist/vite.config.d.ts +2 -0
- package/package.json +39 -0
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
(function(H,J){typeof exports=="object"&&typeof module<"u"?J(exports,require("lit")):typeof define=="function"&&define.amd?define(["exports","lit"],J):(H=typeof globalThis<"u"?globalThis:H||self,J(H.HancWebrtcWidgets={},H.lit))})(this,function(H,J){"use strict";/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2017 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
5
|
+
*/const dt=w=>(p,r)=>{r!==void 0?r.addInitializer(()=>{customElements.define(w,p)}):customElements.define(w,p)};/**
|
|
6
|
+
* @license
|
|
7
|
+
* Copyright 2019 Google LLC
|
|
8
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
9
|
+
*/const Ae=globalThis,Je=Ae.ShadowRoot&&(Ae.ShadyCSS===void 0||Ae.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ft=Symbol(),pt=new WeakMap;let Tn=class{constructor(p,r,l){if(this._$cssResult$=!0,l!==ft)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=p,this.t=r}get styleSheet(){let p=this.o;const r=this.t;if(Je&&p===void 0){const l=r!==void 0&&r.length===1;l&&(p=pt.get(r)),p===void 0&&((this.o=p=new CSSStyleSheet).replaceSync(this.cssText),l&&pt.set(r,p))}return p}toString(){return this.cssText}};const Pn=w=>new Tn(typeof w=="string"?w:w+"",void 0,ft),In=(w,p)=>{if(Je)w.adoptedStyleSheets=p.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(const r of p){const l=document.createElement("style"),h=Ae.litNonce;h!==void 0&&l.setAttribute("nonce",h),l.textContent=r.cssText,w.appendChild(l)}},ht=Je?w=>w:w=>w instanceof CSSStyleSheet?(p=>{let r="";for(const l of p.cssRules)r+=l.cssText;return Pn(r)})(w):w;/**
|
|
10
|
+
* @license
|
|
11
|
+
* Copyright 2017 Google LLC
|
|
12
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
13
|
+
*/const{is:kn,defineProperty:Rn,getOwnPropertyDescriptor:An,getOwnPropertyNames:xn,getOwnPropertySymbols:Dn,getPrototypeOf:On}=Object,ue=globalThis,vt=ue.trustedTypes,Mn=vt?vt.emptyScript:"",Ke=ue.reactiveElementPolyfillSupport,Ee=(w,p)=>w,xe={toAttribute(w,p){switch(p){case Boolean:w=w?Mn:null;break;case Object:case Array:w=w==null?w:JSON.stringify(w)}return w},fromAttribute(w,p){let r=w;switch(p){case Boolean:r=w!==null;break;case Number:r=w===null?null:Number(w);break;case Object:case Array:try{r=JSON.parse(w)}catch{r=null}}return r}},Qe=(w,p)=>!kn(w,p),gt={attribute:!0,type:String,converter:xe,reflect:!1,hasChanged:Qe};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ue.litPropertyMetadata??(ue.litPropertyMetadata=new WeakMap);class Te extends HTMLElement{static addInitializer(p){this._$Ei(),(this.l??(this.l=[])).push(p)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(p,r=gt){if(r.state&&(r.attribute=!1),this._$Ei(),this.elementProperties.set(p,r),!r.noAccessor){const l=Symbol(),h=this.getPropertyDescriptor(p,l,r);h!==void 0&&Rn(this.prototype,p,h)}}static getPropertyDescriptor(p,r,l){const{get:h,set:b}=An(this.prototype,p)??{get(){return this[r]},set(S){this[r]=S}};return{get(){return h==null?void 0:h.call(this)},set(S){const m=h==null?void 0:h.call(this);b.call(this,S),this.requestUpdate(p,m,l)},configurable:!0,enumerable:!0}}static getPropertyOptions(p){return this.elementProperties.get(p)??gt}static _$Ei(){if(this.hasOwnProperty(Ee("elementProperties")))return;const p=On(this);p.finalize(),p.l!==void 0&&(this.l=[...p.l]),this.elementProperties=new Map(p.elementProperties)}static finalize(){if(this.hasOwnProperty(Ee("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ee("properties"))){const r=this.properties,l=[...xn(r),...Dn(r)];for(const h of l)this.createProperty(h,r[h])}const p=this[Symbol.metadata];if(p!==null){const r=litPropertyMetadata.get(p);if(r!==void 0)for(const[l,h]of r)this.elementProperties.set(l,h)}this._$Eh=new Map;for(const[r,l]of this.elementProperties){const h=this._$Eu(r,l);h!==void 0&&this._$Eh.set(h,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(p){const r=[];if(Array.isArray(p)){const l=new Set(p.flat(1/0).reverse());for(const h of l)r.unshift(ht(h))}else p!==void 0&&r.push(ht(p));return r}static _$Eu(p,r){const l=r.attribute;return l===!1?void 0:typeof l=="string"?l:typeof p=="string"?p.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var p;this._$ES=new Promise(r=>this.enableUpdating=r),this._$AL=new Map,this._$E_(),this.requestUpdate(),(p=this.constructor.l)==null||p.forEach(r=>r(this))}addController(p){var r;(this._$EO??(this._$EO=new Set)).add(p),this.renderRoot!==void 0&&this.isConnected&&((r=p.hostConnected)==null||r.call(p))}removeController(p){var r;(r=this._$EO)==null||r.delete(p)}_$E_(){const p=new Map,r=this.constructor.elementProperties;for(const l of r.keys())this.hasOwnProperty(l)&&(p.set(l,this[l]),delete this[l]);p.size>0&&(this._$Ep=p)}createRenderRoot(){const p=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return In(p,this.constructor.elementStyles),p}connectedCallback(){var p;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(p=this._$EO)==null||p.forEach(r=>{var l;return(l=r.hostConnected)==null?void 0:l.call(r)})}enableUpdating(p){}disconnectedCallback(){var p;(p=this._$EO)==null||p.forEach(r=>{var l;return(l=r.hostDisconnected)==null?void 0:l.call(r)})}attributeChangedCallback(p,r,l){this._$AK(p,l)}_$EC(p,r){var b;const l=this.constructor.elementProperties.get(p),h=this.constructor._$Eu(p,l);if(h!==void 0&&l.reflect===!0){const S=(((b=l.converter)==null?void 0:b.toAttribute)!==void 0?l.converter:xe).toAttribute(r,l.type);this._$Em=p,S==null?this.removeAttribute(h):this.setAttribute(h,S),this._$Em=null}}_$AK(p,r){var b;const l=this.constructor,h=l._$Eh.get(p);if(h!==void 0&&this._$Em!==h){const S=l.getPropertyOptions(h),m=typeof S.converter=="function"?{fromAttribute:S.converter}:((b=S.converter)==null?void 0:b.fromAttribute)!==void 0?S.converter:xe;this._$Em=h,this[h]=m.fromAttribute(r,S.type),this._$Em=null}}requestUpdate(p,r,l){if(p!==void 0){if(l??(l=this.constructor.getPropertyOptions(p)),!(l.hasChanged??Qe)(this[p],r))return;this.P(p,r,l)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(p,r,l){this._$AL.has(p)||this._$AL.set(p,r),l.reflect===!0&&this._$Em!==p&&(this._$Ej??(this._$Ej=new Set)).add(p)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}const p=this.scheduleUpdate();return p!=null&&await p,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var l;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[b,S]of this._$Ep)this[b]=S;this._$Ep=void 0}const h=this.constructor.elementProperties;if(h.size>0)for(const[b,S]of h)S.wrapped!==!0||this._$AL.has(b)||this[b]===void 0||this.P(b,this[b],S)}let p=!1;const r=this._$AL;try{p=this.shouldUpdate(r),p?(this.willUpdate(r),(l=this._$EO)==null||l.forEach(h=>{var b;return(b=h.hostUpdate)==null?void 0:b.call(h)}),this.update(r)):this._$EU()}catch(h){throw p=!1,this._$EU(),h}p&&this._$AE(r)}willUpdate(p){}_$AE(p){var r;(r=this._$EO)==null||r.forEach(l=>{var h;return(h=l.hostUpdated)==null?void 0:h.call(l)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(p)),this.updated(p)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(p){return!0}update(p){this._$Ej&&(this._$Ej=this._$Ej.forEach(r=>this._$EC(r,this[r]))),this._$EU()}updated(p){}firstUpdated(p){}}Te.elementStyles=[],Te.shadowRootOptions={mode:"open"},Te[Ee("elementProperties")]=new Map,Te[Ee("finalized")]=new Map,Ke==null||Ke({ReactiveElement:Te}),(ue.reactiveElementVersions??(ue.reactiveElementVersions=[])).push("2.0.4");/**
|
|
14
|
+
* @license
|
|
15
|
+
* Copyright 2017 Google LLC
|
|
16
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
17
|
+
*/const Ln={attribute:!0,type:String,converter:xe,reflect:!1,hasChanged:Qe},jn=(w=Ln,p,r)=>{const{kind:l,metadata:h}=r;let b=globalThis.litPropertyMetadata.get(h);if(b===void 0&&globalThis.litPropertyMetadata.set(h,b=new Map),b.set(r.name,w),l==="accessor"){const{name:S}=r;return{set(m){const E=p.get.call(this);p.set.call(this,m),this.requestUpdate(S,E,w)},init(m){return m!==void 0&&this.P(S,void 0,w),m}}}if(l==="setter"){const{name:S}=r;return function(m){const E=this[S];p.call(this,m),this.requestUpdate(S,E,w)}}throw Error("Unsupported decorator location: "+l)};function Xe(w){return(p,r)=>typeof r=="object"?jn(w,p,r):((l,h,b)=>{const S=h.hasOwnProperty(b);return h.constructor.createProperty(b,S?{...l,wrapped:!0}:l),S?Object.getOwnPropertyDescriptor(h,b):void 0})(w,p,r)}/**
|
|
18
|
+
* @license
|
|
19
|
+
* Copyright 2017 Google LLC
|
|
20
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
21
|
+
*/function mt(w){return Xe({...w,state:!0,attribute:!1})}/**
|
|
22
|
+
* @license
|
|
23
|
+
* Copyright 2017 Google LLC
|
|
24
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
25
|
+
*/const Un=(w,p,r)=>(r.configurable=!0,r.enumerable=!0,Reflect.decorate&&typeof p!="object"&&Object.defineProperty(w,p,r),r);/**
|
|
26
|
+
* @license
|
|
27
|
+
* Copyright 2017 Google LLC
|
|
28
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
29
|
+
*/function _t(w,p){return(r,l,h)=>{const b=S=>{var m;return((m=S.renderRoot)==null?void 0:m.querySelector(w))??null};return Un(r,l,{get(){return b(this)}})}}const Nn=J.css`
|
|
30
|
+
.wrapper {
|
|
31
|
+
position: relative;
|
|
32
|
+
overflow: hidden;
|
|
33
|
+
aspect-ratio: 1 / 1;
|
|
34
|
+
border-radius: 50%;
|
|
35
|
+
max-width: 380px;
|
|
36
|
+
max-height: 380px;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
video {
|
|
40
|
+
object-fit: cover;
|
|
41
|
+
object-position: center;
|
|
42
|
+
width: 100%;
|
|
43
|
+
height: 100%;
|
|
44
|
+
display: block;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
.filter-light,
|
|
48
|
+
.filter-gradient,
|
|
49
|
+
.filter-overlay {
|
|
50
|
+
position: absolute;
|
|
51
|
+
inset: 0;
|
|
52
|
+
width: 100%;
|
|
53
|
+
height: 100%;
|
|
54
|
+
border-radius: 50%;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
.filter-light {
|
|
58
|
+
background: radial-gradient(circle, rgba(255, 255, 255, 0.3), transparent);
|
|
59
|
+
opacity: 0.4;
|
|
60
|
+
z-index: 10;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
.filter-gradient {
|
|
64
|
+
background: linear-gradient(to right, #63b3ed, #06b6d4, #2563eb);
|
|
65
|
+
background-size: 200% 200%;
|
|
66
|
+
animation: gradientAnimation 8s ease infinite;
|
|
67
|
+
mix-blend-mode: overlay;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
.filter-overlay {
|
|
71
|
+
background: linear-gradient(to right, #63b3ed, #06b6d4, #2563eb);
|
|
72
|
+
background-size: 200% 200%;
|
|
73
|
+
animation: gradientAnimation 8s ease infinite;
|
|
74
|
+
transition: opacity 0.5s;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
.filter-overlay[data-calling='true'] {
|
|
78
|
+
opacity: 0;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
.filter-overlay[data-calling='false'] {
|
|
82
|
+
opacity: 0.7;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
@keyframes gradientAnimation {
|
|
86
|
+
0% {
|
|
87
|
+
background-position: 0% 50%;
|
|
88
|
+
}
|
|
89
|
+
50% {
|
|
90
|
+
background-position: 100% 50%;
|
|
91
|
+
}
|
|
92
|
+
100% {
|
|
93
|
+
background-position: 0% 50%;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
.content-wrapper {
|
|
98
|
+
position: absolute;
|
|
99
|
+
inset: 0;
|
|
100
|
+
display: flex;
|
|
101
|
+
justify-content: center;
|
|
102
|
+
align-items: center;
|
|
103
|
+
z-index: 20;
|
|
104
|
+
padding: 1rem;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
.button {
|
|
108
|
+
font-weight: bold;
|
|
109
|
+
border-radius: 9999px;
|
|
110
|
+
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
|
|
111
|
+
0 4px 6px -4px rgba(0, 0, 0, 0.1);
|
|
112
|
+
transition: all 0.3s ease;
|
|
113
|
+
display: flex;
|
|
114
|
+
align-items: center;
|
|
115
|
+
gap: 1rem;
|
|
116
|
+
animation: pulse 2s infinite;
|
|
117
|
+
padding: 1rem 2rem;
|
|
118
|
+
font-size: 1.25rem;
|
|
119
|
+
border: none;
|
|
120
|
+
cursor: pointer;
|
|
121
|
+
background-color: #dc2626;
|
|
122
|
+
color: white;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
.button[data-calling='true'] {
|
|
126
|
+
background-color: black;
|
|
127
|
+
color: white;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
.button[data-calling='false']:hover {
|
|
131
|
+
background-color: #b91c1c;
|
|
132
|
+
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
.button[data-calling='true'] {
|
|
136
|
+
border-radius: 9999px;
|
|
137
|
+
display: flex;
|
|
138
|
+
align-items: center;
|
|
139
|
+
justify-content: center;
|
|
140
|
+
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
|
|
141
|
+
0 4px 6px -4px rgba(0, 0, 0, 0.1);
|
|
142
|
+
transition: all 0.3s ease;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
@keyframes pulse {
|
|
146
|
+
0% {
|
|
147
|
+
box-shadow: 0 0 #fff6;
|
|
148
|
+
}
|
|
149
|
+
70% {
|
|
150
|
+
box-shadow: 0 0 0 20px #fff0;
|
|
151
|
+
}
|
|
152
|
+
100% {
|
|
153
|
+
box-shadow: 0 0 #fff0;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
.icon-button {
|
|
158
|
+
background-color: rgba(255, 255, 255, 0.2);
|
|
159
|
+
border-radius: 9999px;
|
|
160
|
+
display: flex;
|
|
161
|
+
align-items: center;
|
|
162
|
+
justify-content: center;
|
|
163
|
+
padding: 0.75rem;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
.call-off-icon {
|
|
167
|
+
display: flex;
|
|
168
|
+
align-items: center;
|
|
169
|
+
justify-content: center;
|
|
170
|
+
}
|
|
171
|
+
`,yt=J.css`
|
|
172
|
+
* {
|
|
173
|
+
box-sizing: border-box;
|
|
174
|
+
margin: 0;
|
|
175
|
+
padding: 0;
|
|
176
|
+
border: 0;
|
|
177
|
+
}
|
|
178
|
+
`;var Ye=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ze={},le={},De={exports:{}},bt;function Z(){if(bt)return De.exports;bt=1;var w=typeof Reflect=="object"?Reflect:null,p=w&&typeof w.apply=="function"?w.apply:function(a,f,I){return Function.prototype.apply.call(a,f,I)},r;w&&typeof w.ownKeys=="function"?r=w.ownKeys:Object.getOwnPropertySymbols?r=function(a){return Object.getOwnPropertyNames(a).concat(Object.getOwnPropertySymbols(a))}:r=function(a){return Object.getOwnPropertyNames(a)};function l(c){console&&console.warn&&console.warn(c)}var h=Number.isNaN||function(a){return a!==a};function b(){b.init.call(this)}De.exports=b,De.exports.once=i,b.EventEmitter=b,b.prototype._events=void 0,b.prototype._eventsCount=0,b.prototype._maxListeners=void 0;var S=10;function m(c){if(typeof c!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof c)}Object.defineProperty(b,"defaultMaxListeners",{enumerable:!0,get:function(){return S},set:function(c){if(typeof c!="number"||c<0||h(c))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+c+".");S=c}}),b.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},b.prototype.setMaxListeners=function(a){if(typeof a!="number"||a<0||h(a))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+a+".");return this._maxListeners=a,this};function E(c){return c._maxListeners===void 0?b.defaultMaxListeners:c._maxListeners}b.prototype.getMaxListeners=function(){return E(this)},b.prototype.emit=function(a){for(var f=[],I=1;I<arguments.length;I++)f.push(arguments[I]);var v=a==="error",O=this._events;if(O!==void 0)v=v&&O.error===void 0;else if(!v)return!1;if(v){var T;if(f.length>0&&(T=f[0]),T instanceof Error)throw T;var R=new Error("Unhandled error."+(T?" ("+T.message+")":""));throw R.context=T,R}var P=O[a];if(P===void 0)return!1;if(typeof P=="function")p(P,this,f);else for(var A=P.length,d=t(P,A),I=0;I<A;++I)p(d[I],this,f);return!0};function C(c,a,f,I){var v,O,T;if(m(f),O=c._events,O===void 0?(O=c._events=Object.create(null),c._eventsCount=0):(O.newListener!==void 0&&(c.emit("newListener",a,f.listener?f.listener:f),O=c._events),T=O[a]),T===void 0)T=O[a]=f,++c._eventsCount;else if(typeof T=="function"?T=O[a]=I?[f,T]:[T,f]:I?T.unshift(f):T.push(f),v=E(c),v>0&&T.length>v&&!T.warned){T.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+T.length+" "+String(a)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=c,R.type=a,R.count=T.length,l(R)}return c}b.prototype.addListener=function(a,f){return C(this,a,f,!1)},b.prototype.on=b.prototype.addListener,b.prototype.prependListener=function(a,f){return C(this,a,f,!0)};function y(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _(c,a,f){var I={fired:!1,wrapFn:void 0,target:c,type:a,listener:f},v=y.bind(I);return v.listener=f,I.wrapFn=v,v}b.prototype.once=function(a,f){return m(f),this.on(a,_(this,a,f)),this},b.prototype.prependOnceListener=function(a,f){return m(f),this.prependListener(a,_(this,a,f)),this},b.prototype.removeListener=function(a,f){var I,v,O,T,R;if(m(f),v=this._events,v===void 0)return this;if(I=v[a],I===void 0)return this;if(I===f||I.listener===f)--this._eventsCount===0?this._events=Object.create(null):(delete v[a],v.removeListener&&this.emit("removeListener",a,I.listener||f));else if(typeof I!="function"){for(O=-1,T=I.length-1;T>=0;T--)if(I[T]===f||I[T].listener===f){R=I[T].listener,O=T;break}if(O<0)return this;O===0?I.shift():e(I,O),I.length===1&&(v[a]=I[0]),v.removeListener!==void 0&&this.emit("removeListener",a,R||f)}return this},b.prototype.off=b.prototype.removeListener,b.prototype.removeAllListeners=function(a){var f,I,v;if(I=this._events,I===void 0)return this;if(I.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):I[a]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete I[a]),this;if(arguments.length===0){var O=Object.keys(I),T;for(v=0;v<O.length;++v)T=O[v],T!=="removeListener"&&this.removeAllListeners(T);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(f=I[a],typeof f=="function")this.removeListener(a,f);else if(f!==void 0)for(v=f.length-1;v>=0;v--)this.removeListener(a,f[v]);return this};function s(c,a,f){var I=c._events;if(I===void 0)return[];var v=I[a];return v===void 0?[]:typeof v=="function"?f?[v.listener||v]:[v]:f?n(v):t(v,v.length)}b.prototype.listeners=function(a){return s(this,a,!0)},b.prototype.rawListeners=function(a){return s(this,a,!1)},b.listenerCount=function(c,a){return typeof c.listenerCount=="function"?c.listenerCount(a):g.call(c,a)},b.prototype.listenerCount=g;function g(c){var a=this._events;if(a!==void 0){var f=a[c];if(typeof f=="function")return 1;if(f!==void 0)return f.length}return 0}b.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]};function t(c,a){for(var f=new Array(a),I=0;I<a;++I)f[I]=c[I];return f}function e(c,a){for(;a+1<c.length;a++)c[a]=c[a+1];c.pop()}function n(c){for(var a=new Array(c.length),f=0;f<a.length;++f)a[f]=c[f].listener||c[f];return a}function i(c,a){return new Promise(function(f,I){function v(T){c.removeListener(a,O),I(T)}function O(){typeof c.removeListener=="function"&&c.removeListener("error",v),f([].slice.call(arguments))}u(c,a,O,{once:!0}),a!=="error"&&o(c,v,{once:!0})})}function o(c,a,f){typeof c.on=="function"&&u(c,"error",a,f)}function u(c,a,f,I){if(typeof c.on=="function")I.once?c.once(a,f):c.on(a,f);else if(typeof c.addEventListener=="function")c.addEventListener(a,function v(O){I.once&&c.removeEventListener(a,v),f(O)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof c)}return De.exports}var ge={},St;function Ct(){if(St)return ge;St=1;var w=ge&&ge.__extends||function(){var l=function(h,b){return l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(S,m){S.__proto__=m}||function(S,m){for(var E in m)Object.prototype.hasOwnProperty.call(m,E)&&(S[E]=m[E])},l(h,b)};return function(h,b){l(h,b);function S(){this.constructor=h}h.prototype=b===null?Object.create(b):(S.prototype=b.prototype,new S)}}();Object.defineProperty(ge,"__esModule",{value:!0});var p=Z(),r=function(l){w(h,l);function h(b){var S=l.call(this)||this;return Object.defineProperties(S,{_attempts:{value:0,writable:!0},_duration:{enumerable:!1,get:function(){var m=this._min*Math.pow(this._factor,this._attempts);if(this._jitter){var E=Math.random(),C=Math.floor(E*this._jitter*m);m=(Math.floor(E*10)&1)===0?m-C:m+C}return Math.min(m,this._max)|0}},_factor:{value:b.factor||2},_jitter:{value:b.jitter>0&&b.jitter<=1?b.jitter:0},_max:{value:b.max||1e4},_min:{value:b.min||100},_timeoutID:{value:null,writable:!0}}),S}return h.prototype.backoff=function(){var b=this,S=this._duration;this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null),this.emit("backoff",this._attempts,S),this._timeoutID=setTimeout(function(){b.emit("ready",b._attempts,S),b._attempts++},S)},h.prototype.reset=function(){this._attempts=0,this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null)},h}(p.EventEmitter);return ge.default=r,ge}var Q={},Oe={exports:{}},Fn=Oe.exports,wt;function Et(){return wt||(wt=1,function(w){(function(p,r){w.exports?w.exports=r():p.log=r()})(Fn,function(){var p=function(){},r="undefined",l=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),h=["trace","debug","info","warn","error"];function b(e,n){var i=e[n];if(typeof i.bind=="function")return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch{return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function S(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function m(e){return e==="debug"&&(e="log"),typeof console===r?!1:e==="trace"&&l?S:console[e]!==void 0?b(console,e):console.log!==void 0?b(console,"log"):p}function E(e,n){for(var i=0;i<h.length;i++){var o=h[i];this[o]=i<e?p:this.methodFactory(o,e,n)}this.log=this.debug}function C(e,n,i){return function(){typeof console!==r&&(E.call(this,n,i),this[e].apply(this,arguments))}}function y(e,n,i){return m(e)||C.apply(this,arguments)}function _(e,n,i){var o=this,u,c="loglevel";e&&(c+=":"+e);function a(v){var O=(h[v]||"silent").toUpperCase();if(typeof window!==r){try{window.localStorage[c]=O;return}catch{}try{window.document.cookie=encodeURIComponent(c)+"="+O+";"}catch{}}}function f(){var v;if(typeof window!==r){try{v=window.localStorage[c]}catch{}if(typeof v===r)try{var O=window.document.cookie,T=O.indexOf(encodeURIComponent(c)+"=");T!==-1&&(v=/^([^;]+)/.exec(O.slice(T))[1])}catch{}return o.levels[v]===void 0&&(v=void 0),v}}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=i||y,o.getLevel=function(){return u},o.setLevel=function(v,O){if(typeof v=="string"&&o.levels[v.toUpperCase()]!==void 0&&(v=o.levels[v.toUpperCase()]),typeof v=="number"&&v>=0&&v<=o.levels.SILENT){if(u=v,O!==!1&&a(v),E.call(o,v,e),typeof console===r&&v<o.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+v},o.setDefaultLevel=function(v){f()||o.setLevel(v,!1)},o.enableAll=function(v){o.setLevel(o.levels.TRACE,v)},o.disableAll=function(v){o.setLevel(o.levels.SILENT,v)};var I=f();I==null&&(I=n??"WARN"),o.setLevel(I,!1)}var s=new _,g={};s.getLogger=function(n){if(typeof n!="string"||n==="")throw new TypeError("You must supply a name when creating a logger.");var i=g[n];return i||(i=g[n]=new _(n,s.getLevel(),s.methodFactory)),i};var t=typeof window!==r?window.log:void 0;return s.noConflict=function(){return typeof window!==r&&window.log===s&&(window.log=t),s},s.getLoggers=function(){return g},s})}(Oe)),Oe.exports}var ne={},Pe={},Ie={},me={},Tt;function qn(){if(Tt)return me;Tt=1;var w=me&&me.__extends||function(){var r=function(l,h){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,S){b.__proto__=S}||function(b,S){for(var m in S)Object.prototype.hasOwnProperty.call(S,m)&&(b[m]=S[m])},r(l,h)};return function(l,h){r(l,h);function b(){this.constructor=l}l.prototype=h===null?Object.create(h):(b.prototype=h.prototype,new b)}}();Object.defineProperty(me,"__esModule",{value:!0});var p=function(r){w(l,r);function l(h,b){var S=r.call(this)||this;Object.setPrototypeOf(S,l.prototype);var m=typeof h=="string"?h:S.explanation,E=typeof h=="object"?h:b;return S.message=S.name+" ("+S.code+"): "+m,S.originalError=E,S}return l}(Error);return me.default=p,me}var Pt;function Bn(){return Pt||(Pt=1,function(w){var p=Ie&&Ie.__extends||function(){var s=function(g,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])},s(g,t)};return function(g,t){s(g,t);function e(){this.constructor=g}g.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}}();Object.defineProperty(w,"__esModule",{value:!0}),w.errorsByCode=w.MediaErrors=w.SignalingErrors=w.UserMediaErrors=w.MalformedRequestErrors=w.GeneralErrors=w.SIPServerErrors=w.ClientErrors=w.SignatureValidationErrors=w.AuthorizationErrors=w.TwilioError=void 0;var r=qn();w.TwilioError=r.default;var l;(function(s){var g=function(n){p(i,n);function i(o,u){var c=n.call(this,o,u)||this;c.causes=[],c.code=20101,c.description="Invalid access token",c.explanation="Twilio was unable to validate your Access Token",c.name="AccessTokenInvalid",c.solutions=[],Object.setPrototypeOf(c,s.AccessTokenInvalid.prototype);var a=typeof o=="string"?o:c.explanation,f=typeof o=="object"?o:u;return c.message=c.name+" ("+c.code+"): "+a,c.originalError=f,c}return i}(r.default);s.AccessTokenInvalid=g;var t=function(n){p(i,n);function i(o,u){var c=n.call(this,o,u)||this;c.causes=[],c.code=20104,c.description="Access token expired or expiration date invalid",c.explanation="The Access Token provided to the Twilio API has expired, the expiration time specified in the token was invalid, or the expiration time specified was too far in the future",c.name="AccessTokenExpired",c.solutions=[],Object.setPrototypeOf(c,s.AccessTokenExpired.prototype);var a=typeof o=="string"?o:c.explanation,f=typeof o=="object"?o:u;return c.message=c.name+" ("+c.code+"): "+a,c.originalError=f,c}return i}(r.default);s.AccessTokenExpired=t;var e=function(n){p(i,n);function i(o,u){var c=n.call(this,o,u)||this;c.causes=[],c.code=20151,c.description="Authentication Failed",c.explanation="The Authentication with the provided JWT failed",c.name="AuthenticationFailed",c.solutions=[],Object.setPrototypeOf(c,s.AuthenticationFailed.prototype);var a=typeof o=="string"?o:c.explanation,f=typeof o=="object"?o:u;return c.message=c.name+" ("+c.code+"): "+a,c.originalError=f,c}return i}(r.default);s.AuthenticationFailed=e})(l=w.AuthorizationErrors||(w.AuthorizationErrors={}));var h;(function(s){var g=function(t){p(e,t);function e(n,i){var o=t.call(this,n,i)||this;o.causes=["The access token has an invalid Account SID, API Key, or API Key Secret."],o.code=31202,o.description="Signature validation failed.",o.explanation="The provided access token failed signature validation.",o.name="AccessTokenSignatureValidationFailed",o.solutions=["Ensure the Account SID, API Key, and API Key Secret are valid when generating your access token."],Object.setPrototypeOf(o,s.AccessTokenSignatureValidationFailed.prototype);var u=typeof n=="string"?n:o.explanation,c=typeof n=="object"?n:i;return o.message=o.name+" ("+o.code+"): "+u,o.originalError=c,o}return e}(r.default);s.AccessTokenSignatureValidationFailed=g})(h=w.SignatureValidationErrors||(w.SignatureValidationErrors={}));var b;(function(s){var g=function(i){p(o,i);function o(u,c){var a=i.call(this,u,c)||this;a.causes=[],a.code=31400,a.description="Bad Request (HTTP/SIP)",a.explanation="The request could not be understood due to malformed syntax.",a.name="BadRequest",a.solutions=[],Object.setPrototypeOf(a,s.BadRequest.prototype);var f=typeof u=="string"?u:a.explanation,I=typeof u=="object"?u:c;return a.message=a.name+" ("+a.code+"): "+f,a.originalError=I,a}return o}(r.default);s.BadRequest=g;var t=function(i){p(o,i);function o(u,c){var a=i.call(this,u,c)||this;a.causes=["The outbound call was made to an invalid phone number.","The TwiML application sid is missing a Voice URL."],a.code=31404,a.description="Not Found (HTTP/SIP)",a.explanation="The server has not found anything matching the request.",a.name="NotFound",a.solutions=["Ensure the phone number dialed is valid.","Ensure the TwiML application is configured correctly with a Voice URL link."],Object.setPrototypeOf(a,s.NotFound.prototype);var f=typeof u=="string"?u:a.explanation,I=typeof u=="object"?u:c;return a.message=a.name+" ("+a.code+"): "+f,a.originalError=I,a}return o}(r.default);s.NotFound=t;var e=function(i){p(o,i);function o(u,c){var a=i.call(this,u,c)||this;a.causes=[],a.code=31480,a.description="Temporarily Unavailable (SIP)",a.explanation="The callee is currently unavailable.",a.name="TemporarilyUnavailable",a.solutions=[],Object.setPrototypeOf(a,s.TemporarilyUnavailable.prototype);var f=typeof u=="string"?u:a.explanation,I=typeof u=="object"?u:c;return a.message=a.name+" ("+a.code+"): "+f,a.originalError=I,a}return o}(r.default);s.TemporarilyUnavailable=e;var n=function(i){p(o,i);function o(u,c){var a=i.call(this,u,c)||this;a.causes=[],a.code=31486,a.description="Busy Here (SIP)",a.explanation="The callee is busy.",a.name="BusyHere",a.solutions=[],Object.setPrototypeOf(a,s.BusyHere.prototype);var f=typeof u=="string"?u:a.explanation,I=typeof u=="object"?u:c;return a.message=a.name+" ("+a.code+"): "+f,a.originalError=I,a}return o}(r.default);s.BusyHere=n})(b=w.ClientErrors||(w.ClientErrors={}));var S;(function(s){var g=function(t){p(e,t);function e(n,i){var o=t.call(this,n,i)||this;o.causes=[],o.code=31603,o.description="Decline (SIP)",o.explanation="The callee does not wish to participate in the call.",o.name="Decline",o.solutions=[],Object.setPrototypeOf(o,s.Decline.prototype);var u=typeof n=="string"?n:o.explanation,c=typeof n=="object"?n:i;return o.message=o.name+" ("+o.code+"): "+u,o.originalError=c,o}return e}(r.default);s.Decline=g})(S=w.SIPServerErrors||(w.SIPServerErrors={}));var m;(function(s){var g=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31e3,v.description="Unknown Error",v.explanation="An unknown error has occurred. See error details for more information.",v.name="UnknownError",v.solutions=[],Object.setPrototypeOf(v,s.UnknownError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.UnknownError=g;var t=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31001,v.description="Application Not Found",v.explanation="",v.name="ApplicationNotFoundError",v.solutions=[],Object.setPrototypeOf(v,s.ApplicationNotFoundError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.ApplicationNotFoundError=t;var e=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31002,v.description="Connection Declined",v.explanation="",v.name="ConnectionDeclinedError",v.solutions=[],Object.setPrototypeOf(v,s.ConnectionDeclinedError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.ConnectionDeclinedError=e;var n=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31003,v.description="Connection Timeout",v.explanation="The server could not produce a response within a suitable amount of time.",v.name="ConnectionTimeoutError",v.solutions=[],Object.setPrototypeOf(v,s.ConnectionTimeoutError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.ConnectionTimeoutError=n;var i=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31005,v.description="Connection error",v.explanation="A connection error occurred during the call",v.name="ConnectionError",v.solutions=[],Object.setPrototypeOf(v,s.ConnectionError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.ConnectionError=i;var o=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=["The incoming call was cancelled because it was not answered in time or it was accepted/rejected by another application instance registered with the same identity."],v.code=31008,v.description="Call cancelled",v.explanation="Unable to answer because the call has ended",v.name="CallCancelledError",v.solutions=[],Object.setPrototypeOf(v,s.CallCancelledError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.CallCancelledError=o;var u=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31009,v.description="Transport error",v.explanation="No transport available to send or receive messages",v.name="TransportError",v.solutions=[],Object.setPrototypeOf(v,s.TransportError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.TransportError=u})(m=w.GeneralErrors||(w.GeneralErrors={}));var E;(function(s){var g=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=["Invalid content or MessageType passed to sendMessage method."],v.code=31100,v.description="The request had malformed syntax.",v.explanation="The request could not be understood due to malformed syntax.",v.name="MalformedRequestError",v.solutions=["Ensure content and MessageType passed to sendMessage method are valid."],Object.setPrototypeOf(v,s.MalformedRequestError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.MalformedRequestError=g;var t=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31101,v.description="Missing parameter array in request",v.explanation="",v.name="MissingParameterArrayError",v.solutions=[],Object.setPrototypeOf(v,s.MissingParameterArrayError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.MissingParameterArrayError=t;var e=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31102,v.description="Authorization token missing in request.",v.explanation="",v.name="AuthorizationTokenMissingError",v.solutions=[],Object.setPrototypeOf(v,s.AuthorizationTokenMissingError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.AuthorizationTokenMissingError=e;var n=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31103,v.description="Maximum parameter length has been exceeded.",v.explanation="Length of parameters cannot exceed MAX_PARAM_LENGTH.",v.name="MaxParameterLengthExceededError",v.solutions=[],Object.setPrototypeOf(v,s.MaxParameterLengthExceededError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.MaxParameterLengthExceededError=n;var i=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31104,v.description="Invalid bridge token",v.explanation="",v.name="InvalidBridgeTokenError",v.solutions=[],Object.setPrototypeOf(v,s.InvalidBridgeTokenError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.InvalidBridgeTokenError=i;var o=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=["Client name contains invalid characters."],v.code=31105,v.description="Invalid client name",v.explanation="Client name should not contain control, space, delims, or unwise characters.",v.name="InvalidClientNameError",v.solutions=["Make sure that client name does not contain any of the invalid characters."],Object.setPrototypeOf(v,s.InvalidClientNameError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.InvalidClientNameError=o;var u=function(c){p(a,c);function a(f,I){var v=c.call(this,f,I)||this;v.causes=[],v.code=31107,v.description="The reconnect parameter is invalid",v.explanation="",v.name="ReconnectParameterInvalidError",v.solutions=[],Object.setPrototypeOf(v,s.ReconnectParameterInvalidError.prototype);var O=typeof f=="string"?f:v.explanation,T=typeof f=="object"?f:I;return v.message=v.name+" ("+v.code+"): "+O,v.originalError=T,v}return a}(r.default);s.ReconnectParameterInvalidError=u})(E=w.MalformedRequestErrors||(w.MalformedRequestErrors={})),function(s){var g=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=[],T.code=31201,T.description="Authorization error",T.explanation="The request requires user authentication. The server understood the request, but is refusing to fulfill it.",T.name="AuthorizationError",T.solutions=[],Object.setPrototypeOf(T,s.AuthorizationError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.AuthorizationError=g;var t=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=[],T.code=31203,T.description="No valid account",T.explanation="",T.name="NoValidAccountError",T.solutions=[],Object.setPrototypeOf(T,s.NoValidAccountError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.NoValidAccountError=t;var e=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=[],T.code=31204,T.description="Invalid JWT token",T.explanation="",T.name="InvalidJWTTokenError",T.solutions=[],Object.setPrototypeOf(T,s.InvalidJWTTokenError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.InvalidJWTTokenError=e;var n=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=[],T.code=31205,T.description="JWT token expired",T.explanation="",T.name="JWTTokenExpiredError",T.solutions=[],Object.setPrototypeOf(T,s.JWTTokenExpiredError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.JWTTokenExpiredError=n;var i=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=["Rate limit exceeded."],T.code=31206,T.description="Rate exceeded authorized limit.",T.explanation="The request performed exceeds the authorized limit.",T.name="RateExceededError",T.solutions=["Ensure message send rate does not exceed authorized limits."],Object.setPrototypeOf(T,s.RateExceededError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.RateExceededError=i;var o=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=[],T.code=31207,T.description="JWT token expiration too long",T.explanation="",T.name="JWTTokenExpirationTooLongError",T.solutions=[],Object.setPrototypeOf(T,s.JWTTokenExpirationTooLongError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.JWTTokenExpirationTooLongError=o;var u=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=[],T.code=31209,T.description="Reconnect attempt is not authorized.",T.explanation="",T.name="ReconnectAttemptError",T.solutions=[],Object.setPrototypeOf(T,s.ReconnectAttemptError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.ReconnectAttemptError=u;var c=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=["The Call Message Event Type is invalid and is not understood by Twilio Voice."],T.code=31210,T.description="Call Message Event Type is invalid.",T.explanation="The Call Message Event Type is invalid and is not understood by Twilio Voice.",T.name="CallMessageEventTypeInvalidError",T.solutions=["Ensure the Call Message Event Type is Valid and understood by Twilio Voice and try again."],Object.setPrototypeOf(T,s.CallMessageEventTypeInvalidError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.CallMessageEventTypeInvalidError=c;var a=function(f){p(I,f);function I(v,O){var T=f.call(this,v,O)||this;T.causes=["The payload size of Call Message Event exceeds the authorized limit."],T.code=31212,T.description="Call Message Event Payload size exceeded authorized limit.",T.explanation="The request performed to send a Call Message Event exceeds the payload size authorized limit",T.name="PayloadSizeExceededError",T.solutions=["Reduce payload size of Call Message Event to be within the authorized limit and try again."],Object.setPrototypeOf(T,s.PayloadSizeExceededError.prototype);var R=typeof v=="string"?v:T.explanation,P=typeof v=="object"?v:O;return T.message=T.name+" ("+T.code+"): "+R,T.originalError=P,T}return I}(r.default);s.PayloadSizeExceededError=a}(l=w.AuthorizationErrors||(w.AuthorizationErrors={}));var C;(function(s){var g=function(e){p(n,e);function n(i,o){var u=e.call(this,i,o)||this;u.causes=["The user denied the getUserMedia request.","The browser denied the getUserMedia request."],u.code=31401,u.description="UserMedia Permission Denied Error",u.explanation="The browser or end-user denied permissions to user media. Therefore we were unable to acquire input audio.",u.name="PermissionDeniedError",u.solutions=["The user should accept the request next time prompted. If the browser saved the deny, the user should change that permission in their browser.","The user should to verify that the browser has permission to access the microphone at this address."],Object.setPrototypeOf(u,s.PermissionDeniedError.prototype);var c=typeof i=="string"?i:u.explanation,a=typeof i=="object"?i:o;return u.message=u.name+" ("+u.code+"): "+c,u.originalError=a,u}return n}(r.default);s.PermissionDeniedError=g;var t=function(e){p(n,e);function n(i,o){var u=e.call(this,i,o)||this;u.causes=["NotFoundError - The deviceID specified was not found.","The getUserMedia constraints were overconstrained and no devices matched."],u.code=31402,u.description="UserMedia Acquisition Failed Error",u.explanation="The browser and end-user allowed permissions, however getting the media failed. Usually this is due to bad constraints, but can sometimes fail due to browser, OS or hardware issues.",u.name="AcquisitionFailedError",u.solutions=["Ensure the deviceID being specified exists.","Try acquiring media with fewer constraints."],Object.setPrototypeOf(u,s.AcquisitionFailedError.prototype);var c=typeof i=="string"?i:u.explanation,a=typeof i=="object"?i:o;return u.message=u.name+" ("+u.code+"): "+c,u.originalError=a,u}return n}(r.default);s.AcquisitionFailedError=t})(C=w.UserMediaErrors||(w.UserMediaErrors={}));var y;(function(s){var g=function(e){p(n,e);function n(i,o){var u=e.call(this,i,o)||this;u.causes=[],u.code=53e3,u.description="Signaling connection error",u.explanation="Raised whenever a signaling connection error occurs that is not covered by a more specific error code.",u.name="ConnectionError",u.solutions=[],Object.setPrototypeOf(u,s.ConnectionError.prototype);var c=typeof i=="string"?i:u.explanation,a=typeof i=="object"?i:o;return u.message=u.name+" ("+u.code+"): "+c,u.originalError=a,u}return n}(r.default);s.ConnectionError=g;var t=function(e){p(n,e);function n(i,o){var u=e.call(this,i,o)||this;u.causes=["The device running your application lost its Internet connection."],u.code=53001,u.description="Signaling connection disconnected",u.explanation="Raised whenever the signaling connection is unexpectedly disconnected.",u.name="ConnectionDisconnected",u.solutions=["Ensure the device running your application has access to a stable Internet connection."],Object.setPrototypeOf(u,s.ConnectionDisconnected.prototype);var c=typeof i=="string"?i:u.explanation,a=typeof i=="object"?i:o;return u.message=u.name+" ("+u.code+"): "+c,u.originalError=a,u}return n}(r.default);s.ConnectionDisconnected=t})(y=w.SignalingErrors||(w.SignalingErrors={}));var _;(function(s){var g=function(n){p(i,n);function i(o,u){var c=n.call(this,o,u)||this;c.causes=["The Client may not be using a supported WebRTC implementation.","The Client may not have the necessary resources to create or apply a new media description."],c.code=53400,c.description="Client is unable to create or apply a local media description",c.explanation="Raised whenever a Client is unable to create or apply a local media description.",c.name="ClientLocalDescFailed",c.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(c,s.ClientLocalDescFailed.prototype);var a=typeof o=="string"?o:c.explanation,f=typeof o=="object"?o:u;return c.message=c.name+" ("+c.code+"): "+a,c.originalError=f,c}return i}(r.default);s.ClientLocalDescFailed=g;var t=function(n){p(i,n);function i(o,u){var c=n.call(this,o,u)||this;c.causes=["The Client may not be using a supported WebRTC implementation.","The Client may be connecting peer-to-peer with another Participant that is not using a supported WebRTC implementation.","The Client may not have the necessary resources to apply a new media description."],c.code=53402,c.description="Client is unable to apply a remote media description",c.explanation="Raised whenever the Client receives a remote media description but is unable to apply it.",c.name="ClientRemoteDescFailed",c.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(c,s.ClientRemoteDescFailed.prototype);var a=typeof o=="string"?o:c.explanation,f=typeof o=="object"?o:u;return c.message=c.name+" ("+c.code+"): "+a,c.originalError=f,c}return i}(r.default);s.ClientRemoteDescFailed=t;var e=function(n){p(i,n);function i(o,u){var c=n.call(this,o,u)||this;c.causes=["The Client was unable to establish a media connection.","A media connection which was active failed liveliness checks."],c.code=53405,c.description="Media connection failed",c.explanation="Raised by the Client or Server whenever a media connection fails.",c.name="ConnectionError",c.solutions=["If the problem persists, try connecting to another region.","Check your Client's network connectivity.","If you've provided custom ICE Servers then ensure that the URLs and credentials are valid."],Object.setPrototypeOf(c,s.ConnectionError.prototype);var a=typeof o=="string"?o:c.explanation,f=typeof o=="object"?o:u;return c.message=c.name+" ("+c.code+"): "+a,c.originalError=f,c}return i}(r.default);s.ConnectionError=e})(_=w.MediaErrors||(w.MediaErrors={})),w.errorsByCode=new Map([[20101,l.AccessTokenInvalid],[20104,l.AccessTokenExpired],[20151,l.AuthenticationFailed],[31202,h.AccessTokenSignatureValidationFailed],[31400,b.BadRequest],[31404,b.NotFound],[31480,b.TemporarilyUnavailable],[31486,b.BusyHere],[31603,S.Decline],[31e3,m.UnknownError],[31001,m.ApplicationNotFoundError],[31002,m.ConnectionDeclinedError],[31003,m.ConnectionTimeoutError],[31005,m.ConnectionError],[31008,m.CallCancelledError],[31009,m.TransportError],[31100,E.MalformedRequestError],[31101,E.MissingParameterArrayError],[31102,E.AuthorizationTokenMissingError],[31103,E.MaxParameterLengthExceededError],[31104,E.InvalidBridgeTokenError],[31105,E.InvalidClientNameError],[31107,E.ReconnectParameterInvalidError],[31201,l.AuthorizationError],[31203,l.NoValidAccountError],[31204,l.InvalidJWTTokenError],[31205,l.JWTTokenExpiredError],[31206,l.RateExceededError],[31207,l.JWTTokenExpirationTooLongError],[31209,l.ReconnectAttemptError],[31210,l.CallMessageEventTypeInvalidError],[31212,l.PayloadSizeExceededError],[31401,C.PermissionDeniedError],[31402,C.AcquisitionFailedError],[53e3,y.ConnectionError],[53001,y.ConnectionDisconnected],[53400,_.ClientLocalDescFailed],[53402,_.ClientRemoteDescFailed],[53405,_.ConnectionError]]),Object.freeze(w.errorsByCode)}(Ie)),Ie}var It;function $(){return It||(It=1,function(w){var p=Pe&&Pe.__extends||function(){var y=function(_,s){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,t){g.__proto__=t}||function(g,t){for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&(g[e]=t[e])},y(_,s)};return function(_,s){y(_,s);function g(){this.constructor=_}_.prototype=s===null?Object.create(s):(g.prototype=s.prototype,new g)}}();Object.defineProperty(w,"__esModule",{value:!0}),w.UserMediaErrors=w.TwilioError=w.SIPServerErrors=w.SignatureValidationErrors=w.SignalingErrors=w.MediaErrors=w.MalformedRequestErrors=w.GeneralErrors=w.ClientErrors=w.AuthorizationErrors=w.hasErrorByCode=w.getErrorByCode=w.NotSupportedError=w.InvalidStateError=w.InvalidArgumentError=w.getPreciseSignalingErrorByCode=void 0;var r=Bn();Object.defineProperty(w,"AuthorizationErrors",{enumerable:!0,get:function(){return r.AuthorizationErrors}}),Object.defineProperty(w,"ClientErrors",{enumerable:!0,get:function(){return r.ClientErrors}}),Object.defineProperty(w,"GeneralErrors",{enumerable:!0,get:function(){return r.GeneralErrors}}),Object.defineProperty(w,"MalformedRequestErrors",{enumerable:!0,get:function(){return r.MalformedRequestErrors}}),Object.defineProperty(w,"MediaErrors",{enumerable:!0,get:function(){return r.MediaErrors}}),Object.defineProperty(w,"SignalingErrors",{enumerable:!0,get:function(){return r.SignalingErrors}}),Object.defineProperty(w,"SignatureValidationErrors",{enumerable:!0,get:function(){return r.SignatureValidationErrors}}),Object.defineProperty(w,"SIPServerErrors",{enumerable:!0,get:function(){return r.SIPServerErrors}}),Object.defineProperty(w,"TwilioError",{enumerable:!0,get:function(){return r.TwilioError}}),Object.defineProperty(w,"UserMediaErrors",{enumerable:!0,get:function(){return r.UserMediaErrors}});var l=new Set([31001,31002,31003,31101,31102,31103,31104,31105,31107,31201,31202,31203,31204,31205,31207,31404,31480,31486,31603]);function h(y,_){if(typeof _=="number"&&C(_)){var s=y?!0:!l.has(_);if(s)return E(_)}}w.getPreciseSignalingErrorByCode=h;var b=function(y){p(_,y);function _(s){var g=y.call(this,s)||this;return g.name="InvalidArgumentError",g}return _}(Error);w.InvalidArgumentError=b;var S=function(y){p(_,y);function _(s){var g=y.call(this,s)||this;return g.name="InvalidStateError",g}return _}(Error);w.InvalidStateError=S;var m=function(y){p(_,y);function _(s){var g=y.call(this,s)||this;return g.name="NotSupportedError",g}return _}(Error);w.NotSupportedError=m;function E(y){var _=r.errorsByCode.get(y);if(!_)throw new b("Error code "+y+" not found");return _}w.getErrorByCode=E;function C(y){return r.errorsByCode.has(y)}w.hasErrorByCode=C}(Pe)),Pe}var de={},K={},kt;function _e(){if(kt)return K;kt=1,Object.defineProperty(K,"__esModule",{value:!0}),K.SOUNDS_BASE_URL=K.RELEASE_VERSION=K.PACKAGE_NAME=K.ECHO_TEST_DURATION=K.COWBELL_AUDIO_URL=void 0;var w="@twilio/voice-sdk";K.PACKAGE_NAME=w;var p="2.13.0";K.RELEASE_VERSION=p;var r="https://sdk.twilio.com/js/client/sounds/releases/1.0.0";K.SOUNDS_BASE_URL=r;var l=r+"/cowbell.mp3?cache="+p;K.COWBELL_AUDIO_URL=l;var h=2e4;return K.ECHO_TEST_DURATION=h,K}var Rt;function X(){if(Rt)return de;Rt=1;var w=de&&de.__spreadArrays||function(){for(var h=0,b=0,S=arguments.length;b<S;b++)h+=arguments[b].length;for(var m=Array(h),E=0,b=0;b<S;b++)for(var C=arguments[b],y=0,_=C.length;y<_;y++,E++)m[E]=C[y];return m};Object.defineProperty(de,"__esModule",{value:!0}),de.Logger=void 0;var p=Et(),r=_e(),l=function(){function h(b,S){this._log=h.getLogLevelInstance(S),this._prefix="[TwilioVoice]["+b+"]"}return h.getLogLevelInstance=function(b){if(!h.loglevelInstance)try{h.loglevelInstance=(b&&b.LogLevelModule?b.LogLevelModule:p).getLogger(r.PACKAGE_NAME)}catch{console.warn("Cannot create custom logger"),h.loglevelInstance=console}return h.loglevelInstance},h.prototype.debug=function(){for(var b,S=[],m=0;m<arguments.length;m++)S[m]=arguments[m];(b=this._log).debug.apply(b,w([this._prefix],S))},h.prototype.error=function(){for(var b,S=[],m=0;m<arguments.length;m++)S[m]=arguments[m];(b=this._log).error.apply(b,w([this._prefix],S))},h.prototype.info=function(){for(var b,S=[],m=0;m<arguments.length;m++)S[m]=arguments[m];(b=this._log).info.apply(b,w([this._prefix],S))},h.prototype.setDefaultLevel=function(b){this._log.setDefaultLevel?this._log.setDefaultLevel(b):console.warn("Logger cannot setDefaultLevel")},h.prototype.warn=function(){for(var b,S=[],m=0;m<arguments.length;m++)S[m]=arguments[m];(b=this._log).warn.apply(b,w([this._prefix],S))},h.levels=p.levels,h}();return de.Logger=l.getLogLevelInstance(),de.default=l,de}var Me={},At;function Wn(){if(At)return Me;At=1,Object.defineProperty(Me,"__esModule",{value:!0});var w=_e(),p=$(),r=X(),l=w.SOUNDS_BASE_URL+"/outgoing.mp3",h=function(){function b(S,m,E,C){this._name=S,this._availableDevices=m,this._beforeChange=E,this._isSupported=C,this._activeDevices=new Set,this._log=new r.default("OutputDeviceCollection")}return b.prototype.delete=function(S){this._log.debug(".delete",S);var m=!!this._activeDevices.delete(S),E=this._availableDevices.get("default")||Array.from(this._availableDevices.values())[0];!this._activeDevices.size&&E&&this._activeDevices.add(E);var C=Array.from(this._activeDevices.values()).map(function(y){return y.deviceId});return this._beforeChange(this._name,C),!!m},b.prototype.get=function(){return this._activeDevices},b.prototype.set=function(S){var m=this;if(this._log.debug(".set",S),!this._isSupported)return Promise.reject(new p.NotSupportedError("This browser does not support audio output selection"));var E=Array.isArray(S)?S:[S];if(!E.length)return Promise.reject(new p.InvalidArgumentError("Must specify at least one device to set"));var C=[],y=E.map(function(_){var s=m._availableDevices.get(_);return s||C.push(_),s});return C.length?Promise.reject(new p.InvalidArgumentError("Devices not found: "+C.join(", "))):new Promise(function(_){_(m._beforeChange(m._name,E))}).then(function(){m._activeDevices.clear(),y.forEach(m._activeDevices.add,m._activeDevices)})},b.prototype.test=function(S){return S===void 0&&(S=l),this._isSupported?this._activeDevices.size?Promise.all(Array.from(this._activeDevices).map(function(m){var E;return new Promise(function(C){E=new Audio(S),E.oncanplay=C}).then(function(){return E.setSinkId(m.deviceId).then(function(){return E.play()})})})):Promise.reject(new p.InvalidStateError("No active output devices to test")):Promise.reject(new p.NotSupportedError("This browser does not support audio output selection"))},b}();return Me.default=h,Me}var Le={},xt;function Vn(){if(xt)return Le;xt=1,Object.defineProperty(Le,"__esModule",{value:!0});var w=function(){function p(r){Object.defineProperties(this,{deviceId:{get:function(){return r.deviceId}},groupId:{get:function(){return r.groupId}},kind:{get:function(){return r.kind}},label:{get:function(){return r.label}}})}return p}();return Le.default=w,Le}var V={},Dt;function fe(){if(Dt)return V;Dt=1,Object.defineProperty(V,"__esModule",{value:!0}),V.promisifyEvents=V.flatMap=V.queryToJson=V.isUnifiedPlanDefault=V.isSafari=V.isLegacyEdge=V.isFirefox=V.isChrome=V.isElectron=V.difference=V.average=V.Exception=void 0;function w(g){if(!(this instanceof w))return new w(g);this.message=g}w.prototype.toString=function(){return"Twilio.Exception: "+this.message};function p(g){return g&&g.length?g.reduce(function(t,e){return t+e})/g.length:0}V.average=p;function r(g,t,e){e=e||function(i){return i};var n=new Set(t.map(e));return g.filter(function(i){return!n.has(e(i))})}V.difference=r;function l(g){return!!g.userAgent.match("Electron")}V.isElectron=l;function h(g,t){var e=!!t.userAgent.match("CriOS"),n=!!t.userAgent.match("HeadlessChrome"),i=typeof g.chrome<"u"&&t.vendor==="Google Inc."&&t.userAgent.indexOf("OPR")===-1&&t.userAgent.indexOf("Edge")===-1;return e||l(t)||i||n}V.isChrome=h;function b(g){return g=g||(typeof window>"u"?Ye.navigator:window.navigator),!!g&&typeof g.userAgent=="string"&&/firefox|fxios/i.test(g.userAgent)}V.isFirefox=b;function S(g){return g=g||(typeof window>"u"?Ye.navigator:window.navigator),!!g&&typeof g.userAgent=="string"&&/edge\/\d+/i.test(g.userAgent)}V.isLegacyEdge=S;function m(g){return!!g.vendor&&g.vendor.indexOf("Apple")!==-1&&g.userAgent&&g.userAgent.indexOf("CriOS")===-1&&g.userAgent.indexOf("FxiOS")===-1}V.isSafari=m;function E(g,t,e,n){if(typeof g>"u"||typeof t>"u"||typeof e>"u"||typeof n>"u"||typeof e.prototype>"u"||typeof n.prototype>"u")return!1;if(h(g,t)&&e.prototype.addTransceiver){var i=new e,o=!0;try{i.addTransceiver("audio")}catch{o=!1}return i.close(),o}else{if(b(t))return!0;if(m(t))return"currentDirection"in n.prototype}return!1}V.isUnifiedPlanDefault=E;function C(g){return g?g.split("&").reduce(function(t,e){var n=e.split("="),i=n[0],o=decodeURIComponent((n[1]||"").replace(/\+/g,"%20"));return i&&(t[i]=o),t},{}):""}V.queryToJson=C;function y(g,t){var e=g instanceof Map||g instanceof Set?Array.from(g.values()):g;return t=t||function(n){return n},e.reduce(function(n,i){var o=t(i);return n.concat(o)},[])}V.flatMap=y;function _(g,t,e){return new Promise(function(n,i){function o(){g.removeListener(e,u),n()}function u(){g.removeListener(t,o),i()}g.once(t,o),g.once(e,u)})}V.promisifyEvents=_;var s=w;return V.Exception=s,V}var Ot;function Gn(){if(Ot)return ne;Ot=1;var w=ne&&ne.__extends||function(){var s=function(g,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])},s(g,t)};return function(g,t){s(g,t);function e(){this.constructor=g}g.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}}(),p=ne&&ne.__awaiter||function(s,g,t,e){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function u(f){try{a(e.next(f))}catch(I){o(I)}}function c(f){try{a(e.throw(f))}catch(I){o(I)}}function a(f){f.done?i(f.value):n(f.value).then(u,c)}a((e=e.apply(s,g||[])).next())})},r=ne&&ne.__generator||function(s,g){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},e,n,i,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(a){return function(f){return c([a,f])}}function c(a){if(e)throw new TypeError("Generator is already executing.");for(;t;)try{if(e=1,n&&(i=a[0]&2?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[a[0]&2,i.value]),a[0]){case 0:case 1:i=a;break;case 4:return t.label++,{value:a[1],done:!1};case 5:t.label++,n=a[1],a=[0];continue;case 7:a=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(a[0]===6||a[0]===2)){t=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){t.label=a[1];break}if(a[0]===6&&t.label<i[1]){t.label=i[1],i=a;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(a);break}i[2]&&t.ops.pop(),t.trys.pop();continue}a=g.call(s,t)}catch(f){a=[6,f],n=0}finally{e=i=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};Object.defineProperty(ne,"__esModule",{value:!0});var l=Z(),h=He(),b=$(),S=X(),m=Wn(),E=Vn(),C=fe(),y={audioinput:"Audio Input",audiooutput:"Audio Output"},_=function(s){w(g,s);function g(t,e,n){var i,o=s.call(this)||this;o.availableInputDevices=new Map,o.availableOutputDevices=new Map,o._audioConstraints=null,o._defaultInputDeviceStream=null,o._enabledSounds=(i={},i[h.default.SoundName.Disconnect]=!0,i[h.default.SoundName.Incoming]=!0,i[h.default.SoundName.Outgoing]=!0,i),o._inputDevice=null,o._inputDevicePromise=null,o._isPollingInputVolume=!1,o._log=new S.default("AudioHelper"),o._processedStream=null,o._selectedInputDeviceStream=null,o._unknownDeviceIndexes={audioinput:{},audiooutput:{}},o._updateAvailableDevices=function(){return!o._mediaDevices||!o._enumerateDevices?Promise.reject("Enumeration not supported"):o._enumerateDevices().then(function(f){o._updateDevices(f.filter(function(v){return v.kind==="audiooutput"}),o.availableOutputDevices,o._removeLostOutput),o._updateDevices(f.filter(function(v){return v.kind==="audioinput"}),o.availableInputDevices,o._removeLostInput);var I=o.availableOutputDevices.get("default")||Array.from(o.availableOutputDevices.values())[0];[o.speakerDevices,o.ringtoneDevices].forEach(function(v){!v.get().size&&o.availableOutputDevices.size&&o.isOutputSelectionSupported&&v.set(I.deviceId).catch(function(O){o._log.warn("Unable to set audio output devices. "+O)})})})},o._removeLostInput=function(f){if(!o.inputDevice||o.inputDevice.deviceId!==f.deviceId)return!1;o._destroyProcessedStream(),o._replaceStream(null),o._inputDevice=null,o._maybeStopPollingVolume();var I=o.availableInputDevices.get("default")||Array.from(o.availableInputDevices.values())[0];return I&&o.setInputDevice(I.deviceId),!0},o._removeLostOutput=function(f){var I=o.speakerDevices.delete(f),v=o.ringtoneDevices.delete(f);return I||v},n=Object.assign({AudioContext:typeof AudioContext<"u"&&AudioContext,setSinkId:typeof HTMLAudioElement<"u"&&HTMLAudioElement.prototype.setSinkId},n),o._beforeSetInputDevice=n.beforeSetInputDevice||function(){return Promise.resolve()},o._updateUserOptions(n),o._audioProcessorEventObserver=n.audioProcessorEventObserver,o._mediaDevices=n.mediaDevices||navigator.mediaDevices,o._onActiveInputChanged=e,o._enumerateDevices=typeof n.enumerateDevices=="function"?n.enumerateDevices:o._mediaDevices&&o._mediaDevices.enumerateDevices.bind(o._mediaDevices);var u=!!(n.AudioContext||n.audioContext),c=!!o._enumerateDevices;n.enabledSounds&&(o._enabledSounds=n.enabledSounds);var a=typeof n.setSinkId=="function";return o.isOutputSelectionSupported=c&&a,o.isVolumeSupported=u,o.isVolumeSupported&&(o._audioContext=n.audioContext||n.AudioContext&&new n.AudioContext,o._audioContext&&(o._inputVolumeAnalyser=o._audioContext.createAnalyser(),o._inputVolumeAnalyser.fftSize=32,o._inputVolumeAnalyser.smoothingTimeConstant=.3)),o.ringtoneDevices=new m.default("ringtone",o.availableOutputDevices,t,o.isOutputSelectionSupported),o.speakerDevices=new m.default("speaker",o.availableOutputDevices,t,o.isOutputSelectionSupported),o.addListener("newListener",function(f){f==="inputVolume"&&o._maybeStartPollingVolume()}),o.addListener("removeListener",function(f){f==="inputVolume"&&o._maybeStopPollingVolume()}),o.once("newListener",function(){o.isOutputSelectionSupported||o._log.warn("Warning: This browser does not support audio output selection."),o.isVolumeSupported||o._log.warn("Warning: This browser does not support Twilio's volume indicator feature.")}),c&&o._initializeEnumeration(),navigator&&navigator.permissions&&typeof navigator.permissions.query=="function"?navigator.permissions.query({name:"microphone"}).then(function(f){if(f.state!=="granted"){var I=function(){o._updateAvailableDevices(),o._stopMicrophonePermissionListener()};f.addEventListener("change",I),o._microphonePermissionStatus=f,o._onMicrophonePermissionStatusChanged=I}}).catch(function(f){return o._log.warn("Warning: unable to listen for microphone permission changes. "+f)}):o._log.warn("Warning: current browser does not support permissions API."),o}return Object.defineProperty(g.prototype,"audioConstraints",{get:function(){return this._audioConstraints},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"inputDevice",{get:function(){return this._inputDevice},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"inputStream",{get:function(){return this._processedStream||this._selectedInputDeviceStream},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"processedStream",{get:function(){return this._processedStream},enumerable:!1,configurable:!0}),g.prototype._destroy=function(){this._stopDefaultInputDeviceStream(),this._stopSelectedInputDeviceStream(),this._destroyProcessedStream(),this._maybeStopPollingVolume(),this.removeAllListeners(),this._stopMicrophonePermissionListener(),this._unbind()},g.prototype._getInputDevicePromise=function(){return this._inputDevicePromise},g.prototype._maybeStartPollingVolume=function(){var t=this;if(!(!this.isVolumeSupported||!this.inputStream)&&(this._updateVolumeSource(),!(this._isPollingInputVolume||!this._inputVolumeAnalyser))){var e=this._inputVolumeAnalyser.frequencyBinCount,n=new Uint8Array(e);this._isPollingInputVolume=!0;var i=function(){if(t._isPollingInputVolume){if(t._inputVolumeAnalyser){t._inputVolumeAnalyser.getByteFrequencyData(n);var o=C.average(n);t.emit("inputVolume",o/255)}requestAnimationFrame(i)}};requestAnimationFrame(i)}},g.prototype._maybeStopPollingVolume=function(){this.isVolumeSupported&&(!this._isPollingInputVolume||this.inputStream&&this.listenerCount("inputVolume")||(this._inputVolumeSource&&(this._inputVolumeSource.disconnect(),delete this._inputVolumeSource),this._isPollingInputVolume=!1))},g.prototype._openDefaultDeviceWithConstraints=function(t){var e=this;return this._log.info("Opening default device with constraints",t),this._getUserMedia(t).then(function(n){return e._log.info("Opened default device. Updating available devices."),e._updateAvailableDevices().catch(function(i){e._log.warn("Unable to updateAvailableDevices after gUM call",i)}),e._defaultInputDeviceStream=n,e._maybeCreateProcessedStream(n)})},g.prototype._stopDefaultInputDeviceStream=function(){this._defaultInputDeviceStream&&(this._log.info("stopping default device stream"),this._defaultInputDeviceStream.getTracks().forEach(function(t){return t.stop()}),this._defaultInputDeviceStream=null,this._destroyProcessedStream())},g.prototype._unbind=function(){var t;!((t=this._mediaDevices)===null||t===void 0)&&t.removeEventListener&&this._mediaDevices.removeEventListener("devicechange",this._updateAvailableDevices)},g.prototype._updateUserOptions=function(t){typeof t.enumerateDevices=="function"&&(this._enumerateDevices=t.enumerateDevices),typeof t.getUserMedia=="function"&&(this._getUserMedia=t.getUserMedia)},g.prototype.addProcessor=function(t){if(this._log.debug(".addProcessor"),this._processor)throw new b.NotSupportedError("Adding multiple AudioProcessors is not supported at this time.");if(typeof t!="object"||t===null)throw new b.InvalidArgumentError("Missing AudioProcessor argument.");if(typeof t.createProcessedStream!="function")throw new b.InvalidArgumentError("Missing createProcessedStream() method.");if(typeof t.destroyProcessedStream!="function")throw new b.InvalidArgumentError("Missing destroyProcessedStream() method.");return this._processor=t,this._audioProcessorEventObserver.emit("add"),this._restartStreams()},g.prototype.disconnect=function(t){return this._log.debug(".disconnect",t),this._maybeEnableSound(h.default.SoundName.Disconnect,t)},g.prototype.incoming=function(t){return this._log.debug(".incoming",t),this._maybeEnableSound(h.default.SoundName.Incoming,t)},g.prototype.outgoing=function(t){return this._log.debug(".outgoing",t),this._maybeEnableSound(h.default.SoundName.Outgoing,t)},g.prototype.removeProcessor=function(t){if(this._log.debug(".removeProcessor"),typeof t!="object"||t===null)throw new b.InvalidArgumentError("Missing AudioProcessor argument.");if(this._processor!==t)throw new b.InvalidArgumentError("Cannot remove an AudioProcessor that has not been previously added.");return this._destroyProcessedStream(),this._processor=null,this._audioProcessorEventObserver.emit("remove"),this._restartStreams()},g.prototype.setAudioConstraints=function(t){return this._log.debug(".setAudioConstraints",t),this._audioConstraints=Object.assign({},t),delete this._audioConstraints.deviceId,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()},g.prototype.setInputDevice=function(t){return this._log.debug(".setInputDevice",t),this._setInputDevice(t,!1)},g.prototype.unsetAudioConstraints=function(){return this._log.debug(".unsetAudioConstraints"),this._audioConstraints=null,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()},g.prototype.unsetInputDevice=function(){var t=this;return this._log.debug(".unsetInputDevice",this.inputDevice),this.inputDevice?(this._destroyProcessedStream(),this._onActiveInputChanged(null).then(function(){t._replaceStream(null),t._inputDevice=null,t._maybeStopPollingVolume()})):Promise.resolve()},g.prototype._destroyProcessedStream=function(){if(this._processor&&this._processedStream){this._log.info("destroying processed stream");var t=this._processedStream;this._processedStream.getTracks().forEach(function(e){return e.stop()}),this._processedStream=null,this._processor.destroyProcessedStream(t),this._audioProcessorEventObserver.emit("destroy")}},g.prototype._getUnknownDeviceIndex=function(t){var e=t.deviceId,n=t.kind,i=this._unknownDeviceIndexes[n][e];return i||(i=Object.keys(this._unknownDeviceIndexes[n]).length+1,this._unknownDeviceIndexes[n][e]=i),i},g.prototype._initializeEnumeration=function(){var t=this;if(!this._mediaDevices||!this._enumerateDevices)throw new b.NotSupportedError("Enumeration is not supported");this._mediaDevices.addEventListener&&this._mediaDevices.addEventListener("devicechange",this._updateAvailableDevices),this._updateAvailableDevices().then(function(){t.isOutputSelectionSupported&&Promise.all([t.speakerDevices.set("default"),t.ringtoneDevices.set("default")]).catch(function(e){t._log.warn("Warning: Unable to set audio output devices. "+e)})})},g.prototype._maybeCreateProcessedStream=function(t){var e=this;return this._processor?(this._log.info("Creating processed stream"),this._processor.createProcessedStream(t).then(function(n){return e._processedStream=n,e._audioProcessorEventObserver.emit("create"),e._processedStream})):Promise.resolve(t)},g.prototype._maybeEnableSound=function(t,e){return typeof e<"u"&&(this._enabledSounds[t]=e),this._enabledSounds[t]},g.prototype._replaceStream=function(t){this._log.info("Replacing with new stream."),this._selectedInputDeviceStream&&(this._log.info("Old stream detected. Stopping tracks."),this._stopSelectedInputDeviceStream()),this._selectedInputDeviceStream=t},g.prototype._restartStreams=function(){if(this.inputDevice&&this._selectedInputDeviceStream)return this._log.info("Restarting selected input device"),this._setInputDevice(this.inputDevice.deviceId,!0);if(this._defaultInputDeviceStream){var t=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];return this._log.info("Restarting default input device, now becoming selected."),this._setInputDevice(t.deviceId,!0)}return Promise.resolve()},g.prototype._setInputDevice=function(t,e){return p(this,void 0,void 0,function(){var n,i=this;return r(this,function(o){return n=function(){return p(i,void 0,void 0,function(){var u,c,a=this;return r(this,function(f){switch(f.label){case 0:return[4,this._beforeSetInputDevice()];case 1:if(f.sent(),typeof t!="string")return[2,Promise.reject(new b.InvalidArgumentError("Must specify the device to set"))];if(u=this.availableInputDevices.get(t),!u)return[2,Promise.reject(new b.InvalidArgumentError("Device not found: "+t))];if(this._log.info("Setting input device. ID: "+t),this._inputDevice&&this._inputDevice.deviceId===t&&this._selectedInputDeviceStream){if(!e)return[2,Promise.resolve()];this._log.info("Same track detected on setInputDevice, stopping old tracks."),this._stopSelectedInputDeviceStream()}return this._stopDefaultInputDeviceStream(),c={audio:Object.assign({deviceId:{exact:t}},this.audioConstraints)},this._log.info("setInputDevice: getting new tracks."),[2,this._getUserMedia(c).then(function(I){return a._destroyProcessedStream(),a._maybeCreateProcessedStream(I).then(function(v){return a._log.info("setInputDevice: invoking _onActiveInputChanged."),a._onActiveInputChanged(v).then(function(){a._replaceStream(I),a._inputDevice=u,a._maybeStartPollingVolume()})})})]}})})},[2,this._inputDevicePromise=n().finally(function(){i._inputDevicePromise=null})]})})},g.prototype._stopMicrophonePermissionListener=function(){var t;!((t=this._microphonePermissionStatus)===null||t===void 0)&&t.removeEventListener&&this._microphonePermissionStatus.removeEventListener("change",this._onMicrophonePermissionStatusChanged)},g.prototype._stopSelectedInputDeviceStream=function(){this._selectedInputDeviceStream&&(this._log.info("Stopping selected device stream"),this._selectedInputDeviceStream.getTracks().forEach(function(t){return t.stop()}))},g.prototype._updateDevices=function(t,e,n){var i=this,o=t.map(function(T){return T.deviceId}),u=Array.from(e.values()).map(function(T){return T.deviceId}),c=[],a=C.difference(u,o);a.forEach(function(T){var R=e.get(T);R&&(e.delete(T),n(R)&&c.push(R))});var f=!1;if(t.forEach(function(T){var R=e.get(T.deviceId),P=i._wrapMediaDeviceInfo(T);(!R||R.label!==P.label)&&(e.set(T.deviceId,P),f=!0)}),f||a.length){var I="default",v=this.inputDevice&&this.inputDevice.deviceId===I,O=this._defaultInputDeviceStream&&this.availableInputDevices.get(I);(v||O)&&(this._log.warn("Calling getUserMedia after device change to ensure that the tracks of the active device (default) have not gone stale."),setTimeout(function(){i._setInputDevice(I,!0)},0)),this._log.debug("#deviceChange",c),this.emit("deviceChange",c)}},g.prototype._updateVolumeSource=function(){if(!(!this.inputStream||!this._audioContext||!this._inputVolumeAnalyser)){this._inputVolumeSource&&this._inputVolumeSource.disconnect();try{this._inputVolumeSource=this._audioContext.createMediaStreamSource(this.inputStream),this._inputVolumeSource.connect(this._inputVolumeAnalyser)}catch(t){this._log.warn("Unable to update volume source",t),delete this._inputVolumeSource}}},g.prototype._wrapMediaDeviceInfo=function(t){var e={deviceId:t.deviceId,groupId:t.groupId,kind:t.kind,label:t.label};if(!e.label)if(e.deviceId==="default")e.label="Default";else{var n=this._getUnknownDeviceIndex(t);e.label="Unknown "+y[e.kind]+" Device "+n}return new E.default(e)},g}(l.EventEmitter);return _||(_={}),ne.default=_,ne}var he={},Mt;function Hn(){if(Mt)return he;Mt=1;var w=he&&he.__extends||function(){var h=function(b,S){return h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(m,E){m.__proto__=E}||function(m,E){for(var C in E)Object.prototype.hasOwnProperty.call(E,C)&&(m[C]=E[C])},h(b,S)};return function(b,S){h(b,S);function m(){this.constructor=b}b.prototype=S===null?Object.create(S):(m.prototype=S.prototype,new m)}}();Object.defineProperty(he,"__esModule",{value:!0}),he.AudioProcessorEventObserver=void 0;var p=Z(),r=X(),l=function(h){w(b,h);function b(){var S=h.call(this)||this;return S._log=new r.default("AudioProcessorEventObserver"),S._log.info("Creating AudioProcessorEventObserver instance"),S.on("enabled",function(){return S._reEmitEvent("enabled")}),S.on("add",function(){return S._reEmitEvent("add")}),S.on("remove",function(){return S._reEmitEvent("remove")}),S.on("create",function(){return S._reEmitEvent("create-processed-stream")}),S.on("destroy",function(){return S._reEmitEvent("destroy-processed-stream")}),S}return b.prototype.destroy=function(){this.removeAllListeners()},b.prototype._reEmitEvent=function(S){this._log.info("AudioProcessor:"+S),this.emit("event",{name:S,group:"audio-processor"})},b}(p.EventEmitter);return he.AudioProcessorEventObserver=l,he}var je={},Lt;function $n(){if(Lt)return je;Lt=1,Object.defineProperty(je,"__esModule",{value:!0});var w=$(),p={dtmf0:[1360,960],dtmf1:[1230,720],dtmf2:[1360,720],dtmf3:[1480,720],dtmf4:[1230,790],dtmf5:[1360,790],dtmf6:[1480,790],dtmf7:[1230,870],dtmf8:[1360,870],dtmf9:[1480,870],dtmfh:[1480,960],dtmfs:[1230,960]},r=function(){function l(h){var b=this;this._context=h,this._gainNodes=[],this._gainNodes=[this._context.createGain(),this._context.createGain()],this._gainNodes.forEach(function(S){S.connect(b._context.destination),S.gain.value=.1,b._gainNodes.push(S)})}return l.prototype.cleanup=function(){this._gainNodes.forEach(function(h){h.disconnect()})},l.prototype.play=function(h){var b=this,S=p[h];if(!S)throw new w.InvalidArgumentError("Invalid DTMF sound name");var m=[this._context.createOscillator(),this._context.createOscillator()];m.forEach(function(E,C){E.type="sine",E.frequency.value=S[C],E.connect(b._gainNodes[C]),E.start(),E.stop(b._context.currentTime+.1),E.addEventListener("ended",function(){return E.disconnect()})})},l}();return je.default=r,je}var ye={},Ue={},jt;function zn(){if(jt)return Ue;jt=1,Object.defineProperty(Ue,"__esModule",{value:!0});function w(r,l,h){var b=JSON.stringify(l.body||{}),S=new Headers;l.headers=l.headers||[],Object.entries(l.headers).forEach(function(m){var E=m[0],C=m[1];return S.append(E,C)}),fetch(l.url,{body:b,headers:S,method:r}).then(function(m){return m.text()},h).then(function(m){return h(null,m)},h)}var p=w;return p.get=function(l,h){return new this("GET",l,h)},p.post=function(l,h){return new this("POST",l,h)},Ue.default=p,Ue}var Ut;function Jn(){if(Ut)return ye;Ut=1;var w=ye&&ye.__extends||function(){var S=function(m,E){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,y){C.__proto__=y}||function(C,y){for(var _ in y)Object.prototype.hasOwnProperty.call(y,_)&&(C[_]=y[_])},S(m,E)};return function(m,E){S(m,E);function C(){this.constructor=m}m.prototype=E===null?Object.create(E):(C.prototype=E.prototype,new C)}}();Object.defineProperty(ye,"__esModule",{value:!0});var p=Z(),r=X(),l=zn(),h=function(S){w(m,S);function m(E,C,y){var _=S.call(this)||this;if(!(_ instanceof m))return new m(E,C,y);y=Object.assign({defaultPayload:function(){return{}}},y);var s=y.defaultPayload;typeof s!="function"&&(s=function(){return Object.assign({},y.defaultPayload)});var g=!0,t=Object.assign({app_name:void 0,app_version:void 0},y.metadata);return Object.defineProperties(_,{_defaultPayload:{value:s},_host:{value:y.host,writable:!0},_isEnabled:{get:function(){return g},set:function(e){g=e}},_log:{value:new r.default("EventPublisher")},_request:{value:y.request||l.default,writable:!0},_token:{value:C,writable:!0},isEnabled:{enumerable:!0,get:function(){return g}},metadata:{enumerable:!0,get:function(){return t}},productName:{enumerable:!0,value:E},token:{enumerable:!0,get:function(){return this._token}}}),_}return m}(p.EventEmitter);h.prototype._post=function(m,E,C,y,_,s,g){var t=this;if(!this.isEnabled&&!g||!this._host)return this._log.debug("Publishing cancelled",JSON.stringify({isEnabled:this.isEnabled,force:g,host:this._host})),Promise.resolve();if(!s||(!s.parameters||!s.parameters.CallSid)&&!s.outboundConnectionId)return s?this._log.debug("Publishing cancelled. Missing connection info",JSON.stringify({outboundConnectionId:s.outboundConnectionId,parameters:s.parameters})):this._log.debug("Publishing cancelled. Missing connection object"),Promise.resolve();var e={group:C,level:E.toUpperCase(),name:y,payload:_&&_.forEach?_.slice(0):Object.assign(this._defaultPayload(s),_),payload_type:"application/json",private:!1,publisher:this.productName,timestamp:new Date().toISOString()};this.metadata&&(e.publisher_metadata=this.metadata),m==="EndpointEvents"&&this._log.debug("Publishing insights",JSON.stringify({endpointName:m,event:e,force:g,host:this._host}));var n={body:e,headers:{"Content-Type":"application/json","X-Twilio-Token":this.token},url:"https://"+this._host+"/v4/"+m};return new Promise(function(i,o){t._request.post(n,function(u){u?(t.emit("error",u),o(u)):i()})}).catch(function(i){t._log.error("Unable to post "+C+" "+y+" event to Insights. Received error: "+i)})},h.prototype.post=function(m,E,C,y,_,s){return this._post("EndpointEvents",m,E,C,y,_,s)},h.prototype.debug=function(m,E,C,y){return this.post("debug",m,E,C,y)},h.prototype.info=function(m,E,C,y){return this.post("info",m,E,C,y)},h.prototype.warn=function(m,E,C,y){return this.post("warning",m,E,C,y)},h.prototype.error=function(m,E,C,y){return this.post("error",m,E,C,y)},h.prototype.postMetrics=function(m,E,C,y,_){var s=this;return new Promise(function(g){var t=C.map(b).map(function(e){return Object.assign(e,y)});g(s._post("EndpointMetrics","info",m,E,t,_))})},h.prototype.setHost=function(m){this._host=m},h.prototype.setToken=function(m){this._token=m},h.prototype.enable=function(){this._isEnabled=!0},h.prototype.disable=function(){this._isEnabled=!1};function b(S){return{audio_codec:S.codecName,audio_level_in:S.audioInputLevel,audio_level_out:S.audioOutputLevel,bytes_received:S.bytesReceived,bytes_sent:S.bytesSent,call_volume_input:S.inputVolume,call_volume_output:S.outputVolume,jitter:S.jitter,mos:S.mos&&Math.round(S.mos*100)/100,packets_lost:S.packetsLost,packets_lost_fraction:S.packetsLostFraction&&Math.round(S.packetsLostFraction*100)/100,packets_received:S.packetsReceived,rtt:S.rtt,timestamp:new Date(S.timestamp).toISOString(),total_bytes_received:S.totals.bytesReceived,total_bytes_sent:S.totals.bytesSent,total_packets_lost:S.totals.packetsLost,total_packets_received:S.totals.packetsReceived,total_packets_sent:S.totals.packetsSent}}return ye.default=h,ye}var ee={},oe={},Ne={},Nt;function Kn(){if(Nt)return Ne;Nt=1,Object.defineProperty(Ne,"__esModule",{value:!0});var w=32767,p=typeof window<"u"?window.RTCStatsReport:void 0;function r(u){if(!(this instanceof r))return new r(u);var c=this;Object.defineProperties(this,{_map:{value:u},size:{enumerable:!0,get:function(){return c._map.size}}}),this[Symbol.iterator]=u[Symbol.iterator]}p&&(r.prototype=Object.create(p.prototype),r.prototype.constructor=r),["entries","forEach","get","has","keys","values"].forEach(function(u){r.prototype[u]=function(){for(var c,a=[],f=0;f<arguments.length;f++)a[f]=arguments[f];return(c=this._map)[u].apply(c,a)}}),r.fromArray=function(c){return new r(c.reduce(function(a,f){return a.set(f.id,f),a},new Map))},r.fromRTCStatsResponse=function(c){var a,f=new Map,I=c.result().reduce(function(O,T){var R=T.id;switch(T.type){case"googCertificate":O.set(R,_(T));break;case"datachannel":O.set(R,s(T));break;case"googCandidatePair":i(T,"googActiveConnection")&&(a=R),O.set(R,y(T));break;case"localcandidate":O.set(R,C(T,!1));break;case"remotecandidate":O.set(R,C(T,!0));break;case"ssrc":o(T,"packetsReceived")?O.set("rtp-"+R,m(T)):O.set("rtp-"+R,E(T)),O.set("track-"+R,b(T)),O.set("codec-"+R,h(T));break;case"googComponent":var P=l(T);f.set(P.selectedCandidatePairId,R),O.set(R,l(T));break}return O},new Map);if(a){var v=f.get(a);v&&(I.get(v).dtlsState="connected")}return new r(I)};function l(u){return{bytesReceived:void 0,bytesSent:void 0,dtlsState:void 0,id:u.id,localCertificateId:u.stat("localCertificateId"),remoteCertificateId:u.stat("remoteCertificateId"),rtcpTransportStatsId:void 0,selectedCandidatePairId:u.stat("selectedCandidatePairId"),timestamp:Date.parse(u.timestamp),type:"transport"}}function h(u){return{channels:void 0,clockRate:void 0,id:u.id,implementation:void 0,mimeType:u.stat("mediaType")+"/"+u.stat("googCodecName"),payloadType:void 0,sdpFmtpLine:void 0,timestamp:Date.parse(u.timestamp),type:"codec"}}function b(u){return{audioLevel:o(u,"audioOutputLevel")?e(u,"audioOutputLevel")/w:(e(u,"audioInputLevel")||0)/w,detached:void 0,echoReturnLoss:n(u,"googEchoCancellationReturnLoss"),echoReturnLossEnhancement:n(u,"googEchoCancellationReturnLossEnhancement"),ended:void 0,frameHeight:o(u,"googFrameHeightReceived")?e(u,"googFrameHeightReceived"):e(u,"googFrameHeightSent"),frameWidth:o(u,"googFrameWidthReceived")?e(u,"googFrameWidthReceived"):e(u,"googFrameWidthSent"),framesCorrupted:void 0,framesDecoded:e(u,"framesDecoded"),framesDropped:void 0,framesPerSecond:void 0,framesReceived:void 0,framesSent:e(u,"framesEncoded"),fullFramesLost:void 0,id:u.id,kind:u.stat("mediaType"),partialFramesLost:void 0,remoteSource:void 0,ssrcIds:void 0,timestamp:Date.parse(u.timestamp),trackIdentifier:u.stat("googTrackId"),type:"track"}}function S(u,c){return{associateStatsId:void 0,codecId:"codec-"+u.id,firCount:c?e(u,"googFirsSent"):void 0,id:u.id,isRemote:void 0,mediaType:u.stat("mediaType"),nackCount:c?e(u,"googNacksSent"):e(u,"googNacksReceived"),pliCount:c?e(u,"googPlisSent"):e(u,"googPlisReceived"),qpSum:e(u,"qpSum"),sliCount:void 0,ssrc:u.stat("ssrc"),timestamp:Date.parse(u.timestamp),trackId:"track-"+u.id,transportId:u.stat("transportId")}}function m(u){var c=S(u,!0);return Object.assign(c,{burstDiscardCount:void 0,burstDiscardRate:void 0,burstLossCount:void 0,burstLossRate:void 0,burstPacketsDiscarded:void 0,burstPacketsLost:void 0,bytesReceived:e(u,"bytesReceived"),fractionLost:void 0,framesDecoded:e(u,"framesDecoded"),gapDiscardRate:void 0,gapLossRate:void 0,jitter:g(u.stat("googJitterReceived")),packetsDiscarded:void 0,packetsLost:e(u,"packetsLost"),packetsReceived:e(u,"packetsReceived"),packetsRepaired:void 0,roundTripTime:g(u.stat("googRtt")),type:"inbound-rtp"}),c}function E(u){var c=S(u,!1);return Object.assign(c,{bytesSent:e(u,"bytesSent"),framesEncoded:e(u,"framesEncoded"),packetsSent:e(u,"packetsSent"),remoteTimestamp:void 0,targetBitrate:void 0,type:"outbound-rtp"}),c}function C(u,c){return{candidateType:t(u.stat("candidateType")),deleted:void 0,id:u.id,ip:u.stat("ipAddress"),isRemote:c,port:e(u,"portNumber"),priority:n(u,"priority"),protocol:u.stat("transport"),relayProtocol:void 0,timestamp:Date.parse(u.timestamp),transportId:void 0,type:c?"remote-candidate":"local-candidate",url:void 0}}function y(u){return{availableIncomingBitrate:void 0,availableOutgoingBitrate:void 0,bytesReceived:e(u,"bytesReceived"),bytesSent:e(u,"bytesSent"),consentRequestsSent:e(u,"consentRequestsSent"),currentRoundTripTime:g(u.stat("googRtt")),id:u.id,lastPacketReceivedTimestamp:void 0,lastPacketSentTimestamp:void 0,localCandidateId:u.stat("localCandidateId"),nominated:void 0,priority:void 0,readable:void 0,remoteCandidateId:u.stat("remoteCandidateId"),requestsReceived:e(u,"requestsReceived"),requestsSent:e(u,"requestsSent"),responsesReceived:e(u,"responsesReceived"),responsesSent:e(u,"responsesSent"),retransmissionsReceived:void 0,retransmissionsSent:void 0,state:void 0,timestamp:Date.parse(u.timestamp),totalRoundTripTime:void 0,transportId:u.stat("googChannelId"),type:"candidate-pair",writable:i(u,"googWritable")}}function _(u){return{base64Certificate:u.stat("googDerBase64"),fingerprint:u.stat("googFingerprint"),fingerprintAlgorithm:u.stat("googFingerprintAlgorithm"),id:u.id,issuerCertificateId:u.stat("googIssuerId"),timestamp:Date.parse(u.timestamp),type:"certificate"}}function s(u){return{bytesReceived:void 0,bytesSent:void 0,datachannelid:u.stat("datachannelid"),id:u.id,label:u.stat("label"),messagesReceived:void 0,messagesSent:void 0,protocol:u.stat("protocol"),state:u.stat("state"),timestamp:Date.parse(u.timestamp),transportId:u.stat("transportId"),type:"data-channel"}}function g(u){return isNaN(u)||u===""?void 0:parseInt(u,10)/1e3}function t(u){switch(u){case"peerreflexive":return"prflx";case"serverreflexive":return"srflx";case"host":case"relay":default:return u}}function e(u,c){var a=u.stat(c);return o(u,c)?parseInt(a,10):void 0}function n(u,c){var a=u.stat(c);return o(u,c)?parseFloat(a):void 0}function i(u,c){var a=u.stat(c);return o(u,c)?a==="true"||a===!0:void 0}function o(u,c){var a=u.stat(c);return typeof a<"u"&&a!==""}return Ne.default=r,Ne}var Ft;function qt(){if(Ft)return oe;Ft=1;var w=oe&&oe.__spreadArrays||function(){for(var _=0,s=0,g=arguments.length;s<g;s++)_+=arguments[s].length;for(var t=Array(_),e=0,s=0;s<g;s++)for(var n=arguments[s],i=0,o=n.length;i<o;i++,e++)t[e]=n[i];return t};Object.defineProperty(oe,"__esModule",{value:!0}),oe.getRTCIceCandidateStatsReport=oe.getRTCStats=void 0;var p=$(),r=Kn(),l="PeerConnection is null",h="WebRTC statistics are unsupported";function b(_,s){return typeof _.get=="function"?_.get(s):_.find(function(g){return g.id===s})}function S(_){if(!_)return Promise.reject(new p.InvalidArgumentError(l));if(typeof _.getStats!="function")return Promise.reject(new p.NotSupportedError(h));var s;try{s=_.getStats()}catch{s=new Promise(function(t){return _.getStats(t)}).then(r.default.fromRTCStatsResponse)}return s}function m(_,s){return s=Object.assign({createRTCSample:y},s),S(_).then(s.createRTCSample)}oe.getRTCStats=m;function E(_){return S(_).then(function(s){var g=Array.from(s.values()).reduce(function(c,a){switch(["candidatePairs","localCandidates","remoteCandidates"].forEach(function(f){c[f]||(c[f]=[])}),a.type){case"candidate-pair":c.candidatePairs.push(a);break;case"local-candidate":c.localCandidates.push(a);break;case"remote-candidate":c.remoteCandidates.push(a);break;case"transport":a.selectedCandidatePairId&&(c.transport=a);break}return c},{}),t=g.candidatePairs,e=g.localCandidates,n=g.remoteCandidates,i=g.transport,o=t.find(function(c){return c.selected||i&&c.id===i.selectedCandidatePairId}),u;return o&&(u={localCandidate:e.find(function(c){return c.id===o.localCandidateId}),remoteCandidate:n.find(function(c){return c.id===o.remoteCandidateId})}),{iceCandidateStats:w(e,n),selectedIceCandidatePairStats:u}})}oe.getRTCIceCandidateStatsReport=E;function C(){}function y(_){var s=null,g=new C,t;Array.from(_.values()).forEach(function(u){if(!u.isRemote){var c=u.type.replace("-","");if(t=t||u.timestamp,u.remoteId){var a=b(_,u.remoteId);a&&a.roundTripTime&&(g.rtt=a.roundTripTime*1e3)}switch(c){case"inboundrtp":g.timestamp=g.timestamp||u.timestamp,g.jitter=u.jitter*1e3,g.packetsLost=u.packetsLost,g.packetsReceived=u.packetsReceived,g.bytesReceived=u.bytesReceived;break;case"outboundrtp":if(g.timestamp=u.timestamp,g.packetsSent=u.packetsSent,g.bytesSent=u.bytesSent,u.codecId){var f=b(_,u.codecId);g.codecName=f?f.mimeType&&f.mimeType.match(/(.*\/)?(.*)/)[2]:u.codecId}break;case"transport":s=u.id;break}}}),g.timestamp||(g.timestamp=t);var e=b(_,s);if(!e)return g;var n=b(_,e.selectedCandidatePairId);if(!n)return g;var i=b(_,n.localCandidateId),o=b(_,n.remoteCandidateId);return g.rtt||(g.rtt=n&&n.currentRoundTripTime*1e3),Object.assign(g,{localAddress:i&&(i.address||i.ip),remoteAddress:o&&(o.address||o.ip)}),g}return oe}var Bt;function Wt(){return Bt||(Bt=1,function(w){var p=ee&&ee.__extends||function(){var g=function(t,e){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},g(t,e)};return function(t,e){g(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}}(),r=ee&&ee.__assign||function(){return r=Object.assign||function(g){for(var t,e=1,n=arguments.length;e<n;e++){t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(g[i]=t[i])}return g},r.apply(this,arguments)},l=ee&&ee.__awaiter||function(g,t,e,n){function i(o){return o instanceof e?o:new e(function(u){u(o)})}return new(e||(e=Promise))(function(o,u){function c(I){try{f(n.next(I))}catch(v){u(v)}}function a(I){try{f(n.throw(I))}catch(v){u(v)}}function f(I){I.done?o(I.value):i(I.value).then(c,a)}f((n=n.apply(g,t||[])).next())})},h=ee&&ee.__generator||function(g,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,u;return u={next:c(0),throw:c(1),return:c(2)},typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function c(f){return function(I){return a([f,I])}}function a(f){if(n)throw new TypeError("Generator is already executing.");for(;e;)try{if(n=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return e.label++,{value:f[1],done:!1};case 5:e.label++,i=f[1],f=[0];continue;case 7:f=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){e=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){e.label=f[1];break}if(f[0]===6&&e.label<o[1]){e.label=o[1],o=f;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(f);break}o[2]&&e.ops.pop(),e.trys.pop();continue}f=t.call(g,e)}catch(I){f=[6,I],i=0}finally{n=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}};Object.defineProperty(w,"__esModule",{value:!0}),w.PreflightTest=void 0;var b=Z(),S=ct(),m=He(),E=$(),C=X(),y=qt(),_=_e(),s=function(g){p(t,g);function t(e,n){var i=g.call(this)||this;i._hasInsightsErrored=!1,i._log=new C.default("PreflightTest"),i._networkTiming={},i._options={codecPreferences:[S.default.Codec.PCMU,S.default.Codec.Opus],edge:"roaming",fakeMicInput:!1,logLevel:"error",signalingTimeoutMs:1e4},i._status=t.Status.Connecting,Object.assign(i._options,n),i._samples=[],i._warnings=[],i._startTime=Date.now(),i._initDevice(e,r(r({},i._options),{fileInputStream:i._options.fakeMicInput?i._getStreamFromFile():void 0}));var o=["codecPreferences","edge","fakeMicInput","logLevel","signalingTimeoutMs"],u=["audioContext","deviceFactory","fileInputStream","getRTCIceCandidateStatsReport","iceServers","rtcConfiguration"];if(typeof n=="object"){var c=r({},n);Object.keys(c).forEach(function(a){!o.includes(a)&&!u.includes(a)&&delete c[a],u.includes(a)&&(c[a]=!0)}),i._log.debug(".constructor",JSON.stringify(c))}return i}return t.prototype.stop=function(){var e=this;this._log.debug(".stop");var n=new E.GeneralErrors.CallCancelledError;this._device?(this._device.once(m.default.EventName.Unregistered,function(){return e._onFailed(n)}),this._device.destroy()):this._onFailed(n)},t.prototype._emitWarning=function(e,n,i){var o={name:e,description:n};i&&(o.rtcWarning=i),this._warnings.push(o),this._log.debug("#"+t.Events.Warning,JSON.stringify(o)),this.emit(t.Events.Warning,o)},t.prototype._getCallQuality=function(e){return e>4.2?t.CallQuality.Excellent:e>=4.1&&e<=4.2?t.CallQuality.Great:e>=3.7&&e<=4?t.CallQuality.Good:e>=3.1&&e<=3.6?t.CallQuality.Fair:t.CallQuality.Degraded},t.prototype._getReport=function(){var e,n,i,o=this._getRTCStats(),u={start:this._startTime};this._endTime&&(u.end=this._endTime,u.duration=this._endTime-this._startTime);var c={callSid:this._callSid,edge:this._edge,iceCandidateStats:(n=(e=this._rtcIceCandidateStatsReport)===null||e===void 0?void 0:e.iceCandidateStats)!==null&&n!==void 0?n:[],networkTiming:this._networkTiming,samples:this._samples,selectedEdge:this._options.edge,stats:o,testTiming:u,totals:this._getRTCSampleTotals(),warnings:this._warnings},a=(i=this._rtcIceCandidateStatsReport)===null||i===void 0?void 0:i.selectedIceCandidatePairStats;return a&&(c.selectedIceCandidatePairStats=a,c.isTurnRequired=a.localCandidate.candidateType==="relay"||a.remoteCandidate.candidateType==="relay"),o&&(c.callQuality=this._getCallQuality(o.mos.average)),c},t.prototype._getRTCSampleTotals=function(){if(this._latestSample)return r({},this._latestSample.totals)},t.prototype._getRTCStats=function(){var e=this._samples.findIndex(function(i){return typeof i.mos=="number"&&i.mos>0}),n=e>=0?this._samples.slice(e):[];if(!(!n||!n.length))return["jitter","mos","rtt"].reduce(function(i,o){var u,c=n.map(function(a){return a[o]});return r(r({},i),(u={},u[o]={average:Number((c.reduce(function(a,f){return a+f})/c.length).toPrecision(5)),max:Math.max.apply(Math,c),min:Math.min.apply(Math,c)},u))},{})},t.prototype._getStreamFromFile=function(){var e=this._options.audioContext;if(!e)throw new E.NotSupportedError("Cannot fake input audio stream: AudioContext is not supported by this browser.");var n=new Audio(_.COWBELL_AUDIO_URL);n.addEventListener("canplaythrough",function(){return n.play()}),typeof n.setAttribute=="function"&&n.setAttribute("crossorigin","anonymous");var i=e.createMediaElementSource(n),o=e.createMediaStreamDestination();return i.connect(o),o.stream},t.prototype._initDevice=function(e,n){var i=this;try{this._device=new(n.deviceFactory||m.default)(e,{chunderw:n.chunderw,codecPreferences:n.codecPreferences,edge:n.edge,eventgw:n.eventgw,fileInputStream:n.fileInputStream,logLevel:n.logLevel,preflight:!0}),this._device.once(m.default.EventName.Registered,function(){i._onDeviceRegistered()}),this._device.once(m.default.EventName.Error,function(o){i._onDeviceError(o)}),this._device.register()}catch(o){setTimeout(function(){i._onFailed(o)});return}this._signalingTimeoutTimer=setTimeout(function(){i._onDeviceError(new E.SignalingErrors.ConnectionError("WebSocket Connection Timeout"))},n.signalingTimeoutMs)},t.prototype._onDeviceError=function(e){this._device.destroy(),this._onFailed(e)},t.prototype._onDeviceRegistered=function(){return l(this,void 0,void 0,function(){var e,n,i,o=this;return h(this,function(u){switch(u.label){case 0:return clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),e=this,[4,this._device.connect({rtcConfiguration:this._options.rtcConfiguration})];case 1:return e._call=u.sent(),this._networkTiming.signaling={start:Date.now()},this._setupCallHandlers(this._call),this._edge=this._device.edge||void 0,this._options.fakeMicInput&&(this._echoTimer=setTimeout(function(){return o._device.disconnectAll()},_.ECHO_TEST_DURATION),n=this._device.audio,n&&(n.disconnect(!1),n.outgoing(!1))),this._call.once("disconnect",function(){o._device.once(m.default.EventName.Unregistered,function(){return o._onUnregistered()}),o._device.destroy()}),i=this._call._publisher,i.on("error",function(){o._hasInsightsErrored||o._emitWarning("insights-connection-error","Received an error when attempting to connect to Insights gateway"),o._hasInsightsErrored=!0}),[2]}})})},t.prototype._onFailed=function(e){clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._releaseHandlers(),this._endTime=Date.now(),this._status=t.Status.Failed,this._log.debug("#"+t.Events.Failed,e),this.emit(t.Events.Failed,e)},t.prototype._onUnregistered=function(){var e=this;setTimeout(function(){e._status!==t.Status.Failed&&(clearTimeout(e._echoTimer),clearTimeout(e._signalingTimeoutTimer),e._releaseHandlers(),e._endTime=Date.now(),e._status=t.Status.Completed,e._report=e._getReport(),e._log.debug("#"+t.Events.Completed,JSON.stringify(e._report)),e.emit(t.Events.Completed,e._report))},10)},t.prototype._releaseHandlers=function(){[this._device,this._call].forEach(function(e){e&&e.eventNames().forEach(function(n){return e.removeAllListeners(n)})})},t.prototype._setupCallHandlers=function(e){var n=this;this._options.fakeMicInput&&e.once("volume",function(){e._mediaHandler.outputs.forEach(function(i){return i.audio.muted=!0})}),e.on("warning",function(i,o){n._emitWarning(i,"Received an RTCWarning. See .rtcWarning for the RTCWarning",o)}),e.once("accept",function(){n._callSid=e._mediaHandler.callSid,n._status=t.Status.Connected,n._log.debug("#"+t.Events.Connected),n.emit(t.Events.Connected)}),e.on("sample",function(i){return l(n,void 0,void 0,function(){var o;return h(this,function(u){switch(u.label){case 0:return this._latestSample?[3,2]:(o=this,[4,(this._options.getRTCIceCandidateStatsReport||y.getRTCIceCandidateStatsReport)(e._mediaHandler.version.pc)]);case 1:o._rtcIceCandidateStatsReport=u.sent(),u.label=2;case 2:return this._latestSample=i,this._samples.push(i),this._log.debug("#"+t.Events.Sample,JSON.stringify(i)),this.emit(t.Events.Sample,i),[2]}})})}),[{reportLabel:"peerConnection",type:"pcconnection"},{reportLabel:"ice",type:"iceconnection"},{reportLabel:"dtls",type:"dtlstransport"},{reportLabel:"signaling",type:"signaling"}].forEach(function(i){var o=i.type,u=i.reportLabel,c="on"+o+"statechange",a=e._mediaHandler[c];e._mediaHandler[c]=function(f){var I=n._networkTiming[u]=n._networkTiming[u]||{start:0};f==="connecting"||f==="checking"?I.start=Date.now():(f==="connected"||f==="stable")&&!I.duration&&(I.end=Date.now(),I.duration=I.end-I.start),a(f)}})},Object.defineProperty(t.prototype,"callSid",{get:function(){return this._callSid},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"endTime",{get:function(){return this._endTime},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"latestSample",{get:function(){return this._latestSample},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"report",{get:function(){return this._report},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this._startTime},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"status",{get:function(){return this._status},enumerable:!1,configurable:!0}),t}(b.EventEmitter);w.PreflightTest=s,function(g){(function(t){t.Excellent="excellent",t.Great="great",t.Good="good",t.Fair="fair",t.Degraded="degraded"})(g.CallQuality||(g.CallQuality={})),function(t){t.Completed="completed",t.Connected="connected",t.Failed="failed",t.Sample="sample",t.Warning="warning"}(g.Events||(g.Events={})),function(t){t.Connecting="connecting",t.Connected="connected",t.Completed="completed",t.Failed="failed"}(g.Status||(g.Status={}))}(s=w.PreflightTest||(w.PreflightTest={})),w.PreflightTest=s}(ee)),ee}var be={},ve={},Vt;function Qn(){return Vt||(Vt=1,function(w){var p=ve&&ve.__extends||function(){var i=function(o,u){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,a){c.__proto__=a}||function(c,a){for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(c[f]=a[f])},i(o,u)};return function(o,u){i(o,u);function c(){this.constructor=o}o.prototype=u===null?Object.create(u):(c.prototype=u.prototype,new c)}}(),r=ve&&ve.__assign||function(){return r=Object.assign||function(i){for(var o,u=1,c=arguments.length;u<c;u++){o=arguments[u];for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(i[a]=o[a])}return i},r.apply(this,arguments)};Object.defineProperty(w,"__esModule",{value:!0}),w.WSTransportState=void 0;var l=Z(),h=Ct(),b=$(),S=X(),m=globalThis.WebSocket,E=1e4,C=5e3,y=15e3,_=15e3,s=1/0,g=1e3,t=2e4,e;(function(i){i.Connecting="connecting",i.Closed="closed",i.Open="open"})(e=w.WSTransportState||(w.WSTransportState={}));var n=function(i){p(o,i);function o(u,c){c===void 0&&(c={});var a=i.call(this)||this;return a.state=e.Closed,a._backoffStartTime={preferred:null,primary:null},a._connectedUri=null,a._log=new S.default("WSTransport"),a._shouldFallback=!1,a._uriIndex=0,a._moveUriIndex=function(){a._uriIndex++,a._uriIndex>=a._uris.length&&(a._uriIndex=0)},a._onSocketClose=function(f){if(a._log.error("Received websocket close event code: "+f.code+". Reason: "+f.reason),f.code===1006||f.code===1015){a.emit("error",{code:31005,message:f.reason||"Websocket connection to Twilio's signaling servers were unexpectedly ended. If this is happening consistently, there may be an issue resolving the hostname provided. If a region or an edge is being specified in Device setup, ensure it is valid.",twilioError:new b.SignalingErrors.ConnectionError});var I=a.state===e.Open||a._previousState===e.Open;(a._shouldFallback||!I)&&a._moveUriIndex(),a._shouldFallback=!0}a._closeSocket()},a._onSocketError=function(f){a._log.error("WebSocket received error: "+f.message),a.emit("error",{code:31e3,message:f.message||"WSTransport socket error",twilioError:new b.SignalingErrors.ConnectionDisconnected})},a._onSocketMessage=function(f){if(a._setHeartbeatTimeout(),a._socket&&f.data===`
|
|
179
|
+
`){a._socket.send(`
|
|
180
|
+
`),a._log.debug("heartbeat");return}f&&typeof f.data=="string"&&a._log.debug("Received: "+f.data),a.emit("message",f)},a._onSocketOpen=function(){a._log.info("WebSocket opened successfully."),a._timeOpened=Date.now(),a._shouldFallback=!1,a._setState(e.Open),clearTimeout(a._connectTimeout),a._resetBackoffs(),a._setHeartbeatTimeout(),a.emit("open")},a._options=r(r({},o.defaultConstructorOptions),c),a._uris=u,a._backoff=a._setupBackoffs(),a}return o.prototype.close=function(){this._log.info("WSTransport.close() called..."),this._close()},o.prototype.open=function(){if(this._log.info("WSTransport.open() called..."),this._socket&&(this._socket.readyState===m.CONNECTING||this._socket.readyState===m.OPEN)){this._log.info("WebSocket already open.");return}this._preferredUri?this._connect(this._preferredUri):this._connect(this._uris[this._uriIndex])},o.prototype.send=function(u){if(this._log.debug("Sending: "+u),!this._socket||this._socket.readyState!==m.OPEN)return this._log.debug("Cannot send message. WebSocket is not open."),!1;try{this._socket.send(u)}catch(c){return this._log.error("Error while sending message:",c.message),this._closeSocket(),!1}return!0},o.prototype.updatePreferredURI=function(u){this._preferredUri=u},o.prototype.updateURIs=function(u){typeof u=="string"&&(u=[u]),this._uris=u,this._uriIndex=0},o.prototype._close=function(){this._setState(e.Closed),this._closeSocket()},o.prototype._closeSocket=function(){if(clearTimeout(this._connectTimeout),clearTimeout(this._heartbeatTimeout),this._log.info("Closing and cleaning up WebSocket..."),!this._socket){this._log.info("No WebSocket to clean up.");return}this._socket.removeEventListener("close",this._onSocketClose),this._socket.removeEventListener("error",this._onSocketError),this._socket.removeEventListener("message",this._onSocketMessage),this._socket.removeEventListener("open",this._onSocketOpen),(this._socket.readyState===m.CONNECTING||this._socket.readyState===m.OPEN)&&this._socket.close(),this._timeOpened&&Date.now()-this._timeOpened>E&&this._resetBackoffs(),this.state!==e.Closed&&this._performBackoff(),delete this._socket,this.emit("close")},o.prototype._connect=function(u,c){var a=this;this._log.info(typeof c=="number"?"Attempting to reconnect (retry #"+c+")...":"Attempting to connect..."),this._closeSocket(),this._setState(e.Connecting),this._connectedUri=u;try{this._socket=new this._options.WebSocket(this._connectedUri)}catch(f){this._log.error("Could not connect to endpoint:",f.message),this._close(),this.emit("error",{code:31e3,message:f.message||"Could not connect to "+this._connectedUri,twilioError:new b.SignalingErrors.ConnectionDisconnected});return}this._socket.addEventListener("close",this._onSocketClose),this._socket.addEventListener("error",this._onSocketError),this._socket.addEventListener("message",this._onSocketMessage),this._socket.addEventListener("open",this._onSocketOpen),delete this._timeOpened,this._connectTimeout=setTimeout(function(){a._log.info("WebSocket connection attempt timed out."),a._moveUriIndex(),a._closeSocket()},this._options.connectTimeoutMs)},o.prototype._performBackoff=function(){this._preferredUri?(this._log.info("Preferred URI set; backing off."),this._backoff.preferred.backoff()):(this._log.info("Preferred URI not set; backing off."),this._backoff.primary.backoff())},o.prototype._resetBackoffs=function(){this._backoff.preferred.reset(),this._backoff.primary.reset(),this._backoffStartTime.preferred=null,this._backoffStartTime.primary=null},o.prototype._setHeartbeatTimeout=function(){var u=this;clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=setTimeout(function(){u._log.info("No messages received in "+y/1e3+" seconds. Reconnecting..."),u._shouldFallback=!0,u._closeSocket()},y)},o.prototype._setState=function(u){this._previousState=this.state,this.state=u},o.prototype._setupBackoffs=function(){var u=this,c={factor:2,jitter:.4,max:this._options.maxPreferredDelayMs,min:100};this._log.info("Initializing preferred transport backoff using config: ",c);var a=new h.default(c);a.on("backoff",function(v,O){if(u.state===e.Closed){u._log.info("Preferred backoff initiated but transport state is closed; not attempting a connection.");return}u._log.info("Will attempt to reconnect Websocket to preferred URI in "+O+"ms"),v===0&&(u._backoffStartTime.preferred=Date.now(),u._log.info("Preferred backoff start; "+u._backoffStartTime.preferred))}),a.on("ready",function(v,O){if(u.state===e.Closed){u._log.info("Preferred backoff ready but transport state is closed; not attempting a connection.");return}if(u._backoffStartTime.preferred===null){u._log.info("Preferred backoff start time invalid; not attempting a connection.");return}if(Date.now()-u._backoffStartTime.preferred>u._options.maxPreferredDurationMs){u._log.info("Max preferred backoff attempt time exceeded; falling back to primary backoff."),u._preferredUri=null,u._backoff.primary.backoff();return}if(typeof u._preferredUri!="string"){u._log.info("Preferred URI cleared; falling back to primary backoff."),u._preferredUri=null,u._backoff.primary.backoff();return}u._connect(u._preferredUri,v+1)});var f={factor:2,jitter:.4,max:this._options.maxPrimaryDelayMs,min:this._uris&&this._uris.length>1?Math.floor(Math.random()*4001)+1e3:100};this._log.info("Initializing primary transport backoff using config: ",f);var I=new h.default(f);return I.on("backoff",function(v,O){if(u.state===e.Closed){u._log.info("Primary backoff initiated but transport state is closed; not attempting a connection.");return}u._log.info("Will attempt to reconnect WebSocket in "+O+"ms"),v===0&&(u._backoffStartTime.primary=Date.now(),u._log.info("Primary backoff start; "+u._backoffStartTime.primary))}),I.on("ready",function(v,O){if(u.state===e.Closed){u._log.info("Primary backoff ready but transport state is closed; not attempting a connection.");return}if(u._backoffStartTime.primary===null){u._log.info("Primary backoff start time invalid; not attempting a connection.");return}if(Date.now()-u._backoffStartTime.primary>u._options.maxPrimaryDurationMs){u._log.info("Max primary backoff attempt time exceeded; not attempting a connection.");return}u._connect(u._uris[u._uriIndex],v+1)}),{preferred:a,primary:I}},Object.defineProperty(o.prototype,"uri",{get:function(){return this._connectedUri},enumerable:!1,configurable:!0}),o.defaultConstructorOptions={WebSocket:m,connectTimeoutMs:C,maxPreferredDelayMs:g,maxPreferredDurationMs:_,maxPrimaryDelayMs:t,maxPrimaryDurationMs:s},o}(l.EventEmitter);w.default=n}(ve)),ve}var Gt;function Xn(){if(Gt)return be;Gt=1;var w=be&&be.__extends||function(){var y=function(_,s){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,t){g.__proto__=t}||function(g,t){for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&(g[e]=t[e])},y(_,s)};return function(_,s){y(_,s);function g(){this.constructor=_}_.prototype=s===null?Object.create(s):(g.prototype=s.prototype,new g)}}();Object.defineProperty(be,"__esModule",{value:!0});var p=Z(),r=_e(),l=$(),h=X(),b=Qn(),S="1.6",m=30,E=function(y){w(_,y);function _(s,g,t){var e=y.call(this)||this;if(!(e instanceof _))return new _(s,g,t);var n={TransportFactory:b.default};t=t||{};for(var i in n)i in t||(t[i]=n[i]);e.options=t,e.token=s||"",e.status="disconnected",e.gateway=null,e.region=null,e._messageQueue=[],e._preferredUri=null,e._uris=g,e._handleTransportClose=e._handleTransportClose.bind(e),e._handleTransportError=e._handleTransportError.bind(e),e._handleTransportMessage=e._handleTransportMessage.bind(e),e._handleTransportOpen=e._handleTransportOpen.bind(e),e._log=new h.default("PStream"),e.on("error",function(){e._log.warn("Unexpected error handled in pstream")});var o=e;return e.addListener("ready",function(){o.status="ready"}),e.addListener("offline",function(){o.status="offline"}),e.addListener("close",function(){o._log.info('Received "close" from server. Destroying PStream...'),o._destroy()}),e.transport=new e.options.TransportFactory(e._uris,{backoffMaxMs:e.options.backoffMaxMs,maxPreferredDurationMs:e.options.maxPreferredDurationMs}),Object.defineProperties(e,{uri:{enumerable:!0,get:function(){return this.transport.uri}}}),e.transport.on("close",e._handleTransportClose),e.transport.on("error",e._handleTransportError),e.transport.on("message",e._handleTransportMessage),e.transport.on("open",e._handleTransportOpen),e.transport.open(),e}return _}(p.EventEmitter);E.prototype._handleTransportClose=function(){this.emit("transportClose"),this.status!=="disconnected"&&(this.status!=="offline"&&this.emit("offline",this),this.status="disconnected")},E.prototype._handleTransportError=function(y){if(!y){this.emit("error",{error:{code:31e3,message:"Websocket closed without a provided reason",twilioError:new l.SignalingErrors.ConnectionDisconnected}});return}this.emit("error",typeof y.code<"u"?{error:y}:y)},E.prototype._handleTransportMessage=function(y){if(!(!y||!y.data||typeof y.data!="string")){var _=JSON.parse(y.data),s=_.type,g=_.payload,t=g===void 0?{}:g;this.gateway=t.gateway||this.gateway,this.region=t.region||this.region,s==="error"&&t.error&&(t.error.twilioError=new l.SignalingErrors.ConnectionError),this.emit(s,t)}},E.prototype._handleTransportOpen=function(){var y=this;this.status="connected",this.setToken(this.token),this.emit("transportOpen");var _=this._messageQueue.splice(0,this._messageQueue.length);_.forEach(function(s){return y._publish.apply(y,s)})},E.toString=function(){return"[Twilio.PStream class]"},E.prototype.toString=function(){return"[Twilio.PStream instance]"},E.prototype.setToken=function(y){this._log.info("Setting token and publishing listen"),this.token=y;var _=0,s=this.options.maxPreferredDurationMs;this._log.info("maxPreferredDurationMs:"+s),typeof s=="number"&&s>=0&&(_=Math.min(Math.ceil(s/1e3),m)),this._log.info("reconnectTimeout:"+_);var g={browserinfo:C(),reconnectTimeout:_,token:y};this._publish("listen",g)},E.prototype.sendMessage=function(y,_,s,g,t){s===void 0&&(s="application/json");var e={callsid:y,content:_,contenttype:s,messagetype:g,voiceeventsid:t};this._publish("message",e,!0)},E.prototype.register=function(y){var _={media:y};this._publish("register",_,!0)},E.prototype.invite=function(y,_,s){var g={callsid:_,sdp:y,twilio:s?{params:s}:{}};this._publish("invite",g,!0)},E.prototype.reconnect=function(y,_,s){var g={callsid:_,reconnect:s,sdp:y,twilio:{}};this._publish("invite",g,!0)},E.prototype.answer=function(y,_){this._publish("answer",{sdp:y,callsid:_},!0)},E.prototype.dtmf=function(y,_){this._publish("dtmf",{callsid:y,dtmf:_},!0)},E.prototype.hangup=function(y,_){var s=_?{callsid:y,message:_}:{callsid:y};this._publish("hangup",s,!0)},E.prototype.reject=function(y){this._publish("reject",{callsid:y},!0)},E.prototype.reinvite=function(y,_){this._publish("reinvite",{sdp:y,callsid:_},!1)},E.prototype._destroy=function(){this.transport.removeListener("close",this._handleTransportClose),this.transport.removeListener("error",this._handleTransportError),this.transport.removeListener("message",this._handleTransportMessage),this.transport.removeListener("open",this._handleTransportOpen),this.transport.close(),this.emit("offline",this)},E.prototype.destroy=function(){return this._log.info("PStream.destroy() called..."),this._destroy(),this},E.prototype.updatePreferredURI=function(y){this._preferredUri=y,this.transport.updatePreferredURI(y)},E.prototype.updateURIs=function(y){this._uris=y,this.transport.updateURIs(this._uris)},E.prototype.publish=function(y,_){return this._publish(y,_,!0)},E.prototype._publish=function(y,_,s){var g=JSON.stringify({payload:_,type:y,version:S}),t=!!this.transport.send(g);t||(this.emit("error",{error:{code:31009,message:"No transport available to send or receive messages",twilioError:new l.GeneralErrors.TransportError}}),s&&this._messageQueue.push([y,_,!0]))};function C(){var y=typeof navigator<"u"?navigator:{},_={browser:{platform:y.platform||"unknown",userAgent:y.userAgent||"unknown"},p:"browser",plugin:"rtc",v:r.RELEASE_VERSION};return _}return be.default=E,be}var et={},Ht;function Yn(){return Ht||(Ht=1,function(w){var p;Object.defineProperty(w,"__esModule",{value:!0}),w.getRegionShortcode=w.getChunderURIs=w.createSignalingEndpointURL=w.createEventGatewayURI=w.defaultEdge=w.regionToEdge=w.regionShortcodes=w.Region=w.Edge=void 0;var r=$(),l;(function(_){_.Sydney="sydney",_.SaoPaulo="sao-paulo",_.Dublin="dublin",_.Frankfurt="frankfurt",_.Tokyo="tokyo",_.Singapore="singapore",_.Ashburn="ashburn",_.Umatilla="umatilla",_.Roaming="roaming",_.AshburnIx="ashburn-ix",_.SanJoseIx="san-jose-ix",_.LondonIx="london-ix",_.FrankfurtIx="frankfurt-ix",_.SingaporeIx="singapore-ix",_.SydneyIx="sydney-ix",_.TokyoIx="tokyo-ix"})(l=w.Edge||(w.Edge={}));var h;(function(_){_.Au1="au1",_.Au1Ix="au1-ix",_.Br1="br1",_.De1="de1",_.De1Ix="de1-ix",_.Gll="gll",_.Ie1="ie1",_.Ie1Ix="ie1-ix",_.Ie1Tnx="ie1-tnx",_.Jp1="jp1",_.Jp1Ix="jp1-ix",_.Sg1="sg1",_.Sg1Ix="sg1-ix",_.Sg1Tnx="sg1-tnx",_.Us1="us1",_.Us1Ix="us1-ix",_.Us1Tnx="us1-tnx",_.Us2="us2",_.Us2Ix="us2-ix",_.Us2Tnx="us2-tnx"})(h=w.Region||(w.Region={})),w.regionShortcodes={ASIAPAC_SINGAPORE:h.Sg1,ASIAPAC_SYDNEY:h.Au1,ASIAPAC_TOKYO:h.Jp1,EU_FRANKFURT:h.De1,EU_IRELAND:h.Ie1,SOUTH_AMERICA_SAO_PAULO:h.Br1,US_EAST_VIRGINIA:h.Us1,US_WEST_OREGON:h.Us2},w.regionToEdge=(p={},p[h.Au1]=l.Sydney,p[h.Br1]=l.SaoPaulo,p[h.Ie1]=l.Dublin,p[h.De1]=l.Frankfurt,p[h.Jp1]=l.Tokyo,p[h.Sg1]=l.Singapore,p[h.Us1]=l.Ashburn,p[h.Us2]=l.Umatilla,p[h.Gll]=l.Roaming,p[h.Us1Ix]=l.AshburnIx,p[h.Us2Ix]=l.SanJoseIx,p[h.Ie1Ix]=l.LondonIx,p[h.De1Ix]=l.FrankfurtIx,p[h.Sg1Ix]=l.SingaporeIx,p[h.Au1Ix]=l.SydneyIx,p[h.Jp1Ix]=l.TokyoIx,p[h.Us1Tnx]=l.AshburnIx,p[h.Us2Tnx]=l.AshburnIx,p[h.Ie1Tnx]=l.LondonIx,p[h.Sg1Tnx]=l.SingaporeIx,p),w.defaultEdge=l.Roaming;var b="eventgw.twilio.com";function S(_){return"voice-js."+_+".twilio.com"}function m(_){return _?"eventgw."+_+".twilio.com":b}w.createEventGatewayURI=m;function E(_){return"wss://"+_+"/signal"}w.createSignalingEndpointURL=E;function C(_){if(_&&typeof _!="string"&&!Array.isArray(_))throw new r.InvalidArgumentError("If `edge` is provided, it must be of type `string` or an array of strings.");var s;if(_){var g=Array.isArray(_)?_:[_];s=g.map(function(t){return S(t)})}else s=[S(w.defaultEdge)];return s}w.getChunderURIs=C;function y(_){return w.regionShortcodes[_]||null}w.getRegionShortcode=y}(et)),et}var ae={},Fe={},qe={},te={},$t;function tt(){if($t)return te;$t=1,Object.defineProperty(te,"__esModule",{value:!0}),te.setMaxAverageBitrate=te.setIceAggressiveNomination=te.setCodecPreferences=te.getPreferredCodecInfo=void 0;var w=fe(),p={0:"PCMU",8:"PCMA"},r=111,l=51e4,h=6e3;function b(e){var n=/a=rtpmap:(\d+) (\S+)/m.exec(e)||[null,"",""],i=n[1],o=n[2],u=new RegExp("a=fmtp:"+i+" (\\S+)","m"),c=u.exec(e)||[null,""],a=c[1];return{codecName:o,codecParams:a}}te.getPreferredCodecInfo=b;function S(e){return w.isChrome(window,window.navigator)?e.split(`
|
|
181
|
+
`).filter(function(n){return n.indexOf("a=ice-lite")===-1}).join(`
|
|
182
|
+
`):e}te.setIceAggressiveNomination=S;function m(e,n){if(typeof n!="number"||n<h||n>l)return e;var i=/a=rtpmap:(\d+) opus/m.exec(e),o=i&&i.length?i[1]:r,u=new RegExp("a=fmtp:"+o),c=e.split(`
|
|
183
|
+
`).map(function(a){return u.test(a)?a+(";maxaveragebitrate="+n):a});return c.join(`
|
|
184
|
+
`)}te.setMaxAverageBitrate=m;function E(e,n){var i=C(e),o=e.split(`\r
|
|
185
|
+
m=`)[0];return[o].concat(i.map(function(u){if(!/^m=(audio|video)/.test(u))return u;var c=u.match(/^m=(audio|video)/)[1],a=y(u),f=_(a,n),I=s(f,u),v=a.get("pcma")||[],O=a.get("pcmu")||[],T=c==="audio"?new Set(v.concat(O)):new Set;return T.has(f[0])?I.replace(/\r\nb=(AS|TIAS):([0-9]+)/g,""):I})).join(`\r
|
|
186
|
+
`)}te.setCodecPreferences=E;function C(e,n,i){return e.replace(/\r\n\r\n$/,`\r
|
|
187
|
+
`).split(`\r
|
|
188
|
+
m=`).slice(1).map(function(o){return"m="+o}).filter(function(o){var u=new RegExp("m=.*","gm"),c=new RegExp("a=.*","gm");return u.test(o)&&c.test(o)})}function y(e){return Array.from(g(e)).reduce(function(n,i){var o=i[0],u=i[1],c=n.get(u)||[];return n.set(u,c.concat(o))},new Map)}function _(e,n){n=n.map(function(c){return c.toLowerCase()});var i=w.flatMap(n,function(c){return e.get(c)||[]}),o=w.difference(Array.from(e.keys()),n),u=w.flatMap(o,function(c){return e.get(c)});return i.concat(u)}function s(e,n){var i=n.split(`\r
|
|
189
|
+
`),o=i[0],u=i.slice(1);return o=o.replace(/([0-9]+\s?)+$/,e.join(" ")),[o].concat(u).join(`\r
|
|
190
|
+
`)}function g(e){return t(e).reduce(function(n,i){var o=new RegExp("a=rtpmap:"+i+" ([^/]+)"),u=e.match(o),c=u?u[1].toLowerCase():p[i]?p[i].toLowerCase():"";return n.set(i,c)},new Map)}function t(e){var n=e.split(`\r
|
|
191
|
+
`)[0],i=n.match(/([0-9]+)/g);return i?i.slice(1).map(function(o){return parseInt(o,10)}):[]}return te}var nt={exports:{}},zt;function Zn(){return zt||(zt=1,function(w){var p={};p.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)},p.localCName=p.generateIdentifier(),p.splitLines=function(r){return r.trim().split(`
|
|
192
|
+
`).map(function(l){return l.trim()})},p.splitSections=function(r){var l=r.split(`
|
|
193
|
+
m=`);return l.map(function(h,b){return(b>0?"m="+h:h).trim()+`\r
|
|
194
|
+
`})},p.getDescription=function(r){var l=p.splitSections(r);return l&&l[0]},p.getMediaSections=function(r){var l=p.splitSections(r);return l.shift(),l},p.matchPrefix=function(r,l){return p.splitLines(r).filter(function(h){return h.indexOf(l)===0})},p.parseCandidate=function(r){var l;r.indexOf("a=candidate:")===0?l=r.substring(12).split(" "):l=r.substring(10).split(" ");for(var h={foundation:l[0],component:parseInt(l[1],10),protocol:l[2].toLowerCase(),priority:parseInt(l[3],10),ip:l[4],address:l[4],port:parseInt(l[5],10),type:l[7]},b=8;b<l.length;b+=2)switch(l[b]){case"raddr":h.relatedAddress=l[b+1];break;case"rport":h.relatedPort=parseInt(l[b+1],10);break;case"tcptype":h.tcpType=l[b+1];break;case"ufrag":h.ufrag=l[b+1],h.usernameFragment=l[b+1];break;default:h[l[b]]=l[b+1];break}return h},p.writeCandidate=function(r){var l=[];l.push(r.foundation),l.push(r.component),l.push(r.protocol.toUpperCase()),l.push(r.priority),l.push(r.address||r.ip),l.push(r.port);var h=r.type;return l.push("typ"),l.push(h),h!=="host"&&r.relatedAddress&&r.relatedPort&&(l.push("raddr"),l.push(r.relatedAddress),l.push("rport"),l.push(r.relatedPort)),r.tcpType&&r.protocol.toLowerCase()==="tcp"&&(l.push("tcptype"),l.push(r.tcpType)),(r.usernameFragment||r.ufrag)&&(l.push("ufrag"),l.push(r.usernameFragment||r.ufrag)),"candidate:"+l.join(" ")},p.parseIceOptions=function(r){return r.substr(14).split(" ")},p.parseRtpMap=function(r){var l=r.substr(9).split(" "),h={payloadType:parseInt(l.shift(),10)};return l=l[0].split("/"),h.name=l[0],h.clockRate=parseInt(l[1],10),h.channels=l.length===3?parseInt(l[2],10):1,h.numChannels=h.channels,h},p.writeRtpMap=function(r){var l=r.payloadType;r.preferredPayloadType!==void 0&&(l=r.preferredPayloadType);var h=r.channels||r.numChannels||1;return"a=rtpmap:"+l+" "+r.name+"/"+r.clockRate+(h!==1?"/"+h:"")+`\r
|
|
195
|
+
`},p.parseExtmap=function(r){var l=r.substr(9).split(" ");return{id:parseInt(l[0],10),direction:l[0].indexOf("/")>0?l[0].split("/")[1]:"sendrecv",uri:l[1]}},p.writeExtmap=function(r){return"a=extmap:"+(r.id||r.preferredId)+(r.direction&&r.direction!=="sendrecv"?"/"+r.direction:"")+" "+r.uri+`\r
|
|
196
|
+
`},p.parseFmtp=function(r){for(var l={},h,b=r.substr(r.indexOf(" ")+1).split(";"),S=0;S<b.length;S++)h=b[S].trim().split("="),l[h[0].trim()]=h[1];return l},p.writeFmtp=function(r){var l="",h=r.payloadType;if(r.preferredPayloadType!==void 0&&(h=r.preferredPayloadType),r.parameters&&Object.keys(r.parameters).length){var b=[];Object.keys(r.parameters).forEach(function(S){r.parameters[S]?b.push(S+"="+r.parameters[S]):b.push(S)}),l+="a=fmtp:"+h+" "+b.join(";")+`\r
|
|
197
|
+
`}return l},p.parseRtcpFb=function(r){var l=r.substr(r.indexOf(" ")+1).split(" ");return{type:l.shift(),parameter:l.join(" ")}},p.writeRtcpFb=function(r){var l="",h=r.payloadType;return r.preferredPayloadType!==void 0&&(h=r.preferredPayloadType),r.rtcpFeedback&&r.rtcpFeedback.length&&r.rtcpFeedback.forEach(function(b){l+="a=rtcp-fb:"+h+" "+b.type+(b.parameter&&b.parameter.length?" "+b.parameter:"")+`\r
|
|
198
|
+
`}),l},p.parseSsrcMedia=function(r){var l=r.indexOf(" "),h={ssrc:parseInt(r.substr(7,l-7),10)},b=r.indexOf(":",l);return b>-1?(h.attribute=r.substr(l+1,b-l-1),h.value=r.substr(b+1)):h.attribute=r.substr(l+1),h},p.parseSsrcGroup=function(r){var l=r.substr(13).split(" ");return{semantics:l.shift(),ssrcs:l.map(function(h){return parseInt(h,10)})}},p.getMid=function(r){var l=p.matchPrefix(r,"a=mid:")[0];if(l)return l.substr(6)},p.parseFingerprint=function(r){var l=r.substr(14).split(" ");return{algorithm:l[0].toLowerCase(),value:l[1]}},p.getDtlsParameters=function(r,l){var h=p.matchPrefix(r+l,"a=fingerprint:");return{role:"auto",fingerprints:h.map(p.parseFingerprint)}},p.writeDtlsParameters=function(r,l){var h="a=setup:"+l+`\r
|
|
199
|
+
`;return r.fingerprints.forEach(function(b){h+="a=fingerprint:"+b.algorithm+" "+b.value+`\r
|
|
200
|
+
`}),h},p.parseCryptoLine=function(r){var l=r.substr(9).split(" ");return{tag:parseInt(l[0],10),cryptoSuite:l[1],keyParams:l[2],sessionParams:l.slice(3)}},p.writeCryptoLine=function(r){return"a=crypto:"+r.tag+" "+r.cryptoSuite+" "+(typeof r.keyParams=="object"?p.writeCryptoKeyParams(r.keyParams):r.keyParams)+(r.sessionParams?" "+r.sessionParams.join(" "):"")+`\r
|
|
201
|
+
`},p.parseCryptoKeyParams=function(r){if(r.indexOf("inline:")!==0)return null;var l=r.substr(7).split("|");return{keyMethod:"inline",keySalt:l[0],lifeTime:l[1],mkiValue:l[2]?l[2].split(":")[0]:void 0,mkiLength:l[2]?l[2].split(":")[1]:void 0}},p.writeCryptoKeyParams=function(r){return r.keyMethod+":"+r.keySalt+(r.lifeTime?"|"+r.lifeTime:"")+(r.mkiValue&&r.mkiLength?"|"+r.mkiValue+":"+r.mkiLength:"")},p.getCryptoParameters=function(r,l){var h=p.matchPrefix(r+l,"a=crypto:");return h.map(p.parseCryptoLine)},p.getIceParameters=function(r,l){var h=p.matchPrefix(r+l,"a=ice-ufrag:")[0],b=p.matchPrefix(r+l,"a=ice-pwd:")[0];return h&&b?{usernameFragment:h.substr(12),password:b.substr(10)}:null},p.writeIceParameters=function(r){return"a=ice-ufrag:"+r.usernameFragment+`\r
|
|
202
|
+
a=ice-pwd:`+r.password+`\r
|
|
203
|
+
`},p.parseRtpParameters=function(r){for(var l={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},h=p.splitLines(r),b=h[0].split(" "),S=3;S<b.length;S++){var m=b[S],E=p.matchPrefix(r,"a=rtpmap:"+m+" ")[0];if(E){var C=p.parseRtpMap(E),y=p.matchPrefix(r,"a=fmtp:"+m+" ");switch(C.parameters=y.length?p.parseFmtp(y[0]):{},C.rtcpFeedback=p.matchPrefix(r,"a=rtcp-fb:"+m+" ").map(p.parseRtcpFb),l.codecs.push(C),C.name.toUpperCase()){case"RED":case"ULPFEC":l.fecMechanisms.push(C.name.toUpperCase());break}}}return p.matchPrefix(r,"a=extmap:").forEach(function(_){l.headerExtensions.push(p.parseExtmap(_))}),l},p.writeRtpDescription=function(r,l){var h="";h+="m="+r+" ",h+=l.codecs.length>0?"9":"0",h+=" UDP/TLS/RTP/SAVPF ",h+=l.codecs.map(function(S){return S.preferredPayloadType!==void 0?S.preferredPayloadType:S.payloadType}).join(" ")+`\r
|
|
204
|
+
`,h+=`c=IN IP4 0.0.0.0\r
|
|
205
|
+
`,h+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
206
|
+
`,l.codecs.forEach(function(S){h+=p.writeRtpMap(S),h+=p.writeFmtp(S),h+=p.writeRtcpFb(S)});var b=0;return l.codecs.forEach(function(S){S.maxptime>b&&(b=S.maxptime)}),b>0&&(h+="a=maxptime:"+b+`\r
|
|
207
|
+
`),h+=`a=rtcp-mux\r
|
|
208
|
+
`,l.headerExtensions&&l.headerExtensions.forEach(function(S){h+=p.writeExtmap(S)}),h},p.parseRtpEncodingParameters=function(r){var l=[],h=p.parseRtpParameters(r),b=h.fecMechanisms.indexOf("RED")!==-1,S=h.fecMechanisms.indexOf("ULPFEC")!==-1,m=p.matchPrefix(r,"a=ssrc:").map(function(s){return p.parseSsrcMedia(s)}).filter(function(s){return s.attribute==="cname"}),E=m.length>0&&m[0].ssrc,C,y=p.matchPrefix(r,"a=ssrc-group:FID").map(function(s){var g=s.substr(17).split(" ");return g.map(function(t){return parseInt(t,10)})});y.length>0&&y[0].length>1&&y[0][0]===E&&(C=y[0][1]),h.codecs.forEach(function(s){if(s.name.toUpperCase()==="RTX"&&s.parameters.apt){var g={ssrc:E,codecPayloadType:parseInt(s.parameters.apt,10)};E&&C&&(g.rtx={ssrc:C}),l.push(g),b&&(g=JSON.parse(JSON.stringify(g)),g.fec={ssrc:E,mechanism:S?"red+ulpfec":"red"},l.push(g))}}),l.length===0&&E&&l.push({ssrc:E});var _=p.matchPrefix(r,"b=");return _.length&&(_[0].indexOf("b=TIAS:")===0?_=parseInt(_[0].substr(7),10):_[0].indexOf("b=AS:")===0?_=parseInt(_[0].substr(5),10)*1e3*.95-50*40*8:_=void 0,l.forEach(function(s){s.maxBitrate=_})),l},p.parseRtcpParameters=function(r){var l={},h=p.matchPrefix(r,"a=ssrc:").map(function(m){return p.parseSsrcMedia(m)}).filter(function(m){return m.attribute==="cname"})[0];h&&(l.cname=h.value,l.ssrc=h.ssrc);var b=p.matchPrefix(r,"a=rtcp-rsize");l.reducedSize=b.length>0,l.compound=b.length===0;var S=p.matchPrefix(r,"a=rtcp-mux");return l.mux=S.length>0,l},p.parseMsid=function(r){var l,h=p.matchPrefix(r,"a=msid:");if(h.length===1)return l=h[0].substr(7).split(" "),{stream:l[0],track:l[1]};var b=p.matchPrefix(r,"a=ssrc:").map(function(S){return p.parseSsrcMedia(S)}).filter(function(S){return S.attribute==="msid"});if(b.length>0)return l=b[0].value.split(" "),{stream:l[0],track:l[1]}},p.parseSctpDescription=function(r){var l=p.parseMLine(r),h=p.matchPrefix(r,"a=max-message-size:"),b;h.length>0&&(b=parseInt(h[0].substr(19),10)),isNaN(b)&&(b=65536);var S=p.matchPrefix(r,"a=sctp-port:");if(S.length>0)return{port:parseInt(S[0].substr(12),10),protocol:l.fmt,maxMessageSize:b};var m=p.matchPrefix(r,"a=sctpmap:");if(m.length>0){var E=p.matchPrefix(r,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(E[0],10),protocol:E[1],maxMessageSize:b}}},p.writeSctpDescription=function(r,l){var h=[];return r.protocol!=="DTLS/SCTP"?h=["m="+r.kind+" 9 "+r.protocol+" "+l.protocol+`\r
|
|
209
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
210
|
+
`,"a=sctp-port:"+l.port+`\r
|
|
211
|
+
`]:h=["m="+r.kind+" 9 "+r.protocol+" "+l.port+`\r
|
|
212
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
213
|
+
`,"a=sctpmap:"+l.port+" "+l.protocol+` 65535\r
|
|
214
|
+
`],l.maxMessageSize!==void 0&&h.push("a=max-message-size:"+l.maxMessageSize+`\r
|
|
215
|
+
`),h.join("")},p.generateSessionId=function(){return Math.random().toString().substr(2,21)},p.writeSessionBoilerplate=function(r,l,h){var b,S=l!==void 0?l:2;r?b=r:b=p.generateSessionId();var m=h||"thisisadapterortc";return`v=0\r
|
|
216
|
+
o=`+m+" "+b+" "+S+` IN IP4 127.0.0.1\r
|
|
217
|
+
s=-\r
|
|
218
|
+
t=0 0\r
|
|
219
|
+
`},p.writeMediaSection=function(r,l,h,b){var S=p.writeRtpDescription(r.kind,l);if(S+=p.writeIceParameters(r.iceGatherer.getLocalParameters()),S+=p.writeDtlsParameters(r.dtlsTransport.getLocalParameters(),h==="offer"?"actpass":"active"),S+="a=mid:"+r.mid+`\r
|
|
220
|
+
`,r.direction?S+="a="+r.direction+`\r
|
|
221
|
+
`:r.rtpSender&&r.rtpReceiver?S+=`a=sendrecv\r
|
|
222
|
+
`:r.rtpSender?S+=`a=sendonly\r
|
|
223
|
+
`:r.rtpReceiver?S+=`a=recvonly\r
|
|
224
|
+
`:S+=`a=inactive\r
|
|
225
|
+
`,r.rtpSender){var m="msid:"+b.id+" "+r.rtpSender.track.id+`\r
|
|
226
|
+
`;S+="a="+m,S+="a=ssrc:"+r.sendEncodingParameters[0].ssrc+" "+m,r.sendEncodingParameters[0].rtx&&(S+="a=ssrc:"+r.sendEncodingParameters[0].rtx.ssrc+" "+m,S+="a=ssrc-group:FID "+r.sendEncodingParameters[0].ssrc+" "+r.sendEncodingParameters[0].rtx.ssrc+`\r
|
|
227
|
+
`)}return S+="a=ssrc:"+r.sendEncodingParameters[0].ssrc+" cname:"+p.localCName+`\r
|
|
228
|
+
`,r.rtpSender&&r.sendEncodingParameters[0].rtx&&(S+="a=ssrc:"+r.sendEncodingParameters[0].rtx.ssrc+" cname:"+p.localCName+`\r
|
|
229
|
+
`),S},p.getDirection=function(r,l){for(var h=p.splitLines(r),b=0;b<h.length;b++)switch(h[b]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return h[b].substr(2)}return l?p.getDirection(l):"sendrecv"},p.getKind=function(r){var l=p.splitLines(r),h=l[0].split(" ");return h[0].substr(2)},p.isRejected=function(r){return r.split(" ",2)[1]==="0"},p.parseMLine=function(r){var l=p.splitLines(r),h=l[0].substr(2).split(" ");return{kind:h[0],port:parseInt(h[1],10),protocol:h[2],fmt:h.slice(3).join(" ")}},p.parseOLine=function(r){var l=p.matchPrefix(r,"o=")[0],h=l.substr(2).split(" ");return{username:h[0],sessionId:h[1],sessionVersion:parseInt(h[2],10),netType:h[3],addressType:h[4],address:h[5]}},p.isValidSDP=function(r){if(typeof r!="string"||r.length===0)return!1;for(var l=p.splitLines(r),h=0;h<l.length;h++)if(l[h].length<2||l[h].charAt(1)!=="=")return!1;return!0},w.exports=p}(nt)),nt.exports}var rt,Jt;function er(){if(Jt)return rt;Jt=1;var w=Zn();function p(m,E,C,y,_){var s=w.writeRtpDescription(m.kind,E);if(s+=w.writeIceParameters(m.iceGatherer.getLocalParameters()),s+=w.writeDtlsParameters(m.dtlsTransport.getLocalParameters(),C==="offer"?"actpass":_||"active"),s+="a=mid:"+m.mid+`\r
|
|
230
|
+
`,m.rtpSender&&m.rtpReceiver?s+=`a=sendrecv\r
|
|
231
|
+
`:m.rtpSender?s+=`a=sendonly\r
|
|
232
|
+
`:m.rtpReceiver?s+=`a=recvonly\r
|
|
233
|
+
`:s+=`a=inactive\r
|
|
234
|
+
`,m.rtpSender){var g=m.rtpSender._initialTrackId||m.rtpSender.track.id;m.rtpSender._initialTrackId=g;var t="msid:"+(y?y.id:"-")+" "+g+`\r
|
|
235
|
+
`;s+="a="+t,s+="a=ssrc:"+m.sendEncodingParameters[0].ssrc+" "+t,m.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+m.sendEncodingParameters[0].rtx.ssrc+" "+t,s+="a=ssrc-group:FID "+m.sendEncodingParameters[0].ssrc+" "+m.sendEncodingParameters[0].rtx.ssrc+`\r
|
|
236
|
+
`)}return s+="a=ssrc:"+m.sendEncodingParameters[0].ssrc+" cname:"+w.localCName+`\r
|
|
237
|
+
`,m.rtpSender&&m.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+m.sendEncodingParameters[0].rtx.ssrc+" cname:"+w.localCName+`\r
|
|
238
|
+
`),s}function r(m,E){var C=!1;return m=JSON.parse(JSON.stringify(m)),m.filter(function(y){if(y&&(y.urls||y.url)){var _=y.urls||y.url;y.url&&!y.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s=typeof _=="string";return s&&(_=[_]),_=_.filter(function(g){var t=g.indexOf("turn:")===0&&g.indexOf("transport=udp")!==-1&&g.indexOf("turn:[")===-1&&!C;return t?(C=!0,!0):g.indexOf("stun:")===0&&E>=14393&&g.indexOf("?transport=udp")===-1}),delete y.url,y.urls=s?_[0]:_,!!_.length}})}function l(m,E){var C={codecs:[],headerExtensions:[],fecMechanisms:[]},y=function(s,g){s=parseInt(s,10);for(var t=0;t<g.length;t++)if(g[t].payloadType===s||g[t].preferredPayloadType===s)return g[t]},_=function(s,g,t,e){var n=y(s.parameters.apt,t),i=y(g.parameters.apt,e);return n&&i&&n.name.toLowerCase()===i.name.toLowerCase()};return m.codecs.forEach(function(s){for(var g=0;g<E.codecs.length;g++){var t=E.codecs[g];if(s.name.toLowerCase()===t.name.toLowerCase()&&s.clockRate===t.clockRate){if(s.name.toLowerCase()==="rtx"&&s.parameters&&t.parameters.apt&&!_(s,t,m.codecs,E.codecs))continue;t=JSON.parse(JSON.stringify(t)),t.numChannels=Math.min(s.numChannels,t.numChannels),C.codecs.push(t),t.rtcpFeedback=t.rtcpFeedback.filter(function(e){for(var n=0;n<s.rtcpFeedback.length;n++)if(s.rtcpFeedback[n].type===e.type&&s.rtcpFeedback[n].parameter===e.parameter)return!0;return!1});break}}}),m.headerExtensions.forEach(function(s){for(var g=0;g<E.headerExtensions.length;g++){var t=E.headerExtensions[g];if(s.uri===t.uri){C.headerExtensions.push(t);break}}}),C}function h(m,E,C){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[E][m].indexOf(C)!==-1}function b(m,E){var C=m.getRemoteCandidates().find(function(y){return E.foundation===y.foundation&&E.ip===y.ip&&E.port===y.port&&E.priority===y.priority&&E.protocol===y.protocol&&E.type===y.type});return C||m.addRemoteCandidate(E),!C}function S(m,E){var C=new Error(E);return C.name=m,C}return rt=function(m,E){function C(t,e){e.addTrack(t),e.dispatchEvent(new m.MediaStreamTrackEvent("addtrack",{track:t}))}function y(t,e){e.removeTrack(t),e.dispatchEvent(new m.MediaStreamTrackEvent("removetrack",{track:t}))}function _(t,e,n,i){var o=new Event("track");o.track=e,o.receiver=n,o.transceiver={receiver:n},o.streams=i,m.setTimeout(function(){t._dispatchEvent("track",o)})}var s=function(t){var e=this,n=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(o){e[o]=n[o].bind(n)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this.localDescription=null,this.remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.iceGatheringState="new",t=JSON.parse(JSON.stringify(t||{})),this.usingBundle=t.bundlePolicy==="max-bundle",t.rtcpMuxPolicy==="negotiate")throw S("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(t.rtcpMuxPolicy||(t.rtcpMuxPolicy="require"),t.iceTransportPolicy){case"all":case"relay":break;default:t.iceTransportPolicy="all";break}switch(t.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:t.bundlePolicy="balanced";break}if(t.iceServers=r(t.iceServers||[],E),this._iceGatherers=[],t.iceCandidatePoolSize)for(var i=t.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new m.RTCIceGatherer({iceServers:t.iceServers,gatherPolicy:t.iceTransportPolicy}));else t.iceCandidatePoolSize=0;this._config=t,this.transceivers=[],this._sdpSessionId=w.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(t,e){this._isClosed||(this.dispatchEvent(e),typeof this["on"+t]=="function"&&this["on"+t](e))},s.prototype._emitGatheringStateChange=function(){var t=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",t)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(t){var e=this.transceivers.length>0,n={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:t,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&e)n.iceTransport=this.transceivers[0].iceTransport,n.dtlsTransport=this.transceivers[0].dtlsTransport;else{var i=this._createIceAndDtlsTransports();n.iceTransport=i.iceTransport,n.dtlsTransport=i.dtlsTransport}return this.transceivers.push(n),n},s.prototype.addTrack=function(t,e){if(this._isClosed)throw S("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var n=this.transceivers.find(function(u){return u.track===t});if(n)throw S("InvalidAccessError","Track already exists.");for(var i,o=0;o<this.transceivers.length;o++)!this.transceivers[o].track&&this.transceivers[o].kind===t.kind&&(i=this.transceivers[o]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(e)===-1&&this.localStreams.push(e),i.track=t,i.stream=e,i.rtpSender=new m.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},s.prototype.addStream=function(t){var e=this;if(E>=15025)t.getTracks().forEach(function(i){e.addTrack(i,t)});else{var n=t.clone();t.getTracks().forEach(function(i,o){var u=n.getTracks()[o];i.addEventListener("enabled",function(c){u.enabled=c.enabled})}),n.getTracks().forEach(function(i){e.addTrack(i,n)})}},s.prototype.removeTrack=function(t){if(this._isClosed)throw S("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof m.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var e=this.transceivers.find(function(o){return o.rtpSender===t});if(!e)throw S("InvalidAccessError","Sender was not created by this connection.");var n=e.stream;e.rtpSender.stop(),e.rtpSender=null,e.track=null,e.stream=null;var i=this.transceivers.map(function(o){return o.stream});i.indexOf(n)===-1&&this.localStreams.indexOf(n)>-1&&this.localStreams.splice(this.localStreams.indexOf(n),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(t){var e=this;t.getTracks().forEach(function(n){var i=e.getSenders().find(function(o){return o.track===n});i&&e.removeTrack(i)})},s.prototype.getSenders=function(){return this.transceivers.filter(function(t){return!!t.rtpSender}).map(function(t){return t.rtpSender})},s.prototype.getReceivers=function(){return this.transceivers.filter(function(t){return!!t.rtpReceiver}).map(function(t){return t.rtpReceiver})},s.prototype._createIceGatherer=function(t,e){var n=this;if(e&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var i=new m.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(i,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(o){var u=!o.candidate||Object.keys(o.candidate).length===0;i.state=u?"completed":"gathering",n.transceivers[t].bufferedCandidateEvents!==null&&n.transceivers[t].bufferedCandidateEvents.push(o)},i.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),i},s.prototype._gather=function(t,e){var n=this,i=this.transceivers[e].iceGatherer;if(!i.onlocalcandidate){var o=this.transceivers[e].bufferedCandidateEvents;this.transceivers[e].bufferedCandidateEvents=null,i.removeEventListener("localcandidate",this.transceivers[e].bufferCandidates),i.onlocalcandidate=function(u){if(!(n.usingBundle&&e>0)){var c=new Event("icecandidate");c.candidate={sdpMid:t,sdpMLineIndex:e};var a=u.candidate,f=!a||Object.keys(a).length===0;if(f)(i.state==="new"||i.state==="gathering")&&(i.state="completed");else{i.state==="new"&&(i.state="gathering"),a.component=1;var I=w.writeCandidate(a);c.candidate=Object.assign(c.candidate,w.parseCandidate(I)),c.candidate.candidate=I}var v=w.getMediaSections(n.localDescription.sdp);f?v[c.candidate.sdpMLineIndex]+=`a=end-of-candidates\r
|
|
239
|
+
`:v[c.candidate.sdpMLineIndex]+="a="+c.candidate.candidate+`\r
|
|
240
|
+
`,n.localDescription.sdp=w.getDescription(n.localDescription.sdp)+v.join("");var O=n.transceivers.every(function(T){return T.iceGatherer&&T.iceGatherer.state==="completed"});n.iceGatheringState!=="gathering"&&(n.iceGatheringState="gathering",n._emitGatheringStateChange()),f||n._dispatchEvent("icecandidate",c),O&&(n._dispatchEvent("icecandidate",new Event("icecandidate")),n.iceGatheringState="complete",n._emitGatheringStateChange())}},m.setTimeout(function(){o.forEach(function(u){i.onlocalcandidate(u)})},0)}},s.prototype._createIceAndDtlsTransports=function(){var t=this,e=new m.RTCIceTransport(null);e.onicestatechange=function(){t._updateConnectionState()};var n=new m.RTCDtlsTransport(e);return n.ondtlsstatechange=function(){t._updateConnectionState()},n.onerror=function(){Object.defineProperty(n,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:e,dtlsTransport:n}},s.prototype._disposeIceAndDtlsTransports=function(t){var e=this.transceivers[t].iceGatherer;e&&(delete e.onlocalcandidate,delete this.transceivers[t].iceGatherer);var n=this.transceivers[t].iceTransport;n&&(delete n.onicestatechange,delete this.transceivers[t].iceTransport);var i=this.transceivers[t].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[t].dtlsTransport)},s.prototype._transceive=function(t,e,n){var i=l(t.localCapabilities,t.remoteCapabilities);e&&t.rtpSender&&(i.encodings=t.sendEncodingParameters,i.rtcp={cname:w.localCName,compound:t.rtcpParameters.compound},t.recvEncodingParameters.length&&(i.rtcp.ssrc=t.recvEncodingParameters[0].ssrc),t.rtpSender.send(i)),n&&t.rtpReceiver&&i.codecs.length>0&&(t.kind==="video"&&t.recvEncodingParameters&&E<15019&&t.recvEncodingParameters.forEach(function(o){delete o.rtx}),t.recvEncodingParameters.length?i.encodings=t.recvEncodingParameters:i.encodings=[{}],i.rtcp={compound:t.rtcpParameters.compound},t.rtcpParameters.cname&&(i.rtcp.cname=t.rtcpParameters.cname),t.sendEncodingParameters.length&&(i.rtcp.ssrc=t.sendEncodingParameters[0].ssrc),t.rtpReceiver.receive(i))},s.prototype.setLocalDescription=function(t){var e=this;if(["offer","answer"].indexOf(t.type)===-1)return Promise.reject(S("TypeError",'Unsupported type "'+t.type+'"'));if(!h("setLocalDescription",t.type,e.signalingState)||e._isClosed)return Promise.reject(S("InvalidStateError","Can not set local "+t.type+" in state "+e.signalingState));var n,i;if(t.type==="offer")n=w.splitSections(t.sdp),i=n.shift(),n.forEach(function(u,c){var a=w.parseRtpParameters(u);e.transceivers[c].localCapabilities=a}),e.transceivers.forEach(function(u,c){e._gather(u.mid,c)});else if(t.type==="answer"){n=w.splitSections(e.remoteDescription.sdp),i=n.shift();var o=w.matchPrefix(i,"a=ice-lite").length>0;n.forEach(function(u,c){var a=e.transceivers[c],f=a.iceGatherer,I=a.iceTransport,v=a.dtlsTransport,O=a.localCapabilities,T=a.remoteCapabilities,R=w.isRejected(u)&&w.matchPrefix(u,"a=bundle-only").length===0;if(!R&&!a.isDatachannel){var P=w.getIceParameters(u,i),A=w.getDtlsParameters(u,i);o&&(A.role="server"),(!e.usingBundle||c===0)&&(e._gather(a.mid,c),I.state==="new"&&I.start(f,P,o?"controlling":"controlled"),v.state==="new"&&v.start(A));var d=l(O,T);e._transceive(a,d.codecs.length>0,!1)}})}return e.localDescription={type:t.type,sdp:t.sdp},t.type==="offer"?e._updateSignalingState("have-local-offer"):e._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(t){var e=this;if(["offer","answer"].indexOf(t.type)===-1)return Promise.reject(S("TypeError",'Unsupported type "'+t.type+'"'));if(!h("setRemoteDescription",t.type,e.signalingState)||e._isClosed)return Promise.reject(S("InvalidStateError","Can not set remote "+t.type+" in state "+e.signalingState));var n={};e.remoteStreams.forEach(function(I){n[I.id]=I});var i=[],o=w.splitSections(t.sdp),u=o.shift(),c=w.matchPrefix(u,"a=ice-lite").length>0,a=w.matchPrefix(u,"a=group:BUNDLE ").length>0;e.usingBundle=a;var f=w.matchPrefix(u,"a=ice-options:")[0];return f?e.canTrickleIceCandidates=f.substr(14).split(" ").indexOf("trickle")>=0:e.canTrickleIceCandidates=!1,o.forEach(function(I,v){var O=w.splitLines(I),T=w.getKind(I),R=w.isRejected(I)&&w.matchPrefix(I,"a=bundle-only").length===0,P=O[0].substr(2).split(" ")[2],A=w.getDirection(I,u),d=w.parseMsid(I),j=w.getMid(I)||w.generateIdentifier();if(T==="application"&&P==="DTLS/SCTP"){e.transceivers[v]={mid:j,isDatachannel:!0};return}var k,N,D,U,x,M,L,F,q,B=w.parseRtpParameters(I),G,W;R||(G=w.getIceParameters(I,u),W=w.getDtlsParameters(I,u),W.role="client"),L=w.parseRtpEncodingParameters(I);var z=w.parseRtcpParameters(I),ce=w.matchPrefix(I,"a=end-of-candidates",u).length>0,Ce=w.matchPrefix(I,"a=candidate:").map(function(Y){return w.parseCandidate(Y)}).filter(function(Y){return Y.component===1});if((t.type==="offer"||t.type==="answer")&&!R&&a&&v>0&&e.transceivers[v]&&(e._disposeIceAndDtlsTransports(v),e.transceivers[v].iceGatherer=e.transceivers[0].iceGatherer,e.transceivers[v].iceTransport=e.transceivers[0].iceTransport,e.transceivers[v].dtlsTransport=e.transceivers[0].dtlsTransport,e.transceivers[v].rtpSender&&e.transceivers[v].rtpSender.setTransport(e.transceivers[0].dtlsTransport),e.transceivers[v].rtpReceiver&&e.transceivers[v].rtpReceiver.setTransport(e.transceivers[0].dtlsTransport)),t.type==="offer"&&!R){k=e.transceivers[v]||e._createTransceiver(T),k.mid=j,k.iceGatherer||(k.iceGatherer=e._createIceGatherer(v,a)),Ce.length&&k.iceTransport.state==="new"&&(ce&&(!a||v===0)?k.iceTransport.setRemoteCandidates(Ce):Ce.forEach(function(Y){b(k.iceTransport,Y)})),F=m.RTCRtpReceiver.getCapabilities(T),E<15019&&(F.codecs=F.codecs.filter(function(Y){return Y.name!=="rtx"})),M=k.sendEncodingParameters||[{ssrc:(2*v+2)*1001}];var lt=!1;if(A==="sendrecv"||A==="sendonly"){if(lt=!k.rtpReceiver,x=k.rtpReceiver||new m.RTCRtpReceiver(k.dtlsTransport,T),lt){var we;q=x.track,d&&d.stream==="-"||(d?(n[d.stream]||(n[d.stream]=new m.MediaStream,Object.defineProperty(n[d.stream],"id",{get:function(){return d.stream}})),Object.defineProperty(q,"id",{get:function(){return d.track}}),we=n[d.stream]):(n.default||(n.default=new m.MediaStream),we=n.default)),we&&(C(q,we),k.associatedRemoteMediaStreams.push(we)),i.push([q,x,we])}}else k.rtpReceiver&&k.rtpReceiver.track&&(k.associatedRemoteMediaStreams.forEach(function(Y){var En=Y.getTracks().find(function(Sr){return Sr.id===k.rtpReceiver.track.id});En&&y(En,Y)}),k.associatedRemoteMediaStreams=[]);k.localCapabilities=F,k.remoteCapabilities=B,k.rtpReceiver=x,k.rtcpParameters=z,k.sendEncodingParameters=M,k.recvEncodingParameters=L,e._transceive(e.transceivers[v],!1,lt)}else t.type==="answer"&&!R&&(k=e.transceivers[v],N=k.iceGatherer,D=k.iceTransport,U=k.dtlsTransport,x=k.rtpReceiver,M=k.sendEncodingParameters,F=k.localCapabilities,e.transceivers[v].recvEncodingParameters=L,e.transceivers[v].remoteCapabilities=B,e.transceivers[v].rtcpParameters=z,Ce.length&&D.state==="new"&&((c||ce)&&(!a||v===0)?D.setRemoteCandidates(Ce):Ce.forEach(function(Y){b(k.iceTransport,Y)})),(!a||v===0)&&(D.state==="new"&&D.start(N,G,"controlling"),U.state==="new"&&U.start(W)),e._transceive(k,A==="sendrecv"||A==="recvonly",A==="sendrecv"||A==="sendonly"),x&&(A==="sendrecv"||A==="sendonly")?(q=x.track,d?(n[d.stream]||(n[d.stream]=new m.MediaStream),C(q,n[d.stream]),i.push([q,x,n[d.stream]])):(n.default||(n.default=new m.MediaStream),C(q,n.default),i.push([q,x,n.default]))):delete k.rtpReceiver)}),e._dtlsRole===void 0&&(e._dtlsRole=t.type==="offer"?"active":"passive"),e.remoteDescription={type:t.type,sdp:t.sdp},t.type==="offer"?e._updateSignalingState("have-remote-offer"):e._updateSignalingState("stable"),Object.keys(n).forEach(function(I){var v=n[I];if(v.getTracks().length){if(e.remoteStreams.indexOf(v)===-1){e.remoteStreams.push(v);var O=new Event("addstream");O.stream=v,m.setTimeout(function(){e._dispatchEvent("addstream",O)})}i.forEach(function(T){var R=T[0],P=T[1];v.id===T[2].id&&_(e,R,P,[v])})}}),i.forEach(function(I){I[2]||_(e,I[0],I[1],[])}),m.setTimeout(function(){e&&e.transceivers&&e.transceivers.forEach(function(I){I.iceTransport&&I.iceTransport.state==="new"&&I.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),I.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},s.prototype.close=function(){this.transceivers.forEach(function(t){t.iceTransport&&t.iceTransport.stop(),t.dtlsTransport&&t.dtlsTransport.stop(),t.rtpSender&&t.rtpSender.stop(),t.rtpReceiver&&t.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},s.prototype._updateSignalingState=function(t){this.signalingState=t;var e=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",e)},s.prototype._maybeFireNegotiationNeeded=function(){var t=this;this.signalingState!=="stable"||this.needNegotiation===!0||(this.needNegotiation=!0,m.setTimeout(function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}},0))},s.prototype._updateConnectionState=function(){var t,e={new:0,closed:0,connecting:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(i){e[i.iceTransport.state]++,e[i.dtlsTransport.state]++}),e.connected+=e.completed,t="new",e.failed>0?t="failed":e.connecting>0||e.checking>0?t="connecting":e.disconnected>0?t="disconnected":e.new>0?t="new":(e.connected>0||e.completed>0)&&(t="connected"),t!==this.iceConnectionState){this.iceConnectionState=t;var n=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",n)}},s.prototype.createOffer=function(){var t=this;if(t._isClosed)return Promise.reject(S("InvalidStateError","Can not call createOffer after close"));var e=t.transceivers.filter(function(c){return c.kind==="audio"}).length,n=t.transceivers.filter(function(c){return c.kind==="video"}).length,i=arguments[0];if(i){if(i.mandatory||i.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");i.offerToReceiveAudio!==void 0&&(i.offerToReceiveAudio===!0?e=1:i.offerToReceiveAudio===!1?e=0:e=i.offerToReceiveAudio),i.offerToReceiveVideo!==void 0&&(i.offerToReceiveVideo===!0?n=1:i.offerToReceiveVideo===!1?n=0:n=i.offerToReceiveVideo)}for(t.transceivers.forEach(function(c){c.kind==="audio"?(e--,e<0&&(c.wantReceive=!1)):c.kind==="video"&&(n--,n<0&&(c.wantReceive=!1))});e>0||n>0;)e>0&&(t._createTransceiver("audio"),e--),n>0&&(t._createTransceiver("video"),n--);var o=w.writeSessionBoilerplate(t._sdpSessionId,t._sdpSessionVersion++);t.transceivers.forEach(function(c,a){var f=c.track,I=c.kind,v=c.mid||w.generateIdentifier();c.mid=v,c.iceGatherer||(c.iceGatherer=t._createIceGatherer(a,t.usingBundle));var O=m.RTCRtpSender.getCapabilities(I);E<15019&&(O.codecs=O.codecs.filter(function(R){return R.name!=="rtx"})),O.codecs.forEach(function(R){R.name==="H264"&&R.parameters["level-asymmetry-allowed"]===void 0&&(R.parameters["level-asymmetry-allowed"]="1"),c.remoteCapabilities&&c.remoteCapabilities.codecs&&c.remoteCapabilities.codecs.forEach(function(P){R.name.toLowerCase()===P.name.toLowerCase()&&R.clockRate===P.clockRate&&(R.preferredPayloadType=P.payloadType)})}),O.headerExtensions.forEach(function(R){var P=c.remoteCapabilities&&c.remoteCapabilities.headerExtensions||[];P.forEach(function(A){R.uri===A.uri&&(R.id=A.id)})});var T=c.sendEncodingParameters||[{ssrc:(2*a+1)*1001}];f&&E>=15019&&I==="video"&&!T[0].rtx&&(T[0].rtx={ssrc:T[0].ssrc+1}),c.wantReceive&&(c.rtpReceiver=new m.RTCRtpReceiver(c.dtlsTransport,I)),c.localCapabilities=O,c.sendEncodingParameters=T}),t._config.bundlePolicy!=="max-compat"&&(o+="a=group:BUNDLE "+t.transceivers.map(function(c){return c.mid}).join(" ")+`\r
|
|
241
|
+
`),o+=`a=ice-options:trickle\r
|
|
242
|
+
`,t.transceivers.forEach(function(c,a){o+=p(c,c.localCapabilities,"offer",c.stream,t._dtlsRole),o+=`a=rtcp-rsize\r
|
|
243
|
+
`,c.iceGatherer&&t.iceGatheringState!=="new"&&(a===0||!t.usingBundle)&&(c.iceGatherer.getLocalCandidates().forEach(function(f){f.component=1,o+="a="+w.writeCandidate(f)+`\r
|
|
244
|
+
`}),c.iceGatherer.state==="completed"&&(o+=`a=end-of-candidates\r
|
|
245
|
+
`))});var u=new m.RTCSessionDescription({type:"offer",sdp:o});return Promise.resolve(u)},s.prototype.createAnswer=function(){var t=this;if(t._isClosed)return Promise.reject(S("InvalidStateError","Can not call createAnswer after close"));var e=w.writeSessionBoilerplate(t._sdpSessionId,t._sdpSessionVersion++);t.usingBundle&&(e+="a=group:BUNDLE "+t.transceivers.map(function(o){return o.mid}).join(" ")+`\r
|
|
246
|
+
`);var n=w.getMediaSections(t.remoteDescription.sdp).length;t.transceivers.forEach(function(o,u){if(!(u+1>n)){if(o.isDatachannel){e+=`m=application 0 DTLS/SCTP 5000\r
|
|
247
|
+
c=IN IP4 0.0.0.0\r
|
|
248
|
+
a=mid:`+o.mid+`\r
|
|
249
|
+
`;return}if(o.stream){var c;o.kind==="audio"?c=o.stream.getAudioTracks()[0]:o.kind==="video"&&(c=o.stream.getVideoTracks()[0]),c&&E>=15019&&o.kind==="video"&&!o.sendEncodingParameters[0].rtx&&(o.sendEncodingParameters[0].rtx={ssrc:o.sendEncodingParameters[0].ssrc+1})}var a=l(o.localCapabilities,o.remoteCapabilities),f=a.codecs.filter(function(I){return I.name.toLowerCase()==="rtx"}).length;!f&&o.sendEncodingParameters[0].rtx&&delete o.sendEncodingParameters[0].rtx,e+=p(o,a,"answer",o.stream,t._dtlsRole),o.rtcpParameters&&o.rtcpParameters.reducedSize&&(e+=`a=rtcp-rsize\r
|
|
250
|
+
`)}});var i=new m.RTCSessionDescription({type:"answer",sdp:e});return Promise.resolve(i)},s.prototype.addIceCandidate=function(t){var e=this,n;return t&&!(t.sdpMLineIndex!==void 0||t.sdpMid)?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(i,o){if(e.remoteDescription)if(!t||t.candidate==="")for(var u=0;u<e.transceivers.length&&!(!e.transceivers[u].isDatachannel&&(e.transceivers[u].iceTransport.addRemoteCandidate({}),n=w.getMediaSections(e.remoteDescription.sdp),n[u]+=`a=end-of-candidates\r
|
|
251
|
+
`,e.remoteDescription.sdp=w.getDescription(e.remoteDescription.sdp)+n.join(""),e.usingBundle));u++);else{var c=t.sdpMLineIndex;if(t.sdpMid){for(var a=0;a<e.transceivers.length;a++)if(e.transceivers[a].mid===t.sdpMid){c=a;break}}var f=e.transceivers[c];if(f){if(f.isDatachannel)return i();var I=Object.keys(t.candidate).length>0?w.parseCandidate(t.candidate):{};if(I.protocol==="tcp"&&(I.port===0||I.port===9)||I.component&&I.component!==1)return i();if((c===0||c>0&&f.iceTransport!==e.transceivers[0].iceTransport)&&!b(f.iceTransport,I))return o(S("OperationError","Can not add ICE candidate"));var v=t.candidate.trim();v.indexOf("a=")===0&&(v=v.substr(2)),n=w.getMediaSections(e.remoteDescription.sdp),n[c]+="a="+(I.type?v:"end-of-candidates")+`\r
|
|
252
|
+
`,e.remoteDescription.sdp=n.join("")}else return o(S("OperationError","Can not add ICE candidate"))}else return o(S("InvalidStateError","Can not add ICE candidate without a remote description"));i()})},s.prototype.getStats=function(){var t=[];this.transceivers.forEach(function(n){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(i){n[i]&&t.push(n[i].getStats())})});var e=function(n){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[n.type]||n.type};return new Promise(function(n){var i=new Map;Promise.all(t).then(function(o){o.forEach(function(u){Object.keys(u).forEach(function(c){u[c].type=e(u[c]),i.set(c,u[c])})}),n(i)})})};var g=["createOffer","createAnswer"];return g.forEach(function(t){var e=s.prototype[t];s.prototype[t]=function(){var n=arguments;return typeof n[0]=="function"||typeof n[1]=="function"?e.apply(this,[arguments[2]]).then(function(i){typeof n[0]=="function"&&n[0].apply(null,[i])},function(i){typeof n[1]=="function"&&n[1].apply(null,[i])}):e.apply(this,arguments)}}),g=["setLocalDescription","setRemoteDescription","addIceCandidate"],g.forEach(function(t){var e=s.prototype[t];s.prototype[t]=function(){var n=arguments;return typeof n[1]=="function"||typeof n[2]=="function"?e.apply(this,arguments).then(function(){typeof n[1]=="function"&&n[1].apply(null)},function(i){typeof n[2]=="function"&&n[2].apply(null,[i])}):e.apply(this,arguments)}}),["getStats"].forEach(function(t){var e=s.prototype[t];s.prototype[t]=function(){var n=arguments;return typeof n[1]=="function"?e.apply(this,arguments).then(function(){typeof n[1]=="function"&&n[1].apply(null)}):e.apply(this,arguments)}}),s},rt}var Kt;function Qt(){if(Kt)return qe;Kt=1,Object.defineProperty(qe,"__esModule",{value:!0});var w=X(),p=fe(),r=tt(),l=er();function h(E){if(typeof window>"u"){this.log.info("No RTCPeerConnection implementation available. The window object was not found.");return}E&&E.RTCPeerConnection?this.RTCPeerConnection=E.RTCPeerConnection:p.isLegacyEdge()?this.RTCPeerConnection=new l(typeof window<"u"?window:Ye):typeof window.RTCPeerConnection=="function"?this.RTCPeerConnection=window.RTCPeerConnection:typeof window.webkitRTCPeerConnection=="function"?this.RTCPeerConnection=webkitRTCPeerConnection:typeof window.mozRTCPeerConnection=="function"?(this.RTCPeerConnection=mozRTCPeerConnection,window.RTCSessionDescription=mozRTCSessionDescription,window.RTCIceCandidate=mozRTCIceCandidate):this.log.info("No RTCPeerConnection implementation available")}h.prototype.create=function(E){this.log=new w.default("RTCPC"),this.pc=new this.RTCPeerConnection(E)},h.prototype.createModernConstraints=function(E){if(typeof E>"u")return null;var C=Object.assign({},E);return typeof webkitRTCPeerConnection<"u"&&!p.isLegacyEdge()?(C.mandatory={},typeof E.audio<"u"&&(C.mandatory.OfferToReceiveAudio=E.audio),typeof E.video<"u"&&(C.mandatory.OfferToReceiveVideo=E.video)):(typeof E.audio<"u"&&(C.offerToReceiveAudio=E.audio),typeof E.video<"u"&&(C.offerToReceiveVideo=E.video)),delete C.audio,delete C.video,C},h.prototype.createOffer=function(E,C,y,_,s){var g=this;return y=this.createModernConstraints(y),S(this.pc.createOffer,this.pc)(y).then(function(t){if(!g.pc)return Promise.resolve();var e=r.setMaxAverageBitrate(t.sdp,E);return m(g.pc.setLocalDescription,g.pc)(new RTCSessionDescription({sdp:r.setCodecPreferences(e,C),type:"offer"}))}).then(_,s)},h.prototype.createAnswer=function(E,C,y,_,s){var g=this;return y=this.createModernConstraints(y),S(this.pc.createAnswer,this.pc)(y).then(function(t){if(!g.pc)return Promise.resolve();var e=r.setMaxAverageBitrate(t.sdp,E);return m(g.pc.setLocalDescription,g.pc)(new RTCSessionDescription({sdp:r.setCodecPreferences(e,C),type:"answer"}))}).then(_,s)},h.prototype.processSDP=function(E,C,y,_,s,g){var t=this;y=r.setCodecPreferences(y,C);var e=new RTCSessionDescription({sdp:y,type:"offer"});return m(this.pc.setRemoteDescription,this.pc)(e).then(function(){t.createAnswer(E,C,_,s,g)})},h.prototype.getSDP=function(){return this.pc.localDescription.sdp},h.prototype.processAnswer=function(E,C,y,_){return this.pc?(C=r.setCodecPreferences(C,E),m(this.pc.setRemoteDescription,this.pc)(new RTCSessionDescription({sdp:C,type:"answer"})).then(y,_)):Promise.resolve()},h.test=function(){if(typeof navigator=="object"){var E=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.getUserMedia;if(p.isLegacyEdge(navigator))return!1;if(E&&typeof window.RTCPeerConnection=="function")return!0;if(E&&typeof window.webkitRTCPeerConnection=="function")return!0;if(E&&typeof window.mozRTCPeerConnection=="function"){try{var C=new window.mozRTCPeerConnection;if(typeof C.getLocalStreams!="function")return!1}catch{return!1}return!0}else if(typeof RTCIceGatherer<"u")return!0}return!1};function b(E,C,y,_){return function(){var s=Array.prototype.slice.call(arguments);return new Promise(function(g){var t=E.apply(C,s);if(!_){g(t);return}if(typeof t=="object"&&typeof t.then=="function")g(t);else throw new Error}).catch(function(){return new Promise(function(g,t){E.apply(C,y?[g,t].concat(s):s.concat([g,t]))})})}}function S(E,C){return b(E,C,!0,!0)}function m(E,C){return b(E,C,!1,!1)}return qe.default=h,qe}var Xt;function tr(){if(Xt)return Fe;Xt=1,Object.defineProperty(Fe,"__esModule",{value:!0});var w=$(),p=X(),r=fe(),l=Qt(),h=tt(),b=15e3,S="none",m="timeout",E="new",C=50;function y(e,n,i){if(!e||!n)throw new w.InvalidArgumentError("Audiohelper, and pstream are required arguments");if(!(this instanceof y))return new y(e,n,i);this._log=new p.default("PeerConnection");function o(){this._log.warn("Unexpected noop call in peerconnection")}this.onaudio=o,this.onopen=o,this.onerror=o,this.onclose=o,this.ondisconnected=o,this.onfailed=o,this.onconnected=o,this.onreconnected=o,this.onsignalingstatechange=o,this.ondtlstransportstatechange=o,this.onicegatheringfailure=o,this.onicegatheringstatechange=o,this.oniceconnectionstatechange=o,this.onpcconnectionstatechange=o,this.onicecandidate=o,this.onselectedcandidatepairchange=o,this.onvolume=o,this.version=null,this.pstream=n,this.stream=null,this.sinkIds=new Set(["default"]),this.outputs=new Map,this.status="connecting",this.callSid=null,this.isMuted=!1;var u=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);return this._isSinkSupported=!!u&&typeof HTMLAudioElement<"u"&&HTMLAudioElement.prototype.setSinkId,this._audioContext=u&&e._audioContext,this._audioHelper=e,this._hasIceCandidates=!1,this._hasIceGatheringFailures=!1,this._iceGatheringTimeoutId=null,this._masterAudio=null,this._masterAudioDeviceId=null,this._mediaStreamSource=null,this._dtmfSender=null,this._dtmfSenderUnsupported=!1,this._callEvents=[],this._nextTimeToPublish=Date.now(),this._onAnswerOrRinging=o,this._onHangup=o,this._remoteStream=null,this._shouldManageStream=!0,this._iceState=E,this._isUnifiedPlan=i.isUnifiedPlan,this.options=i=i||{},this.navigator=i.navigator||(typeof navigator<"u"?navigator:null),this.util=i.util||r,this.codecPreferences=i.codecPreferences,this}y.prototype.uri=function(){return this._uri},y.prototype.openDefaultDeviceWithConstraints=function(e){return this._audioHelper._openDefaultDeviceWithConstraints(e).then(this._setInputTracksFromStream.bind(this,!1))},y.prototype.setInputTracksFromStream=function(e){var n=this;return this._setInputTracksFromStream(!0,e).then(function(){n._shouldManageStream=!1})},y.prototype._createAnalyser=function(e,n){n=Object.assign({fftSize:32,smoothingTimeConstant:.3},n);var i=e.createAnalyser();for(var o in n)i[o]=n[o];return i},y.prototype._setVolumeHandler=function(e){this.onvolume=e},y.prototype._startPollingVolume=function(){if(!(!this._audioContext||!this.stream||!this._remoteStream)){var e=this._audioContext,n=this._inputAnalyser=this._createAnalyser(e),i=n.frequencyBinCount,o=new Uint8Array(i);this._inputAnalyser2=this._createAnalyser(e,{maxDecibels:0,minDecibels:-127,smoothingTimeConstant:0});var u=this._outputAnalyser=this._createAnalyser(e),c=u.frequencyBinCount,a=new Uint8Array(c);this._outputAnalyser2=this._createAnalyser(e,{maxDecibels:0,minDecibels:-127,smoothingTimeConstant:0}),this._updateInputStreamSource(this.stream),this._updateOutputStreamSource(this._remoteStream);var f=this;setTimeout(function I(){if(f._audioContext){if(f.status==="closed"){f._inputAnalyser.disconnect(),f._outputAnalyser.disconnect(),f._inputAnalyser2.disconnect(),f._outputAnalyser2.disconnect();return}}else return;f._inputAnalyser.getByteFrequencyData(o);var v=f.util.average(o);f._inputAnalyser2.getByteFrequencyData(o);var O=f.util.average(o);f._outputAnalyser.getByteFrequencyData(a);var T=f.util.average(a);f._outputAnalyser2.getByteFrequencyData(a);var R=f.util.average(a);f.onvolume(v/255,T/255,O,R),setTimeout(I,C)},C)}},y.prototype._stopStream=function(){this._shouldManageStream&&this._audioHelper._stopDefaultInputDeviceStream()},y.prototype._updateInputStreamSource=function(e){this._inputStreamSource&&this._inputStreamSource.disconnect();try{this._inputStreamSource=this._audioContext.createMediaStreamSource(e),this._inputStreamSource.connect(this._inputAnalyser),this._inputStreamSource.connect(this._inputAnalyser2)}catch(n){this._log.warn("Unable to update input MediaStreamSource",n),this._inputStreamSource=null}},y.prototype._updateOutputStreamSource=function(e){this._outputStreamSource&&this._outputStreamSource.disconnect();try{this._outputStreamSource=this._audioContext.createMediaStreamSource(e),this._outputStreamSource.connect(this._outputAnalyser),this._outputStreamSource.connect(this._outputAnalyser2)}catch(n){this._log.warn("Unable to update output MediaStreamSource",n),this._outputStreamSource=null}},y.prototype._setInputTracksFromStream=function(e,n){return this._isUnifiedPlan?this._setInputTracksForUnifiedPlan(e,n):this._setInputTracksForPlanB(e,n)},y.prototype._setInputTracksForPlanB=function(e,n){var i=this;if(!n)return Promise.reject(new w.InvalidArgumentError("Can not set input stream to null while in a call"));if(!n.getAudioTracks().length)return Promise.reject(new w.InvalidArgumentError("Supplied input stream has no audio tracks"));var o=this.stream;return o?(this._stopStream(),g(this.version.pc,o),o.getAudioTracks().forEach(o.removeTrack,o),n.getAudioTracks().forEach(o.addTrack,o),_(this.version.pc,n),this._updateInputStreamSource(this.stream)):this.stream=e?s(n):n,this.mute(this.isMuted),this.version?new Promise(function(u,c){i.version.createOffer(i.options.maxAverageBitrate,i.codecPreferences,{audio:!0},function(){i.version.processAnswer(i.codecPreferences,i._answerSdp,function(){u(i.stream)},c)},c)}):Promise.resolve(this.stream)},y.prototype._setInputTracksForUnifiedPlan=function(e,n){var i=this;if(!n)return Promise.reject(new w.InvalidArgumentError("Can not set input stream to null while in a call"));if(!n.getAudioTracks().length)return Promise.reject(new w.InvalidArgumentError("Supplied input stream has no audio tracks"));var o=this.stream,u=function(){return i.mute(i.isMuted),Promise.resolve(i.stream)};if(!o)this.stream=e?s(n,this.options.MediaStream):n;else return this._shouldManageStream&&this._stopStream(),this._sender||(this._sender=this.version.pc.getSenders()[0]),this._sender.replaceTrack(n.getAudioTracks()[0]).then(function(){return i._updateInputStreamSource(n),i.stream=e?s(n,i.options.MediaStream):n,u()});return u()},y.prototype._onInputDevicesChanged=function(){if(this.stream){var e=this.stream.getAudioTracks().every(function(n){return n.readyState==="ended"});e&&this._shouldManageStream&&this.openDefaultDeviceWithConstraints({audio:!0})}},y.prototype._onIceGatheringFailure=function(e){this._hasIceGatheringFailures=!0,this.onicegatheringfailure(e)},y.prototype._onMediaConnectionStateChange=function(e){var n=this._iceState;if(!(n===e||e!=="connected"&&e!=="disconnected"&&e!=="failed")){this._iceState=e;var i;switch(e){case"connected":n==="disconnected"||n==="failed"?(i="ICE liveliness check succeeded. Connection with Twilio restored",this._log.info(i),this.onreconnected(i)):(i="Media connection established.",this._log.info(i),this.onconnected(i)),this._stopIceGatheringTimeout(),this._hasIceGatheringFailures=!1;break;case"disconnected":i="ICE liveliness check failed. May be having trouble connecting to Twilio",this._log.warn(i),this.ondisconnected(i);break;case"failed":i="Connection with Twilio was interrupted.",this._log.warn(i),this.onfailed(i);break}}},y.prototype._setSinkIds=function(e){return this._isSinkSupported?(this.sinkIds=new Set(e.forEach?e:[e]),this.version?this._updateAudioOutputs():Promise.resolve()):Promise.reject(new w.NotSupportedError("Audio output selection is not supported by this browser"))},y.prototype._startIceGatheringTimeout=function(){var n=this;this._stopIceGatheringTimeout(),this._iceGatheringTimeoutId=setTimeout(function(){n._onIceGatheringFailure(m)},b)},y.prototype._stopIceGatheringTimeout=function(){clearInterval(this._iceGatheringTimeoutId)},y.prototype._updateAudioOutputs=function(){var n=Array.from(this.sinkIds).filter(function(c){return!this.outputs.has(c)},this),i=Array.from(this.outputs.keys()).filter(function(c){return!this.sinkIds.has(c)},this),o=this,u=n.map(this._createAudioOutput,this);return Promise.all(u).then(function(){return Promise.all(i.map(o._removeAudioOutput,o))})},y.prototype._createAudio=function(n){var i=new Audio(n);return this.onaudio(i),i},y.prototype._createAudioOutput=function(n){var i=null;this._mediaStreamSource&&(i=this._audioContext.createMediaStreamDestination(),this._mediaStreamSource.connect(i));var o=this._createAudio();t(o,i&&i.stream?i.stream:this.pcStream);var u=this;return o.setSinkId(n).then(function(){return o.play()}).then(function(){u.outputs.set(n,{audio:o,dest:i})})},y.prototype._removeAudioOutputs=function(){return this._masterAudio&&typeof this._masterAudioDeviceId<"u"&&(this._disableOutput(this,this._masterAudioDeviceId),this.outputs.delete(this._masterAudioDeviceId),this._masterAudioDeviceId=null,this._masterAudio.paused||this._masterAudio.pause(),typeof this._masterAudio.srcObject<"u"?this._masterAudio.srcObject=null:this._masterAudio.src="",this._masterAudio=null),Array.from(this.outputs.keys()).map(this._removeAudioOutput,this)},y.prototype._disableOutput=function(n,i){var o=n.outputs.get(i);o&&(o.audio&&(o.audio.pause(),o.audio.src=""),o.dest&&o.dest.disconnect())},y.prototype._reassignMasterOutput=function(n,i){var o=n.outputs.get(i);n.outputs.delete(i);var u=this,c=Array.from(n.outputs.keys())[0],a=typeof c=="string"?c:"default";return o.audio.setSinkId(a).then(function(){u._disableOutput(n,a),n.outputs.set(a,o),n._masterAudioDeviceId=a}).catch(function(){n.outputs.set(i,o),u._log.info("Could not reassign master output. Attempted to roll back.")})},y.prototype._removeAudioOutput=function(n){return this._masterAudioDeviceId===n?this._reassignMasterOutput(this,n):(this._disableOutput(this,n),this.outputs.delete(n),Promise.resolve())},y.prototype._onAddTrack=function(n,i){var o=n._masterAudio=this._createAudio();t(o,i),o.play();var u=Array.from(n.outputs.keys())[0],c=typeof u=="string"?u:"default";n._masterAudioDeviceId=c,n.outputs.set(c,{audio:o});try{n._mediaStreamSource=n._audioContext.createMediaStreamSource(i)}catch(a){this._log.warn("Unable to create a MediaStreamSource from onAddTrack",a),this._mediaStreamSource=null}n.pcStream=i,n._updateAudioOutputs()},y.prototype._fallbackOnAddTrack=function(n,i){var o=document&&document.createElement("audio");o.autoplay=!0,t(o,i)||n._log.info("Error attaching stream to element."),n.outputs.set("default",{audio:o})},y.prototype._setEncodingParameters=function(e){if(!(!e||!this._sender||typeof this._sender.getParameters!="function"||typeof this._sender.setParameters!="function")){var n=this._sender.getParameters();!n.priority&&!(n.encodings&&n.encodings.length)||(n.priority="high",n.encodings&&n.encodings.length&&n.encodings.forEach(function(i){i.priority="high",i.networkPriority="high"}),this._sender.setParameters(n))}},y.prototype._setupPeerConnection=function(e){var n=this,i=this,o=new(this.options.rtcpcFactory||l.default)({RTCPeerConnection:this.options.RTCPeerConnection});o.create(e),_(o.pc,this.stream);var u="ontrack"in o.pc?"ontrack":"onaddstream";return o.pc[u]=function(c){var a=i._remoteStream=c.stream||c.streams[0];typeof o.pc.getSenders=="function"&&(n._sender=o.pc.getSenders()[0]),i._isSinkSupported?i._onAddTrack(i,a):i._fallbackOnAddTrack(i,a),i._startPollingVolume()},o},y.prototype._maybeSetIceAggressiveNomination=function(e){return this.options.forceAggressiveIceNomination?h.setIceAggressiveNomination(e):e},y.prototype._setupChannel=function(){var e=this,n=this.version.pc;this.version.pc.onopen=function(){e.status="open",e.onopen()},this.version.pc.onstatechange=function(){e.version.pc&&e.version.pc.readyState==="stable"&&(e.status="open",e.onopen())},this.version.pc.onsignalingstatechange=function(){var i=n.signalingState;e._log.info('signalingState is "'+i+'"'),e.version.pc&&e.version.pc.signalingState==="stable"&&(e.status="open",e.onopen()),e.onsignalingstatechange(n.signalingState)},n.onconnectionstatechange=function(i){var o=n.connectionState;if(!o&&i&&i.target){var u=i.target;o=u.connectionState||u.connectionState_,e._log.info("pc.connectionState not detected. Using target PC. State="+o)}o?e._log.info('pc.connectionState is "'+o+'"'):e._log.warn('onconnectionstatechange detected but state is "'+o+'"'),e.onpcconnectionstatechange(o),e._onMediaConnectionStateChange(o)},n.onicecandidate=function(i){var o=i.candidate;o&&(e._hasIceCandidates=!0,e.onicecandidate(o),e._setupRTCIceTransportListener()),e._log.info("ICE Candidate: "+JSON.stringify(o))},n.onicegatheringstatechange=function(){var i=n.iceGatheringState;i==="gathering"?e._startIceGatheringTimeout():i==="complete"&&(e._stopIceGatheringTimeout(),e._hasIceCandidates||e._onIceGatheringFailure(S),e._hasIceCandidates&&e._hasIceGatheringFailures&&e._startIceGatheringTimeout()),e._log.info('pc.iceGatheringState is "'+n.iceGatheringState+'"'),e.onicegatheringstatechange(i)},n.oniceconnectionstatechange=function(){e._log.info('pc.iceConnectionState is "'+n.iceConnectionState+'"'),e.oniceconnectionstatechange(n.iceConnectionState),e._onMediaConnectionStateChange(n.iceConnectionState)}},y.prototype._initializeMediaStream=function(e){return this.status==="open"?!1:this.pstream.status==="disconnected"?(this.onerror({info:{code:31e3,message:"Cannot establish connection. Client is disconnected",twilioError:new w.SignalingErrors.ConnectionDisconnected}}),this.close(),!1):(this.version=this._setupPeerConnection(e),this._setupChannel(),!0)},y.prototype._removeReconnectionListeners=function(){this.pstream&&(this.pstream.removeListener("answer",this._onAnswerOrRinging),this.pstream.removeListener("hangup",this._onHangup))},y.prototype._setupRTCDtlsTransportListener=function(){var e=this,n=this.getRTCDtlsTransport();if(!(!n||n.onstatechange)){var i=function(){e._log.info('dtlsTransportState is "'+n.state+'"'),e.ondtlstransportstatechange(n.state)};i(),n.onstatechange=i}},y.prototype._setupRTCIceTransportListener=function(){var e=this,n=this._getRTCIceTransport();!n||n.onselectedcandidatepairchange||(n.onselectedcandidatepairchange=function(){return e.onselectedcandidatepairchange(n.getSelectedCandidatePair())})},y.prototype.iceRestart=function(){var e=this;this._log.info("Attempting to restart ICE..."),this._hasIceCandidates=!1,this.version.createOffer(this.options.maxAverageBitrate,this.codecPreferences,{iceRestart:!0}).then(function(){e._removeReconnectionListeners(),e._onAnswerOrRinging=function(n){if(e._removeReconnectionListeners(),!n.sdp||e.version.pc.signalingState!=="have-local-offer"){var i="Invalid state or param during ICE Restart:"+("hasSdp:"+!!n.sdp+", signalingState:"+e.version.pc.signalingState);e._log.warn(i);return}var o=e._maybeSetIceAggressiveNomination(n.sdp);e._answerSdp=o,e.status!=="closed"&&e.version.processAnswer(e.codecPreferences,o,null,function(u){var c=u&&u.message?u.message:u;e._log.error("Failed to process answer during ICE Restart. Error: "+c)})},e._onHangup=function(){e._log.info("Received hangup during ICE Restart"),e._removeReconnectionListeners()},e.pstream.on("answer",e._onAnswerOrRinging),e.pstream.on("hangup",e._onHangup),e.pstream.reinvite(e.version.getSDP(),e.callSid)}).catch(function(n){var i=n&&n.message?n.message:n;e._log.error("Failed to createOffer during ICE Restart. Error: "+i),e.onfailed(i)})},y.prototype.makeOutgoingCall=function(e,n,i,o,u){var c=this;if(!this._initializeMediaStream(o))return;var a=this;this.callSid=i;function f(){a.options&&a._setEncodingParameters(a.options.dscp),u(a.version.pc)}function I(T){var R=T.message||T;a.onerror({info:{code:31e3,message:"Error processing answer: "+R,twilioError:new w.MediaErrors.ClientRemoteDescFailed}})}this._onAnswerOrRinging=function(T){if(T.sdp){var R=c._maybeSetIceAggressiveNomination(T.sdp);a._answerSdp=R,a.status!=="closed"&&a.version.processAnswer(c.codecPreferences,R,f,I),a.pstream.removeListener("answer",a._onAnswerOrRinging),a.pstream.removeListener("ringing",a._onAnswerOrRinging)}},this.pstream.on("answer",this._onAnswerOrRinging),this.pstream.on("ringing",this._onAnswerOrRinging);function v(){a.status!=="closed"&&(n?a.pstream.reconnect(a.version.getSDP(),a.callSid,n):a.pstream.invite(a.version.getSDP(),a.callSid,e),a._setupRTCDtlsTransportListener())}function O(T){var R=T.message||T;a.onerror({info:{code:31e3,message:"Error creating the offer: "+R,twilioError:new w.MediaErrors.ClientLocalDescFailed}})}this.version.createOffer(this.options.maxAverageBitrate,this.codecPreferences,{audio:!0},v,O)},y.prototype.answerIncomingCall=function(e,n,i,o){if(!this._initializeMediaStream(i))return;n=this._maybeSetIceAggressiveNomination(n),this._answerSdp=n.replace(/^a=setup:actpass$/gm,"a=setup:passive"),this.callSid=e;var u=this;function c(){u.status!=="closed"&&(u.pstream.answer(u.version.getSDP(),e),u.options&&u._setEncodingParameters(u.options.dscp),o(u.version.pc),u._setupRTCDtlsTransportListener())}function a(f){var I=f.message||f;u.onerror({info:{code:31e3,message:"Error creating the answer: "+I,twilioError:new w.MediaErrors.ClientRemoteDescFailed}})}this.version.processSDP(this.options.maxAverageBitrate,this.codecPreferences,n,{audio:!0},c,a)},y.prototype.close=function(){this.version&&this.version.pc&&(this.version.pc.signalingState!=="closed"&&this.version.pc.close(),this.version.pc=null),this.stream&&(this.mute(!1),this._stopStream()),this.stream=null,this._removeReconnectionListeners(),this._stopIceGatheringTimeout(),Promise.all(this._removeAudioOutputs()).catch(function(){}),this._mediaStreamSource&&this._mediaStreamSource.disconnect(),this._inputAnalyser&&this._inputAnalyser.disconnect(),this._outputAnalyser&&this._outputAnalyser.disconnect(),this._inputAnalyser2&&this._inputAnalyser2.disconnect(),this._outputAnalyser2&&this._outputAnalyser2.disconnect(),this.status="closed",this.onclose()},y.prototype.reject=function(e){this.callSid=e},y.prototype.ignore=function(e){this.callSid=e},y.prototype.mute=function(e){if(this.isMuted=e,!!this.stream)if(this._sender&&this._sender.track)this._sender.track.enabled=!e;else{var n=typeof this.stream.getAudioTracks=="function"?this.stream.getAudioTracks():this.stream.audioTracks;n.forEach(function(i){i.enabled=!e})}},y.prototype.getOrCreateDTMFSender=function(){if(this._dtmfSender||this._dtmfSenderUnsupported)return this._dtmfSender||null;var n=this,i=this.version.pc;if(!i)return this._log.warn("No RTCPeerConnection available to call createDTMFSender on"),null;if(typeof i.getSenders=="function"&&(typeof RTCDTMFSender=="function"||typeof RTCDtmfSender=="function")){var o=i.getSenders().find(function(c){return c.dtmf});if(o)return this._log.info("Using RTCRtpSender#dtmf"),this._dtmfSender=o.dtmf,this._dtmfSender}if(typeof i.createDTMFSender=="function"&&typeof i.getLocalStreams=="function"){var u=i.getLocalStreams().map(function(c){var a=n._getAudioTracks(c);return a&&a[0]})[0];return u?(this._log.info("Creating RTCDTMFSender"),this._dtmfSender=i.createDTMFSender(u),this._dtmfSender):(this._log.warn("No local audio MediaStreamTrack available on the RTCPeerConnection to pass to createDTMFSender"),null)}return this._log.info("RTCPeerConnection does not support RTCDTMFSender"),this._dtmfSenderUnsupported=!0,null},y.prototype.getRTCDtlsTransport=function(){var n=this.version&&this.version.pc&&typeof this.version.pc.getSenders=="function"&&this.version.pc.getSenders()[0];return n&&n.transport||null},y.prototype._canStopMediaStreamTrack=function(){return typeof MediaStreamTrack.prototype.stop=="function"},y.prototype._getAudioTracks=function(e){return typeof e.getAudioTracks=="function"?e.getAudioTracks():e.audioTracks},y.prototype._getRTCIceTransport=function(){var n=this.getRTCDtlsTransport();return n&&n.iceTransport||null},y.protocol=function(){return l.default.test()?new l.default:null}();function _(e,n){typeof e.addTrack=="function"?n.getAudioTracks().forEach(function(i){e.addTrack(i,n)}):e.addStream(n)}function s(e,n){var i;return n?i=new n:typeof MediaStream<"u"?i=new MediaStream:i=new webkitMediaStream,e.getAudioTracks().forEach(i.addTrack,i),i}function g(e,n){typeof e.removeTrack=="function"?e.getSenders().forEach(function(i){e.removeTrack(i)}):e.removeStream(n)}function t(e,n){if(typeof e.srcObject<"u")e.srcObject=n;else if(typeof e.mozSrcObject<"u")e.mozSrcObject=n;else if(typeof e.src<"u"){var i=e.options.window||window;e.src=(i.URL||i.webkitURL).createObjectURL(n)}else return!1;return!0}return y.enabled=l.default.test(),Fe.default=y,Fe}var Yt;function Zt(){if(Yt)return ae;Yt=1,Object.defineProperty(ae,"__esModule",{value:!0}),ae.PeerConnection=ae.getMediaEngine=ae.enabled=void 0;var w=tr();ae.PeerConnection=w.default;var p=Qt();function r(){return p.default.test()}ae.enabled=r;function l(){return typeof RTCIceGatherer<"u"?"ORTC":"WebRTC"}return ae.getMediaEngine=l,ae}var Be={},en;function nr(){if(en)return Be;en=1,Object.defineProperty(Be,"__esModule",{value:!0});var w=$(),p=fe();function r(l,h){return h=h||{},h.util=h.util||p,h.navigator=h.navigator||(typeof navigator<"u"?navigator:null),new Promise(function(b,S){if(!h.navigator)throw new w.NotSupportedError("getUserMedia is not supported");switch("function"){case typeof(h.navigator.mediaDevices&&h.navigator.mediaDevices.getUserMedia):return b(h.navigator.mediaDevices.getUserMedia(l));case typeof h.navigator.webkitGetUserMedia:return h.navigator.webkitGetUserMedia(l,b,S);case typeof h.navigator.mozGetUserMedia:return h.navigator.mozGetUserMedia(l,b,S);case typeof h.navigator.getUserMedia:return h.navigator.getUserMedia(l,b,S);default:throw new w.NotSupportedError("getUserMedia is not supported")}}).catch(function(b){throw h.util.isFirefox()&&b.name==="NotReadableError"?new w.NotSupportedError(`Firefox does not currently support opening multiple audio input trackssimultaneously, even across different tabs.
|
|
253
|
+
Related Bugzilla thread: https://bugzilla.mozilla.org/show_bug.cgi?id=1299324`):b})}return Be.default=r,Be}var We={},se={},Ve={},tn;function rr(){if(tn)return Ve;tn=1,Object.defineProperty(Ve,"__esModule",{value:!0});var w=function(){function p(){var r=this;this._promise=new Promise(function(l,h){r._resolve=l,r._reject=h})}return Object.defineProperty(p.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),p.prototype.reject=function(r){this._reject(r)},p.prototype.resolve=function(r){this._resolve(r)},p}();return Ve.default=w,Ve}var nn;function ir(){if(nn)return se;nn=1;var w=se&&se.__awaiter||function(h,b,S,m){function E(C){return C instanceof S?C:new S(function(y){y(C)})}return new(S||(S=Promise))(function(C,y){function _(t){try{g(m.next(t))}catch(e){y(e)}}function s(t){try{g(m.throw(t))}catch(e){y(e)}}function g(t){t.done?C(t.value):E(t.value).then(_,s)}g((m=m.apply(h,b||[])).next())})},p=se&&se.__generator||function(h,b){var S={label:0,sent:function(){if(C[0]&1)throw C[1];return C[1]},trys:[],ops:[]},m,E,C,y;return y={next:_(0),throw:_(1),return:_(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function _(g){return function(t){return s([g,t])}}function s(g){if(m)throw new TypeError("Generator is already executing.");for(;S;)try{if(m=1,E&&(C=g[0]&2?E.return:g[0]?E.throw||((C=E.return)&&C.call(E),0):E.next)&&!(C=C.call(E,g[1])).done)return C;switch(E=0,C&&(g=[g[0]&2,C.value]),g[0]){case 0:case 1:C=g;break;case 4:return S.label++,{value:g[1],done:!1};case 5:S.label++,E=g[1],g=[0];continue;case 7:g=S.ops.pop(),S.trys.pop();continue;default:if(C=S.trys,!(C=C.length>0&&C[C.length-1])&&(g[0]===6||g[0]===2)){S=0;continue}if(g[0]===3&&(!C||g[1]>C[0]&&g[1]<C[3])){S.label=g[1];break}if(g[0]===6&&S.label<C[1]){S.label=C[1],C=g;break}if(C&&S.label<C[2]){S.label=C[2],S.ops.push(g);break}C[2]&&S.ops.pop(),S.trys.pop();continue}g=b.call(h,S)}catch(t){g=[6,t],E=0}finally{m=C=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}};Object.defineProperty(se,"__esModule",{value:!0}),se.AsyncQueue=void 0;var r=rr(),l=function(){function h(){this._operations=[]}return h.prototype.enqueue=function(b){var S=!!this._operations.length,m=new r.default;return this._operations.push({deferred:m,callback:b}),S||this._processQueue(),m.promise},h.prototype._processQueue=function(){return w(this,void 0,void 0,function(){var b,S,m,E,C,y,_;return p(this,function(s){switch(s.label){case 0:if(!this._operations.length)return[3,5];b=this._operations[0],S=b.deferred,m=b.callback,E=void 0,C=void 0,y=void 0,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,m()];case 2:return E=s.sent(),y=!0,[3,4];case 3:return _=s.sent(),C=_,[3,4];case 4:return this._operations.shift(),y?S.resolve(E):S.reject(C),[3,0];case 5:return[2]}})})},h}();return se.AsyncQueue=l,se}var re={},Ge={},rn;function or(){if(rn)return Ge;rn=1,Object.defineProperty(Ge,"__esModule",{value:!0});var w=function(){function p(){var r=this;this.promise=new Promise(function(l,h){r._resolve=l,r._reject=h})}return Object.defineProperty(p.prototype,"reject",{get:function(){return this._reject},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"resolve",{get:function(){return this._resolve},enumerable:!1,configurable:!0}),p}();return Ge.default=w,Ge}var Se={},on;function ar(){if(on)return Se;on=1;var w=Se&&Se.__spreadArrays||function(){for(var l=0,h=0,b=arguments.length;h<b;h++)l+=arguments[h].length;for(var S=Array(l),m=0,h=0;h<b;h++)for(var E=arguments[h],C=0,y=E.length;C<y;C++,m++)S[m]=E[C];return S};Object.defineProperty(Se,"__esModule",{value:!0});var p=Z(),r=function(){function l(){this._eventEmitter=new p.EventEmitter}return l.prototype.addEventListener=function(h,b){return this._eventEmitter.addListener(h,b)},l.prototype.dispatchEvent=function(h){for(var b,S=[],m=1;m<arguments.length;m++)S[m-1]=arguments[m];return(b=this._eventEmitter).emit.apply(b,w([h],S))},l.prototype.removeEventListener=function(h,b){return this._eventEmitter.removeListener(h,b)},l}();return Se.default=r,Se}var an;function sr(){if(an)return re;an=1;var w=re&&re.__extends||function(){var m=function(E,C){return m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,_){y.__proto__=_}||function(y,_){for(var s in _)Object.prototype.hasOwnProperty.call(_,s)&&(y[s]=_[s])},m(E,C)};return function(E,C){m(E,C);function y(){this.constructor=E}E.prototype=C===null?Object.create(C):(y.prototype=C.prototype,new y)}}(),p=re&&re.__awaiter||function(m,E,C,y){function _(s){return s instanceof C?s:new C(function(g){g(s)})}return new(C||(C=Promise))(function(s,g){function t(i){try{n(y.next(i))}catch(o){g(o)}}function e(i){try{n(y.throw(i))}catch(o){g(o)}}function n(i){i.done?s(i.value):_(i.value).then(t,e)}n((y=y.apply(m,E||[])).next())})},r=re&&re.__generator||function(m,E){var C={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},y,_,s,g;return g={next:t(0),throw:t(1),return:t(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function t(n){return function(i){return e([n,i])}}function e(n){if(y)throw new TypeError("Generator is already executing.");for(;C;)try{if(y=1,_&&(s=n[0]&2?_.return:n[0]?_.throw||((s=_.return)&&s.call(_),0):_.next)&&!(s=s.call(_,n[1])).done)return s;switch(_=0,s&&(n=[n[0]&2,s.value]),n[0]){case 0:case 1:s=n;break;case 4:return C.label++,{value:n[1],done:!1};case 5:C.label++,_=n[1],n=[0];continue;case 7:n=C.ops.pop(),C.trys.pop();continue;default:if(s=C.trys,!(s=s.length>0&&s[s.length-1])&&(n[0]===6||n[0]===2)){C=0;continue}if(n[0]===3&&(!s||n[1]>s[0]&&n[1]<s[3])){C.label=n[1];break}if(n[0]===6&&C.label<s[1]){C.label=s[1],s=n;break}if(s&&C.label<s[2]){C.label=s[2],C.ops.push(n);break}s[2]&&C.ops.pop(),C.trys.pop();continue}n=E.call(m,C)}catch(i){n=[6,i],_=0}finally{y=s=0}if(n[0]&5)throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}};Object.defineProperty(re,"__esModule",{value:!0});var l=or(),h=ar(),b=function(m){w(E,m);function E(C,y,_){y===void 0&&(y={}),_===void 0&&(_={});var s=m.call(this)||this;return s._audioNode=null,s._loop=!1,s._pendingPlayDeferreds=[],s._sinkId="default",s._src="",typeof y!="string"&&(_=y),s._audioContext=C,s._audioElement=new(_.AudioFactory||Audio),s._bufferPromise=s._createPlayDeferred().promise,s._destination=s._audioContext.destination,s._gainNode=s._audioContext.createGain(),s._gainNode.connect(s._destination),s._XMLHttpRequest=_.XMLHttpRequestFactory||XMLHttpRequest,s.addEventListener("canplaythrough",function(){s._resolvePlayDeferreds()}),typeof y=="string"&&(s.src=y),s}return Object.defineProperty(E.prototype,"destination",{get:function(){return this._destination},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"loop",{get:function(){return this._loop},set:function(C){var y=this;function _(){y._audioNode.removeEventListener("ended",_),y.pause()}!C&&this.loop&&!this.paused&&this._audioNode.addEventListener("ended",_),this._loop=C},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"muted",{get:function(){return this._gainNode.gain.value===0},set:function(C){this._gainNode.gain.value=C?0:1},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"paused",{get:function(){return this._audioNode===null},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"src",{get:function(){return this._src},set:function(C){this._load(C)},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"srcObject",{get:function(){return this._audioElement.srcObject},set:function(C){this._audioElement.srcObject=C},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"sinkId",{get:function(){return this._sinkId},enumerable:!1,configurable:!0}),E.prototype.load=function(){this._load(this._src)},E.prototype.pause=function(){this.paused||(this._audioElement.pause(),this._audioNode.stop(),this._audioNode.disconnect(this._gainNode),this._audioNode=null,this._rejectPlayDeferreds(new Error("The play() request was interrupted by a call to pause().")))},E.prototype.play=function(){return p(this,void 0,void 0,function(){var C,y=this;return r(this,function(_){switch(_.label){case 0:return this.paused?[3,2]:[4,this._bufferPromise];case 1:if(_.sent(),!this.paused)return[2];throw new Error("The play() request was interrupted by a call to pause().");case 2:return this._audioNode=this._audioContext.createBufferSource(),this._audioNode.loop=this.loop,this._audioNode.addEventListener("ended",function(){y._audioNode&&y._audioNode.loop||y.dispatchEvent("ended")}),[4,this._bufferPromise];case 3:if(C=_.sent(),this.paused)throw new Error("The play() request was interrupted by a call to pause().");return this._audioNode.buffer=C,this._audioNode.connect(this._gainNode),this._audioNode.start(),this._audioElement.srcObject?[2,this._audioElement.play()]:[2]}})})},E.prototype.setSinkId=function(C){return p(this,void 0,void 0,function(){return r(this,function(y){switch(y.label){case 0:if(typeof this._audioElement.setSinkId!="function")throw new Error("This browser does not support setSinkId.");return C===this.sinkId?[2]:C==="default"?(this.paused||this._gainNode.disconnect(this._destination),this._audioElement.srcObject=null,this._destination=this._audioContext.destination,this._gainNode.connect(this._destination),this._sinkId=C,[2]):[4,this._audioElement.setSinkId(C)];case 1:return y.sent(),this._audioElement.srcObject?[2]:(this._gainNode.disconnect(this._audioContext.destination),this._destination=this._audioContext.createMediaStreamDestination(),this._audioElement.srcObject=this._destination.stream,this._sinkId=C,this._gainNode.connect(this._destination),[2])}})})},E.prototype._createPlayDeferred=function(){var C=new l.default;return this._pendingPlayDeferreds.push(C),C},E.prototype._load=function(C){var y=this;this._src&&this._src!==C&&this.pause(),this._src=C,this._bufferPromise=new Promise(function(_,s){return p(y,void 0,void 0,function(){var g;return r(this,function(t){switch(t.label){case 0:return C?[4,S(this._audioContext,this._XMLHttpRequest,C)]:[2,this._createPlayDeferred().promise];case 1:return g=t.sent(),this.dispatchEvent("canplaythrough"),_(g),[2]}})})})},E.prototype._rejectPlayDeferreds=function(C){var y=this._pendingPlayDeferreds;y.splice(0,y.length).forEach(function(_){var s=_.reject;return s(C)})},E.prototype._resolvePlayDeferreds=function(C){var y=this._pendingPlayDeferreds;y.splice(0,y.length).forEach(function(_){var s=_.resolve;return s(C)})},E}(h.default);function S(m,E,C){return p(this,void 0,void 0,function(){var y,_;return r(this,function(s){switch(s.label){case 0:return y=new E,y.open("GET",C,!0),y.responseType="arraybuffer",[4,new Promise(function(g){y.addEventListener("load",g),y.send()})];case 1:_=s.sent();try{return[2,m.decodeAudioData(_.target.response)]}catch{return[2,new Promise(function(t){m.decodeAudioData(_.target.response,t)})]}return[2]}})})}return re.default=b,re}var sn;function cr(){if(sn)return We;sn=1,Object.defineProperty(We,"__esModule",{value:!0});var w=ir(),p=sr(),r=$();function l(b,S,m){if(!(this instanceof l))return new l(b,S,m);if(!b||!S)throw new r.InvalidArgumentError("name and url are required arguments");m=Object.assign({AudioFactory:typeof Audio<"u"?Audio:null,maxDuration:0,shouldLoop:!1},m),m.AudioPlayer=m.audioContext?p.default.bind(p.default,m.audioContext):m.AudioFactory,Object.defineProperties(this,{_Audio:{value:m.AudioPlayer},_activeEls:{value:new Map},_isSinkSupported:{value:m.AudioFactory!==null&&typeof m.AudioFactory.prototype.setSinkId=="function"},_maxDuration:{value:m.maxDuration},_maxDurationTimeout:{value:null,writable:!0},_operations:{value:new w.AsyncQueue},_playPromise:{value:null,writable:!0},_shouldLoop:{value:m.shouldLoop},_sinkIds:{value:["default"]},isPlaying:{enumerable:!0,get:function(){return!!this._playPromise}},name:{enumerable:!0,value:b},url:{enumerable:!0,value:S}}),this._Audio&&this._play(!0,!1)}function h(b){b&&(b.pause(),b.src="",b.srcObject=null,b.load())}return l.prototype._playAudioElement=function(S,m,E){var C=this,y=this._activeEls.get(S);if(!y)throw new r.InvalidArgumentError('sinkId: "'+S+`" doesn't have an audio element`);return y.muted=!!m,y.loop=!!E,y.play().then(function(){return y}).catch(function(_){throw h(y),C._activeEls.delete(S),_})},l.prototype._play=function(S,m){this.isPlaying&&this._stop(),this._maxDuration>0&&(this._maxDurationTimeout=setTimeout(this._stop.bind(this),this._maxDuration)),m=typeof m=="boolean"?m:this._shouldLoop;var E=this,C=this._playPromise=Promise.all(this._sinkIds.map(function(_){if(!E._Audio)return Promise.resolve();var s=E._activeEls.get(_);return s?E._playAudioElement(_,S,m):(s=new E._Audio(E.url),typeof s.setAttribute=="function"&&s.setAttribute("crossorigin","anonymous"),new Promise(function(g){s.addEventListener("canplaythrough",g)}).then(function(){return(E._isSinkSupported?s.setSinkId(_):Promise.resolve()).then(function(){return E._activeEls.set(_,s),E._playPromise?E._playAudioElement(_,S,m):Promise.resolve()})}))}));return C},l.prototype._stop=function(){var S=this;this._activeEls.forEach(function(m,E){S._sinkIds.includes(E)?(m.pause(),m.currentTime=0):(h(m),S._activeEls.delete(E))}),clearTimeout(this._maxDurationTimeout),this._playPromise=null,this._maxDurationTimeout=null},l.prototype.setSinkIds=function(S){this._isSinkSupported&&(S=S.forEach?S:[S],[].splice.apply(this._sinkIds,[0,this._sinkIds.length].concat(S)))},l.prototype.stop=function(){var S=this;this._operations.enqueue(function(){return S._stop(),Promise.resolve()})},l.prototype.play=function(){var S=this;return this._operations.enqueue(function(){return S._play()})},We.default=l,We}var ke={},it={exports:{}},ot={exports:{}},cn;function ur(){return cn||(cn=1,function(){var w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p={rotl:function(r,l){return r<<l|r>>>32-l},rotr:function(r,l){return r<<32-l|r>>>l},endian:function(r){if(r.constructor==Number)return p.rotl(r,8)&16711935|p.rotl(r,24)&4278255360;for(var l=0;l<r.length;l++)r[l]=p.endian(r[l]);return r},randomBytes:function(r){for(var l=[];r>0;r--)l.push(Math.floor(Math.random()*256));return l},bytesToWords:function(r){for(var l=[],h=0,b=0;h<r.length;h++,b+=8)l[b>>>5]|=r[h]<<24-b%32;return l},wordsToBytes:function(r){for(var l=[],h=0;h<r.length*32;h+=8)l.push(r[h>>>5]>>>24-h%32&255);return l},bytesToHex:function(r){for(var l=[],h=0;h<r.length;h++)l.push((r[h]>>>4).toString(16)),l.push((r[h]&15).toString(16));return l.join("")},hexToBytes:function(r){for(var l=[],h=0;h<r.length;h+=2)l.push(parseInt(r.substr(h,2),16));return l},bytesToBase64:function(r){for(var l=[],h=0;h<r.length;h+=3)for(var b=r[h]<<16|r[h+1]<<8|r[h+2],S=0;S<4;S++)h*8+S*6<=r.length*8?l.push(w.charAt(b>>>6*(3-S)&63)):l.push("=");return l.join("")},base64ToBytes:function(r){r=r.replace(/[^A-Z0-9+\/]/ig,"");for(var l=[],h=0,b=0;h<r.length;b=++h%4)b!=0&&l.push((w.indexOf(r.charAt(h-1))&Math.pow(2,-2*b+8)-1)<<b*2|w.indexOf(r.charAt(h))>>>6-b*2);return l}};ot.exports=p}()),ot.exports}var at,un;function ln(){if(un)return at;un=1;var w={utf8:{stringToBytes:function(p){return w.bin.stringToBytes(unescape(encodeURIComponent(p)))},bytesToString:function(p){return decodeURIComponent(escape(w.bin.bytesToString(p)))}},bin:{stringToBytes:function(p){for(var r=[],l=0;l<p.length;l++)r.push(p.charCodeAt(l)&255);return r},bytesToString:function(p){for(var r=[],l=0;l<p.length;l++)r.push(String.fromCharCode(p[l]));return r.join("")}}};return at=w,at}/*!
|
|
254
|
+
* Determine if an object is a Buffer
|
|
255
|
+
*
|
|
256
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
257
|
+
* @license MIT
|
|
258
|
+
*/var st,dn;function lr(){if(dn)return st;dn=1,st=function(r){return r!=null&&(w(r)||p(r)||!!r._isBuffer)};function w(r){return!!r.constructor&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}function p(r){return typeof r.readFloatLE=="function"&&typeof r.slice=="function"&&w(r.slice(0,0))}return st}var fn;function dr(){return fn||(fn=1,function(){var w=ur(),p=ln().utf8,r=lr(),l=ln().bin,h=function(b,S){b.constructor==String?S&&S.encoding==="binary"?b=l.stringToBytes(b):b=p.stringToBytes(b):r(b)?b=Array.prototype.slice.call(b,0):!Array.isArray(b)&&b.constructor!==Uint8Array&&(b=b.toString());for(var m=w.bytesToWords(b),E=b.length*8,C=1732584193,y=-271733879,_=-1732584194,s=271733878,g=0;g<m.length;g++)m[g]=(m[g]<<8|m[g]>>>24)&16711935|(m[g]<<24|m[g]>>>8)&4278255360;m[E>>>5]|=128<<E%32,m[(E+64>>>9<<4)+14]=E;for(var t=h._ff,e=h._gg,n=h._hh,i=h._ii,g=0;g<m.length;g+=16){var o=C,u=y,c=_,a=s;C=t(C,y,_,s,m[g+0],7,-680876936),s=t(s,C,y,_,m[g+1],12,-389564586),_=t(_,s,C,y,m[g+2],17,606105819),y=t(y,_,s,C,m[g+3],22,-1044525330),C=t(C,y,_,s,m[g+4],7,-176418897),s=t(s,C,y,_,m[g+5],12,1200080426),_=t(_,s,C,y,m[g+6],17,-1473231341),y=t(y,_,s,C,m[g+7],22,-45705983),C=t(C,y,_,s,m[g+8],7,1770035416),s=t(s,C,y,_,m[g+9],12,-1958414417),_=t(_,s,C,y,m[g+10],17,-42063),y=t(y,_,s,C,m[g+11],22,-1990404162),C=t(C,y,_,s,m[g+12],7,1804603682),s=t(s,C,y,_,m[g+13],12,-40341101),_=t(_,s,C,y,m[g+14],17,-1502002290),y=t(y,_,s,C,m[g+15],22,1236535329),C=e(C,y,_,s,m[g+1],5,-165796510),s=e(s,C,y,_,m[g+6],9,-1069501632),_=e(_,s,C,y,m[g+11],14,643717713),y=e(y,_,s,C,m[g+0],20,-373897302),C=e(C,y,_,s,m[g+5],5,-701558691),s=e(s,C,y,_,m[g+10],9,38016083),_=e(_,s,C,y,m[g+15],14,-660478335),y=e(y,_,s,C,m[g+4],20,-405537848),C=e(C,y,_,s,m[g+9],5,568446438),s=e(s,C,y,_,m[g+14],9,-1019803690),_=e(_,s,C,y,m[g+3],14,-187363961),y=e(y,_,s,C,m[g+8],20,1163531501),C=e(C,y,_,s,m[g+13],5,-1444681467),s=e(s,C,y,_,m[g+2],9,-51403784),_=e(_,s,C,y,m[g+7],14,1735328473),y=e(y,_,s,C,m[g+12],20,-1926607734),C=n(C,y,_,s,m[g+5],4,-378558),s=n(s,C,y,_,m[g+8],11,-2022574463),_=n(_,s,C,y,m[g+11],16,1839030562),y=n(y,_,s,C,m[g+14],23,-35309556),C=n(C,y,_,s,m[g+1],4,-1530992060),s=n(s,C,y,_,m[g+4],11,1272893353),_=n(_,s,C,y,m[g+7],16,-155497632),y=n(y,_,s,C,m[g+10],23,-1094730640),C=n(C,y,_,s,m[g+13],4,681279174),s=n(s,C,y,_,m[g+0],11,-358537222),_=n(_,s,C,y,m[g+3],16,-722521979),y=n(y,_,s,C,m[g+6],23,76029189),C=n(C,y,_,s,m[g+9],4,-640364487),s=n(s,C,y,_,m[g+12],11,-421815835),_=n(_,s,C,y,m[g+15],16,530742520),y=n(y,_,s,C,m[g+2],23,-995338651),C=i(C,y,_,s,m[g+0],6,-198630844),s=i(s,C,y,_,m[g+7],10,1126891415),_=i(_,s,C,y,m[g+14],15,-1416354905),y=i(y,_,s,C,m[g+5],21,-57434055),C=i(C,y,_,s,m[g+12],6,1700485571),s=i(s,C,y,_,m[g+3],10,-1894986606),_=i(_,s,C,y,m[g+10],15,-1051523),y=i(y,_,s,C,m[g+1],21,-2054922799),C=i(C,y,_,s,m[g+8],6,1873313359),s=i(s,C,y,_,m[g+15],10,-30611744),_=i(_,s,C,y,m[g+6],15,-1560198380),y=i(y,_,s,C,m[g+13],21,1309151649),C=i(C,y,_,s,m[g+4],6,-145523070),s=i(s,C,y,_,m[g+11],10,-1120210379),_=i(_,s,C,y,m[g+2],15,718787259),y=i(y,_,s,C,m[g+9],21,-343485551),C=C+o>>>0,y=y+u>>>0,_=_+c>>>0,s=s+a>>>0}return w.endian([C,y,_,s])};h._ff=function(b,S,m,E,C,y,_){var s=b+(S&m|~S&E)+(C>>>0)+_;return(s<<y|s>>>32-y)+S},h._gg=function(b,S,m,E,C,y,_){var s=b+(S&E|m&~E)+(C>>>0)+_;return(s<<y|s>>>32-y)+S},h._hh=function(b,S,m,E,C,y,_){var s=b+(S^m^E)+(C>>>0)+_;return(s<<y|s>>>32-y)+S},h._ii=function(b,S,m,E,C,y,_){var s=b+(m^(S|~E))+(C>>>0)+_;return(s<<y|s>>>32-y)+S},h._blocksize=16,h._digestsize=16,it.exports=function(b,S){if(b==null)throw new Error("Illegal argument "+b);var m=w.wordsToBytes(h(b,S));return S&&S.asBytes?m:S&&S.asString?l.bytesToString(m):w.bytesToHex(m)}}()),it.exports}var pn;function hn(){if(pn)return ke;pn=1,Object.defineProperty(ke,"__esModule",{value:!0}),ke.generateVoiceEventSid=void 0;var w=dr(),p=$(),r=typeof w=="function"?w:w.default;function l(){if(typeof window!="object")throw new p.NotSupportedError("This platform is not supported.");var b=window.crypto;if(typeof b!="object")throw new p.NotSupportedError("The `crypto` module is not available on this platform.");if(typeof(b.randomUUID||b.getRandomValues)>"u")throw new p.NotSupportedError("Neither `crypto.randomUUID` or `crypto.getRandomValues` are available on this platform.");var S=window.Uint32Array;if(typeof S>"u")throw new p.NotSupportedError("The `Uint32Array` module is not available on this platform.");var m=typeof b.randomUUID=="function"?function(){return b.randomUUID()}:function(){return b.getRandomValues(new Uint32Array(32)).toString()};return r(m())}function h(){return"KX"+l()}return ke.generateVoiceEventSid=h,ke}var vn;function He(){if(vn)return Q;vn=1;var w=Q&&Q.__extends||function(){var R=function(P,A){return R=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,j){d.__proto__=j}||function(d,j){for(var k in j)Object.prototype.hasOwnProperty.call(j,k)&&(d[k]=j[k])},R(P,A)};return function(P,A){R(P,A);function d(){this.constructor=P}P.prototype=A===null?Object.create(A):(d.prototype=A.prototype,new d)}}(),p=Q&&Q.__assign||function(){return p=Object.assign||function(R){for(var P,A=1,d=arguments.length;A<d;A++){P=arguments[A];for(var j in P)Object.prototype.hasOwnProperty.call(P,j)&&(R[j]=P[j])}return R},p.apply(this,arguments)},r=Q&&Q.__awaiter||function(R,P,A,d){function j(k){return k instanceof A?k:new A(function(N){N(k)})}return new(A||(A=Promise))(function(k,N){function D(M){try{x(d.next(M))}catch(L){N(L)}}function U(M){try{x(d.throw(M))}catch(L){N(L)}}function x(M){M.done?k(M.value):j(M.value).then(D,U)}x((d=d.apply(R,P||[])).next())})},l=Q&&Q.__generator||function(R,P){var A={label:0,sent:function(){if(k[0]&1)throw k[1];return k[1]},trys:[],ops:[]},d,j,k,N;return N={next:D(0),throw:D(1),return:D(2)},typeof Symbol=="function"&&(N[Symbol.iterator]=function(){return this}),N;function D(x){return function(M){return U([x,M])}}function U(x){if(d)throw new TypeError("Generator is already executing.");for(;A;)try{if(d=1,j&&(k=x[0]&2?j.return:x[0]?j.throw||((k=j.return)&&k.call(j),0):j.next)&&!(k=k.call(j,x[1])).done)return k;switch(j=0,k&&(x=[x[0]&2,k.value]),x[0]){case 0:case 1:k=x;break;case 4:return A.label++,{value:x[1],done:!1};case 5:A.label++,j=x[1],x=[0];continue;case 7:x=A.ops.pop(),A.trys.pop();continue;default:if(k=A.trys,!(k=k.length>0&&k[k.length-1])&&(x[0]===6||x[0]===2)){A=0;continue}if(x[0]===3&&(!k||x[1]>k[0]&&x[1]<k[3])){A.label=x[1];break}if(x[0]===6&&A.label<k[1]){A.label=k[1],k=x;break}if(k&&A.label<k[2]){A.label=k[2],A.ops.push(x);break}k[2]&&A.ops.pop(),A.trys.pop();continue}x=P.call(R,A)}catch(M){x=[6,M],j=0}finally{d=k=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}};Object.defineProperty(Q,"__esModule",{value:!0});var h=Z(),b=Et(),S=Gn(),m=Hn(),E=ct(),C=_e(),y=$n(),_=$(),s=Jn(),g=X(),t=Wt(),e=Xn(),n=Yn(),i=Zt(),o=nr(),u=cr(),c=fe(),a=hn(),f=3e4,I=2e3,v="twilio-js-sdk",O='Parameter "token" must be of type "string".',T=function(R){w(P,R);function P(A,d){var j;d===void 0&&(d={});var k=R.call(this)||this;if(k._activeCall=null,k._audio=null,k._audioProcessorEventObserver=null,k._callInputStream=null,k._calls=[],k._callSinkIds=["default"],k._chunderURIs=[],k._defaultOptions={allowIncomingWhileBusy:!1,closeProtection:!1,codecPreferences:[E.default.Codec.PCMU,E.default.Codec.Opus],dscp:!0,enableImprovedSignalingErrorPrecision:!1,forceAggressiveIceNomination:!1,logLevel:b.levels.ERROR,maxCallSignalingTimeoutMs:0,preflight:!1,sounds:{},tokenRefreshMs:1e4,voiceEventSidGenerator:a.generateVoiceEventSid},k._edge=null,k._home=null,k._identity=null,k._log=new g.default("Device"),k._makeCallPromise=null,k._options={},k._preferredURI=null,k._publisher=null,k._region=null,k._regTimer=null,k._shouldReRegister=!1,k._soundcache=new Map,k._state=P.State.Unregistered,k._stateEventMapping=(j={},j[P.State.Destroyed]=P.EventName.Destroyed,j[P.State.Unregistered]=P.EventName.Unregistered,j[P.State.Registering]=P.EventName.Registering,j[P.State.Registered]=P.EventName.Registered,j),k._stream=null,k._streamConnectedPromise=null,k._tokenWillExpireTimeout=null,k._createDefaultPayload=function(x){var M={aggressive_nomination:k._options.forceAggressiveIceNomination,browser_extension:k._isBrowserExtension,dscp:!!k._options.dscp,ice_restart_enabled:!0,platform:i.getMediaEngine(),sdk_version:C.RELEASE_VERSION};function L(q,B){B&&(M[q]=B)}if(x){var F=x.parameters.CallSid;L("call_sid",/^TJ/.test(F)?void 0:F),L("temp_call_sid",x.outboundConnectionId),L("audio_codec",x.codec),M.direction=x.direction}return L("gateway",k._stream&&k._stream.gateway),L("region",k._stream&&k._stream.region),M},k._onSignalingClose=function(){k._stream=null,k._streamConnectedPromise=null},k._onSignalingConnected=function(x){var M,L=n.getRegionShortcode(x.region);if(k._edge=x.edge||n.regionToEdge[L]||x.region,k._region=L||x.region,k._home=x.home,(M=k._publisher)===null||M===void 0||M.setHost(n.createEventGatewayURI(x.home)),x.token&&(k._identity=x.token.identity,typeof x.token.ttl=="number"&&typeof k._options.tokenRefreshMs=="number")){var F=x.token.ttl*1e3,q=Math.max(0,F-k._options.tokenRefreshMs);k._tokenWillExpireTimeout=setTimeout(function(){k._log.debug("#tokenWillExpire"),k.emit("tokenWillExpire",k),k._tokenWillExpireTimeout&&(clearTimeout(k._tokenWillExpireTimeout),k._tokenWillExpireTimeout=null)},q)}var B=k._getChunderws()||n.getChunderURIs(k._edge);if(B.length>0){var G=B[0];k._preferredURI=n.createSignalingEndpointURL(G)}else k._log.warn("Could not parse a preferred URI from the stream#connected event.");k._shouldReRegister&&k.register()},k._onSignalingError=function(x){if(typeof x!="object"){k._log.warn("Invalid signaling error payload",x);return}var M=x.error,L=x.callsid,F=x.voiceeventsid;if(typeof M!="object"||F){k._log.warn("Ignoring signaling error payload",{originalError:M,voiceeventsid:F});return}var q=typeof L=="string"&&k._findCall(L)||void 0,B=M.code,G=M.message,W=M.twilioError;if(typeof B=="number")if(B===31201)W=new _.AuthorizationErrors.AuthenticationFailed(M);else if(B===31204)W=new _.AuthorizationErrors.AccessTokenInvalid(M);else if(B===31205)k._stopRegistrationTimer(),W=new _.AuthorizationErrors.AccessTokenExpired(M);else{var z=_.getPreciseSignalingErrorByCode(!!k._options.enableImprovedSignalingErrorPrecision,B);typeof z<"u"&&(W=new z(M))}W||(k._log.error("Unknown signaling error: ",M),W=new _.GeneralErrors.UnknownError(G,M)),k._log.error("Received error: ",W),k._log.debug("#error",M),k.emit(P.EventName.Error,W,q)},k._onSignalingInvite=function(x){return r(k,void 0,void 0,function(){var M,L,F,q,B,G=this,W;return l(this,function(z){switch(z.label){case 0:if(M=!!this._activeCall,M&&!this._options.allowIncomingWhileBusy)return this._log.info("Device busy; ignoring incoming invite"),[2];if(!x.callsid||!x.sdp)return this._log.debug("#error",x),this.emit(P.EventName.Error,new _.ClientErrors.BadRequest("Malformed invite from gateway")),[2];L=x.parameters||{},L.CallSid=L.CallSid||x.callsid,F=Object.assign({},c.queryToJson(L.Params)),this._makeCallPromise=this._makeCall(F,{callParameters:L,enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,offerSdp:x.sdp,reconnectToken:x.reconnect,voiceEventSidGenerator:this._options.voiceEventSidGenerator}),z.label=1;case 1:return z.trys.push([1,,3,4]),[4,this._makeCallPromise];case 2:return q=z.sent(),[3,4];case 3:return this._makeCallPromise=null,[7];case 4:return this._calls.push(q),q.once("accept",function(){G._soundcache.get(P.SoundName.Incoming).stop(),G._publishNetworkChange()}),B=!((W=this._audio)===null||W===void 0)&&W.incoming()&&!M?function(){return G._soundcache.get(P.SoundName.Incoming).play()}:function(){return Promise.resolve()},this._showIncomingCall(q,B),[2]}})})},k._onSignalingOffline=function(){k._log.info("Stream is offline"),k._edge=null,k._region=null,k._shouldReRegister=k.state!==P.State.Unregistered,k._setState(P.State.Unregistered)},k._onSignalingReady=function(){k._log.info("Stream is ready"),k._setState(P.State.Registered)},k._publishNetworkChange=function(){k._activeCall&&k._networkInformation&&k._publisher.info("network-information","network-change",{connection_type:k._networkInformation.type,downlink:k._networkInformation.downlink,downlinkMax:k._networkInformation.downlinkMax,effective_type:k._networkInformation.effectiveType,rtt:k._networkInformation.rtt},k._activeCall)},k._updateInputStream=function(x){var M=k._activeCall;return M&&!x?Promise.reject(new _.InvalidStateError("Cannot unset input device while a call is in progress.")):(k._callInputStream=x,M?M._setInputTracksFromStream(x):Promise.resolve())},k._updateSinkIds=function(x,M){var L=x==="ringtone"?k._updateRingtoneSinkIds(M):k._updateSpeakerSinkIds(M);return L.then(function(){k._publisher.info("audio",x+"-devices-set",{audio_device_ids:M},k._activeCall)},function(F){throw k._publisher.error("audio",x+"-devices-set-failed",{audio_device_ids:M,message:F.message},k._activeCall),F})},k._setupLoglevel(d.logLevel),k._logOptions("constructor",d),k.updateToken(A),c.isLegacyEdge())throw new _.NotSupportedError("Microsoft Edge Legacy (https://support.microsoft.com/en-us/help/4533505/what-is-microsoft-edge-legacy) is deprecated and will not be able to connect to Twilio to make or receive calls after September 1st, 2020. Please see this documentation for a list of supported browsers https://www.twilio.com/docs/voice/client/javascript#supported-browsers");if(!P.isSupported&&d.ignoreBrowserSupport)throw window&&window.location&&window.location.protocol==="http:"?new _.NotSupportedError("twilio.js wasn't able to find WebRTC browser support. This is most likely because this page is served over http rather than https, which does not support WebRTC in many browsers. Please load this page over https and try again."):new _.NotSupportedError("twilio.js 1.3+ SDKs require WebRTC browser support. For more information, see <https://www.twilio.com/docs/api/client/twilio-js>. If you have any questions about this announcement, please contact Twilio Support at <help@twilio.com>.");var N=globalThis,D=N.msBrowser||N.browser||N.chrome;if(k._isBrowserExtension=!!D&&!!D.runtime&&!!D.runtime.id||!!N.safari&&!!N.safari.extension,k._isBrowserExtension&&k._log.info("Running as browser extension."),navigator){var U=navigator;k._networkInformation=U.connection||U.mozConnection||U.webkitConnection}return k._networkInformation&&typeof k._networkInformation.addEventListener=="function"&&k._networkInformation.addEventListener("change",k._publishNetworkChange),P._getOrCreateAudioContext(),P._audioContext&&(P._dialtonePlayer||(P._dialtonePlayer=new y.default(P._audioContext))),typeof P._isUnifiedPlanDefault>"u"&&(P._isUnifiedPlanDefault=typeof window<"u"&&typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u"?c.isUnifiedPlanDefault(window,window.navigator,RTCPeerConnection,RTCRtpTransceiver):!1),k._boundDestroy=k.destroy.bind(k),k._boundConfirmClose=k._confirmClose.bind(k),typeof window<"u"&&window.addEventListener&&(window.addEventListener("unload",k._boundDestroy),window.addEventListener("pagehide",k._boundDestroy)),k.updateOptions(d),k}return Object.defineProperty(P,"audioContext",{get:function(){return P._audioContext},enumerable:!1,configurable:!0}),Object.defineProperty(P,"extension",{get:function(){var A=typeof document<"u"?document.createElement("audio"):{canPlayType:!1},d;try{d=A.canPlayType&&!!A.canPlayType("audio/mpeg").replace(/no/,"")}catch{d=!1}var j;try{j=A.canPlayType&&!!A.canPlayType("audio/ogg;codecs='vorbis'").replace(/no/,"")}catch{j=!1}return j&&!d?"ogg":"mp3"},enumerable:!1,configurable:!0}),Object.defineProperty(P,"isSupported",{get:function(){return i.enabled()},enumerable:!1,configurable:!0}),Object.defineProperty(P,"packageName",{get:function(){return C.PACKAGE_NAME},enumerable:!1,configurable:!0}),P.runPreflight=function(A,d){return new t.PreflightTest(A,p({audioContext:P._getOrCreateAudioContext()},d))},P.toString=function(){return"[Twilio.Device class]"},Object.defineProperty(P,"version",{get:function(){return C.RELEASE_VERSION},enumerable:!1,configurable:!0}),P._getOrCreateAudioContext=function(){return P._audioContext||(typeof AudioContext<"u"?P._audioContext=new AudioContext:typeof webkitAudioContext<"u"&&(P._audioContext=new webkitAudioContext)),P._audioContext},Object.defineProperty(P.prototype,"audio",{get:function(){return this._audio},enumerable:!1,configurable:!0}),P.prototype.connect=function(A){return A===void 0&&(A={}),r(this,void 0,void 0,function(){var d,j,k,N,D,U,x,M,L;return l(this,function(F){switch(F.label){case 0:if(this._log.debug(".connect",JSON.stringify(A)),this._throwIfDestroyed(),this._activeCall)throw new _.InvalidStateError("A Call is already active");if(A.connectToken){try{N=JSON.parse(decodeURIComponent(atob(A.connectToken))),d=N.customParameters,j=N.parameters,k=N.signalingReconnectToken}catch{throw new _.InvalidArgumentError("Cannot parse connectToken")}if(!j||!j.CallSid||!k)throw new _.InvalidArgumentError("Invalid connectToken")}D=!1,U={},x={enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,rtcConfiguration:A.rtcConfiguration,voiceEventSidGenerator:this._options.voiceEventSidGenerator},k&&j?(D=!0,x.callParameters=j,x.reconnectCallSid=j.CallSid,x.reconnectToken=k,U=d||U):U=A.params||U,this._makeCallPromise=this._makeCall(U,x,D),F.label=1;case 1:return F.trys.push([1,,3,4]),L=this,[4,this._makeCallPromise];case 2:return M=L._activeCall=F.sent(),[3,4];case 3:return this._makeCallPromise=null,[7];case 4:return this._calls.splice(0).forEach(function(q){return q.ignore()}),this._soundcache.get(P.SoundName.Incoming).stop(),M.accept({rtcConstraints:A.rtcConstraints}),this._publishNetworkChange(),[2,M]}})})},Object.defineProperty(P.prototype,"calls",{get:function(){return this._calls},enumerable:!1,configurable:!0}),P.prototype.destroy=function(){var A;this._log.debug(".destroy"),this._log.debug("Rejecting any incoming calls");var d=this._calls.slice(0);d.forEach(function(j){return j.reject()}),this.disconnectAll(),this._stopRegistrationTimer(),this._destroyStream(),this._destroyAudioHelper(),(A=this._audioProcessorEventObserver)===null||A===void 0||A.destroy(),this._destroyPublisher(),this._networkInformation&&typeof this._networkInformation.removeEventListener=="function"&&this._networkInformation.removeEventListener("change",this._publishNetworkChange),typeof window<"u"&&window.removeEventListener&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.removeEventListener("unload",this._boundDestroy),window.removeEventListener("pagehide",this._boundDestroy)),this._setState(P.State.Destroyed),h.EventEmitter.prototype.removeAllListeners.call(this)},P.prototype.disconnectAll=function(){this._log.debug(".disconnectAll");var A=this._calls.splice(0);A.forEach(function(d){return d.disconnect()}),this._activeCall&&this._activeCall.disconnect()},Object.defineProperty(P.prototype,"edge",{get:function(){return this._edge},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"home",{get:function(){return this._home},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"identity",{get:function(){return this._identity},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"isBusy",{get:function(){return!!this._activeCall},enumerable:!1,configurable:!0}),P.prototype.register=function(){return r(this,void 0,void 0,function(){return l(this,function(A){switch(A.label){case 0:if(this._log.debug(".register"),this.state!==P.State.Unregistered)throw new _.InvalidStateError('Attempt to register when device is in state "'+this.state+'". '+('Must be "'+P.State.Unregistered+'".'));return this._shouldReRegister=!1,this._setState(P.State.Registering),[4,this._streamConnectedPromise||this._setupStream()];case 1:return A.sent(),[4,this._sendPresence(!0)];case 2:return A.sent(),[4,c.promisifyEvents(this,P.State.Registered,P.State.Unregistered)];case 3:return A.sent(),[2]}})})},Object.defineProperty(P.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"token",{get:function(){return this._token},enumerable:!1,configurable:!0}),P.prototype.toString=function(){return"[Twilio.Device instance]"},P.prototype.unregister=function(){return r(this,void 0,void 0,function(){var A,d;return l(this,function(j){switch(j.label){case 0:if(this._log.debug(".unregister"),this.state!==P.State.Registered)throw new _.InvalidStateError('Attempt to unregister when device is in state "'+this.state+'". '+('Must be "'+P.State.Registered+'".'));return this._shouldReRegister=!1,[4,this._streamConnectedPromise];case 1:return A=j.sent(),d=new Promise(function(k){A.on("offline",k)}),[4,this._sendPresence(!1)];case 2:return j.sent(),[4,d];case 3:return j.sent(),[2]}})})},P.prototype.updateOptions=function(A){if(A===void 0&&(A={}),this._logOptions("updateOptions",A),this.state===P.State.Destroyed)throw new _.InvalidStateError('Attempt to "updateOptions" when device is in state "'+this.state+'".');this._options=p(p(p({},this._defaultOptions),this._options),A);var d=new Set(this._chunderURIs),j=this._chunderURIs=(this._getChunderws()||n.getChunderURIs(this._options.edge)).map(n.createSignalingEndpointURL),k=d.size!==j.length;if(!k)for(var N=0,D=j;N<D.length;N++){var U=D[N];if(!d.has(U)){k=!0;break}}if(this.isBusy&&k)throw new _.InvalidStateError("Cannot change Edge while on an active Call");this._setupLoglevel(this._options.logLevel);for(var x=0,M=Object.keys(P._defaultSounds);x<M.length;x++){var L=M[x],F=P._defaultSounds[L],q=C.SOUNDS_BASE_URL+"/"+F.filename+"."+P.extension+("?cache="+C.RELEASE_VERSION),B=this._options.sounds&&this._options.sounds[L]||q,G=new(this._options.Sound||u.default)(L,B,{audioContext:this._options.disableAudioContextSounds?null:P.audioContext,maxDuration:F.maxDuration,shouldLoop:F.shouldLoop});this._soundcache.set(L,G)}this._setupAudioHelper(),this._setupPublisher(),k&&this._streamConnectedPromise&&this._setupStream(),typeof window<"u"&&typeof window.addEventListener=="function"&&this._options.closeProtection&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.addEventListener("beforeunload",this._boundConfirmClose))},P.prototype.updateToken=function(A){if(this._log.debug(".updateToken"),this.state===P.State.Destroyed)throw new _.InvalidStateError('Attempt to "updateToken" when device is in state "'+this.state+'".');if(typeof A!="string")throw new _.InvalidArgumentError(O);this._token=A,this._stream&&this._stream.setToken(this._token),this._publisher&&this._publisher.setToken(this._token)},P.prototype._confirmClose=function(A){if(!this._activeCall)return"";var d=this._options.closeProtection||!1,j=typeof d!="string"?"A call is currently in-progress. Leaving or reloading this page will end the call.":d;return(A||window.event).returnValue=j,j},P.prototype._destroyAudioHelper=function(){this._audio&&(this._audio._destroy(),this._audio=null)},P.prototype._destroyPublisher=function(){this._publisher&&(this._publisher=null)},P.prototype._destroyStream=function(){this._stream&&(this._stream.removeListener("close",this._onSignalingClose),this._stream.removeListener("connected",this._onSignalingConnected),this._stream.removeListener("error",this._onSignalingError),this._stream.removeListener("invite",this._onSignalingInvite),this._stream.removeListener("offline",this._onSignalingOffline),this._stream.removeListener("ready",this._onSignalingReady),this._stream.destroy(),this._stream=null),this._onSignalingOffline(),this._streamConnectedPromise=null},P.prototype._findCall=function(A){return this._calls.find(function(d){return d.parameters.CallSid===A||d.outboundConnectionId===A})||null},P.prototype._getChunderws=function(){return typeof this._options.chunderw=="string"?[this._options.chunderw]:Array.isArray(this._options.chunderw)?this._options.chunderw:null},P.prototype._logOptions=function(A,d){d===void 0&&(d={});var j=["allowIncomingWhileBusy","appName","appVersion","closeProtection","codecPreferences","disableAudioContextSounds","dscp","edge","enableImprovedSignalingErrorPrecision","forceAggressiveIceNomination","logLevel","maxAverageBitrate","maxCallSignalingTimeoutMs","sounds","tokenRefreshMs"],k=["RTCPeerConnection","enumerateDevices","getUserMedia","MediaStream"];if(typeof d=="object"){var N=p({},d);Object.keys(N).forEach(function(D){!j.includes(D)&&!k.includes(D)&&delete N[D],k.includes(D)&&(N[D]=!0)}),this._log.debug("."+A,JSON.stringify(N))}},P.prototype._makeCall=function(A,d,j){var k;return j===void 0&&(j=!1),r(this,void 0,void 0,function(){var N,D,U,x,M,L=this;return l(this,function(F){switch(F.label){case 0:if(typeof P._isUnifiedPlanDefault>"u")throw new _.InvalidStateError("Device has not been initialized.");return N=(k=this._audio)===null||k===void 0?void 0:k._getInputDevicePromise(),N?(this._log.debug("inputDevicePromise detected, waiting..."),[4,N]):[3,2];case 1:F.sent(),this._log.debug("inputDevicePromise resolved"),F.label=2;case 2:return M={audioHelper:this._audio,isUnifiedPlanDefault:P._isUnifiedPlanDefault,onIgnore:function(){L._soundcache.get(P.SoundName.Incoming).stop()}},[4,this._streamConnectedPromise||this._setupStream()];case 3:return D=(M.pstream=F.sent(),M.publisher=this._publisher,M.soundcache=this._soundcache,M),d=Object.assign({MediaStream:this._options.MediaStream,RTCPeerConnection:this._options.RTCPeerConnection,beforeAccept:function(q){!L._activeCall||L._activeCall===q||(L._activeCall.disconnect(),L._removeCall(L._activeCall))},codecPreferences:this._options.codecPreferences,customSounds:this._options.sounds,dialtonePlayer:P._dialtonePlayer,dscp:this._options.dscp,forceAggressiveIceNomination:this._options.forceAggressiveIceNomination,getInputStream:function(){return L._options.fileInputStream||L._callInputStream},getSinkIds:function(){return L._callSinkIds},maxAverageBitrate:this._options.maxAverageBitrate,preflight:this._options.preflight,rtcConstraints:this._options.rtcConstraints,shouldPlayDisconnect:function(){var q;return(q=L._audio)===null||q===void 0?void 0:q.disconnect()},twimlParams:A,voiceEventSidGenerator:this._options.voiceEventSidGenerator},d),U=function(){if(!L._stream){L._log.warn("UnsetPreferredUri called without a stream");return}L._activeCall===null&&L._calls.length===0&&L._stream.updatePreferredURI(null)},x=new(this._options.Call||E.default)(D,d),this._publisher.info("settings","init",{MediaStream:!!this._options.MediaStream,RTCPeerConnection:!!this._options.RTCPeerConnection,enumerateDevices:!!this._options.enumerateDevices,getUserMedia:!!this._options.getUserMedia},x),x.once("accept",function(){var q,B,G;L._stream.updatePreferredURI(L._preferredURI),L._removeCall(x),L._activeCall=x,L._audio&&L._audio._maybeStartPollingVolume(),x.direction===E.default.CallDirection.Outgoing&&(!((q=L._audio)===null||q===void 0)&&q.outgoing())&&!j&&L._soundcache.get(P.SoundName.Outgoing).play();var W={edge:L._edge||L._region};L._options.edge&&(W.selected_edge=Array.isArray(L._options.edge)?L._options.edge:[L._options.edge]),L._publisher.info("settings","edge",W,x),!((B=L._audio)===null||B===void 0)&&B.processedStream&&((G=L._audioProcessorEventObserver)===null||G===void 0||G.emit("enabled"))}),x.addListener("error",function(q){x.status()==="closed"&&(L._removeCall(x),U()),L._audio&&L._audio._maybeStopPollingVolume(),L._maybeStopIncomingSound()}),x.once("cancel",function(){L._log.info("Canceled: "+x.parameters.CallSid),L._removeCall(x),U(),L._audio&&L._audio._maybeStopPollingVolume(),L._maybeStopIncomingSound()}),x.once("disconnect",function(){L._audio&&L._audio._maybeStopPollingVolume(),L._removeCall(x),U(),L._maybeStopIncomingSound()}),x.once("reject",function(){L._log.info("Rejected: "+x.parameters.CallSid),L._audio&&L._audio._maybeStopPollingVolume(),L._removeCall(x),U(),L._maybeStopIncomingSound()}),x.on("transportClose",function(){x.status()===E.default.State.Pending&&(L._audio&&L._audio._maybeStopPollingVolume(),L._removeCall(x),L._maybeStopIncomingSound())}),[2,x]}})})},P.prototype._maybeStopIncomingSound=function(){this._calls.length||this._soundcache.get(P.SoundName.Incoming).stop()},P.prototype._removeCall=function(A){this._activeCall===A&&(this._activeCall=null,this._makeCallPromise=null);for(var d=this._calls.length-1;d>=0;d--)A===this._calls[d]&&this._calls.splice(d,1)},P.prototype._sendPresence=function(A){return r(this,void 0,void 0,function(){var d;return l(this,function(j){switch(j.label){case 0:return[4,this._streamConnectedPromise];case 1:return d=j.sent(),d?(d.register({audio:A}),A?this._startRegistrationTimer():this._stopRegistrationTimer(),[2]):[2]}})})},P.prototype._setState=function(A){if(A!==this.state){this._state=A;var d=this._stateEventMapping[A];this._log.debug("#"+d),this.emit(d)}},P.prototype._setupAudioHelper=function(){var A=this;this._audioProcessorEventObserver||(this._audioProcessorEventObserver=new m.AudioProcessorEventObserver,this._audioProcessorEventObserver.on("event",function(j){var k=j.name,N=j.group;A._publisher.info(N,k,{},A._activeCall)}));var d={audioContext:P.audioContext,audioProcessorEventObserver:this._audioProcessorEventObserver,beforeSetInputDevice:function(){return A._makeCallPromise?(A._log.debug("beforeSetInputDevice pause detected"),A._makeCallPromise):(A._log.debug("beforeSetInputDevice pause not detected, setting default"),Promise.resolve())},enumerateDevices:this._options.enumerateDevices,getUserMedia:this._options.getUserMedia||o.default};if(this._audio){this._log.info("Found existing audio helper; updating options..."),this._audio._updateUserOptions(d);return}this._audio=new(this._options.AudioHelper||S.default)(this._updateSinkIds,this._updateInputStream,d),this._audio.on("deviceChange",function(j){var k=A._activeCall,N=j.map(function(D){return D.deviceId});A._publisher.info("audio","device-change",{lost_active_device_ids:N},k),k&&k._mediaHandler._onInputDevicesChanged()})},P.prototype._setupLoglevel=function(A){var d=typeof A=="number"||typeof A=="string"?A:b.levels.ERROR;this._log.setDefaultLevel(d),this._log.info("Set logger default level to",d)},P.prototype._setupPublisher=function(){var A=this;this._publisher&&(this._log.info("Found existing publisher; destroying..."),this._destroyPublisher());var d={defaultPayload:this._createDefaultPayload,metadata:{app_name:this._options.appName,app_version:this._options.appVersion}};return this._options.eventgw&&(d.host=this._options.eventgw),this._home&&(d.host=n.createEventGatewayURI(this._home)),this._publisher=new(this._options.Publisher||s.default)(v,this.token,d),this._options.publishEvents===!1?this._publisher.disable():this._publisher.on("error",function(j){A._log.warn("Cannot connect to insights.",j)}),this._publisher},P.prototype._setupStream=function(){var A=this;return this._stream&&(this._log.info("Found existing stream; destroying..."),this._destroyStream()),this._log.info("Setting up VSP"),this._stream=new(this._options.PStream||e.default)(this.token,this._chunderURIs,{backoffMaxMs:this._options.backoffMaxMs,maxPreferredDurationMs:this._options.maxCallSignalingTimeoutMs}),this._stream.addListener("close",this._onSignalingClose),this._stream.addListener("connected",this._onSignalingConnected),this._stream.addListener("error",this._onSignalingError),this._stream.addListener("invite",this._onSignalingInvite),this._stream.addListener("offline",this._onSignalingOffline),this._stream.addListener("ready",this._onSignalingReady),this._streamConnectedPromise=c.promisifyEvents(this._stream,"connected","close").then(function(){return A._stream})},P.prototype._showIncomingCall=function(A,d){var j=this,k;return Promise.race([d(),new Promise(function(N,D){k=setTimeout(function(){var U="Playing incoming ringtone took too long; it might not play. Continuing execution...";D(new Error(U))},I)})]).catch(function(N){j._log.warn(N.message)}).then(function(){clearTimeout(k),j._log.debug("#incoming",JSON.stringify({customParameters:A.customParameters,parameters:A.parameters})),j.emit(P.EventName.Incoming,A)})},P.prototype._startRegistrationTimer=function(){var A=this;this._stopRegistrationTimer(),this._regTimer=setTimeout(function(){A._sendPresence(!0)},f)},P.prototype._stopRegistrationTimer=function(){this._regTimer&&clearTimeout(this._regTimer)},P.prototype._throwIfDestroyed=function(){if(this.state===P.State.Destroyed)throw new _.InvalidStateError("Device has been destroyed.")},P.prototype._updateRingtoneSinkIds=function(A){return Promise.resolve(this._soundcache.get(P.SoundName.Incoming).setSinkIds(A))},P.prototype._updateSpeakerSinkIds=function(A){Array.from(this._soundcache.entries()).filter(function(j){return j[0]!==P.SoundName.Incoming}).forEach(function(j){return j[1].setSinkIds(A)}),this._callSinkIds=A;var d=this._activeCall;return d?d._setSinkIds(A):Promise.resolve()},P._defaultSounds={disconnect:{filename:"disconnect",maxDuration:3e3},dtmf0:{filename:"dtmf-0",maxDuration:1e3},dtmf1:{filename:"dtmf-1",maxDuration:1e3},dtmf2:{filename:"dtmf-2",maxDuration:1e3},dtmf3:{filename:"dtmf-3",maxDuration:1e3},dtmf4:{filename:"dtmf-4",maxDuration:1e3},dtmf5:{filename:"dtmf-5",maxDuration:1e3},dtmf6:{filename:"dtmf-6",maxDuration:1e3},dtmf7:{filename:"dtmf-7",maxDuration:1e3},dtmf8:{filename:"dtmf-8",maxDuration:1e3},dtmf9:{filename:"dtmf-9",maxDuration:1e3},dtmfh:{filename:"dtmf-hash",maxDuration:1e3},dtmfs:{filename:"dtmf-star",maxDuration:1e3},incoming:{filename:"incoming",shouldLoop:!0},outgoing:{filename:"outgoing",maxDuration:3e3}},P}(h.EventEmitter);return function(R){(function(P){P.Error="error",P.Incoming="incoming",P.Destroyed="destroyed",P.Unregistered="unregistered",P.Registering="registering",P.Registered="registered",P.TokenWillExpire="tokenWillExpire"})(R.EventName||(R.EventName={})),function(P){P.Destroyed="destroyed",P.Unregistered="unregistered",P.Registering="registering",P.Registered="registered"}(R.State||(R.State={})),function(P){P.Incoming="incoming",P.Outgoing="outgoing",P.Disconnect="disconnect",P.Dtmf0="dtmf0",P.Dtmf1="dtmf1",P.Dtmf2="dtmf2",P.Dtmf3="dtmf3",P.Dtmf4="dtmf4",P.Dtmf5="dtmf5",P.Dtmf6="dtmf6",P.Dtmf7="dtmf7",P.Dtmf8="dtmf8",P.Dtmf9="dtmf9",P.DtmfS="dtmfs",P.DtmfH="dtmfh"}(R.SoundName||(R.SoundName={}))}(T||(T={})),Q.default=T,Q}var Re={},gn;function fr(){if(gn)return Re;gn=1,Object.defineProperty(Re,"__esModule",{value:!0}),Re.IceCandidate=void 0;var w=function(){function p(r,l){l===void 0&&(l=!1),this.deleted=!1;var h,b=r.candidate.split("network-cost ");b[1]&&(h=parseInt(b[1],10)),this.candidateType=r.type,this.ip=r.ip||r.address,this.isRemote=l,this.networkCost=h,this.port=r.port,this.priority=r.priority,this.protocol=r.protocol,this.relatedAddress=r.relatedAddress,this.relatedPort=r.relatedPort,this.tcpType=r.tcpType,this.transportId=r.sdpMid}return p.prototype.toPayload=function(){return{candidate_type:this.candidateType,deleted:this.deleted,ip:this.ip,is_remote:this.isRemote,"network-cost":this.networkCost,port:this.port,priority:this.priority,protocol:this.protocol,related_address:this.relatedAddress,related_port:this.relatedPort,tcp_type:this.tcpType,transport_id:this.transportId}},p}();return Re.IceCandidate=w,Re}var ie={},pe={},mn;function pr(){if(mn)return pe;mn=1,Object.defineProperty(pe,"__esModule",{value:!0}),pe.isNonNegativeNumber=pe.calculate=void 0;var w=94.768;function p(l,h,b){if(typeof l!="number"||typeof h!="number"||typeof b!="number"||!r(l)||!r(h)||!r(b))return null;var S=l+h*2+10,m=0;switch(!0){case S<160:m=w-S/40;break;case S<1e3:m=w-(S-120)/10;break}switch(!0){case b<=m/2.5:m=Math.max(m-b*2.5,6.52);break;default:m=0;break}var E=1+.035*m+7e-6*m*(m-60)*(100-m);return E}pe.calculate=p;function r(l){return typeof l=="number"&&!isNaN(l)&&isFinite(l)&&l>=0}return pe.isNonNegativeNumber=r,pe.default={calculate:p,isNonNegativeNumber:r},pe}var _n;function hr(){if(_n)return ie;_n=1;var w=ie&&ie.__extends||function(){var u=function(c,a){return u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,I){f.__proto__=I}||function(f,I){for(var v in I)Object.prototype.hasOwnProperty.call(I,v)&&(f[v]=I[v])},u(c,a)};return function(c,a){u(c,a);function f(){this.constructor=c}c.prototype=a===null?Object.create(a):(f.prototype=a.prototype,new f)}}(),p=ie&&ie.__assign||function(){return p=Object.assign||function(u){for(var c,a=1,f=arguments.length;a<f;a++){c=arguments[a];for(var I in c)Object.prototype.hasOwnProperty.call(c,I)&&(u[I]=c[I])}return u},p.apply(this,arguments)},r=ie&&ie.__spreadArrays||function(){for(var u=0,c=0,a=arguments.length;c<a;c++)u+=arguments[c].length;for(var f=Array(u),I=0,c=0;c<a;c++)for(var v=arguments[c],O=0,T=v.length;O<T;O++,I++)f[I]=v[O];return f};Object.defineProperty(ie,"__esModule",{value:!0});var l=Z(),h=$(),b=pr(),S=qt(),m=fe(),E=5,C=0,y=3,_=1e3,s=5*1e3,g={audioInputLevel:{minStandardDeviation:327.67,sampleCount:10},audioOutputLevel:{minStandardDeviation:327.67,sampleCount:10},bytesReceived:{clearCount:2,min:1,raiseCount:3,sampleCount:3},bytesSent:{clearCount:2,min:1,raiseCount:3,sampleCount:3},jitter:{max:30},mos:{min:3},packetsLostFraction:[{max:1},{clearValue:1,maxAverage:3,sampleCount:7}],rtt:{max:400}};function t(u,c){return c.reduce(function(a,f){return a+=f>u?1:0},0)}function e(u,c){return c.reduce(function(a,f){return a+=f<u?1:0},0)}function n(u){if(u.length<=0)return null;var c=u.reduce(function(I,v){return I+v},0)/u.length,a=u.map(function(I){return Math.pow(I-c,2)}),f=Math.sqrt(a.reduce(function(I,v){return I+v},0)/a.length);return f}function i(u){return u.reduce(function(c,a){return r(c,a)},[])}var o=function(u){w(c,u);function c(a){var f=u.call(this)||this;f._activeWarnings=new Map,f._currentStreaks=new Map,f._inputVolumes=[],f._outputVolumes=[],f._sampleBuffer=[],f._supplementalSampleBuffers={audioInputLevel:[],audioOutputLevel:[]},f._warningsEnabled=!0,a=a||{},f._getRTCStats=a.getRTCStats||S.getRTCStats,f._mos=a.Mos||b.default,f._peerConnection=a.peerConnection,f._thresholds=p(p({},g),a.thresholds);var I=Object.values(f._thresholds).map(function(v){return v.sampleCount}).filter(function(v){return!!v});return f._maxSampleCount=Math.max.apply(Math,r([E],I)),f._peerConnection&&f.enable(f._peerConnection),f}return c.prototype.addVolumes=function(a,f){this._inputVolumes.push(a),this._outputVolumes.push(f)},c.prototype.disable=function(){return this._sampleInterval&&(clearInterval(this._sampleInterval),delete this._sampleInterval),this},c.prototype.disableWarnings=function(){return this._warningsEnabled&&this._activeWarnings.clear(),this._warningsEnabled=!1,this},c.prototype.enable=function(a){if(a){if(this._peerConnection&&a!==this._peerConnection)throw new h.InvalidArgumentError("Attempted to replace an existing PeerConnection in StatsMonitor.enable");this._peerConnection=a}if(!this._peerConnection)throw new h.InvalidArgumentError("Can not enable StatsMonitor without a PeerConnection");return this._sampleInterval=this._sampleInterval||setInterval(this._fetchSample.bind(this),_),this},c.prototype.enableWarnings=function(){return this._warningsEnabled=!0,this},c.prototype.hasActiveWarning=function(a,f){var I=a+":"+f;return!!this._activeWarnings.get(I)},c.prototype._addSample=function(a){var f=this._sampleBuffer;f.push(a),f.length>this._maxSampleCount&&f.splice(0,f.length-this._maxSampleCount)},c.prototype._clearWarning=function(a,f,I){var v=a+":"+f,O=this._activeWarnings.get(v);!O||Date.now()-O.timeRaised<s||(this._activeWarnings.delete(v),this.emit("warning-cleared",p(p({},I),{name:a,threshold:{name:f,value:this._thresholds[a][f]}})))},c.prototype._createSample=function(a,f){var I=f&&f.totals.bytesSent||0,v=f&&f.totals.bytesReceived||0,O=f&&f.totals.packetsSent||0,T=f&&f.totals.packetsReceived||0,R=f&&f.totals.packetsLost||0,P=a.bytesSent-I,A=a.bytesReceived-v,d=a.packetsSent-O,j=a.packetsReceived-T,k=a.packetsLost-R,N=j+k,D=N>0?k/N*100:0,U=a.packetsReceived+a.packetsLost,x=U>0?a.packetsLost/U*100:100,M=typeof a.rtt=="number"||!f?a.rtt:f.rtt,L=this._inputVolumes.splice(0);this._supplementalSampleBuffers.audioInputLevel.push(L);var F=this._outputVolumes.splice(0);return this._supplementalSampleBuffers.audioOutputLevel.push(F),{audioInputLevel:Math.round(m.average(L)),audioOutputLevel:Math.round(m.average(F)),bytesReceived:A,bytesSent:P,codecName:a.codecName,jitter:a.jitter,mos:this._mos.calculate(M,a.jitter,f&&D),packetsLost:k,packetsLostFraction:D,packetsReceived:j,packetsSent:d,rtt:M,timestamp:a.timestamp,totals:{bytesReceived:a.bytesReceived,bytesSent:a.bytesSent,packetsLost:a.packetsLost,packetsLostFraction:x,packetsReceived:a.packetsReceived,packetsSent:a.packetsSent}}},c.prototype._fetchSample=function(){var a=this;this._getSample().then(function(f){a._addSample(f),a._raiseWarnings(),a.emit("sample",f)}).catch(function(f){a.disable(),a.emit("error",f)})},c.prototype._getSample=function(){var a=this;return this._getRTCStats(this._peerConnection).then(function(f){var I=null;return a._sampleBuffer.length&&(I=a._sampleBuffer[a._sampleBuffer.length-1]),a._createSample(f,I)})},c.prototype._raiseWarning=function(a,f,I){var v=a+":"+f;if(!this._activeWarnings.has(v)){this._activeWarnings.set(v,{timeRaised:Date.now()});var O=this._thresholds[a],T;if(Array.isArray(O)){var R=O.find(function(P){return f in P});R&&(T=R[f])}else T=this._thresholds[a][f];this.emit("warning",p(p({},I),{name:a,threshold:{name:f,value:T}}))}},c.prototype._raiseWarnings=function(){var a=this;this._warningsEnabled&&Object.keys(this._thresholds).forEach(function(f){return a._raiseWarningsForStat(f)})},c.prototype._raiseWarningsForStat=function(a){var f=this,I=Array.isArray(this._thresholds[a])?this._thresholds[a]:[this._thresholds[a]];I.forEach(function(v){var O=f._sampleBuffer,T=v.clearCount||C,R=v.raiseCount||y,P=v.sampleCount||f._maxSampleCount,A=O.slice(-P),d=A.map(function(q){return q[a]}),j=d.some(function(q){return typeof q>"u"||q===null});if(!j){var k;if(typeof v.max=="number"&&(k=t(v.max,d),k>=R?f._raiseWarning(a,"max",{values:d,samples:A}):k<=T&&f._clearWarning(a,"max",{values:d,samples:A})),typeof v.min=="number"&&(k=e(v.min,d),k>=R?f._raiseWarning(a,"min",{values:d,samples:A}):k<=T&&f._clearWarning(a,"min",{values:d,samples:A})),typeof v.maxDuration=="number"&&O.length>1){A=O.slice(-2);var N=A[0][a],D=A[1][a],U=f._currentStreaks.get(a)||0,x=N===D?U+1:0;f._currentStreaks.set(a,x),x>=v.maxDuration?f._raiseWarning(a,"maxDuration",{value:x}):x===0&&f._clearWarning(a,"maxDuration",{value:U})}if(typeof v.minStandardDeviation=="number"){var M=f._supplementalSampleBuffers[a];if(!M||M.length<v.sampleCount)return;M.length>v.sampleCount&&M.splice(0,M.length-v.sampleCount);var L=i(M.slice(-P)),F=n(L);if(typeof F!="number")return;F<v.minStandardDeviation?f._raiseWarning(a,"minStandardDeviation",{value:F}):f._clearWarning(a,"minStandardDeviation",{value:F})}[["maxAverage",function(q,B){return q>B}],["minAverage",function(q,B){return q<B}]].forEach(function(q){var B=q[0],G=q[1];if(typeof v[B]=="number"&&d.length>=P){var W=m.average(d);G(W,v[B])?f._raiseWarning(a,B,{values:d,samples:A}):G(W,v.clearValue||v[B])||f._clearWarning(a,B,{values:d,samples:A})}})}})},c}(l.EventEmitter);return ie.default=o,ie}var yn;function ct(){if(yn)return le;yn=1;var w=le&&le.__extends||function(){var T=function(R,P){return T=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(A,d){A.__proto__=d}||function(A,d){for(var j in d)Object.prototype.hasOwnProperty.call(d,j)&&(A[j]=d[j])},T(R,P)};return function(R,P){T(R,P);function A(){this.constructor=R}R.prototype=P===null?Object.create(P):(A.prototype=P.prototype,new A)}}(),p=le&&le.__assign||function(){return p=Object.assign||function(T){for(var R,P=1,A=arguments.length;P<A;P++){R=arguments[P];for(var d in R)Object.prototype.hasOwnProperty.call(R,d)&&(T[d]=R[d])}return T},p.apply(this,arguments)};Object.defineProperty(le,"__esModule",{value:!0});var r=Z(),l=Ct(),h=He(),b=$(),S=X(),m=Zt(),E=fr(),C=tt(),y=hr(),_=fe(),s=hn(),g=_e(),t={factor:1.1,jitter:.5,max:3e4,min:1},e=70,n=500,i=160,o=10,u=5e3,c={disconnect:!0,info:{code:31003,message:"Connection with Twilio was interrupted.",twilioError:new b.MediaErrors.ConnectionError}},a={packetsLostFraction:{max:"packet-loss",maxAverage:"packets-lost-fraction"}},f={audioInputLevel:"audio-input-level",audioOutputLevel:"audio-output-level",bytesReceived:"bytes-received",bytesSent:"bytes-sent",jitter:"jitter",mos:"mos",rtt:"rtt"},I={max:"high-",maxAverage:"high-",maxDuration:"constant-",min:"low-",minStandardDeviation:"constant-"},v=function(T){w(R,T);function R(P,A){var d=T.call(this)||this;d.parameters={},d._inputVolumeStreak=0,d._isAnswered=!1,d._isCancelled=!1,d._isRejected=!1,d._latestInputVolume=0,d._latestOutputVolume=0,d._log=new S.default("Call"),d._mediaStatus=R.State.Pending,d._messages=new Map,d._metricsSamples=[],d._options={MediaHandler:m.PeerConnection,MediaStream:null,enableImprovedSignalingErrorPrecision:!1,offerSdp:null,shouldPlayDisconnect:function(){return!0},voiceEventSidGenerator:s.generateVoiceEventSid},d._outputVolumeStreak=0,d._shouldSendHangup=!0,d._signalingStatus=R.State.Pending,d._soundcache=new Map,d._status=R.State.Pending,d._wasConnected=!1,d.toString=function(){return"[Twilio.Call instance]"},d._emitWarning=function(D,U,x,M,L,F){var q=L?"-cleared":"-raised",B=D+"warning"+q;if(!(U==="constant-audio-input-level"&&d.isMuted())){var G=L?"info":"warning";U==="constant-audio-output-level"&&(G="info");var W={threshold:x};if(M&&(M instanceof Array?W.values=M.map(function(ce){return typeof ce=="number"?Math.round(ce*100)/100:M}):W.value=M),d._publisher.post(G,B,U,{data:W},d),U!=="constant-audio-output-level"){var z=L?"warning-cleared":"warning";d._log.debug("#"+z,U),d.emit(z,U,F&&!L?F:null)}}},d._onAck=function(D){var U=D.acktype,x=D.callsid,M=D.voiceeventsid;if(d.parameters.CallSid!==x){d._log.warn("Received ack from a different callsid: "+x);return}U==="message"&&d._onMessageSent(M)},d._onAnswer=function(D){typeof D.reconnect=="string"&&(d._signalingReconnectToken=D.reconnect),!(d._isAnswered&&d._status!==R.State.Reconnecting)&&(d._setCallSid(D),d._isAnswered=!0,d._maybeTransitionToOpen())},d._onCancel=function(D){var U=D.callsid;d.parameters.CallSid===U&&(d._isCancelled=!0,d._publisher.info("connection","cancel",null,d),d._cleanupEventListeners(),d._mediaHandler.close(),d._status=R.State.Closed,d._log.debug("#cancel"),d.emit("cancel"),d._pstream.removeListener("cancel",d._onCancel))},d._onConnected=function(){d._log.info("Received connected from pstream"),d._signalingReconnectToken&&d._mediaHandler.version&&d._pstream.reconnect(d._mediaHandler.version.getSDP(),d.parameters.CallSid,d._signalingReconnectToken)},d._onHangup=function(D){if(d.status()!==R.State.Closed){if(D.callsid&&(d.parameters.CallSid||d.outboundConnectionId)){if(D.callsid!==d.parameters.CallSid&&D.callsid!==d.outboundConnectionId)return}else if(D.callsid)return;if(d._log.info("Received HANGUP from gateway"),D.error){var U=D.error.code,x=b.getPreciseSignalingErrorByCode(d._options.enableImprovedSignalingErrorPrecision,U),M=typeof x<"u"?new x(D.error.message):new b.GeneralErrors.ConnectionError("Error sent from gateway in HANGUP",D.error);d._log.error("Received an error from the gateway:",M),d._log.debug("#error",M),d.emit("error",M)}d._shouldSendHangup=!1,d._publisher.info("connection","disconnected-by-remote",null,d),d._disconnect(null,!0),d._cleanupEventListeners()}},d._onMediaFailure=function(D){var U=R.MediaFailure,x=U.ConnectionDisconnected,M=U.ConnectionFailed,L=U.IceGatheringFailed,F=U.LowBytes,q=D===M||D===L;if(!_.isChrome(window,window.navigator)&&D===M)return d._mediaHandler.onerror(c);if(d._mediaStatus===R.State.Reconnecting){if(q){if(Date.now()-d._mediaReconnectStartTime>t.max)return d._log.warn("Exceeded max ICE retries"),d._mediaHandler.onerror(c);try{d._mediaReconnectBackoff.backoff()}catch(ce){if(!(ce.message&&ce.message==="Backoff in progress."))throw ce}}return}var B=d._mediaHandler.version.pc,G=B&&B.iceConnectionState==="disconnected",W=d._monitor.hasActiveWarning("bytesSent","min")||d._monitor.hasActiveWarning("bytesReceived","min");if(D===F&&G||D===x&&W||q){var z=new b.MediaErrors.ConnectionError("Media connection failed.");d._log.warn("ICE Connection disconnected."),d._publisher.warn("connection","error",z,d),d._publisher.info("connection","reconnecting",null,d),d._mediaReconnectStartTime=Date.now(),d._status=R.State.Reconnecting,d._mediaStatus=R.State.Reconnecting,d._mediaReconnectBackoff.reset(),d._mediaReconnectBackoff.backoff(),d._log.debug("#reconnecting"),d.emit("reconnecting",z)}},d._onMediaReconnected=function(){d._mediaStatus===R.State.Reconnecting&&(d._log.info("ICE Connection reestablished."),d._mediaStatus=R.State.Open,d._signalingStatus===R.State.Open&&(d._publisher.info("connection","reconnected",null,d),d._log.debug("#reconnected"),d.emit("reconnected"),d._status=R.State.Open))},d._onMessageReceived=function(D){var U=D.callsid,x=D.content,M=D.contenttype,L=D.messagetype,F=D.voiceeventsid;if(d.parameters.CallSid!==U){d._log.warn("Received a message from a different callsid: "+U);return}var q={content:x,contentType:M,messageType:L,voiceEventSid:F};d._publisher.info("call-message",L,{content_type:M,event_type:"received",voice_event_sid:F},d),d._log.debug("#messageReceived",JSON.stringify(q)),d.emit("messageReceived",q)},d._onMessageSent=function(D){if(!d._messages.has(D)){d._log.warn("Received a messageSent with a voiceEventSid that doesn't exists: "+D);return}var U=d._messages.get(D);d._messages.delete(D),d._publisher.info("call-message",U==null?void 0:U.messageType,{content_type:U==null?void 0:U.contentType,event_type:"sent",voice_event_sid:D},d),d._log.debug("#messageSent",JSON.stringify(U)),d.emit("messageSent",U)},d._onRinging=function(D){if(d._setCallSid(D),!(d._status!==R.State.Connecting&&d._status!==R.State.Ringing)){var U=!!D.sdp;d._status=R.State.Ringing,d._publisher.info("connection","outgoing-ringing",{hasEarlyMedia:U},d),d._log.debug("#ringing"),d.emit("ringing",U)}},d._onRTCSample=function(D){var U=p(p({},D),{inputVolume:d._latestInputVolume,outputVolume:d._latestOutputVolume});d._codec=U.codecName,d._metricsSamples.push(U),d._metricsSamples.length>=o&&d._publishMetrics(),d.emit("sample",D)},d._onSignalingError=function(D){var U=D.callsid,x=D.voiceeventsid,M=D.error;if(d.parameters.CallSid!==U){d._log.warn("Received an error from a different callsid: "+U);return}if(x&&d._messages.has(x)){d._messages.delete(x),d._log.warn("Received an error while sending a message.",D),d._publisher.error("call-message","error",{code:M.code,message:M.message,voice_event_sid:x},d);var L=void 0,F=b.getPreciseSignalingErrorByCode(!!d._options.enableImprovedSignalingErrorPrecision,M.code);typeof F<"u"&&(L=new F(M)),L||(d._log.error("Unknown Call Message Error: ",M),L=new b.GeneralErrors.UnknownError(M.message,M)),d._log.debug("#error",M,L),d.emit("error",L)}},d._onSignalingReconnected=function(){d._signalingStatus===R.State.Reconnecting&&(d._log.info("Signaling Connection reestablished."),d._signalingStatus=R.State.Open,d._mediaStatus===R.State.Open&&(d._publisher.info("connection","reconnected",null,d),d._log.debug("#reconnected"),d.emit("reconnected"),d._status=R.State.Open))},d._onTransportClose=function(){d._log.error("Received transportClose from pstream"),d._log.debug("#transportClose"),d.emit("transportClose"),d._signalingReconnectToken?(d._status=R.State.Reconnecting,d._signalingStatus=R.State.Reconnecting,d._log.debug("#reconnecting"),d.emit("reconnecting",new b.SignalingErrors.ConnectionDisconnected)):(d._status=R.State.Closed,d._signalingStatus=R.State.Closed)},d._reemitWarning=function(D,U){var x=/^audio/.test(D.name)?"audio-level-":"network-quality-",M=I[D.threshold.name],L;D.name in a?L=a[D.name][D.threshold.name]:D.name in f&&(L=f[D.name]);var F=M+L;d._emitWarning(x,F,D.threshold.value,D.values||D.value,U,D)},d._reemitWarningCleared=function(D){d._reemitWarning(D,!0)},d._isUnifiedPlanDefault=P.isUnifiedPlanDefault,d._soundcache=P.soundcache,typeof P.onIgnore=="function"&&(d._onIgnore=P.onIgnore);var j=A&&A.twimlParams||{};d.customParameters=new Map(Object.entries(j).map(function(D){var U=D[0],x=D[1];return[U,String(x)]})),Object.assign(d._options,A),d._options.callParameters&&(d.parameters=d._options.callParameters),d._options.reconnectToken&&(d._signalingReconnectToken=d._options.reconnectToken),d._voiceEventSidGenerator=d._options.voiceEventSidGenerator||s.generateVoiceEventSid,d._direction=d.parameters.CallSid&&!d._options.reconnectCallSid?R.CallDirection.Incoming:R.CallDirection.Outgoing,d.parameters?d.callerInfo=d.parameters.StirStatus?{isVerified:d.parameters.StirStatus==="TN-Validation-Passed-A"}:null:d.callerInfo=null,d._mediaReconnectBackoff=new l.default(t),d._mediaReconnectBackoff.on("ready",function(){return d._mediaHandler.iceRestart()}),d.outboundConnectionId=O();var k=d._publisher=P.publisher;d._direction===R.CallDirection.Incoming?k.info("connection","incoming",null,d):k.info("connection","outgoing",{preflight:d._options.preflight,reconnect:!!d._options.reconnectCallSid},d);var N=d._monitor=new(d._options.StatsMonitor||y.default);return N.on("sample",d._onRTCSample),N.disableWarnings(),setTimeout(function(){return N.enableWarnings()},u),N.on("warning",function(D,U){(D.name==="bytesSent"||D.name==="bytesReceived")&&d._onMediaFailure(R.MediaFailure.LowBytes),d._reemitWarning(D,U)}),N.on("warning-cleared",function(D){d._reemitWarningCleared(D)}),d._mediaHandler=new d._options.MediaHandler(P.audioHelper,P.pstream,{MediaStream:d._options.MediaStream,RTCPeerConnection:d._options.RTCPeerConnection,codecPreferences:d._options.codecPreferences,dscp:d._options.dscp,forceAggressiveIceNomination:d._options.forceAggressiveIceNomination,isUnifiedPlan:d._isUnifiedPlanDefault,maxAverageBitrate:d._options.maxAverageBitrate}),d.on("volume",function(D,U){d._inputVolumeStreak=d._checkVolume(D,d._inputVolumeStreak,d._latestInputVolume,"input"),d._outputVolumeStreak=d._checkVolume(U,d._outputVolumeStreak,d._latestOutputVolume,"output"),d._latestInputVolume=D,d._latestOutputVolume=U}),d._mediaHandler.onaudio=function(D){d._log.debug("#audio"),d.emit("audio",D)},d._mediaHandler.onvolume=function(D,U,x,M){N.addVolumes(x/255*32767,M/255*32767),d.emit("volume",D,U)},d._mediaHandler.ondtlstransportstatechange=function(D){var U=D==="failed"?"error":"debug";d._publisher.post(U,"dtls-transport-state",D,null,d)},d._mediaHandler.onpcconnectionstatechange=function(D){var U="debug",x=d._mediaHandler.getRTCDtlsTransport();D==="failed"&&(U=x&&x.state==="failed"?"error":"warning"),d._publisher.post(U,"pc-connection-state",D,null,d)},d._mediaHandler.onicecandidate=function(D){var U=new E.IceCandidate(D).toPayload();d._publisher.debug("ice-candidate","ice-candidate",U,d)},d._mediaHandler.onselectedcandidatepairchange=function(D){var U=new E.IceCandidate(D.local).toPayload(),x=new E.IceCandidate(D.remote,!0).toPayload();d._publisher.debug("ice-candidate","selected-ice-candidate-pair",{local_candidate:U,remote_candidate:x},d)},d._mediaHandler.oniceconnectionstatechange=function(D){var U=D==="failed"?"error":"debug";d._publisher.post(U,"ice-connection-state",D,null,d)},d._mediaHandler.onicegatheringfailure=function(D){d._publisher.warn("ice-gathering-state",D,null,d),d._onMediaFailure(R.MediaFailure.IceGatheringFailed)},d._mediaHandler.onicegatheringstatechange=function(D){d._publisher.debug("ice-gathering-state",D,null,d)},d._mediaHandler.onsignalingstatechange=function(D){d._publisher.debug("signaling-state",D,null,d)},d._mediaHandler.ondisconnected=function(D){d._log.warn(D),d._publisher.warn("network-quality-warning-raised","ice-connectivity-lost",{message:D},d),d._log.debug("#warning","ice-connectivity-lost"),d.emit("warning","ice-connectivity-lost"),d._onMediaFailure(R.MediaFailure.ConnectionDisconnected)},d._mediaHandler.onfailed=function(D){d._onMediaFailure(R.MediaFailure.ConnectionFailed)},d._mediaHandler.onconnected=function(){d._status===R.State.Reconnecting&&d._onMediaReconnected()},d._mediaHandler.onreconnected=function(D){d._log.info(D),d._publisher.info("network-quality-warning-cleared","ice-connectivity-lost",{message:D},d),d._log.debug("#warning-cleared","ice-connectivity-lost"),d.emit("warning-cleared","ice-connectivity-lost"),d._onMediaReconnected()},d._mediaHandler.onerror=function(D){D.disconnect===!0&&d._disconnect(D.info&&D.info.message);var U=D.info.twilioError||new b.GeneralErrors.UnknownError(D.info.message);d._log.error("Received an error from MediaStream:",D),d._log.debug("#error",U),d.emit("error",U)},d._mediaHandler.onopen=function(){d._status===R.State.Open||d._status===R.State.Reconnecting||(d._status===R.State.Ringing||d._status===R.State.Connecting?(d.mute(d._mediaHandler.isMuted),d._mediaStatus=R.State.Open,d._maybeTransitionToOpen()):d._mediaHandler.close())},d._mediaHandler.onclose=function(){d._status=R.State.Closed,d._options.shouldPlayDisconnect&&d._options.shouldPlayDisconnect()&&!d._isCancelled&&!d._isRejected&&d._soundcache.get(h.default.SoundName.Disconnect).play(),N.disable(),d._publishMetrics(),!d._isCancelled&&!d._isRejected&&(d._log.debug("#disconnect"),d.emit("disconnect",d))},d._pstream=P.pstream,d._pstream.on("ack",d._onAck),d._pstream.on("cancel",d._onCancel),d._pstream.on("error",d._onSignalingError),d._pstream.on("ringing",d._onRinging),d._pstream.on("transportClose",d._onTransportClose),d._pstream.on("connected",d._onConnected),d._pstream.on("message",d._onMessageReceived),d.on("error",function(D){d._publisher.error("connection","error",{code:D.code,message:D.message},d),d._pstream&&d._pstream.status==="disconnected"&&d._cleanupEventListeners()}),d.on("disconnect",function(){d._cleanupEventListeners()}),d}return Object.defineProperty(R.prototype,"direction",{get:function(){return this._direction},enumerable:!1,configurable:!0}),Object.defineProperty(R.prototype,"codec",{get:function(){return this._codec},enumerable:!1,configurable:!0}),Object.defineProperty(R.prototype,"connectToken",{get:function(){var P=this,A=this._signalingReconnectToken,d=this.parameters&&this.parameters.CallSid?this.parameters.CallSid:void 0;if(!(!A||!d)){var j=this.customParameters&&typeof this.customParameters.keys=="function"?Array.from(this.customParameters.keys()).reduce(function(N,D){return N[D]=P.customParameters.get(D),N},{}):{},k=this.parameters||{};return btoa(encodeURIComponent(JSON.stringify({customParameters:j,parameters:k,signalingReconnectToken:A})))}},enumerable:!1,configurable:!0}),R.prototype._setInputTracksFromStream=function(P){return this._mediaHandler.setInputTracksFromStream(P)},R.prototype._setSinkIds=function(P){return this._mediaHandler._setSinkIds(P)},R.prototype.accept=function(P){var A=this;if(this._log.debug(".accept",P),this._status!==R.State.Pending){this._log.debug(".accept noop. status is '"+this._status+"'");return}P=P||{};var d=P.rtcConfiguration||this._options.rtcConfiguration,j=P.rtcConstraints||this._options.rtcConstraints||{},k={audio:typeof j.audio<"u"?j.audio:!0};this._status=R.State.Connecting;var N=function(){if(A._status!==R.State.Connecting){A._cleanupEventListeners(),A._mediaHandler.close();return}var x=function(F){var q=A._direction===R.CallDirection.Incoming?"accepted-by-local":"accepted-by-remote";A._publisher.info("connection",q,null,A);var B=C.getPreferredCodecInfo(A._mediaHandler.version.getSDP()),G=B.codecName,W=B.codecParams;A._publisher.info("settings","codec",{codec_params:W,selected_codec:G},A),A._monitor.enable(F)},M=typeof A._options.getSinkIds=="function"&&A._options.getSinkIds();if(Array.isArray(M)&&A._mediaHandler._setSinkIds(M).catch(function(){}),A._pstream.addListener("hangup",A._onHangup),A._direction===R.CallDirection.Incoming)A._isAnswered=!0,A._pstream.on("answer",A._onAnswer),A._mediaHandler.answerIncomingCall(A.parameters.CallSid,A._options.offerSdp,d,x);else{var L=Array.from(A.customParameters.entries()).map(function(F){return encodeURIComponent(F[0])+"="+encodeURIComponent(F[1])}).join("&");A._pstream.on("answer",A._onAnswer),A._mediaHandler.makeOutgoingCall(L,A._signalingReconnectToken,A._options.reconnectCallSid||A.outboundConnectionId,d,x)}};this._options.beforeAccept&&this._options.beforeAccept(this);var D=typeof this._options.getInputStream=="function"&&this._options.getInputStream(),U=D?this._mediaHandler.setInputTracksFromStream(D):this._mediaHandler.openDefaultDeviceWithConstraints(k);U.then(function(){A._publisher.info("get-user-media","succeeded",{data:{audioConstraints:k}},A),N()},function(x){var M;x.code===31208||["PermissionDeniedError","NotAllowedError"].indexOf(x.name)!==-1?(M=new b.UserMediaErrors.PermissionDeniedError,A._publisher.error("get-user-media","denied",{data:{audioConstraints:k,error:x}},A)):(M=new b.UserMediaErrors.AcquisitionFailedError,A._publisher.error("get-user-media","failed",{data:{audioConstraints:k,error:x}},A)),A._disconnect(),A._log.debug("#error",x),A.emit("error",M)})},R.prototype.disconnect=function(){this._log.debug(".disconnect"),this._disconnect()},R.prototype.getLocalStream=function(){return this._mediaHandler&&this._mediaHandler.stream},R.prototype.getRemoteStream=function(){return this._mediaHandler&&this._mediaHandler._remoteStream},R.prototype.ignore=function(){if(this._log.debug(".ignore"),this._status!==R.State.Pending){this._log.debug(".ignore noop. status is '"+this._status+"'");return}this._status=R.State.Closed,this._mediaHandler.ignore(this.parameters.CallSid),this._publisher.info("connection","ignored-by-local",null,this),this._onIgnore&&this._onIgnore()},R.prototype.isMuted=function(){return this._mediaHandler.isMuted},R.prototype.mute=function(P){P===void 0&&(P=!0),this._log.debug(".mute",P);var A=this._mediaHandler.isMuted;this._mediaHandler.mute(P);var d=this._mediaHandler.isMuted;A!==d&&(this._publisher.info("connection",d?"muted":"unmuted",null,this),this._log.debug("#mute",d),this.emit("mute",d,this))},R.prototype.postFeedback=function(P,A){if(typeof P>"u"||P===null)return this._postFeedbackDeclined();if(!Object.values(R.FeedbackScore).includes(P))throw new b.InvalidArgumentError("Feedback score must be one of: "+Object.values(R.FeedbackScore));if(typeof A<"u"&&A!==null&&!Object.values(R.FeedbackIssue).includes(A))throw new b.InvalidArgumentError("Feedback issue must be one of: "+Object.values(R.FeedbackIssue));return this._publisher.info("feedback","received",{issue_name:A,quality_score:P},this,!0)},R.prototype.reject=function(){if(this._log.debug(".reject"),this._status!==R.State.Pending){this._log.debug(".reject noop. status is '"+this._status+"'");return}this._isRejected=!0,this._pstream.reject(this.parameters.CallSid),this._mediaHandler.reject(this.parameters.CallSid),this._publisher.info("connection","rejected-by-local",null,this),this._cleanupEventListeners(),this._mediaHandler.close(),this._status=R.State.Closed,this._log.debug("#reject"),this.emit("reject")},R.prototype.sendDigits=function(P){var A=this;if(this._log.debug(".sendDigits",P),P.match(/[^0-9*#w]/))throw new b.InvalidArgumentError("Illegal character passed into sendDigits");var d=this._options.customSounds||{},j=[];P.split("").forEach(function(x){var M=x!=="w"?"dtmf"+x:"";M==="dtmf*"&&(M="dtmfs"),M==="dtmf#"&&(M="dtmfh"),j.push(M)});var k=function(){var x=j.shift();x&&(A._options.dialtonePlayer&&!d[x]?A._options.dialtonePlayer.play(x):A._soundcache.get(x).play()),j.length&&setTimeout(function(){return k()},200)};k();var N=this._mediaHandler.getOrCreateDTMFSender();function D(x){if(x.length){var M=x.shift();M&&M.length&&N.insertDTMF(M,i,e),setTimeout(D.bind(null,x),n)}}if(N){if(!("canInsertDTMF"in N)||N.canInsertDTMF){this._log.info("Sending digits using RTCDTMFSender"),D(P.split("w"));return}this._log.info("RTCDTMFSender cannot insert DTMF")}if(this._log.info("Sending digits over PStream"),this._pstream!==null&&this._pstream.status!=="disconnected")this._pstream.dtmf(this.parameters.CallSid,P);else{var U=new b.GeneralErrors.ConnectionError("Could not send DTMF: Signaling channel is disconnected");this._log.debug("#error",U),this.emit("error",U)}},R.prototype.sendMessage=function(P){this._log.debug(".sendMessage",JSON.stringify(P));var A=P.content,d=P.contentType,j=P.messageType;if(typeof A>"u"||A===null)throw new b.InvalidArgumentError("`content` is empty");if(typeof j!="string")throw new b.InvalidArgumentError("`messageType` must be a string.");if(j.length===0)throw new b.InvalidArgumentError("`messageType` must be a non-empty string.");if(this._pstream===null)throw new b.InvalidStateError("Could not send CallMessage; Signaling channel is disconnected");var k=this.parameters.CallSid;if(typeof this.parameters.CallSid>"u")throw new b.InvalidStateError("Could not send CallMessage; Call has no CallSid");var N=this._voiceEventSidGenerator();return this._messages.set(N,{content:A,contentType:d,messageType:j,voiceEventSid:N}),this._pstream.sendMessage(k,A,d,j,N),N},R.prototype.status=function(){return this._status},R.prototype._checkVolume=function(P,A,d,j){var k=A>=10,N=0;return d===P&&(N=A),N>=10?this._emitWarning("audio-level-","constant-audio-"+j+"-level",10,N,!1):k&&this._emitWarning("audio-level-","constant-audio-"+j+"-level",10,N,!0),N},R.prototype._cleanupEventListeners=function(){var P=this,A=function(){P._pstream&&(P._pstream.removeListener("ack",P._onAck),P._pstream.removeListener("answer",P._onAnswer),P._pstream.removeListener("cancel",P._onCancel),P._pstream.removeListener("error",P._onSignalingError),P._pstream.removeListener("hangup",P._onHangup),P._pstream.removeListener("ringing",P._onRinging),P._pstream.removeListener("transportClose",P._onTransportClose),P._pstream.removeListener("connected",P._onConnected),P._pstream.removeListener("message",P._onMessageReceived))};A(),setTimeout(A,0)},R.prototype._createMetricPayload=function(){var P={call_sid:this.parameters.CallSid,dscp:!!this._options.dscp,sdk_version:g.RELEASE_VERSION};return this._options.gateway&&(P.gateway=this._options.gateway),P.direction=this._direction,P},R.prototype._disconnect=function(P,A){if(P=typeof P=="string"?P:null,!(this._status!==R.State.Open&&this._status!==R.State.Connecting&&this._status!==R.State.Reconnecting&&this._status!==R.State.Ringing)){if(this._log.info("Disconnecting..."),this._pstream!==null&&this._pstream.status!=="disconnected"&&this._shouldSendHangup){var d=this.parameters.CallSid||this.outboundConnectionId;d&&this._pstream.hangup(d,P)}this._cleanupEventListeners(),this._mediaHandler.close(),A||this._publisher.info("connection","disconnected-by-local",null,this)}},R.prototype._maybeTransitionToOpen=function(){this._wasConnected,this._isAnswered&&(this._onSignalingReconnected(),this._signalingStatus=R.State.Open,this._mediaHandler&&this._mediaHandler.status==="open"&&(this._status=R.State.Open,this._wasConnected||(this._wasConnected=!0,this._log.debug("#accept"),this.emit("accept",this))))},R.prototype._postFeedbackDeclined=function(){return this._publisher.info("feedback","received-none",null,this,!0)},R.prototype._publishMetrics=function(){var P=this;this._metricsSamples.length!==0&&this._publisher.postMetrics("quality-metrics-samples","metrics-sample",this._metricsSamples.splice(0),this._createMetricPayload(),this).catch(function(A){P._log.warn("Unable to post metrics to Insights. Received error:",A)})},R.prototype._setCallSid=function(P){var A=P.callsid;A&&(this.parameters.CallSid=A,this._mediaHandler.callSid=A)},R.toString=function(){return"[Twilio.Call class]"},R}(r.EventEmitter);(function(T){(function(R){R.Closed="closed",R.Connecting="connecting",R.Open="open",R.Pending="pending",R.Reconnecting="reconnecting",R.Ringing="ringing"})(T.State||(T.State={})),function(R){R.AudioLatency="audio-latency",R.ChoppyAudio="choppy-audio",R.DroppedCall="dropped-call",R.Echo="echo",R.NoisyCall="noisy-call",R.OneWayAudio="one-way-audio"}(T.FeedbackIssue||(T.FeedbackIssue={})),function(R){R[R.One=1]="One",R[R.Two=2]="Two",R[R.Three=3]="Three",R[R.Four=4]="Four",R[R.Five=5]="Five"}(T.FeedbackScore||(T.FeedbackScore={})),function(R){R.Incoming="INCOMING",R.Outgoing="OUTGOING"}(T.CallDirection||(T.CallDirection={})),function(R){R.Opus="opus",R.PCMU="pcmu"}(T.Codec||(T.Codec={})),function(R){R.None="none",R.Timeout="timeout"}(T.IceGatheringFailureReason||(T.IceGatheringFailureReason={})),function(R){R.ConnectionDisconnected="ConnectionDisconnected",R.ConnectionFailed="ConnectionFailed",R.IceGatheringFailed="IceGatheringFailed",R.LowBytes="LowBytes"}(T.MediaFailure||(T.MediaFailure={}))})(v||(v={}));function O(){return"TJSxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(T){var R=Math.random()*16|0,P=T==="x"?R:R&3|8;return P.toString(16)})}return le.default=v,le}var bn;function vr(){return bn||(bn=1,function(w){Object.defineProperty(w,"__esModule",{value:!0}),w.TwilioError=w.Logger=w.PreflightTest=w.Device=w.Call=void 0;var p=ct();w.Call=p.default;var r=He();w.Device=r.default;var l=$();w.TwilioError=l;var h=X();Object.defineProperty(w,"Logger",{enumerable:!0,get:function(){return h.Logger}});var b=Wt();Object.defineProperty(w,"PreflightTest",{enumerable:!0,get:function(){return b.PreflightTest}})}(Ze)),Ze}var ut=vr();class Sn extends EventTarget{constructor(){super(...arguments),this.device=null,this.activeCall=null,this.callStatus="idle",this.isReady=!1,this.error=null}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get call(){return this.activeCall}updateStatus(p){this.callStatus=p,this.dispatchEvent(new CustomEvent("status-changed",{detail:p}))}async makeCall({agentId:p,passCode:r}){if(!this.activeCall){this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.device&&(this.device.disconnectAll(),this.device.destroy(),this.device=null);try{const l=await fetch("https://voice.dev.hanc.me/token");if(!l.ok)throw new Error(await l.text());const{token:h}=await l.json(),b=new ut.Device(h,{logLevel:1,codecPreferences:[ut.Call.Codec.Opus,ut.Call.Codec.PCMU],enableImprovedSignalingErrorPrecision:!0,edge:"dublin"});this.device=b,b.on("registered",async()=>{this.isReady=!0,this.updateStatus("idle");const S=await b.connect({params:{agent_id:p,pass_code:r}});this.attachCallListeners(S),this.activeCall=S}),b.on("connect",S=>{this.updateStatus("connected"),this.attachCallListeners(S),this.activeCall=S}),b.on("error",()=>{var S,m;this.updateStatus("error"),this.isReady=!1,(S=this.activeCall)==null||S.disconnect(),this.activeCall=null,(m=this.device)==null||m.destroy(),this.device=null}),await b.register()}catch{this.updateStatus("error"),this.isReady=!1}}}attachCallListeners(p){p.on("disconnect",()=>{this.updateStatus("disconnecting"),setTimeout(()=>{var r;this.updateStatus("disconnected"),this.activeCall=null,(r=this.device)==null||r.destroy(),this.device=null},100)}),p.on("error",()=>{var r;this.updateStatus("error"),this.activeCall=null,(r=this.device)==null||r.destroy(),this.device=null}),p.on("ringing",()=>{this.updateStatus("ringing")})}hangUp(){var p;this.activeCall?(this.updateStatus("disconnecting"),this.activeCall.disconnect(),this.activeCall=null,(p=this.device)==null||p.destroy(),this.device=null):this.device&&(this.device.disconnectAll(),this.updateStatus("disconnecting"),this.device.destroy(),this.device=null)}}const Cn=J.html`
|
|
259
|
+
<svg
|
|
260
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
261
|
+
width="22"
|
|
262
|
+
height="22"
|
|
263
|
+
viewBox="0 0 24 24"
|
|
264
|
+
fill="none"
|
|
265
|
+
stroke="currentColor"
|
|
266
|
+
stroke-width="2"
|
|
267
|
+
stroke-linecap="round"
|
|
268
|
+
stroke-linejoin="round"
|
|
269
|
+
>
|
|
270
|
+
<path
|
|
271
|
+
d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07
|
|
272
|
+
19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2
|
|
273
|
+
2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0
|
|
274
|
+
0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0
|
|
275
|
+
0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0
|
|
276
|
+
0 0 2.81.7A2 2 0 0 1 22 16.92z"
|
|
277
|
+
/>
|
|
278
|
+
</svg>
|
|
279
|
+
`,wn=J.html`
|
|
280
|
+
<svg
|
|
281
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
282
|
+
width="22"
|
|
283
|
+
height="22"
|
|
284
|
+
viewBox="0 0 24 24"
|
|
285
|
+
fill="none"
|
|
286
|
+
stroke="currentColor"
|
|
287
|
+
stroke-width="2"
|
|
288
|
+
stroke-linecap="round"
|
|
289
|
+
stroke-linejoin="round"
|
|
290
|
+
>
|
|
291
|
+
<path
|
|
292
|
+
d="M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2
|
|
293
|
+
2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0
|
|
294
|
+
1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0
|
|
295
|
+
1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79
|
|
296
|
+
19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0
|
|
297
|
+
1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0
|
|
298
|
+
1-.45 2.11L8.09 9.91"
|
|
299
|
+
/>
|
|
300
|
+
<line x1="22" x2="2" y1="2" y2="22" />
|
|
301
|
+
</svg>
|
|
302
|
+
`;var gr=Object.defineProperty,mr=Object.getOwnPropertyDescriptor,$e=(w,p,r,l)=>{for(var h=l>1?void 0:l?mr(p,r):p,b=w.length-1,S;b>=0;b--)(S=w[b])&&(h=(l?S(p,r,h):S(h))||h);return l&&h&&gr(p,r,h),h};H.CallControl=class extends J.LitElement{constructor(){super(...arguments),this.callManager=new Sn,this.isCalling=!1,this.handleStatusChange=p=>{const r=p.detail;(r==="disconnected"||r==="error")&&(this.isCalling=!1)},this.toggleCall=async()=>{if(!this.agentId)return new Error("Agent ID is required to make a call.");this.isCalling=!this.isCalling,this.isCalling?(await this.callManager.makeCall({agentId:this.agentId,passCode:this.agentId}),await this.videoElement.play()):(this.callManager.hangUp(),this.videoElement.pause(),this.videoElement.currentTime=0)}}connectedCallback(){super.connectedCallback(),this.callManager.addEventListener("status-changed",this.handleStatusChange)}disconnectedCallback(){super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.hangUp()}updated(p){super.updated(p),p.has("agentId")&&(this.callManager.hangUp(),this.isCalling=!1)}render(){return J.html`
|
|
303
|
+
<div class="wrapper" part="wrapper">
|
|
304
|
+
<div class="filter-light" part="filter-light"></div>
|
|
305
|
+
<div class="filter-gradient" part="filter-gradient"></div>
|
|
306
|
+
<div
|
|
307
|
+
class="filter-overlay"
|
|
308
|
+
part="filter-overlay"
|
|
309
|
+
data-calling=${String(this.isCalling)}
|
|
310
|
+
></div>
|
|
311
|
+
|
|
312
|
+
<video
|
|
313
|
+
muted
|
|
314
|
+
loop
|
|
315
|
+
src="https://cdn.hanc.ai/video/overlay.mp4"
|
|
316
|
+
part="video"
|
|
317
|
+
></video>
|
|
318
|
+
|
|
319
|
+
<div class="content-wrapper" part="content-wrapper">
|
|
320
|
+
<button
|
|
321
|
+
part="button"
|
|
322
|
+
@click=${this.toggleCall}
|
|
323
|
+
class="button"
|
|
324
|
+
data-calling=${String(this.isCalling)}
|
|
325
|
+
>
|
|
326
|
+
${this.isCalling?J.html`<div part="call-off-icon" class="call-off-icon">
|
|
327
|
+
${wn}
|
|
328
|
+
</div>`:J.html`
|
|
329
|
+
<div part="icon-button" class="icon-button">${Cn}</div>
|
|
330
|
+
<span part="button-text">Click to speak to AI</span>
|
|
331
|
+
`}
|
|
332
|
+
</button>
|
|
333
|
+
</div>
|
|
334
|
+
</div>
|
|
335
|
+
`}},H.CallControl.styles=[yt,Nn],$e([Xe({type:String,attribute:"agent-id"})],H.CallControl.prototype,"agentId",2),$e([mt()],H.CallControl.prototype,"isCalling",2),$e([_t("video")],H.CallControl.prototype,"videoElement",2),H.CallControl=$e([dt("hanc-ai-call-control")],H.CallControl);const _r=J.css`
|
|
336
|
+
.root {
|
|
337
|
+
position: fixed;
|
|
338
|
+
right: 24px;
|
|
339
|
+
bottom: 24px;
|
|
340
|
+
background: #fff;
|
|
341
|
+
border-radius: 16px;
|
|
342
|
+
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
|
|
343
|
+
padding: 16px;
|
|
344
|
+
display: flex;
|
|
345
|
+
align-items: center;
|
|
346
|
+
gap: 16px;
|
|
347
|
+
z-index: 9999;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
.avatar-wrapper {
|
|
351
|
+
position: relative;
|
|
352
|
+
overflow: hidden;
|
|
353
|
+
aspect-ratio: 1 / 1;
|
|
354
|
+
border-radius: 50%;
|
|
355
|
+
width: 56px;
|
|
356
|
+
height: 56px;
|
|
357
|
+
min-width: 56px;
|
|
358
|
+
min-height: 56px;
|
|
359
|
+
max-width: 56px;
|
|
360
|
+
max-height: 56px;
|
|
361
|
+
flex-shrink: 0;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
.avatar-video {
|
|
365
|
+
object-fit: cover;
|
|
366
|
+
object-position: center;
|
|
367
|
+
width: 100%;
|
|
368
|
+
height: 100%;
|
|
369
|
+
display: block;
|
|
370
|
+
border-radius: 50%;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
.filter-light,
|
|
374
|
+
.filter-gradient,
|
|
375
|
+
.filter-overlay {
|
|
376
|
+
position: absolute;
|
|
377
|
+
inset: 0;
|
|
378
|
+
width: 100%;
|
|
379
|
+
height: 100%;
|
|
380
|
+
border-radius: 50%;
|
|
381
|
+
pointer-events: none;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
.filter-light {
|
|
385
|
+
background: radial-gradient(circle, rgba(255, 255, 255, 0.3), transparent);
|
|
386
|
+
opacity: 0.4;
|
|
387
|
+
z-index: 10;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
.filter-gradient {
|
|
391
|
+
background: linear-gradient(to right, #63b3ed, #06b6d4, #2563eb);
|
|
392
|
+
background-size: 200% 200%;
|
|
393
|
+
animation: gradientAnimation 8s ease infinite;
|
|
394
|
+
mix-blend-mode: overlay;
|
|
395
|
+
z-index: 11;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
.filter-overlay {
|
|
399
|
+
background: linear-gradient(to right, #63b3ed, #06b6d4, #2563eb);
|
|
400
|
+
background-size: 200% 200%;
|
|
401
|
+
animation: gradientAnimation 8s ease infinite;
|
|
402
|
+
transition: opacity 0.5s;
|
|
403
|
+
z-index: 12;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
.filter-overlay[data-calling='true'] {
|
|
407
|
+
opacity: 0;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
.filter-overlay[data-calling='false'] {
|
|
411
|
+
opacity: 0.7;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
@keyframes gradientAnimation {
|
|
415
|
+
0% {
|
|
416
|
+
background-position: 0% 50%;
|
|
417
|
+
}
|
|
418
|
+
50% {
|
|
419
|
+
background-position: 100% 50%;
|
|
420
|
+
}
|
|
421
|
+
100% {
|
|
422
|
+
background-position: 0% 50%;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
.content {
|
|
427
|
+
display: flex;
|
|
428
|
+
flex-direction: column;
|
|
429
|
+
align-items: flex-start;
|
|
430
|
+
gap: 8px;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
.title {
|
|
434
|
+
font-size: 1.25rem;
|
|
435
|
+
font-weight: 500;
|
|
436
|
+
white-space: nowrap;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
.button {
|
|
440
|
+
background: #000;
|
|
441
|
+
border-radius: 9999px;
|
|
442
|
+
color: #fff;
|
|
443
|
+
display: flex;
|
|
444
|
+
align-items: center;
|
|
445
|
+
justify-content: center;
|
|
446
|
+
gap: 8px;
|
|
447
|
+
font-size: 16px;
|
|
448
|
+
line-height: 20px;
|
|
449
|
+
padding: 0px 10px;
|
|
450
|
+
height: 40px;
|
|
451
|
+
width: 194px;
|
|
452
|
+
border: none;
|
|
453
|
+
cursor: pointer;
|
|
454
|
+
transition: background 0.2s;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
.button:hover {
|
|
458
|
+
background: #6e6e6e;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
.icon-button {
|
|
462
|
+
display: flex;
|
|
463
|
+
align-items: center;
|
|
464
|
+
justify-content: center;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
.icon-button svg {
|
|
468
|
+
width: 16px;
|
|
469
|
+
height: 16px;
|
|
470
|
+
}
|
|
471
|
+
`;var yr=Object.defineProperty,br=Object.getOwnPropertyDescriptor,ze=(w,p,r,l)=>{for(var h=l>1?void 0:l?br(p,r):p,b=w.length-1,S;b>=0;b--)(S=w[b])&&(h=(l?S(p,r,h):S(h))||h);return l&&h&&yr(p,r,h),h};H.FloatingCall=class extends J.LitElement{constructor(){super(...arguments),this.callManager=new Sn,this.isCalling=!1,this.handleStatusChange=p=>{const r=p.detail;(r==="disconnected"||r==="error")&&(this.isCalling=!1)},this.toggleCall=async()=>{if(!this.agentId)return new Error("Agent ID is required to make a call.");this.isCalling=!this.isCalling,this.isCalling?(await this.callManager.makeCall({agentId:this.agentId,passCode:this.agentId}),await this.videoElement.play()):(this.callManager.hangUp(),this.videoElement.pause(),this.videoElement.currentTime=0)}}connectedCallback(){super.connectedCallback(),this.callManager.addEventListener("status-changed",this.handleStatusChange)}disconnectedCallback(){super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.hangUp()}updated(p){super.updated(p),p.has("agentId")&&(this.callManager.hangUp(),this.isCalling=!1)}render(){return J.html`
|
|
472
|
+
<div class="root" part="root">
|
|
473
|
+
<div class="avatar-wrapper" part="avatar-wrapper">
|
|
474
|
+
<div class="filter-light" part="filter-light"></div>
|
|
475
|
+
<div class="filter-gradient" part="filter-gradient"></div>
|
|
476
|
+
<div
|
|
477
|
+
class="filter-overlay"
|
|
478
|
+
part="filter-overlay"
|
|
479
|
+
data-calling=${String(this.isCalling)}
|
|
480
|
+
></div>
|
|
481
|
+
<video
|
|
482
|
+
class="avatar-video"
|
|
483
|
+
part="avatar-video"
|
|
484
|
+
muted
|
|
485
|
+
loop
|
|
486
|
+
src="https://cdn.hanc.ai/video/overlay.mp4"
|
|
487
|
+
></video>
|
|
488
|
+
</div>
|
|
489
|
+
<div class="content" part="content">
|
|
490
|
+
<div class="title" part="title">Need help?</div>
|
|
491
|
+
<button
|
|
492
|
+
part="button"
|
|
493
|
+
@click=${this.toggleCall}
|
|
494
|
+
class="button"
|
|
495
|
+
data-calling=${String(this.isCalling)}
|
|
496
|
+
>
|
|
497
|
+
<div part="icon-button" class="icon-button">
|
|
498
|
+
${this.isCalling?wn:Cn}
|
|
499
|
+
</div>
|
|
500
|
+
<span part="button-text">
|
|
501
|
+
${this.isCalling?"End call":"Start a call"}
|
|
502
|
+
</span>
|
|
503
|
+
</button>
|
|
504
|
+
</div>
|
|
505
|
+
</div>
|
|
506
|
+
`}},H.FloatingCall.styles=[yt,_r],ze([Xe({type:String,attribute:"agent-id"})],H.FloatingCall.prototype,"agentId",2),ze([mt()],H.FloatingCall.prototype,"isCalling",2),ze([_t("video")],H.FloatingCall.prototype,"videoElement",2),H.FloatingCall=ze([dt("hanc-ai-floating-call")],H.FloatingCall),Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});
|