react-sip-kit 0.5.21 → 0.7.0-beta
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/LICENSE +21 -21
- package/README.md +254 -212
- package/dist/components/audio/index.d.ts +2 -2
- package/dist/components/video/index.d.ts +2 -2
- package/dist/configs/index.d.ts +1 -3
- package/dist/configs/types.d.ts +1 -19
- package/dist/constructors/line.d.ts +6 -3
- package/dist/events/registration/index.d.ts +4 -4
- package/dist/events/session/index.d.ts +3 -3
- package/dist/events/transport/index.d.ts +5 -5
- package/dist/hooks/useSipManager/index.d.ts +3 -3
- package/dist/hooks/useWatchConfigs/index.d.ts +1 -0
- package/dist/hooks/useWatchSessionData/index.d.ts +69 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.mjs +1 -1
- package/dist/initializer.d.ts +2 -1
- package/dist/manager.d.ts +70 -68
- package/dist/methods/registration/index.d.ts +4 -4
- package/dist/methods/session/index.d.ts +15 -17
- package/dist/methods/session/spdOptions/index.d.ts +3 -3
- package/dist/store/index.d.ts +3 -3
- package/dist/store/types.d.ts +42 -24
- package/dist/types.d.ts +58 -1
- package/dist/utils/generateUUID.d.ts +1 -0
- package/dist/utils/getMediaDevices/index.d.ts +2 -2
- package/dist/utils/index.d.ts +1 -0
- package/package.json +99 -99
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react"),t=require("react/jsx-runtime");const s=e=>{let t;const s=new Set,i=(e,i)=>{const r="function"==typeof e?e(t):e;if(!Object.is(r,t)){const e=t;t=(null!=i?i:"object"!=typeof r||null===r)?r:Object.assign({},t,r),s.forEach(s=>s(t,e))}},r=()=>t,n={setState:i,getState:r,getInitialState:()=>o,subscribe:e=>(s.add(e),()=>s.delete(e))},o=t=e(i,r,n);return n},i=e=>e;const r=t=>{const r=(e=>e?s(e):s)(t),n=t=>function(t,s=i){const r=e.useSyncExternalStore(t.subscribe,()=>s(t.getState()),()=>s(t.getInitialState()));return e.useDebugValue(r),r}(r,t);return Object.assign(n,r),n};let n=0;const o=(a=(e,t)=>({configs:null,statuses:null,userAgents:void 0,devicesInfo:{hasVideoDevice:!1,hasAudioDevice:!1,hasSpeakerDevice:!1,audioInputDevices:[],videoInputDevices:[],speakerDevices:[]},lines:{},usernamesByLineNumber:{},setSipStore:t=>e(e=>({...e,...t})),setConfig:(t,s)=>{e(e=>({...e,configs:{...e.configs,[t]:s}}))},setUserAgent:(t,s)=>{e(e=>({...e,userAgents:{...e.userAgents,[t]:s}}))},addLine:(t,s)=>{e(e=>({...e,lines:{...e.lines,[t]:{...e.lines?.[t],[s.lineNumber]:s}},usernamesByLineNumber:{...e.usernamesByLineNumber,[s.lineNumber]:t}}))},updateLine:s=>{const i=t().getUsernameByNumber(s.lineNumber);if(!i)return null;e(e=>e.lines?.[i]?.[s.lineNumber]?{...e,lines:{...e.lines,[i]:{...e.lines?.[i],[s.lineNumber]:s}}}:e)},removeLine:s=>{const i=t().getUsernameByNumber(s);if(!i)return null;e(e=>{if(!e.lines?.[i]?.[s])return e;const{[s]:t,...r}=e.lines[i],{[s]:n,...o}=e.usernamesByLineNumber;return{...e,lines:{...e.lines,[i]:{...r}},usernamesByLineNumber:{...o}}})},remove:t=>{if(!t)return null;e(e=>{if(!e.lines?.[t]?.[n])return e;const{[t]:s,...i}=e.lines,{[t]:r,...o}=e.configs,{[t]:a,...c}=e.userAgents,{[t]:d,...h}=e.statuses;return{...e,lines:{...i},configs:{...o},userAgents:{...c},statuses:{...h}}})},removeAll:()=>{e(e=>({...e,lines:{},configs:{},userAgents:{},statuses:{}}))},findLineByNumber:e=>{const s=t().getUsernameByNumber(e);return s?t().lines?.[s]?.[e]??null:null},getSessionByNumber:e=>{const s=t().getUsernameByNumber(e);return s?t().lines?.[s]?.[e]?.sipSession??null:null},getUsernameByNumber:e=>t().usernamesByLineNumber[e]??null,getNewLineNumber:()=>++n}))?r(a):r;var a;const c=e=>{o.setState(t=>({...t,...e}))},d=()=>o.getState(),h=e=>o.getState()?.userAgents?.[e]??null,l=e=>o?.getState()?.configs?.[e]??null;function u({username:t}){return()=>{const s=o(e=>t&&e.lines?.[t]?Object.keys(e.lines?.[t]).length:0),i=o.getState().lines?.[t]??{},r=e.useMemo(()=>Object.values(i),[s]);return{status:o(e=>e?.statuses?.[t])??"connecting",lines:r}}}var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function p(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var f,m={exports:{}};var v=(f||(f=1,function(e,t){var s="__lodash_hash_undefined__",i=9007199254740991,r="[object Arguments]",n="[object Array]",o="[object Boolean]",a="[object Date]",c="[object Error]",d="[object Function]",h="[object Map]",l="[object Number]",u="[object Object]",p="[object Promise]",f="[object RegExp]",m="[object Set]",v="[object String]",w="[object Symbol]",b="[object WeakMap]",S="[object ArrayBuffer]",y="[object DataView]",T=/^\[object .+?Constructor\]$/,$=/^(?:0|[1-9]\d*)$/,E={};E["[object Float32Array]"]=E["[object Float64Array]"]=E["[object Int8Array]"]=E["[object Int16Array]"]=E["[object Int32Array]"]=E["[object Uint8Array]"]=E["[object Uint8ClampedArray]"]=E["[object Uint16Array]"]=E["[object Uint32Array]"]=!0,E[r]=E[n]=E[S]=E[o]=E[y]=E[a]=E[c]=E[d]=E[h]=E[l]=E[u]=E[f]=E[m]=E[v]=E[b]=!1;var R="object"==typeof g&&g&&g.Object===Object&&g,I="object"==typeof self&&self&&self.Object===Object&&self,C=R||I||Function("return this")(),D=t&&!t.nodeType&&t,A=D&&e&&!e.nodeType&&e,_=A&&A.exports===D,k=_&&R.process,H=function(){try{return k&&k.binding&&k.binding("util")}catch(e){}}(),x=H&&H.isTypedArray;function P(e,t){for(var s=-1,i=null==e?0:e.length;++s<i;)if(t(e[s],s,e))return!0;return!1}function O(e){var t=-1,s=Array(e.size);return e.forEach(function(e,i){s[++t]=[i,e]}),s}function q(e){var t=-1,s=Array(e.size);return e.forEach(function(e){s[++t]=e}),s}var M,N,j,F=Array.prototype,L=Function.prototype,U=Object.prototype,B=C["__core-js_shared__"],G=L.toString,V=U.hasOwnProperty,Y=(M=/[^.]+$/.exec(B&&B.keys&&B.keys.IE_PROTO||""))?"Symbol(src)_1."+M:"",W=U.toString,K=RegExp("^"+G.call(V).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),J=_?C.Buffer:void 0,Z=C.Symbol,z=C.Uint8Array,X=U.propertyIsEnumerable,Q=F.splice,ee=Z?Z.toStringTag:void 0,te=Object.getOwnPropertySymbols,se=J?J.isBuffer:void 0,ie=(N=Object.keys,j=Object,function(e){return N(j(e))}),re=He(C,"DataView"),ne=He(C,"Map"),oe=He(C,"Promise"),ae=He(C,"Set"),ce=He(C,"WeakMap"),de=He(Object,"create"),he=qe(re),le=qe(ne),ue=qe(oe),ge=qe(ae),pe=qe(ce),fe=Z?Z.prototype:void 0,me=fe?fe.valueOf:void 0;function ve(e){var t=-1,s=null==e?0:e.length;for(this.clear();++t<s;){var i=e[t];this.set(i[0],i[1])}}function we(e){var t=-1,s=null==e?0:e.length;for(this.clear();++t<s;){var i=e[t];this.set(i[0],i[1])}}function be(e){var t=-1,s=null==e?0:e.length;for(this.clear();++t<s;){var i=e[t];this.set(i[0],i[1])}}function Se(e){var t=-1,s=null==e?0:e.length;for(this.__data__=new be;++t<s;)this.add(e[t])}function ye(e){var t=this.__data__=new we(e);this.size=t.size}function Te(e,t){var s=je(e),i=!s&&Ne(e),r=!s&&!i&&Fe(e),n=!s&&!i&&!r&&Ve(e),o=s||i||r||n,a=o?function(e,t){for(var s=-1,i=Array(e);++s<e;)i[s]=t(s);return i}(e.length,String):[],c=a.length;for(var d in e)!V.call(e,d)||o&&("length"==d||r&&("offset"==d||"parent"==d)||n&&("buffer"==d||"byteLength"==d||"byteOffset"==d)||Oe(d,c))||a.push(d);return a}function $e(e,t){for(var s=e.length;s--;)if(Me(e[s][0],t))return s;return-1}function Ee(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ee&&ee in Object(e)?function(e){var t=V.call(e,ee),s=e[ee];try{e[ee]=void 0;var i=!0}catch(e){}var r=W.call(e);return i&&(t?e[ee]=s:delete e[ee]),r}(e):function(e){return W.call(e)}(e)}function Re(e){return Ge(e)&&Ee(e)==r}function Ie(e,t,s,i,d){return e===t||(null==e||null==t||!Ge(e)&&!Ge(t)?e!=e&&t!=t:function(e,t,s,i,d,g){var p=je(e),b=je(t),T=p?n:Pe(e),$=b?n:Pe(t),E=(T=T==r?u:T)==u,R=($=$==r?u:$)==u,I=T==$;if(I&&Fe(e)){if(!Fe(t))return!1;p=!0,E=!1}if(I&&!E)return g||(g=new ye),p||Ve(e)?Ae(e,t,s,i,d,g):function(e,t,s,i,r,n,d){switch(s){case y:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case S:return!(e.byteLength!=t.byteLength||!n(new z(e),new z(t)));case o:case a:case l:return Me(+e,+t);case c:return e.name==t.name&&e.message==t.message;case f:case v:return e==t+"";case h:var u=O;case m:var g=1&i;if(u||(u=q),e.size!=t.size&&!g)return!1;var p=d.get(e);if(p)return p==t;i|=2,d.set(e,t);var b=Ae(u(e),u(t),i,r,n,d);return d.delete(e),b;case w:if(me)return me.call(e)==me.call(t)}return!1}(e,t,T,s,i,d,g);if(!(1&s)){var C=E&&V.call(e,"__wrapped__"),D=R&&V.call(t,"__wrapped__");if(C||D){var A=C?e.value():e,_=D?t.value():t;return g||(g=new ye),d(A,_,s,i,g)}}return!!I&&(g||(g=new ye),function(e,t,s,i,r,n){var o=1&s,a=_e(e),c=a.length,d=_e(t),h=d.length;if(c!=h&&!o)return!1;for(var l=c;l--;){var u=a[l];if(!(o?u in t:V.call(t,u)))return!1}var g=n.get(e);if(g&&n.get(t))return g==t;var p=!0;n.set(e,t),n.set(t,e);for(var f=o;++l<c;){var m=e[u=a[l]],v=t[u];if(i)var w=o?i(v,m,u,t,e,n):i(m,v,u,e,t,n);if(!(void 0===w?m===v||r(m,v,s,i,n):w)){p=!1;break}f||(f="constructor"==u)}if(p&&!f){var b=e.constructor,S=t.constructor;b==S||!("constructor"in e)||!("constructor"in t)||"function"==typeof b&&b instanceof b&&"function"==typeof S&&S instanceof S||(p=!1)}return n.delete(e),n.delete(t),p}(e,t,s,i,d,g))}(e,t,s,i,Ie,d))}function Ce(e){return!(!Be(e)||function(e){return!!Y&&Y in e}(e))&&(Le(e)?K:T).test(qe(e))}function De(e){if(s=(t=e)&&t.constructor,i="function"==typeof s&&s.prototype||U,t!==i)return ie(e);var t,s,i,r=[];for(var n in Object(e))V.call(e,n)&&"constructor"!=n&&r.push(n);return r}function Ae(e,t,s,i,r,n){var o=1&s,a=e.length,c=t.length;if(a!=c&&!(o&&c>a))return!1;var d=n.get(e);if(d&&n.get(t))return d==t;var h=-1,l=!0,u=2&s?new Se:void 0;for(n.set(e,t),n.set(t,e);++h<a;){var g=e[h],p=t[h];if(i)var f=o?i(p,g,h,t,e,n):i(g,p,h,e,t,n);if(void 0!==f){if(f)continue;l=!1;break}if(u){if(!P(t,function(e,t){if(o=t,!u.has(o)&&(g===e||r(g,e,s,i,n)))return u.push(t);var o})){l=!1;break}}else if(g!==p&&!r(g,p,s,i,n)){l=!1;break}}return n.delete(e),n.delete(t),l}function _e(e){return function(e,t,s){var i=t(e);return je(e)?i:function(e,t){for(var s=-1,i=t.length,r=e.length;++s<i;)e[r+s]=t[s];return e}(i,s(e))}(e,Ye,xe)}function ke(e,t){var s,i,r=e.__data__;return("string"==(i=typeof(s=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==s:null===s)?r["string"==typeof t?"string":"hash"]:r.map}function He(e,t){var s=function(e,t){return null==e?void 0:e[t]}(e,t);return Ce(s)?s:void 0}ve.prototype.clear=function(){this.__data__=de?de(null):{},this.size=0},ve.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},ve.prototype.get=function(e){var t=this.__data__;if(de){var i=t[e];return i===s?void 0:i}return V.call(t,e)?t[e]:void 0},ve.prototype.has=function(e){var t=this.__data__;return de?void 0!==t[e]:V.call(t,e)},ve.prototype.set=function(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=de&&void 0===t?s:t,this},we.prototype.clear=function(){this.__data__=[],this.size=0},we.prototype.delete=function(e){var t=this.__data__,s=$e(t,e);return!(s<0||(s==t.length-1?t.pop():Q.call(t,s,1),--this.size,0))},we.prototype.get=function(e){var t=this.__data__,s=$e(t,e);return s<0?void 0:t[s][1]},we.prototype.has=function(e){return $e(this.__data__,e)>-1},we.prototype.set=function(e,t){var s=this.__data__,i=$e(s,e);return i<0?(++this.size,s.push([e,t])):s[i][1]=t,this},be.prototype.clear=function(){this.size=0,this.__data__={hash:new ve,map:new(ne||we),string:new ve}},be.prototype.delete=function(e){var t=ke(this,e).delete(e);return this.size-=t?1:0,t},be.prototype.get=function(e){return ke(this,e).get(e)},be.prototype.has=function(e){return ke(this,e).has(e)},be.prototype.set=function(e,t){var s=ke(this,e),i=s.size;return s.set(e,t),this.size+=s.size==i?0:1,this},Se.prototype.add=Se.prototype.push=function(e){return this.__data__.set(e,s),this},Se.prototype.has=function(e){return this.__data__.has(e)},ye.prototype.clear=function(){this.__data__=new we,this.size=0},ye.prototype.delete=function(e){var t=this.__data__,s=t.delete(e);return this.size=t.size,s},ye.prototype.get=function(e){return this.__data__.get(e)},ye.prototype.has=function(e){return this.__data__.has(e)},ye.prototype.set=function(e,t){var s=this.__data__;if(s instanceof we){var i=s.__data__;if(!ne||i.length<199)return i.push([e,t]),this.size=++s.size,this;s=this.__data__=new be(i)}return s.set(e,t),this.size=s.size,this};var xe=te?function(e){return null==e?[]:(e=Object(e),function(e,t){for(var s=-1,i=null==e?0:e.length,r=0,n=[];++s<i;){var o=e[s];t(o,s,e)&&(n[r++]=o)}return n}(te(e),function(t){return X.call(e,t)}))}:function(){return[]},Pe=Ee;function Oe(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||$.test(e))&&e>-1&&e%1==0&&e<t}function qe(e){if(null!=e){try{return G.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Me(e,t){return e===t||e!=e&&t!=t}(re&&Pe(new re(new ArrayBuffer(1)))!=y||ne&&Pe(new ne)!=h||oe&&Pe(oe.resolve())!=p||ae&&Pe(new ae)!=m||ce&&Pe(new ce)!=b)&&(Pe=function(e){var t=Ee(e),s=t==u?e.constructor:void 0,i=s?qe(s):"";if(i)switch(i){case he:return y;case le:return h;case ue:return p;case ge:return m;case pe:return b}return t});var Ne=Re(function(){return arguments}())?Re:function(e){return Ge(e)&&V.call(e,"callee")&&!X.call(e,"callee")},je=Array.isArray,Fe=se||function(){return!1};function Le(e){if(!Be(e))return!1;var t=Ee(e);return t==d||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Ue(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}function Be(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Ge(e){return null!=e&&"object"==typeof e}var Ve=x?function(e){return function(t){return e(t)}}(x):function(e){return Ge(e)&&Ue(e.length)&&!!E[Ee(e)]};function Ye(e){return null!=(t=e)&&Ue(t.length)&&!Le(t)?Te(e):De(e);var t}e.exports=function(e,t){return Ie(e,t)}}(m,m.exports)),m.exports),w=p(v);function b(t){const s=e.useRef(),i=e.useRef();return e=>{const r=t(e),n=S(r);return void 0!==i.current&&w(i.current,n)||(i.current=n,s.current=y(r)),s.current}}function S(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if("function"==typeof e)return"__fn__";if(t.has(e))return"__circular__";if(t.set(e,!0),Array.isArray(e))return e.map(e=>S(e,t));if(Object.getPrototypeOf(e)!==Object.prototype)return`__${Object.prototype.toString.call(e)}__`;const s={};for(const i in e)try{s[i]=S(e[i],t)}catch{s[i]="__unclonable__"}return s}function y(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);if("function"==typeof e)return e;if(Array.isArray(e)){const s=[];t.set(e,s);for(const i of e)s.push(y(i,t));return s}if(Object.getPrototypeOf(e)!==Object.prototype)return e;const s={};t.set(e,s);for(const i in e)s[i]=y(e[i],t);return s}function T(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}const $={account:{username:"",password:"",domain:"",wssServer:"",webSocketPort:7443,serverPath:"/ws"},features:{enableVideo:!0,enableRingtone:!0,enableTextMessaging:!0,enableTransfer:!0,enableConference:!0,enableTextExpressions:!1,enableTextDictate:!1,enableAlphanumericDial:!0,enableAccountSettings:!0,enableAppearanceSettings:!0,enableNotificationSettings:!0},media:{audioInputDeviceId:"default",audioOutputDeviceId:"default",videoInputDeviceId:"default",ringerOutputDeviceId:"default",maxFrameRate:30,videoHeight:720,videoAspectRatio:1.777,autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,mirrorVideo:"auto",maxVideoBandwidth:2048,startVideoFullScreen:!1},policy:{autoAnswerPolicy:"manual",doNotDisturbPolicy:"off",callWaitingPolicy:"on",callRecordingPolicy:"manual",intercomPolicy:"off"},registration:{transportConnectionTimeout:15e3,transportReconnectionAttempts:999,transportReconnectionTimeout:3e3,registerExpires:3600,registerExtraHeaders:"",registerExtraContactParams:"",registerContactParams:"",wssInTransport:!0,ipInContact:!1,bundlePolicy:"balanced",iceStunServerJson:"",iceStunCheckTimeout:5e3,subscribeToYourself:!1,voiceMailSubscribe:!1,voicemailDid:"",subscribeVoicemailExpires:3600,inviteExtraHeaders:"",noAnswerTimeout:120},storage:{streamBuffer:50,maxDataStoreDays:0,posterJpegQuality:80},recording:{videoResampleSize:"HD",recordingVideoSize:"HD",recordingVideoFps:12,recordingLayout:"grid"},advanced:{didLength:4,maxDidLength:8,singleInstance:!0,chatEngine:"default"},xmpp:{server:"",websocketPort:"",websocketPath:"",domain:"",profileUser:"",realm:"",realmSeparator:"",chatGroupService:""},permissions:{enableSendFiles:!0,enableSendImages:!0,enableAudioRecording:!0,enableVideoRecording:!0,enableSms:!1,enableFax:!1,enableEmail:!1}};function E(e,t=h(e)){if(!t)return;if(t?.registering)return;if(t.isRegistered())return;t.registering=!0,t.registerer.register({requestDelegate:{onReject(t){!function(e){const t=h(e);if(!t)return;t.registering=!1;const{userAgents:s,statuses:i}=d();c({userAgents:{...s,[e]:t},statuses:{...i,[e]:"disconnected"}})}(e,t.message.reasonPhrase,t.message.statusCode)}}});const{userAgents:s}=d();c({userAgents:{...s,[e]:t}})}function R(e,t=h(e)){if(!t)return;t.isReRegister=!1,t.transport.attemptingReconnection=!1,t.transport.reconnectionAttempts=$.registration.transportReconnectionAttempts,t.transport.attemptingReconnection||t.registering||window.setTimeout(function(){E(e,t)},500);const{userAgents:s,statuses:i}=d();c({userAgents:{...s,[e]:t},statuses:{...i,[e]:"connecting"}})}function I(e,t,s=h(t)){if(!s)return;s.isReRegister=!1;try{s.registerer.unregister()}catch(e){}C(t,s);const{userAgents:i,statuses:r}=d();c({userAgents:{...i,[t]:s},statuses:{...r,[t]:"disconnected"}})}function C(e,t=h(e)){if(!t)return;if(t.registering=!1,t.transport&&t.transport.isConnected())return void R(e,t);setTimeout(function(){t.transport&&t.transport.isConnected()?R(e,t):t.transport.reconnectionAttempts>0&&(t.transport.attemptingReconnection=!0,t.reconnect().catch(function(s){t.transport.attemptingReconnection=!1,C(e,t)}))},l(e)?.registration.transportReconnectionTimeout),t.transport.reconnectionAttempts=t.transport.reconnectionAttempts-1;const{userAgents:s,statuses:i}=d();c({userAgents:{...s,[e]:t},statuses:{...i,[e]:"connecting"}})}class D{lineNumber;displayNumber;sipSession;localSoundMeter;remoteSoundMeter;constructor(e,t){this.lineNumber=e,this.displayNumber=t,this.sipSession=null,this.localSoundMeter=null,this.remoteSoundMeter=null}}var A;!function(e){e.SOUND_TOGGLE="SOUND_TOGGLE",e.VIDEO_TOGGLE="VIDEO_TOGGLE",e.SCREEN_SHARE_TOGGLE="SCREEN_SHARE_TOGGLE",e.VIDEO_TOGGLE_ACK="VIDEO_TOGGLE_ACK"}(A||(A={}));var _,k={exports:{}};var H,x=(_||(_=1,k.exports=function(){var e=1e3,t=6e4,s=36e5,i="millisecond",r="second",n="minute",o="hour",a="day",c="week",d="month",h="quarter",l="year",u="date",g="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,f=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,m={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(e){var t=["th","st","nd","rd"],s=e%100;return"["+e+(t[(s-20)%10]||t[s]||t[0])+"]"}},v=function(e,t,s){var i=String(e);return!i||i.length>=t?e:""+Array(t+1-i.length).join(s)+e},w={s:v,z:function(e){var t=-e.utcOffset(),s=Math.abs(t),i=Math.floor(s/60),r=s%60;return(t<=0?"+":"-")+v(i,2,"0")+":"+v(r,2,"0")},m:function e(t,s){if(t.date()<s.date())return-e(s,t);var i=12*(s.year()-t.year())+(s.month()-t.month()),r=t.clone().add(i,d),n=s-r<0,o=t.clone().add(i+(n?-1:1),d);return+(-(i+(s-r)/(n?r-o:o-r))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:d,y:l,w:c,d:a,D:u,h:o,m:n,s:r,ms:i,Q:h}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},b="en",S={};S[b]=m;var y="$isDayjsObject",T=function(e){return e instanceof I||!(!e||!e[y])},$=function e(t,s,i){var r;if(!t)return b;if("string"==typeof t){var n=t.toLowerCase();S[n]&&(r=n),s&&(S[n]=s,r=n);var o=t.split("-");if(!r&&o.length>1)return e(o[0])}else{var a=t.name;S[a]=t,r=a}return!i&&r&&(b=r),r||!i&&b},E=function(e,t){if(T(e))return e.clone();var s="object"==typeof t?t:{};return s.date=e,s.args=arguments,new I(s)},R=w;R.l=$,R.i=T,R.w=function(e,t){return E(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var I=function(){function m(e){this.$L=$(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[y]=!0}var v=m.prototype;return v.parse=function(e){this.$d=function(e){var t=e.date,s=e.utc;if(null===t)return new Date(NaN);if(R.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var i=t.match(p);if(i){var r=i[2]-1||0,n=(i[7]||"0").substring(0,3);return s?new Date(Date.UTC(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,n)):new Date(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,n)}}return new Date(t)}(e),this.init()},v.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},v.$utils=function(){return R},v.isValid=function(){return!(this.$d.toString()===g)},v.isSame=function(e,t){var s=E(e);return this.startOf(t)<=s&&s<=this.endOf(t)},v.isAfter=function(e,t){return E(e)<this.startOf(t)},v.isBefore=function(e,t){return this.endOf(t)<E(e)},v.$g=function(e,t,s){return R.u(e)?this[t]:this.set(s,e)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(e,t){var s=this,i=!!R.u(t)||t,h=R.p(e),g=function(e,t){var r=R.w(s.$u?Date.UTC(s.$y,t,e):new Date(s.$y,t,e),s);return i?r:r.endOf(a)},p=function(e,t){return R.w(s.toDate()[e].apply(s.toDate("s"),(i?[0,0,0,0]:[23,59,59,999]).slice(t)),s)},f=this.$W,m=this.$M,v=this.$D,w="set"+(this.$u?"UTC":"");switch(h){case l:return i?g(1,0):g(31,11);case d:return i?g(1,m):g(0,m+1);case c:var b=this.$locale().weekStart||0,S=(f<b?f+7:f)-b;return g(i?v-S:v+(6-S),m);case a:case u:return p(w+"Hours",0);case o:return p(w+"Minutes",1);case n:return p(w+"Seconds",2);case r:return p(w+"Milliseconds",3);default:return this.clone()}},v.endOf=function(e){return this.startOf(e,!1)},v.$set=function(e,t){var s,c=R.p(e),h="set"+(this.$u?"UTC":""),g=(s={},s[a]=h+"Date",s[u]=h+"Date",s[d]=h+"Month",s[l]=h+"FullYear",s[o]=h+"Hours",s[n]=h+"Minutes",s[r]=h+"Seconds",s[i]=h+"Milliseconds",s)[c],p=c===a?this.$D+(t-this.$W):t;if(c===d||c===l){var f=this.clone().set(u,1);f.$d[g](p),f.init(),this.$d=f.set(u,Math.min(this.$D,f.daysInMonth())).$d}else g&&this.$d[g](p);return this.init(),this},v.set=function(e,t){return this.clone().$set(e,t)},v.get=function(e){return this[R.p(e)]()},v.add=function(i,h){var u,g=this;i=Number(i);var p=R.p(h),f=function(e){var t=E(g);return R.w(t.date(t.date()+Math.round(e*i)),g)};if(p===d)return this.set(d,this.$M+i);if(p===l)return this.set(l,this.$y+i);if(p===a)return f(1);if(p===c)return f(7);var m=(u={},u[n]=t,u[o]=s,u[r]=e,u)[p]||1,v=this.$d.getTime()+i*m;return R.w(v,this)},v.subtract=function(e,t){return this.add(-1*e,t)},v.format=function(e){var t=this,s=this.$locale();if(!this.isValid())return s.invalidDate||g;var i=e||"YYYY-MM-DDTHH:mm:ssZ",r=R.z(this),n=this.$H,o=this.$m,a=this.$M,c=s.weekdays,d=s.months,h=s.meridiem,l=function(e,s,r,n){return e&&(e[s]||e(t,i))||r[s].slice(0,n)},u=function(e){return R.s(n%12||12,e,"0")},p=h||function(e,t,s){var i=e<12?"AM":"PM";return s?i.toLowerCase():i};return i.replace(f,function(e,i){return i||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return R.s(t.$y,4,"0");case"M":return a+1;case"MM":return R.s(a+1,2,"0");case"MMM":return l(s.monthsShort,a,d,3);case"MMMM":return l(d,a);case"D":return t.$D;case"DD":return R.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return l(s.weekdaysMin,t.$W,c,2);case"ddd":return l(s.weekdaysShort,t.$W,c,3);case"dddd":return c[t.$W];case"H":return String(n);case"HH":return R.s(n,2,"0");case"h":return u(1);case"hh":return u(2);case"a":return p(n,o,!0);case"A":return p(n,o,!1);case"m":return String(o);case"mm":return R.s(o,2,"0");case"s":return String(t.$s);case"ss":return R.s(t.$s,2,"0");case"SSS":return R.s(t.$ms,3,"0");case"Z":return r}return null}(e)||r.replace(":","")})},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(i,u,g){var p,f=this,m=R.p(u),v=E(i),w=(v.utcOffset()-this.utcOffset())*t,b=this-v,S=function(){return R.m(f,v)};switch(m){case l:p=S()/12;break;case d:p=S();break;case h:p=S()/3;break;case c:p=(b-w)/6048e5;break;case a:p=(b-w)/864e5;break;case o:p=b/s;break;case n:p=b/t;break;case r:p=b/e;break;default:p=b}return g?p:R.a(p)},v.daysInMonth=function(){return this.endOf(d).$D},v.$locale=function(){return S[this.$L]},v.locale=function(e,t){if(!e)return this.$L;var s=this.clone(),i=$(e,t,!0);return i&&(s.$L=i),s},v.clone=function(){return R.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},m}(),C=I.prototype;return E.prototype=C,[["$ms",i],["$s",r],["$m",n],["$H",o],["$W",a],["$M",d],["$y",l],["$D",u]].forEach(function(e){C[e[1]]=function(t){return this.$g(t,e[0],e[1])}}),E.extend=function(e,t){return e.$i||(e(t,I,E),e.$i=!0),E},E.locale=$,E.isDayjs=T,E.unix=function(e){return E(1e3*e)},E.en=S[b],E.Ls=S,E.p={},E}()),k.exports),P=p(x),O={exports:{}};var q,M,N,j,F,L,U,B,G,V,Y,W,K,J,Z,z,X,Q,ee,te,se=(H||(H=1,O.exports=(U=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,V=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,Y={years:B=31536e6,months:G=2628e6,days:L=864e5,hours:F=36e5,minutes:j=6e4,seconds:N=1e3,milliseconds:1,weeks:6048e5},W=function(e){return e instanceof ee},K=function(e,t,s){return new ee(e,s,t.$l)},J=function(e){return M.p(e)+"s"},Z=function(e){return e<0},z=function(e){return Z(e)?Math.ceil(e):Math.floor(e)},X=function(e){return Math.abs(e)},Q=function(e,t){return e?Z(e)?{negative:!0,format:""+X(e)+t}:{negative:!1,format:""+e+t}:{negative:!1,format:""}},ee=function(){function e(e,t,s){var i=this;if(this.$d={},this.$l=s,void 0===e&&(this.$ms=0,this.parseFromMilliseconds()),t)return K(e*Y[J(t)],this);if("number"==typeof e)return this.$ms=e,this.parseFromMilliseconds(),this;if("object"==typeof e)return Object.keys(e).forEach(function(t){i.$d[J(t)]=e[t]}),this.calMilliseconds(),this;if("string"==typeof e){var r=e.match(V);if(r){var n=r.slice(2).map(function(e){return null!=e?Number(e):0});return this.$d.years=n[0],this.$d.months=n[1],this.$d.weeks=n[2],this.$d.days=n[3],this.$d.hours=n[4],this.$d.minutes=n[5],this.$d.seconds=n[6],this.calMilliseconds(),this}}return this}var t=e.prototype;return t.calMilliseconds=function(){var e=this;this.$ms=Object.keys(this.$d).reduce(function(t,s){return t+(e.$d[s]||0)*Y[s]},0)},t.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=z(e/B),e%=B,this.$d.months=z(e/G),e%=G,this.$d.days=z(e/L),e%=L,this.$d.hours=z(e/F),e%=F,this.$d.minutes=z(e/j),e%=j,this.$d.seconds=z(e/N),e%=N,this.$d.milliseconds=e},t.toISOString=function(){var e=Q(this.$d.years,"Y"),t=Q(this.$d.months,"M"),s=+this.$d.days||0;this.$d.weeks&&(s+=7*this.$d.weeks);var i=Q(s,"D"),r=Q(this.$d.hours,"H"),n=Q(this.$d.minutes,"M"),o=this.$d.seconds||0;this.$d.milliseconds&&(o+=this.$d.milliseconds/1e3,o=Math.round(1e3*o)/1e3);var a=Q(o,"S"),c=e.negative||t.negative||i.negative||r.negative||n.negative||a.negative,d=r.format||n.format||a.format?"T":"",h=(c?"-":"")+"P"+e.format+t.format+i.format+d+r.format+n.format+a.format;return"P"===h||"-P"===h?"P0D":h},t.toJSON=function(){return this.toISOString()},t.format=function(e){var t=e||"YYYY-MM-DDTHH:mm:ss",s={Y:this.$d.years,YY:M.s(this.$d.years,2,"0"),YYYY:M.s(this.$d.years,4,"0"),M:this.$d.months,MM:M.s(this.$d.months,2,"0"),D:this.$d.days,DD:M.s(this.$d.days,2,"0"),H:this.$d.hours,HH:M.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:M.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:M.s(this.$d.seconds,2,"0"),SSS:M.s(this.$d.milliseconds,3,"0")};return t.replace(U,function(e,t){return t||String(s[e])})},t.as=function(e){return this.$ms/Y[J(e)]},t.get=function(e){var t=this.$ms,s=J(e);return"milliseconds"===s?t%=1e3:t="weeks"===s?z(t/Y[s]):this.$d[s],t||0},t.add=function(e,t,s){var i;return i=t?e*Y[J(t)]:W(e)?e.$ms:K(e,this).$ms,K(this.$ms+i*(s?-1:1),this)},t.subtract=function(e,t){return this.add(e,t,!0)},t.locale=function(e){var t=this.clone();return t.$l=e,t},t.clone=function(){return K(this.$ms,this)},t.humanize=function(e){return q().add(this.$ms,"ms").locale(this.$l).fromNow(!e)},t.valueOf=function(){return this.asMilliseconds()},t.milliseconds=function(){return this.get("milliseconds")},t.asMilliseconds=function(){return this.as("milliseconds")},t.seconds=function(){return this.get("seconds")},t.asSeconds=function(){return this.as("seconds")},t.minutes=function(){return this.get("minutes")},t.asMinutes=function(){return this.as("minutes")},t.hours=function(){return this.get("hours")},t.asHours=function(){return this.as("hours")},t.days=function(){return this.get("days")},t.asDays=function(){return this.as("days")},t.weeks=function(){return this.get("weeks")},t.asWeeks=function(){return this.as("weeks")},t.months=function(){return this.get("months")},t.asMonths=function(){return this.as("months")},t.years=function(){return this.get("years")},t.asYears=function(){return this.as("years")},e}(),te=function(e,t,s){return e.add(t.years()*s,"y").add(t.months()*s,"M").add(t.days()*s,"d").add(t.hours()*s,"h").add(t.minutes()*s,"m").add(t.seconds()*s,"s").add(t.milliseconds()*s,"ms")},function(e,t,s){q=s,M=s().$utils(),s.duration=function(e,t){var i=s.locale();return K(e,{$l:i},t)},s.isDuration=W;var i=t.prototype.add,r=t.prototype.subtract;t.prototype.add=function(e,t){return W(e)?te(this,e,1):i.bind(this)(e,t)},t.prototype.subtract=function(e,t){return W(e)?te(this,e,-1):r.bind(this)(e,t)}})),O.exports),ie=p(se);P.extend(ie);var re,ne={exports:{}};var oe=(re||(re=1,ne.exports=function(){var e="minute",t=/[+-]\d\d(?::?\d\d)?/g,s=/([+-]|\d\d)/g;return function(i,r,n){var o=r.prototype;n.utc=function(e){return new r({date:e,utc:!0,args:arguments})},o.utc=function(t){var s=n(this.toDate(),{locale:this.$L,utc:!0});return t?s.add(this.utcOffset(),e):s},o.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var a=o.parse;o.parse=function(e){e.utc&&(this.$u=!0),this.$utils().u(e.$offset)||(this.$offset=e.$offset),a.call(this,e)};var c=o.init;o.init=function(){if(this.$u){var e=this.$d;this.$y=e.getUTCFullYear(),this.$M=e.getUTCMonth(),this.$D=e.getUTCDate(),this.$W=e.getUTCDay(),this.$H=e.getUTCHours(),this.$m=e.getUTCMinutes(),this.$s=e.getUTCSeconds(),this.$ms=e.getUTCMilliseconds()}else c.call(this)};var d=o.utcOffset;o.utcOffset=function(i,r){var n=this.$utils().u;if(n(i))return this.$u?0:n(this.$offset)?d.call(this):this.$offset;if("string"==typeof i&&(i=function(e){void 0===e&&(e="");var i=e.match(t);if(!i)return null;var r=(""+i[0]).match(s)||["-",0,0],n=r[0],o=60*+r[1]+ +r[2];return 0===o?0:"+"===n?o:-o}(i),null===i))return this;var o=Math.abs(i)<=16?60*i:i,a=this;if(r)return a.$offset=o,a.$u=0===i,a;if(0!==i){var c=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(a=this.local().add(o+c,e)).$offset=o,a.$x.$localOffset=c}else a=this.utc();return a};var h=o.format;o.format=function(e){var t=e||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return h.call(this,t)},o.valueOf=function(){var e=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*e},o.isUTC=function(){return!!this.$u},o.toISOString=function(){return this.toDate().toISOString()},o.toString=function(){return this.toDate().toUTCString()};var l=o.toDate;o.toDate=function(e){return"s"===e&&this.$offset?n(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():l.call(this)};var u=o.diff;o.diff=function(e,t,s){if(e&&this.$u===e.$u)return u.call(this,e,t,s);var i=this.local(),r=n(e).local();return u.call(i,r,t,s)}}}()),ne.exports),ae=p(oe);P.extend(ie),P.extend(ae);const ce=P;function de(e,t){const s={...e};if(e&&"object"==typeof e&&t&&"object"==typeof t)for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=t[e],r=s[e];i&&"object"==typeof i&&!Array.isArray(i)&&r&&"object"==typeof r&&!Array.isArray(r)?s[e]=de(r,i):void 0!==i&&(s[e]=i)}return s}function he(){return ce().utc().toISOString()}const le=async e=>async function(){return await navigator.mediaDevices.enumerateDevices()}().then(t=>{let s=!1,i=[],r=!1,n=[],o=!1,a=[];if(t)for(let c=0;c<t.length;++c)if("audioinput"===t[c].kind)s=!0,i.push(t[c]);else if("audiooutput"===t[c].kind)r=!0,n.push(t[c]);else if("videoinput"===t[c].kind){const s=l(e)?.features?.enableVideo;s&&(o=!0,a.push(t[c]))}return{hasAudioDevice:s,audioInputDevices:i,hasSpeakerDevice:r,speakerDevices:n,hasVideoDevice:o,videoInputDevices:a}}),ue=({username:e})=>{const{audioInputDevices:t,videoInputDevices:s}=d().devicesInfo,{media:{audioInputDeviceId:i,videoInputDeviceId:r,autoGainControl:n,maxFrameRate:o,noiseSuppression:a,videoAspectRatio:c,videoHeight:h,echoCancellation:l},registration:{inviteExtraHeaders:u}}=d().configs?.[e]??$,g=()=>navigator.mediaDevices.getSupportedConstraints(),p={answerAudioSpdOptions:function({option:e}={}){const s=e??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:{exact:"default"}},video:!1}}},r=g(),o=i;if("object"==typeof s.sessionDescriptionHandlerOptions.constraints.audio){if("default"!=o){let e=(e=>{let s=!1;for(let i=0;i<t.length;++i)if(e==t[i].deviceId){s=!0;break}return s})(o);e&&(s.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:o})}return r.autoGainControl&&(s.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=n),r.echoCancellation&&(s.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=l),r.noiseSuppression&&(s.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=a),s}},makeAudioSpdOptions:function({extraHeaders:e}){let t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if(t.extraHeaders=e||[],p.answerAudioSpdOptions({option:t}),u&&""!==u&&"{}"!==u)try{for(const[e,s]of Object.entries(JSON.parse(u)))""==s||t?.extraHeaders?.push(e+": "+s)}catch(e){}return t},answerVideoSpdOptions:function({option:e}={}){const t=e??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}},i=g();p.answerAudioSpdOptions({option:t});const n=r;if("object"==typeof t.sessionDescriptionHandlerOptions.constraints.video){if("default"!=n){let e=(e=>{let t=!1;for(let i=0;i<s.length;++i)if(e===s[i].deviceId){t=!0;break}return t})(n);e&&(t.sessionDescriptionHandlerOptions.constraints.video.deviceId={exact:n})}return i.frameRate&&o&&(t.sessionDescriptionHandlerOptions.constraints.video.frameRate=String(o)),i.height&&h&&(t.sessionDescriptionHandlerOptions.constraints.video.height=String(h)),i.aspectRatio&&c&&(t.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=String(c)),t}},makeVideoSpdOptions:function({extraHeaders:e}){const t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}};if(p.answerVideoSpdOptions({option:t}),t.extraHeaders=e||[],u&&""!==u&&"{}"!==u)try{for(const[e,s]of Object.entries(JSON.parse(u)))""==s||t.extraHeaders.push(e+": "+s)}catch(e){}return t}};return p};class ge extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class pe extends ge{constructor(e){super(e||"Unsupported content type.")}}class fe extends ge{constructor(e){super(e||"Request pending.")}}class me extends ge{constructor(e){super(e||"Unspecified session description handler error.")}}class ve extends ge{constructor(){super("The session has terminated.")}}class we extends ge{constructor(e){super(e||"An error occurred during state transition.")}}class be{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class Se{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class ye{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class Te{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class $e{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class Ee{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class Re extends Ee{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new Re(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class Ie extends Ee{constructor(e="sip",t,s,i,r,n){if(super(r||{}),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:i},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:i}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new Ie(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}}function Ce(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){const s=Object.keys(e.parameters),i=Object.keys(t.parameters);return!!s.filter(e=>i.includes(e)).every(s=>e.parameters[s]===t.parameters[s])&&(!!["user","ttl","method","transport"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s))&&!!["maddr"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s)))}(e,t))return!1;const s=Object.keys(e.headers),i=Object.keys(t.headers);if(0!==s.length||0!==i.length){if(s.length!==i.length)return!1;const r=s.filter(e=>i.includes(e));if(r.length!==i.length)return!1;if(!r.every(s=>e.headers[s].length&&t.headers[s].length&&e.headers[s][0]===t.headers[s][0]))return!1}return!0}function De(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class Ae extends Error{constructor(e,t,s,i){super(),this.message=e,this.expected=t,this.found=s,this.location=i,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,Ae.prototype):this.__proto__=Ae.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ae)}static buildMessage(e,t){function s(e){return e.charCodeAt(0).toString(16).toUpperCase()}function i(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function r(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(e));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(n);let s,i;if(t.sort(),t.length>0){for(s=1,i=1;s<t.length;s++)t[s-1]!==t[s]&&(t[i]=t[s],i++);t.length=i}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((o=t)?'"'+i(o)+'"':"end of input")+" found.");var o}format(e){let t="Error: "+this.message;if(this.location){let s,i=null;for(s=0;s<e.length;s++)if(e[s].source===this.location.source){i=e[s].text.split(/\r\n|\n|\r/g);break}let r=this.location.start,n=this.location.source+":"+r.line+":"+r.column;if(i){let e=this.location.end,s=De("",r.line.toString().length," "),o=i[r.line-1],a=r.line===e.line?e.column:o.length+1;t+="\n --\x3e "+n+"\n"+s+" |\n"+r.line+" | "+o+"\n"+s+" | "+De("",r.column-1," ")+De("",a-r.column,"^")}else t+="\n at "+n}return t}}const _e=function(e,t){const s={},i=(t=void 0!==t?t:{}).grammarSource,r={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let n=119;const o=["\r\n",v("\r\n",!1),/^[0-9]/,w([["0","9"]],!1,!1),/^[a-zA-Z]/,w([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,w([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,w([["\0","ÿ"]],!1,!1),/^["]/,w(['"'],!1,!1)," ",v(" ",!1),"\t",v("\t",!1),/^[a-zA-Z0-9]/,w([["a","z"],["A","Z"],["0","9"]],!1,!1),";",v(";",!1),"/",v("/",!1),"?",v("?",!1),":",v(":",!1),"@",v("@",!1),"&",v("&",!1),"=",v("=",!1),"+",v("+",!1),"$",v("$",!1),",",v(",",!1),"-",v("-",!1),"_",v("_",!1),".",v(".",!1),"!",v("!",!1),"~",v("~",!1),"*",v("*",!1),"'",v("'",!1),"(",v("(",!1),")",v(")",!1),"%",v("%",!1),function(){return" "},function(){return":"},/^[!-~]/,w([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,w([["",""]],!1,!1),/^[\x80-\xBF]/,w([["","¿"]],!1,!1),/^[a-f]/,w([["a","f"]],!1,!1),"`",v("`",!1),"<",v("<",!1),">",v(">",!1),"\\",v("\\",!1),"[",v("[",!1),"]",v("]",!1),"{",v("{",!1),"}",v("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,w([["!","'"]],!1,!1),/^[*-[]/,w([["*","["]],!1,!1),/^[\]-~]/,w([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,w([["#","["]],!1,!1),/^[\0-\t]/,w([["\0","\t"]],!1,!1),/^[\v-\f]/,w([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,w([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new Ie(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new Ie(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",v("sips",!0),"sip",v("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(f().slice(0,-1))},function(){(t=t||{data:{}}).data.password=f()},function(){return(t=t||{data:{}}).data.host=f(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",f()},/^[a-zA-Z0-9_\-]/,w([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,w([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},"::",v("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},function(){return(t=t||{data:{}}).data.host_type="IPv4",f()},"25",v("25",!1),/^[0-5]/,w([["0","5"]],!1,!1),"2",v("2",!1),/^[0-4]/,w([["0","4"]],!1,!1),"1",v("1",!1),/^[1-9]/,w([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",v("transport=",!0),"udp",v("udp",!0),"tcp",v("tcp",!0),"sctp",v("sctp",!0),"tls",v("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",v("user=",!0),"phone",v("phone",!0),"ip",v("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",v("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",v("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",v("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",v("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new Ie(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",v("//",!1),function(){(t=t||{data:{}}).data.scheme=f()},v("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=f()},"INVITE",v("INVITE",!1),"ACK",v("ACK",!1),"VXACH",v("VXACH",!1),"OPTIONS",v("OPTIONS",!1),"BYE",v("BYE",!1),"CANCEL",v("CANCEL",!1),"REGISTER",v("REGISTER",!1),"SUBSCRIBE",v("SUBSCRIBE",!1),"NOTIFY",v("NOTIFY",!1),"REFER",v("REFER",!1),"PUBLISH",v("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=f(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=f()},function(){(t=t||{data:{}}).data=f()},function(){var e,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new Re(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(e){'"'===(e=f().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",v("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",v("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",v("0",!1),function(){return parseFloat(f())},function(e,s){(t=t||{data:{}}).data.params||(t.data.params={}),s=null===s?void 0:s[1],t.data.params[e.toLowerCase()]=s},"render",v("render",!0),"session",v("session",!0),"icon",v("icon",!0),"alert",v("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=f().toLowerCase())},"handling",v("handling",!0),"optional",v("optional",!0),"required",v("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=f()},"text",v("text",!0),"image",v("image",!0),"audio",v("audio",!0),"video",v("video",!0),"application",v("application",!0),"message",v("message",!0),"multipart",v("multipart",!0),"x-",v("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new Re(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",v("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new Re(t.data.uri,t.data.displayName,t.data.params)},"digest",v("Digest",!0),"realm",v("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",v("domain",!0),"nonce",v("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",v("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",v("stale",!0),"true",v("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",v("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",v("algorithm",!0),"md5",v("MD5",!0),"md5-sess",v("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",v("qop",!0),"auth-int",v("auth-int",!0),"auth",v("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new Re(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new Re(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",v("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",v("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",v("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",v("active",!0),"pending",v("pending",!0),"terminated",v("terminated",!0),function(){(t=t||{data:{}}).data.state=f()},"reason",v("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",v("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",v("deactivated",!0),"probation",v("probation",!0),"rejected",v("rejected",!0),"timeout",v("timeout",!0),"giveup",v("giveup",!0),"noresource",v("noresource",!0),"invariant",v("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new Re(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",v("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",v("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",v("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",v("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",v("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},v("UDP",!0),v("TCP",!0),v("TLS",!0),v("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=f()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",v("refresher",!1),"uas",v("uas",!1),"uac",v("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",v("stuns",!0),"stun",v("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",v("?transport=",!1),"turns",v("turns",!0),"turn",v("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=f()},"Referred-By",v("Referred-By",!1),"b",v("b",!1),"cid",v("cid",!1)],a=[T('2 ""6 7!'),T('4"""5!7#'),T('4$""5!7%'),T('4&""5!7\''),T(";'.# &;("),T('4(""5!7)'),T('4*""5!7+'),T('2,""6,7-'),T('2.""6.7/'),T('40""5!71'),T('22""6273. &24""6475.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T(";).# &;,"),T('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),T('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),T('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),T(';.." &"'),T("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),T('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),T('4\\""5!7].# &;3'),T('4^""5!7_'),T('4`""5!7a'),T(';!.) &4b""5!7c'),T('%$;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),T('%$;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),T('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273. &28""6879. &2j""6j7k. &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),T('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),T("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),T("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),T("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),T("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),T("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),T('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),T('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),T("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),T("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),T("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),T("%;//0#;&/'$8\":~\" )(\"'#&'#"),T("%;&/0#;//'$8\":~\" )(\"'#&'#"),T("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),T('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),T("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),T("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:
$!!)($'#(#'#(\"'#&'#"),T(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),T('%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("\'#&\'#'),T("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:$ )($'#(#'#(\"'#&'#"),T("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),T('%3""5$7.) &3""5#7/\' 8!:!! )'),T('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:# )(#\'#("\'#&\'#'),T("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),T('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),T('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:! )'),T('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;U.) &;\\.# &;X/& 8!:! )"),T('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:# )(#\'#("\'#&\'#'),T('$4""5!7/,#0)*4""5!7&&&#'),T('%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("\'#&\'#'),T('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),T('%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),T('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),T("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),T("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),T('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7/,#;!/#$+")("\'#&\'#.# &;!'),T('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),T('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),T(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),T('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),T('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),T('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),T('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),T('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),T('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),T('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),T('%$;j/�#*;j&&&#/"!&,)'),T('%$;j/�#*;j&&&#/"!&,)'),T(";k.) &;+.# &;-"),T('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),T('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),T('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),T("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),T("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),T('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),T(";.# &;r"),T("%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T(";M.# &;t"),T("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),T('%;v.# &;w/J#%26""6677/,#;/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T('%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#\'#("\'#&\'#'),T('%24""6475/,#;{/#$+")("\'#&\'#'),T("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),T(";*.) &;+.# &;-"),T(';+. &;-. &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),T('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),T("$;~0#*;~&"),T(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T('%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),T(";.# &;"),T('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),T('$;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/#0*;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),T("$;y0#*;y&"),T('%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),T('2Õ""6Õ7Ö'),T('2×""6×7Ø'),T('2Ù""6Ù7Ú'),T('2Û""6Û7Ü'),T('2Ý""6Ý7Þ'),T('2ß""6ß7à'),T('2á""6á7â'),T('2ã""6ã7ä'),T('2å""6å7æ'),T('2ç""6ç7è'),T('2é""6é7ê'),T("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),T("%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T("%;/' 8!:ì!! )"),T("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),T("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),T("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),T("%;:.c &%;/Y#$%;A/,#;/#$+\")(\"'#&'#06*%;A/,#;/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),T("%;L.# &;/]#$%;B/,#;/#$+\")(\"'#&'#06*%;B/,#;/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),T("%;.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),T("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),T(";.) &;.# &; "),T("%3ò\"\"5!7ó/:#;</1$;/($8#:ô#! )(#'#(\"'#&'#"),T("%3õ\"\"5'7ö/:#;</1$;/($8#:÷#! )(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ø!! )"),T('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),T('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),T(";6.) &;T.# &;H"),T("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),T(";¥.# &; "),T('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),T("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:Č!! )"),T("%;©/& 8!:č! )"),T("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T(";«.# &;¬"),T('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),T('3Ę""5\'7ę./ &3Ě""5)7ě.# &;'),T(";6.# &;®"),T('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),T(";.# &;6"),T("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),T(";6.# &;H"),T("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),T("%;/' 8!:ğ!! )"),T('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),T('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),T("%;L.# &;/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),T(";¹.# &; "),T("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),T("%;/' 8!:Ħ!! )"),T("%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),T(";¾"),T("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),T("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),T(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),T("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),T("%;I/' 8!:Ĭ!! )"),T("%3ĭ\"\"5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),T(";t.# &;w"),T("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),T("%;I/' 8!:ı!! )"),T("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),T('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),T('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),T('%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),T('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),T("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),T("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),T("%;/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),T('%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),T("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),T("%;/& 8!:Ő! )"),T('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),T('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),T("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),T("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),T("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;/($8#:ū#! )(#'#(\"'#&'#.# &; "),T('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),T(';1." &"'),T('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),T("%;L.# &;/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),T(";¹.# &; "),T("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),T("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),T("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),T("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),T("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),T("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),T("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),T('%3""5#7Ó.# &;6/\' 8!:Ƌ!! )'),T('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),T('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),T('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),T('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),T(";¾"),T('%;/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),T(";ô.# &; "),T('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),T('%;/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),T("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),T("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),T("$;%0#*;%&"),T("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),T('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),T('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),T(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),T('2L""6L7M. &2B""6B7C. &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),T('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),T('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),T('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),T("%;Ą/#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),T("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),T("%;ă/,#;ă/#$+\")(\"'#&'#"),T("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),T("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),T('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),T(";.# &;L"),T("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),T("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,d=0;const h=[{line:1,column:1}];let l,u=0,g=[],p=0;if(void 0!==t.startRule){if(!(t.startRule in r))throw new Error("Can't start parsing from rule \""+t.startRule+'".');n=r[t.startRule]}function f(){return e.substring(d,c)}function m(){return S(d,c)}function v(e,t){return{type:"literal",text:e,ignoreCase:t}}function w(e,t,s){return{type:"class",parts:e,inverted:t,ignoreCase:s}}function b(t){let s,i=h[t];if(i)return i;for(s=t-1;!h[s];)s--;for(i=h[s],i={line:i.line,column:i.column};s<t;)10===e.charCodeAt(s)?(i.line++,i.column=1):i.column++,s++;return h[t]=i,i}function S(e,t){const s=b(e),r=b(t);return{source:i,start:{offset:e,line:s.line,column:s.column},end:{offset:t,line:r.line,column:r.column}}}function y(e){c<u||(c>u&&(u=c,g=[]),g.push(e))}function T(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},l=function t(i){const r=a[i];let n=0;const h=[];let l=r.length;const u=[],g=[];let f;for(;;){for(;n<l;)switch(r[n]){case 0:g.push(o[r[n+1]]),n+=2;break;case 1:g.push(void 0),n++;break;case 2:g.push(null),n++;break;case 3:g.push(s),n++;break;case 4:g.push([]),n++;break;case 5:g.push(c),n++;break;case 6:g.pop(),n++;break;case 7:c=g.pop(),n++;break;case 8:g.length-=r[n+1],n+=2;break;case 9:g.splice(-2,1),n++;break;case 10:g[g.length-2].push(g.pop()),n++;break;case 11:g.push(g.splice(g.length-r[n+1],r[n+1])),n+=2;break;case 12:g.push(e.substring(g.pop(),c)),n++;break;case 13:u.push(l),h.push(n+3+r[n+1]+r[n+2]),g[g.length-1]?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 14:u.push(l),h.push(n+3+r[n+1]+r[n+2]),g[g.length-1]===s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 15:u.push(l),h.push(n+3+r[n+1]+r[n+2]),g[g.length-1]!==s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 16:g[g.length-1]!==s?(u.push(l),h.push(n),l=n+2+r[n+1],n+=2):n+=2+r[n+1];break;case 17:u.push(l),h.push(n+3+r[n+1]+r[n+2]),e.length>c?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 18:u.push(l),h.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length)===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 19:u.push(l),h.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length).toLowerCase()===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 20:u.push(l),h.push(n+4+r[n+2]+r[n+3]),o[r[n+1]].test(e.charAt(c))?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 21:g.push(e.substr(c,r[n+1])),c+=r[n+1],n+=2;break;case 22:g.push(o[r[n+1]]),c+=o[r[n+1]].length,n+=2;break;case 23:g.push(s),0===p&&y(o[r[n+1]]),n+=2;break;case 24:d=g[g.length-1-r[n+1]],n+=2;break;case 25:d=c,n++;break;case 26:f=r.slice(n+4,n+4+r[n+3]).map(function(e){return g[g.length-1-e]}),g.splice(g.length-r[n+2],r[n+2],o[r[n+1]].apply(null,f)),n+=4+r[n+3];break;case 27:g.push(t(r[n+1])),n+=2;break;case 28:p++,n++;break;case 29:p--,n++;break;default:throw new Error("Invalid opcode: "+r[n]+".")}if(!(u.length>0))break;l=u.pop(),n=h.pop()}return g[0]}(n),l!==s&&c===e.length)return l;throw l!==s&&c<e.length&&y({type:"end"}),$=g,E=u<e.length?e.charAt(u):null,R=u<e.length?S(u,u+1):S(u,u),new Ae(Ae.buildMessage($,E),$,E,R);var $,E,R};var ke;!function(e){e.parse=function(e,t){const s={startRule:t};try{_e(e,s)}catch(e){s.data=-1}return s.data},e.nameAddrHeaderParse=function(t){const s=e.parse(t,"Name_Addr_Header");return-1!==s?s:void 0},e.URIParse=function(t){const s=e.parse(t,"SIP_URI");return-1!==s?s:void 0}}(ke=ke||(ke={}));const He={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function xe(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function Pe(e){return He[e]||""}function Oe(){return xe(10)}function qe(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}function Me(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class Ne{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=qe(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[qe(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[qe(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[qe(e)]}parseHeader(e,t=0){if(e=qe(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const s=this.headers[e][t],i=s.raw;if(s.parsed)return s.parsed;const r=ke.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(s.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[qe(e)]=[{raw:t}]}toString(){return this.data}}class je extends Ne{constructor(){super()}}class Fe extends Ne{constructor(){super()}}class Le{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=Le.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=s.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Oe(),this.from=Le.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=Le.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+xe(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,s){const i={};return s&&(i.tag=s),new Re(e,t,i)}getHeader(e){const t=this.headers[qe(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],s=this.headers[qe(e)];if(s)for(const e of s)t.push(e);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)s.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[qe(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[qe(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let s="SIP/2.0/"+t;s+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(s+=";rport"),this.setHeader("via",s),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const s of this.headers[t])e+=t+": "+s+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+Me(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+Me(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function Ue(e){return"application/sdp"===e?"session":"render"}function Be(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Ue(s),contentType:s,content:t}}function Ge(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function Ve(e){let t,s,i;if(e instanceof je&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof Fe&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof Le&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,i=e.body.body}if(Ge(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=Ue(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var Ye,We;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(Ye=Ye||(Ye={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(We=We||(We={}));const Ke=500,Je={T1:Ke,T2:4e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class Ze extends ge{constructor(e){super(e||"Transaction state error.")}}var ze;!function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(ze=ze||(ze={}));const Xe=[ze.ACK,ze.BYE,ze.CANCEL,ze.INFO,ze.INVITE,ze.MESSAGE,ze.NOTIFY,ze.OPTIONS,ze.PRACK,ze.REFER,ze.REGISTER,ze.SUBSCRIBE];class Qe{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class et{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class tt{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof Re))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&s.push("Replaces: "+decodeURIComponent(i));const r=this.referredBy;return r&&s.push("Referred-By: "+r),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var st,it;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(st=st||(st={}));class rt{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=st.Initial,this.delegate=t.delegate,this._stateEventEmitter=new Te,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case st.Initial:case st.Establishing:break;case st.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case st.Terminating:case st.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case st.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case st.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case st.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case st.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case st.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==st.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==st.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new fe("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=Ve(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(st.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,i).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===st.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(st.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,i).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==st.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(st.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==st.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(st.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+Xe.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==st.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==st.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof rt&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const s=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return i.extraHeaders=i.extraHeaders?i.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,s,i)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case Ye.Initial:case Ye.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case Ye.AckWait:return this.stateTransition(st.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(st.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(st.Terminated),i(r)}}});case Ye.Confirmed:{const i=s.bye(e,t);return this.stateTransition(st.Terminated),Promise.resolve(i)}case Ye.Terminated:throw new Error(`Invalid dialog state ${s.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:i})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==st.Established&&this.state!==st.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new be(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case We.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(st.Terminated),Promise.resolve()}case We.Stable:{const i=Ve(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(st.Terminated)}):Promise.resolve()}case We.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(st.Terminated),Promise.resolve()}case We.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(st.Terminated),Promise.resolve()}case We.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===st.Established){if(this.delegate&&this.delegate.onBye){const t=new Se(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(st.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===st.Established)if(this.delegate&&this.delegate.onInfo){const t=new $e(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==st.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=ke.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const i=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,200)}).catch(t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===We.Stable){const t=e.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488))}this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const s=e.reject({statusCode:488});if(this.state!==st.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(st.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===st.Established)if(this.delegate&&this.delegate.onMessage){const t=new Qe(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===st.Established){if(this.onNotify){const t=new et(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new et(e);this.delegate.onNotify(t)}else e.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===st.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==st.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new tt(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=Ve(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case We.Initial:return this.getOffer(e);case We.HaveLocalOffer:return Promise.resolve(void 0);case We.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case We.Stable:return this.state!==st.Established?Promise.resolve(void 0):this.getOffer(e);case We.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>Be(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new pe)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new pe)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).then(()=>s.getDescription(i,r)).then(e=>Be(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case st.Initial:e!==st.Establishing&&e!==st.Established&&e!==st.Terminating&&e!==st.Terminated&&t();break;case st.Establishing:e!==st.Established&&e!==st.Terminating&&e!==st.Terminated&&t();break;case st.Established:e!==st.Terminating&&e!==st.Terminated&&t();break;case st.Terminating:e!==st.Terminated&&t();break;case st.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===st.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let i=Pe(e);return!i&&t&&(i=t),"SIP;cause="+s+';text="'+i+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof Ie)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${i}?Replaces=${encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`)}>`}return t}}!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(it=it||(it={}));const nt={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0};class ot extends rt{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const r=s.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(st.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===st.Initial&&(t.reject({statusCode:487}),this.stateTransition(st.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=ke.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=s.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case st.Initial:case st.Establishing:return this.reject().then(()=>super.dispose());case st.Established:case st.Terminating:case st.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==st.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(st.Establishing),this.sendAccept(e).then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(st.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==st.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===it.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==st.Initial&&this.state!==st.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:Pe(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?Be(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}),this.stateTransition(st.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===st.Initial||this.state===st.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new ye(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(st.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=Ve(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case We.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case We.Stable:return this.setAnswer(t,s).then(()=>{});case We.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case We.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case We.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof pe?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof me?this.logger.error("A session description handler occurred while sending response"):e instanceof ve?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof Ze&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===st.Initial||this.state===st.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(st.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(st.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?Be(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let n;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n}))).then(t=>{let a,c;this._dialog=t.session,t.session.delegate={onPrack:s=>{a=s,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(s=>{try{c=a.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:a,prackResponse:c,progressResponse:t})}catch(e){o(e)}}).catch(e=>o(e)))}};const d=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then(()=>o(new ve)).catch(e=>o(e)))},64*Je.T1),h=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n})}catch(e){return this.waitingForPrack=!1,void o(e)}u=setTimeout(h,l*=2)};let l=Je.T1,u=setTimeout(h,l)}).catch(e=>{this.waitingForPrack=!1,o(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new ve),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class at extends rt{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=Oe(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const i=Object.assign({},s);i.params=Object.assign({},s.params);const r=s.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?ke.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?ke.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const c=Object.assign({},i.params);c.fromTag=this.fromTag;const d=(i.extraHeaders||[]).slice();r&&e.configuration.uri&&(d.push("P-Preferred-Identity: "+e.configuration.uri.toString()),d.push("Privacy: id")),d.push("Contact: "+n),d.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===it.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===it.Required&&d.push("Require: replaces"),i.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(ze.INVITE,t,o,a,c,d,undefined),this._contact=n,this._referralInviterOptions=i,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case st.Initial:case st.Establishing:return this.cancel().then(()=>super.dispose());case st.Established:case st.Terminating:case st.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==st.Initial&&this.state!==st.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(st.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(Pe(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(st.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==st.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(st.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(st.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==st.Terminated&&this.stateTransition(st.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(st.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof rt))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==st.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=ke.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case We.Initial:case We.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(st.Terminated),Promise.reject(new Error("Bad Media Description"));case We.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(st.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(st.Terminated),t})}case We.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(st.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(st.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(st.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(st.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(st.Terminated),t})}case We.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==st.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=ke.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const r=s.getHeader("require"),n=s.getHeader("rseq"),o=!!(r&&r.includes("100rel")&&n?Number(n):void 0),a=[];switch(o&&a.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case We.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case We.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case We.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:s})}).catch(e=>{throw this.stateTransition(st.Terminated),e})}case We.Stable:if(o&&e.prack({extraHeaders:a}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(st.Terminated),e})}return Promise.resolve();case We.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===st.Establishing||this.state===st.Terminating?this.stateTransition(st.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===st.Establishing||this.state===st.Terminating?this.stateTransition(st.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===st.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var ct,dt,ht,lt,ut,gt,pt;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(ct=ct||(ct={}));class ft{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=ct.Initial,this._waiting=!1,this._stateEventEmitter=new Te,this._waitingEventEmitter=new Te,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ft.defaultOptions()),{registrar:s}),ft.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===ke.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const i=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(ze.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||ft.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||ft.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:ft.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new Ie("sip","anonymous","anonymous.invalid"),refreshFrequency:ft.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===ct.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===ct.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new fe("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(i=t.message.parseHeader("contact",r),!i)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&Ce(i.uri,this.userAgent.contact.pubGruu)){s=Number(i.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(i.uri.user===this.userAgent.contact.uri.user){s=Number(i.getParam("expires"));break}}else if(Ce(i.uri,this.userAgent.contact.uri)){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=ke.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=ke.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===ct.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==ct.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new fe("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===ct.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==ct.Registered&&this.stateTransition(ct.Registered)}unregistered(){this.clearTimers(),this._state!==ct.Unregistered&&this.stateTransition(ct.Unregistered)}terminated(){this.clearTimers(),this._state!==ct.Terminated&&this.stateTransition(ct.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ct.Initial:e!==ct.Registered&&e!==ct.Unregistered&&e!==ct.Terminated&&t();break;case ct.Registered:e!==ct.Unregistered&&e!==ct.Terminated&&t();break;case ct.Unregistered:e!==ct.Registered&&e!==ct.Terminated&&t();break;case ct.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===ct.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===ct.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}ft.defaultExpires=600,ft.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(dt=dt||(dt={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(ht=ht||(ht={})),function(e){e.Started="Started",e.Stopped="Stopped"}(lt=lt||(lt={}));class mt{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=mt.hexChars,s=mt.hexOut;let i,r,n,o;for(o=0;o<4;o+=1)for(r=8*o,i=e[o],n=0;n<8;n+=2)s[r+1+n]=t.charAt(15&i),i>>>=4,s[r+0+n]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],i=e[1],r=e[2],n=e[3];s+=(i&r|~i&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[3]-1044525330|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[7]-45705983|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[11]-1990404162|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[15]+1236535329|0,i=(i<<22|i>>>10)+r|0,s+=(i&n|r&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[0]-373897302|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[4]-405537848|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[8]+1163531501|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[12]-1926607734|0,i=(i<<20|i>>>12)+r|0,s+=(i^r^n)+t[5]-378558|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[14]-35309556|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[10]-1094730640|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[6]+76029189|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[2]-995338651|0,i=(i<<23|i>>>9)+r|0,s+=(r^(i|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[5]-57434055|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[1]-2054922799|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[13]+1309151649|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[9]-343485551|0,i=(i<<21|i>>>11)+r|0,e[0]=s+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(mt.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,r,n=this._bufferLength;for(r=0;r<e.length;r+=1){if(i=e.charCodeAt(r),i<128)t[n++]=i;else if(i<2048)t[n++]=(i>>>6)+192,t[n++]=63&i|128;else if(i<55296||i>56319)t[n++]=(i>>>12)+224,t[n++]=i>>>6&63|128,t[n++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++r)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=(i>>>18)+240,t[n++]=i>>>12&63|128,t[n++]=i>>>6&63|128,t[n++]=63&i|128}n>=64&&(this._dataLength+=64,mt._md5cycle(this._state,s),n-=64,s[0]=s[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e.charCodeAt(n++);if(r<64)break;this._dataLength+=64,mt._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e[n++];if(r<64)break;this._dataLength+=64,mt._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}getState(){const e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}}setState(e){const t=e.buffer,s=e.state,i=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,s=this._buffer8,i=this._buffer32,r=1+(t>>2);let n;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(mt.buffer32Identity.subarray(r),r),t>55&&(mt._md5cycle(this._state,i),i.set(mt.buffer32Identity)),n=8*this._dataLength,n<=4294967295)i[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return mt._md5cycle(this._state,i),e?this._state:mt._hex(this._state)}}function vt(e){return mt.hashStr(e)}mt.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),mt.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),mt.hexChars="0123456789abcdef",mt.hexOut=[],mt.onePassHasher=new mt,"5d41402abc4b2a76b9719d911017c592"!==mt.hashStr("hello")&&console.error("Md5 self test failed.");class wt{constructor(e,t,s,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=xe(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=vt(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=vt(this.method+":"+this.uri),this.response=vt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=vt(this.method+":"+this.uri+":"+vt(e||"")),this.response=vt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=vt(this.method+":"+this.uri),this.response=vt(t+":"+this.nonce+":"+s))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(ut=ut||(ut={}));class bt{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(ut.error,e)}warn(e){this.genericLog(ut.warn,e)}log(e){this.genericLog(ut.log,e)}debug(e){this.genericLog(ut.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class St{constructor(){this.builtinEnabled=!0,this._level=ut.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:ut.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new bt(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new bt(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(ut[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case ut.error:console.error(i);break;case ut.warn:console.warn(i);break;case ut.log:console.log(i);break;case ut.debug:console.debug(i)}}}function yt(e,t){const s="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const i=t.reasonPhrase?t.reasonPhrase:Pe(t.statusCode);let r="SIP/2.0 "+t.statusCode+" "+i+s;t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+s,o="Call-ID: "+e.callId+s,a="CSeq: "+e.cseq+" "+e.method+s,c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+s,"");let d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Oe()),d+=";tag="+e}d+=s;let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+s);let l="";t.userAgent&&(l="User-Agent: "+t.userAgent+s);let u="";return t.extraHeaders&&(u=t.extraHeaders.reduce((e,t)=>e+t.trim()+s,"")),r+=c,r+=n,r+=d,r+=a,r+=o,r+=h,r+=l,r+=u,t.body?(r+="Content-Type: "+t.body.contentType+s,r+="Content-Length: "+Me(t.body.content)+s+s,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){let s=t,i=0,r=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===i;){if(r=e.indexOf("\r\n",s),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?s=r+2:i=r}return i}function s(e,t,s,i){const r=t.indexOf(":",s),n=t.substring(s,r).trim(),o=t.substring(r+1,i).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=ke.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=ke.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof Fe&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,i){let r=0,n=e.indexOf("\r\n");if(-1===n)return void i.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=ke.parse(o,"Request_Response");let c,d;if(-1!==a){for(a.status_code?(c=new Fe,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new je,c.method=a.method,c.ruri=a.uri),c.data=e,r=n+2;;){if(n=t(e,r),-2===n){d=r+2;break}if(-1===n)return void i.error("malformed message");const o=s(c,e,r,n);if(o&&!0!==o)return void i.error(o.error);r=n+2}return c.hasHeader("content-length")?c.body=e.substr(d,Number(c.getHeader("content-length"))):c.body=e.substring(d),c}i.warn('error parsing first line of SIP message: "'+o+'"')}}(gt=gt||(gt={}));class Tt extends ge{constructor(e){super(e||"Unspecified transport error.")}}class $t{constructor(e,t,s,i,r){this._transport=e,this._user=t,this._id=s,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof Tt)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new Tt(e.message):new Tt,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Et extends $t{constructor(e,t,s,i,r){super(t,s,e.viaBranch,i,r),this._request=e,this.user=s}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(pt=pt||(pt={}));class Rt extends Et{constructor(e,t,s){super(e,t,s,pt.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case pt.Proceeding:if(e.method===ze.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case pt.Accepted:if(e.method===ze.INVITE)return;break;case pt.Completed:if(e.method===ze.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===ze.ACK)return void this.stateTransition(pt.Confirmed);break;case pt.Confirmed:case pt.Terminated:if(e.method===ze.INVITE||e.method===ze.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case pt.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(pt.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(pt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case pt.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case pt.Completed:case pt.Confirmed:case pt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===pt.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case pt.Proceeding:t();break;case pt.Accepted:case pt.Completed:this.state!==pt.Proceeding&&t();break;case pt.Confirmed:this.state!==pt.Completed&&t();break;case pt.Terminated:this.state!==pt.Accepted&&this.state!==pt.Completed&&this.state!==pt.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===pt.Accepted&&(this.L=setTimeout(()=>this.timerL(),Je.TIMER_L)),e===pt.Completed&&(this.H=setTimeout(()=>this.timerH(),Je.TIMER_H)),e===pt.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Je.TIMER_I)),e===pt.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},Je.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===pt.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(pt.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(pt.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===pt.Accepted&&this.stateTransition(pt.Terminated)}}class It extends $t{constructor(e,t,s,i,r){super(t,s,It.makeId(e),i,r),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class Ct extends It{constructor(e,t,s){super(e,t,s,pt.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Je.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case pt.Trying:if(t>=100&&t<=199)return this.stateTransition(pt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(pt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case pt.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(pt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case pt.Completed:case pt.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(pt.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case pt.Trying:s();break;case pt.Proceeding:this.state!==pt.Trying&&s();break;case pt.Completed:this.state!==pt.Trying&&this.state!==pt.Proceeding&&s();break;case pt.Terminated:this.state!==pt.Trying&&this.state!==pt.Proceeding&&this.state!==pt.Completed&&(t||s());break;default:s()}e===pt.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Je.TIMER_K)),e===pt.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==pt.Trying&&this.state!==pt.Proceeding||(this.onRequestTimeout(),this.stateTransition(pt.Terminated))}timerK(){this.state===pt.Completed&&this.stateTransition(pt.Terminated)}}class Dt{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof Re))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const d=e.from.uri,h=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:d,remoteURI:h,remoteTarget:r,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof Re))throw new Error("Contact not instance of NameAddrHeader.");const n=r.uri,o=e.cseq,a=e.callId,c=t,d=e.fromTag,h=e.from.uri;return{id:a+c+d,early:s,callId:a,localTag:c,remoteTag:d,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:h,remoteTarget:n,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==ze.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,i=this.remoteTag,r=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,d=this.routeSet,h=t&&t.extraHeaders,l=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,s,{callId:o,cseq:a,fromTag:n,toTag:i,routeSet:d},h,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===ze.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class At extends It{constructor(e,t,s){super(e,t,s,pt.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Je.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case pt.Calling:if(t>=100&&t<=199)return this.stateTransition(pt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(pt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(pt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case pt.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(pt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(pt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case pt.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case pt.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case pt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(pt.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,i=this.request.cseq,r=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${i} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case pt.Calling:s();break;case pt.Proceeding:this.state!==pt.Calling&&s();break;case pt.Accepted:case pt.Completed:this.state!==pt.Calling&&this.state!==pt.Proceeding&&s();break;case pt.Terminated:this.state!==pt.Calling&&this.state!==pt.Accepted&&this.state!==pt.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),pt.Proceeding,e===pt.Completed&&(this.D=setTimeout(()=>this.timerD(),Je.TIMER_D)),e===pt.Accepted&&(this.M=setTimeout(()=>this.timerM(),Je.TIMER_M)),e===pt.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===pt.Calling&&(this.onRequestTimeout(),this.stateTransition(pt.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===pt.Completed&&this.stateTransition(pt.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===pt.Accepted&&this.stateTransition(pt.Terminated)}}class _t{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const s=this.core.makeOutgoingRequestMessage(ze.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},t.extraHeaders);return s.branch=this.message.branch,this.message.headers.Route&&(s.headers.Route=this.message.headers.Route),e&&s.setHeader("Reason",e),this.transaction.state===pt.Proceeding?new _t(Ct,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===pt.Proceeding&&new _t(Ct,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let i,r;if(401===s?(i=e.parseHeader("www-authenticate"),r="authorization"):(i=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!i)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==i.stale))return this.logger.warn(s+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,i))return!0;this.challenged=!0,i.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new Fe;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new Fe;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===pt.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}class kt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(ze.BYE,s);super(Ct,e.userAgentCore,i,t),e.dispose()}}class Ht extends Et{constructor(e,t,s){super(e,t,s,pt.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case pt.Trying:break;case pt.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case pt.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case pt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case pt.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(pt.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(pt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case pt.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(pt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case pt.Completed:return;case pt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(pt.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case pt.Trying:s();break;case pt.Proceeding:this.state!==pt.Trying&&s();break;case pt.Completed:this.state!==pt.Trying&&this.state!==pt.Proceeding&&s();break;case pt.Terminated:this.state!==pt.Proceeding&&this.state!==pt.Completed&&(t||s());break;default:s()}e===pt.Completed&&(this.J=setTimeout(()=>this.timerJ(),Je.TIMER_J)),e===pt.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===pt.Completed&&this.stateTransition(pt.Terminated)}}class xt{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:Oe(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new Ze(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new Ze(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new Ze(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError(`Invalid statusCode: ${s}`);const i=new Array;e.forEach(e=>i.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(i);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new Ze(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new Ze(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Rt)return this.transaction.state===pt.Proceeding||this.transaction.state===pt.Accepted;if(this.transaction instanceof Ht)return this.transaction.state===pt.Trying||this.transaction.state===pt.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Rt)return this.transaction.state===pt.Proceeding;if(this.transaction instanceof Ht)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Rt)return this.transaction.state===pt.Proceeding;if(this.transaction instanceof Ht)return this.transaction.state===pt.Trying||this.transaction.state===pt.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Rt)return this.transaction.state===pt.Proceeding;if(this.transaction instanceof Ht)return this.transaction.state===pt.Trying||this.transaction.state===pt.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Rt)return this.transaction.state===pt.Proceeding;if(this.transaction instanceof Ht)return this.transaction.state===pt.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=yt(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===pt.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}class Pt extends xt{constructor(e,t,s){super(Ht,e.userAgentCore,t,s)}}class Ot extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(ze.INFO,s);super(Ct,e.userAgentCore,i,t)}}class qt extends xt{constructor(e,t,s){super(Ht,e.userAgentCore,t,s)}}class Mt extends _t{constructor(e,t,s){super(Ct,e,t,s)}}class Nt extends xt{constructor(e,t,s){super(Ht,e,t,s)}}class jt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(ze.NOTIFY,s);super(Ct,e.userAgentCore,i,t)}}class Ft extends xt{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ht,i,t,s)}}class Lt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(ze.PRACK,s);super(Ct,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class Ut extends xt{constructor(e,t,s){super(Ht,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Bt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(ze.INVITE,s);super(At,e.userAgentCore,i,t),this.delegate=t,e.signalingStateTransition(i),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class Gt extends xt{constructor(e,t,s){super(Rt,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),i}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),i}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class Vt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(ze.REFER,s);super(Ct,e.userAgentCore,i,t)}}class Yt extends xt{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ht,i,t,s)}}class Wt extends Dt{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=We.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof Rt&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=We.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?Ye.Early:this.ackWait?Ye.AckWait:this._signalingState===We.Closed?Ye.Terminated:Ye.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof At))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof At))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(ze.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(s),this.signalingStateTransition(s),{message:s}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Rt){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==pt.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new kt(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Ot(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INVITE request`),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new Bt(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const s=this.createOutgoingRequestMessage(ze.MESSAGE,t);return new Mt(this.core,s,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new jt(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Lt(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new Vt(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==ze.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===ze.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==We.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===ze.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof Re))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case ze.BYE:{const t=new Pt(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case ze.INFO:{const t=new qt(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case ze.INVITE:{const t=new Gt(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case ze.MESSAGE:{const t=new Nt(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case ze.NOTIFY:{const t=new Ft(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case ze.PRACK:{const t=new Ut(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case ze.REFER:{const t=new Yt(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof At)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),i=t&&t.includes("100rel")&&s?Number(s):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0}signalingStateRollback(){this._signalingState!==We.HaveLocalOffer&&this.signalingState!==We.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=We.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=Ve(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===We.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof je)switch(this._signalingState){case We.Initial:case We.Stable:this._signalingState=We.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case We.HaveLocalOffer:this._signalingState=We.Stable,this._answer=t;break;case We.HaveRemoteOffer:case We.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Fe)switch(this._signalingState){case We.Initial:case We.Stable:this._signalingState=We.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case We.HaveLocalOffer:this._signalingState=We.Stable,this._answer=t;break;case We.HaveRemoteOffer:case We.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Le)switch(this._signalingState){case We.Initial:case We.Stable:this._signalingState=We.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case We.HaveLocalOffer:break;case We.HaveRemoteOffer:this._signalingState=We.Stable,this._answer=t;break;case We.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Ge(e))switch(this._signalingState){case We.Initial:case We.Stable:this._signalingState=We.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case We.HaveLocalOffer:break;case We.HaveRemoteOffer:this._signalingState=We.Stable,this._answer=t;break;case We.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Rt){const e=this.initialTransaction;let t=Je.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Je.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===pt.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(i)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Rt){const e=this.reinviteUserAgentServer.transaction;let t=Je.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Je.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===pt.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class Kt extends _t{constructor(e,t,s){super(At,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===pt.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=Dt.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof At))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Wt(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==We.Initial&&s.signalingState!==We.HaveLocalOffer||s.signalingStateTransition(e);const i=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:i,prack:e=>i.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=Dt.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof At))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof At))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Wt(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==We.Initial&&s.signalingState!==We.HaveLocalOffer||s.signalingStateTransition(e);const i=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:i,ack:e=>{const t=i.ack(e);return this.confirmedDialogAcks.set(i.id,t),t}});else{const e=i.ack();this.confirmedDialogAcks.set(i.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class Jt extends xt{constructor(e,t,s){super(Rt,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new Ze(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof Rt))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Dt.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Wt(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact.toString()}`,i="Allow: "+Xe.toString();if(!e.body)if(this.confirmedDialog.signalingState===We.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===We.Initial||this.confirmedDialog.signalingState===We.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i),e.extraHeaders.push(s);const r=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},r),{session:n});return e.body&&this.confirmedDialog.signalingState!==We.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new Ze(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Rt))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Dt.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Wt(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const i=super.progress(e),r=this.earlyDialog,n=Object.assign(Object.assign({},i),{session:r});return e.body&&this.earlyDialog.signalingState!==We.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class Zt extends _t{constructor(e,t,s){super(Ct,e,t,s)}}class zt extends _t{constructor(e,t,s){super(Ct,e,t,s)}}class Xt extends xt{constructor(e,t,s){super(Ht,e,t,s),this.core=e}}class Qt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(ze.SUBSCRIBE,s);super(Ct,e.userAgentCore,i,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class es extends Dt{constructor(e,t,s,i,r,n){super(i,r),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=s,this.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const s=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof Re))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:s,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===ze.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+Xe.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var s;if(this.subscriptionState!==dt.Pending&&this.subscriptionState!==dt.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const i=new Qt(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(s=t.extraHeaders)||void 0===s?void 0:s.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),Je.TIMER_N)),i}terminate(){this.stateTransition(dt.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+Xe.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const i=s.state,r=s.expires?Math.max(s.expires,0):void 0;switch(i){case"pending":this.stateTransition(dt.Pending,r);break;case"active":this.stateTransition(dt.Active,r);break;case"terminated":this.stateTransition(dt.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new Ft(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case dt.Initial:case dt.NotifyWait:return void s();case dt.Pending:if(this.subscriptionState!==dt.NotifyWait&&this.subscriptionState!==dt.Pending)return void s();break;case dt.Active:case dt.Terminated:if(this.subscriptionState!==dt.NotifyWait&&this.subscriptionState!==dt.Pending&&this.subscriptionState!==dt.Active)return void s();break;default:return void s()}e===dt.Pending&&t&&(this.subscriptionExpires=t),e===dt.Active&&t&&(this.subscriptionExpires=t),e===dt.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==dt.Terminated&&(this.stateTransition(dt.Terminated),this.onTerminated())}}class ts extends _t{constructor(e,t,s){const i=t.getHeader("Event");if(!i)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(Ct,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=dt.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const i=s.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${i}`),void e.reject({statusCode:489})}if("terminated"!==i){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=dt.Pending;break;case"active":this.subscriptionState=dt.Active;break;case"terminated":this.subscriptionState=dt.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==dt.Terminated){const t=es.initialDialogStateForSubscription(this.message,e.message);this.dialog=new es(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),Je.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class ss extends xt{constructor(e,t,s){super(Ht,e,t,s),this.core=e}}const is=["application/sdp","application/dtmf-relay"];class rs{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Kt(this,e,t)}message(e,t){return new Mt(this,e,t)}publish(e,t){return new Zt(this,e,t)}register(e,t){return new zt(this,e,t)}subscribe(e,t){return new ts(this,e,t)}request(e,t){return new _t(Ct,this,e,t)}makeOutgoingRequestMessage(e,t,s,i,r,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,d=this.configuration.viaForceRport,h=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===ze.REGISTER&&l.push("path","gruu"),e===ze.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const u={callIdPrefix:a,forceRport:d,fromDisplayName:c,hackViaTcp:h,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},u),r);return new Le(e,t,s,i,g,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:i});const r=yt(e,t);return this.transport.send(r.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),r}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===ze.ACK&&s&&s.transaction.state===pt.Accepted&&s instanceof Jt?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==ze.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof Rt&&s.transaction.state===pt.Proceeding&&s instanceof Jt&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!Xe.includes(e.method)){const t="Allow: "+Xe.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==ze.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==ze.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===ze.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,i=this.subscribers.get(s);if(i){const t=new Ft(this,e);return void i.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===ze.OPTIONS){const t="Allow: "+Xe.toString(),s="Accept: "+is.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==ze.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case ze.ACK:break;case ze.BYE:this.replyStateless(e,{statusCode:481});break;case ze.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case ze.INFO:this.replyStateless(e,{statusCode:405});break;case ze.INVITE:{const t=new Jt(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case ze.MESSAGE:{const t=new Nt(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case ze.NOTIFY:{const t=new Ft(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case ze.OPTIONS:{const t="Allow: "+Xe.toString(),s="Accept: "+is.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case ze.REFER:{const t=new Yt(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case ze.REGISTER:{const t=new Xt(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case ze.SUBSCRIBE:{const t=new ss(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class ns{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var s,i;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(r,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const i=s[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,n)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:i},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===r);n?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===r);t&&(t.stop(),s.removeTrack(t),ns.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),ns.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}s.addTrack(e),ns.dispatchAddTrackEvent(s,e)}))},n=e.getAudioTracks();n.length&&r(n[0]);const o=e.getVideoTracks();return o.length&&r(o[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),ns.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),ns.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),ns.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),ns.dispatchAddTrackEvent(t,e))}updateDirection(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");{const t=t=>{switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const s=t(e.direction);e.direction!==s&&(e.direction=s)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),s=(()=>{switch(t){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==s&&(e.direction=s)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const i=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const i=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const i=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${i}`),"complete"===i&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const i=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const s=e.track.kind,i=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${i}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function os(e){return(t,s)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const i={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==s?void 0:s.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new ns(r,e,i)}}class as{constructor(e,t){if(this._state=ht.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new Te,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,i=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},as.defaultOptions),t);const s=this.configuration.server,i=ke.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===ht.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case ht.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ht.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case ht.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ht.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case ht.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ht.Connecting)}catch(e){if(e instanceof we)return Promise.reject(e);throw e}break;case ht.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ht.Connecting)}catch(e){if(e instanceof we)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(ht.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case ht.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ht.Disconnecting)}catch(e){if(e instanceof we)return Promise.reject(e);throw e}break;case ht.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ht.Disconnecting)}catch(e){if(e instanceof we)return Promise.reject(e);throw e}break;case ht.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ht.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case ht.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ht.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==ht.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,i=this.disconnectPromise?void 0:new Error(s);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(ht.Disconnected,i)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let i;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{i=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e.toString()),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+i+"\n")}else i=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+i+"\n");if(this.state===ht.Connected){if(this.onMessage)try{this.onMessage(i)}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===ht.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(ht.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new we("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case ht.Connecting:e!==ht.Connected&&e!==ht.Disconnecting&&e!==ht.Disconnected&&s();break;case ht.Connected:e!==ht.Disconnecting&&e!==ht.Disconnected&&s();break;case ht.Disconnecting:e!==ht.Connecting&&e!==ht.Disconnected&&s();break;case ht.Disconnected:e!==ht.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===ht.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===ht.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${i} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===ht.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(i===ht.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===ht.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===ht.Connected?r():n(t||new Error("Connect aborted."))}if(i===ht.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===ht.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}as.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class cs{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=lt.Stopped,this._stateEventEmitter=new Te,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},cs.defaultOptions()),{sipjsId:xe(5)}),{uri:new Ie("sip","anonymous."+xe(6),"anonymous.invalid")}),{viaHost:xe(12)+".invalid"}),cs.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new St,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=ut.error;break;case"warn":this.loggerFactory.level=ut.warn;break;case"log":this.loggerFactory.level=ut.log;break;case"debug":this.loggerFactory.level=ut.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,i=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==i&&(this.options.reconnectionDelay=i),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:cs.newUUID(),-1===ke.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return ke.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:os(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:it.Unsupported,sipExtensionReplaces:it.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:as,transportOptions:{},uri:new Ie("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===lt.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===lt.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(lt.Started),this.transport.connect())}async stop(){if(this.state===lt.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(lt.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),r=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in i)i[e]&&await i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await r.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(lt.Stopped)}_makeInviter(e,t){return new at(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=""!==this.options.contactName?this.options.contactName:xe(8),t=this.options.contactParams,s={pubGruu:void 0,tempGruu:void 0,uri:new Ie("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const s=e.anonymous||!1,i=e.outbound||!1,r=e.register||!1;let n="<";return n+=s?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:r?this.contact.uri:this.contact.pubGruu||this.contact.uri,i&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}};return s}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===it.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===it.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>nt[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new wt(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new rs(s,{onInvite:e=>{var t;const s=new ot(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==it.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const i=t.replaces_to_tag;if("string"!=typeof i)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const n=e+i+r,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+r]||this._sessions[e+i]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new Qe(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new et(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==lt.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==lt.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=gt.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===lt.Stopped&&t instanceof je)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof je){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=Me(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof Fe){if(!s())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=Me(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof je)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof Fe))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case lt.Started:e!==lt.Stopped&&s();break;case lt.Stopped:e!==lt.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}const ds=({username:e})=>{const t=d().configs?.[e],s=d().findLineByNumber,i=d().getNewLineNumber,r=d().addLine,n=d().updateLine,o=d().userAgents?.[e],{hasAudioDevice:a,hasVideoDevice:c}=d().devicesInfo,{onInviteAccepted:h,onInviteCancel:u,onInviteProgress:g,onInviteRejected:p,onSessionDescriptionHandlerCreated:f,onSessionReceivedBye:m,onSessionReceivedMessage:v,onSessionReinvited:w,onTransferSessionDescriptionHandlerCreated:b}=(({username:e})=>{const t=d().updateLine;async function s(s,i){const r=s.sipSession;r&&(r.initiateRemoteMediaStreams=({videoEnabled:n=i,pc:o=r.sessionDescriptionHandler.peerConnection,configs:a=l(e)})=>{const c=a?.media,d=new Map,h=new Map,u=`line-${s.lineNumber}-remoteAudios`,g=`line-${s.lineNumber}-remoteVideos`,p=document.getElementById(u),f=document.getElementById(g);o.getTransceivers().forEach(e=>{const t=e.receiver?.track;if(!t)return;const s=new MediaStream([t]);"audio"===t.kind&&d.set(t.id,s),n&&"video"===t.kind&&(t.mid=e.mid,h.set(t.id,s))}),p&&(p.innerHTML="",d.forEach((e,t)=>{const i=document.createElement("audio");i.id=`line-${s.lineNumber}-audio-${t}`,i.autoplay=!0,i.srcObject=e,i.controls=!1,i.onloadedmetadata=()=>{void 0!==i.sinkId&&c?.audioOutputDeviceId&&i.setSinkId(c?.audioOutputDeviceId).then(()=>{}).catch(e=>{}),i.play().catch(e=>{})},p.appendChild(i)})),f&&(f.innerHTML="",h.forEach((e,t)=>{const i=document.createElement("video");i.id=`line-${s.lineNumber}-video-${t}`,i.srcObject=e,i.autoplay=!0,i.playsInline=!0,i.muted=!0,i.onloadedmetadata=()=>{void 0!==i.sinkId&&c?.videoInputDeviceId&&i.setSinkId(c?.videoInputDeviceId).then(()=>{}).catch(e=>{}),i.play().catch(e=>{})},f.appendChild(i)})),t(s)},r.initiateRemoteMediaStreams({videoEnabled:i}))}return{onInviteCancel:function(e,t,s){let i=0;const r=t.headers.Reason;if(void 0!==r&&r.length>0)for(let e=0;e<r.length;e++){const t=r[e].raw.toLowerCase().trim(),s=t.split(";");if(s.length>=2&&("sip"===s[0].trim()||"q.850"===s[0].trim())&&s[1].includes("cause")&&t.includes("call completed elsewhere")){i=parseInt(s[1].substring(s[1].indexOf("=")+1).trim());break}}const n=e.sipSession;n&&(n.data.terminateBy="them",n.data.reasonCode=i,n.data.reasonText=0===i?"Call Cancelled":"Call completed elsewhere",n.dispose().catch(function(e){}),s?.())},onInviteAccepted:async function(s,i,r){const n=s.sipSession;if(!n)return;n.data.earlyMedia&&(n.data.earlyMedia.pause(),n.data.earlyMedia.removeAttribute("src"),n.data.earlyMedia.load(),n.data.earlyMedia=null);const o=he();n.data.startTime=o,n.isOnHold=!1,n.data.started=!0,n.initiateLocalMediaStreams=async({videoEnabled:r=i,pc:o=n.sessionDescriptionHandler.peerConnection,configs:a=l(e)})=>{try{const e=a?.media,i={audio:!e?.audioInputDeviceId||"default"===e.audioInputDeviceId||{deviceId:{exact:e.audioInputDeviceId}},video:!!r&&(!e?.videoInputDeviceId||"default"===e.videoInputDeviceId||{deviceId:{exact:e.videoInputDeviceId}})},n=await navigator.mediaDevices.getUserMedia(i);if(n.getTracks().forEach(e=>{const t=o.getSenders().find(t=>t.track&&t.track.kind===e.kind);t?t.replaceTrack(e):o.addTrack(e,n)}),r){const e=document.getElementById(`line-${s.lineNumber}-localVideo`);e&&(e.srcObject=new MediaStream(n.getVideoTracks()),await e.play().catch(()=>{}))}t(s)}catch(e){}},n.initiateLocalMediaStreams({videoEnabled:i}),t(s)},onInviteTrying:function(e,t){},onInviteProgress:function(e,s){e.sipSession&&(180===s.message.statusCode||s.message.statusCode,t(e))},onInviteRejected:function(e,t,s){const i=e.sipSession;i&&(i.data.terminateBy="them",i.data.reasonCode=t.message.statusCode,i.data.reasonText=t.message.reasonPhrase,s?.())},onInviteRedirected:function(e,t){},onSessionReceivedBye:function(e,t,s){e?.sipSession&&(e.sipSession.data.terminateBy="them",e.sipSession.data.reasonCode=16,e.sipSession.data.reasonText="Normal Call clearing",t.accept(),s?.())},onSessionReinvited:function(e,t){const s=t.body,i=e.sipSession;if(!i)return;i.data.videoChannelNames=[];const r=s.split("m=video");if(r.length>=1)for(let e=0;e<r.length;e++)if(r[e].indexOf("a=mid:")>-1&&r[e].indexOf("a=label:")>-1){const t=r[e].split("\r\n");let s="",n="";for(let e=0;e<t.length;e++)0==t[e].indexOf("a=label:")&&(s=t[e].replace("a=label:","")),0==t[e].indexOf("a=mid:")&&(n=t[e].replace("a=mid:",""));i.data.videoChannelNames.push({mid:n,channel:s})}},onSessionReceivedMessage:function(e,s){try{const i=s.request.headers["Content-Type"].length>=1?s.request.headers["Content-Type"][0].parsed:"Unknown";if(i.indexOf("application/x-asterisk-confbridge-event")>-1){const t=JSON.parse(s.request.body),i=e.sipSession;if(!i)return;if(!i.data)return;i.data.confBridgeChannels||(i.data.confBridgeChannels=[]),i.data.confBridgeEvents||(i.data.confBridgeEvents=[]),"ConfbridgeStart"==t.type||("ConfbridgeWelcome"==t.type?(i.data.confBridgeChannels=t.channels,i.data.confBridgeChannels.forEach(function(e){})):"ConfbridgeJoin"==t.type?t.channels.forEach(function(e){let t=!1;i.data.confBridgeChannels?.forEach(function(s){s.id==e.id&&(t=!0)}),t||(i.data.confBridgeChannels?.push(e),i.data.confBridgeEvents?.push({event:e.caller.name+" ("+e.caller.number+") joined the conference",eventTime:he()}))}):"ConfbridgeLeave"==t.type?t.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t,s){t.id==e.id&&(i.data.confBridgeChannels?.splice(s,1),i.data.confBridgeEvents?.push({event:e.caller.name+" ("+e.caller.number+") left the conference",eventTime:he()}))})}):"ConfbridgeTalking"===t.type||("ConfbridgeMute"==t.type?t.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(t.muted=!0)})}):"ConfbridgeUnmute"===t.type?t.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(t.muted=!1)})}):t.type)),s.accept()}else if(i.indexOf("application/x-myphone-confbridge-chat")>-1)s.accept();else if(i.indexOf("text/plain")>-1){if(!e?.sipSession?.data.remoteMediaStreamStatus)return;const t=JSON.parse(s.request.body);switch(t.type){case A.SOUND_TOGGLE:e.sipSession.data.remoteMediaStreamStatus.soundEnabled=t.value;break;case A.VIDEO_TOGGLE:e.sipSession.data.remoteMediaStreamStatus.videoEnabled=t.value,ls(e.sipSession,A.VIDEO_TOGGLE_ACK,"");break;case A.SCREEN_SHARE_TOGGLE:e.sipSession.data.remoteMediaStreamStatus.screenShareEnabled=t.value;break;case A.VIDEO_TOGGLE_ACK:e.sipSession.data.videoAckReceived=!0;break;default:s.reject()}s.accept()}else s.reject();t(e)}catch(e){}},onSessionDescriptionHandlerCreated:function(e,t,i,r){t&&t.peerConnection&&(t.peerConnection.ontrack=function(t){s(e,r)})},onTrackAddedEvent:s,onTransferSessionDescriptionHandlerCreated:function(e,t,s,i){s&&s.peerConnection&&(s.peerConnection.ontrack=function(){const r=s.peerConnection,n=new MediaStream,o=new MediaStream;r.getReceivers().forEach(e=>{e.track&&("audio"===e.track.kind&&n.addTrack(e.track),i&&"video"===e.track.kind&&o.addTrack(e.track))});const a=document.createElement("audio");if(a.setAttribute("id",`line-${e.lineNumber}-transfer-remoteAudio`),a.srcObject=n,a.onloadedmetadata=function(){void 0!==a.sinkId&&t?.data?.audioOutputDevice&&a.setSinkId(t.data.audioOutputDevice).then(function(){}).catch(function(e){}),a.play()},i&&o.getVideoTracks().length>0){const t=document.createElement("video");o.getVideoTracks().forEach((s,i)=>{const r=new MediaStream;r.trackId=s.id,r.mid=s.mid,r.addTrack(s),t.id=`line-${e.lineNumber}-video-${i}`,t.srcObject=r,t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.className="video-element",t.onloadedmetadata=()=>{t.play().catch(e=>{})}})}})}}})({username:e}),{makeAudioSpdOptions:S,answerAudioSpdOptions:y,answerVideoSpdOptions:T,makeVideoSpdOptions:$}=ue({username:e});function E(e,s,i){if(!o)return;if(!o.isRegistered())return;if(null===e)return;if(!a)return void alert("No audio device detected!");const r=S({extraHeaders:i});if(!r)return;let n=he();const c=cs.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+t?.account.domain);e.sipSession=new at(o,c,r);const d=e.sipSession;d.data={line:e.lineNumber,callDirection:"outbound",remoteNumber:s,startTime:n,videoSourceDevice:null,audioSourceDevice:t?.media.audioInputDeviceId,audioOutputDevice:t?.media.audioOutputDeviceId,terminateBy:"them",localMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:a,videoEnabled:!1},remoteMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},earlyReject:!1},d.data.callType="audio",d.isOnHold=!1,d.delegate={onBye:function(t){m(e,t,()=>hs(e))},onMessage:function(t){v(e,t)},onInvite:function(t){w(e,t)},onSessionDescriptionHandler:function(t,s){f(e,t,s,!1)}};const l={requestDelegate:{onTrying:function(e){},onProgress:function(t){g(e,t)},onRedirect:function(e){},onAccept:function(t){h(e,!1,t)},onReject:function(t){p(e,t,()=>hs(e))}}};d.invite(l).catch(function(e){})}function R(e,s,i){if(null==o)return;if(!o.isRegistered())return;if(null==e)return;if(!a)return void alert("No audio device detected!");if(!c)return void E(e,s);const r=$({extraHeaders:i});if(!r)return;const n=he(),d=cs.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+t?.account.domain);e.sipSession=new at(o,d,r);const l=e.sipSession;l.data={line:e.lineNumber,callDirection:"outbound",remoteNumber:s,startTime:n,localMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!0},remoteMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},videoSourceDevice:t?.media.videoInputDeviceId,audioSourceDevice:t?.media.audioInputDeviceId,audioOutputDevice:t?.media.audioOutputDeviceId,terminateBy:"them"},l.data.callType="video",l.data.earlyReject=!1,l.isOnHold=!1,l.delegate={onBye:function(t){m(e,t,()=>hs(e))},onMessage:function(t){v(e,t)},onInvite:function(t){w(e,t)},onSessionDescriptionHandler:function(t,s){f(e,t,s,!0)}};const u={requestDelegate:{onTrying:function(e){},onProgress:function(t){g(e,t)},onRedirect:function(e){},onAccept:function(t){h(e,!0,t)},onReject:function(t){p(e,t,()=>hs(e))}}};l.invite(u).catch(function(e){})}const I=async e=>{const t=s(e);if(!t||!t.sipSession||"audio"===t.sipSession.data.callType)return;const i=t.sipSession;if(!i.data.localMediaStreamStatus||!i.data.remoteMediaStreamStatus)return;i.data.localMediaStreamStatus.screenShareEnabled&&await C(e);const r=!i.data.localMediaStreamStatus.videoEnabled;i.data.localMediaStreamStatus.videoEnabled=r;const o=i.sessionDescriptionHandler?.peerConnection;if(!o)return;const a=o.getSenders().find(e=>"video"===e.track?.kind);if(a)a.track&&(a.track.enabled=r);else if(r)try{const e=(await navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0];o.addTrack(e)}catch(e){return}await ls(i,A.VIDEO_TOGGLE,r),n(t)};async function C(e){const t=s(e);if(!t||!t.sipSession||"audio"===t.sipSession.data.callType)return;const i=t.sipSession,r=i.sessionDescriptionHandler?.peerConnection;if(!r||!i.data.localMediaStreamStatus)return;if(i.data.localMediaStreamStatus.screenShareEnabled){const e=r.getSenders().find(e=>"video"===e.track?.kind);if(e?.track){const t=i.data.localMediaStreamStatus.videoEnabled;e.track.enabled=t}try{const t=(await navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0];e?await e.replaceTrack(t):r.addTrack(t)}catch(e){}i.data.localMediaStreamStatus.screenShareEnabled=!1,ls(i,A.SCREEN_SHARE_TOGGLE,!1)}else try{const t=(await navigator.mediaDevices.getDisplayMedia({video:!0})).getVideoTracks()[0];t.onended=()=>{C(e)};const s=r.getSenders().find(e=>"video"===e.track?.kind);i.data.localMediaStreamStatus.videoEnabled&&await I(e),s?await s.replaceTrack(t):r.addTrack(t),i.data.localMediaStreamStatus.screenShareEnabled=!0,ls(i,A.SCREEN_SHARE_TOGGLE,!0)}catch(e){return}n(t)}function _(e,t){const i=s(e);if(null==i||null==i.sipSession)return;const r=i.sipSession;if(r.isOnHold===t)return;const o=t??!r.isOnHold;r.isOnHold=o;const a=r.sessionDescriptionHandlerOptionsReInvite;if(a.hold=o,r.sessionDescriptionHandlerOptionsReInvite=a,r&&r.sessionDescriptionHandler&&r.sessionDescriptionHandler.peerConnection){const e=r.sessionDescriptionHandler.peerConnection;e.getReceivers().forEach(function(e){e.track&&(e.track.enabled=o)}),e.getSenders().forEach(function(e){const t=e.track;e.track&&"audio"==e.track.kind?(1==t.IsMixedTrack&&r.data.audioSourceTrack&&"audio"==r.data.audioSourceTrack.kind&&(r.data.audioSourceTrack.enabled=o),t.enabled=o):t&&"video"==t.kind&&(t.enabled=o)})}r.data.isHold=o,n(i)}return{receiveSession:function(s){const n=s.remoteIdentity.displayName||s.remoteIdentity.uri.user||"";let o=s.remoteIdentity.uri.user??"";const a=new D(i(),n);a.sipSession=s;const c=a.sipSession;c.data={},c.data.line=a.lineNumber,c.data.callDirection="inbound",c.data.terminateBy="",c.data.remoteNumber=o,c.data.earlyReject=!1,c.data.callType="audio",c.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},c.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!1,videoEnabled:!1},t?.features.enableVideo&&c.request.body&&c.request.body.indexOf("m=video")>-1&&(c.data.remoteMediaStreamStatus.videoEnabled=!0,c.data.callType="video");const d="video"===c.data.callType,h=c.incomingInviteRequest.message.headers;if(h["P-Asserted-Identity"]){const e=h["P-Asserted-Identity"][0].raw;if(e.includes("<sip:")){const s=e.split("<sip:");s[1].endsWith(">")&&(s[1]=s[1].slice(0,-1)),s[1].includes(`@${t?.account.domain}`)&&(o=s[1].split("@")[0])}}c.delegate={onBye:function(e){m(a,e,()=>hs(a))},onMessage:function(e){v(a,e)},onInvite:function(e){w(a,e)},onSessionDescriptionHandler:function(e,t){f(a,e,t,d)}},c.incomingInviteRequest.delegate={onCancel:function(e){u(a,e,()=>hs(a))}},r(e,a)},answerAudioSession:function(e){if(!a)return void alert("No audio device detected!");const i=s(e);if(null===i)return;const r=i.sipSession;if(!r||r instanceof at)return;r.data.ringerObj&&(r.data.ringerObj.pause(),r.data.ringerObj.removeAttribute("src"),r.data.ringerObj.load(),r.data.ringerObj=null);const n=y();n&&(r.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:a,videoEnabled:!1},r.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},r.data.videoSourceDevice=null,r.data.audioSourceDevice=t?.media.audioInputDeviceId,r.data.audioOutputDevice=t?.media.audioOutputDeviceId,r.accept(n).then(function(){h(i,!1)}).catch(function(e){r.data.reasonCode=500,r.data.reasonText="Client Error",hs(i)}))},answerVideoSession:function(e,i){const r=s(e);if(!r||!t)return;const o=r.sipSession;if(!o||o instanceof at)return;if(o.data.ringerObj&&(o.data.ringerObj.pause(),o.data.ringerObj.removeAttribute("src"),o.data.ringerObj.load(),o.data.ringerObj=null),!a)return void alert("No audio device detected!");const c=T();o.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:i??!0},o.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!0},o.data.videoSourceDevice=t.media.videoInputDeviceId,o.data.audioSourceDevice=t.media.audioInputDeviceId,o.data.audioOutputDevice=t.media.audioOutputDeviceId,o.accept(c).then(async()=>{try{await h(r,!0),o.data.localMediaStreamStatus?.videoEnabled&&await async function(e,t){const s=t?.maxRetries,i=t?.delayMs;let r=0;return new Promise((t,n)=>{const o=async()=>{if(!e?.data?.line)return;const a=d().findLineByNumber(e?.data?.line)?.sipSession?.data?.videoAckReceived;return a?t():r>=s?n(new Error("ACK timeout")):(await ls(e,A.VIDEO_TOGGLE,!0),r++,void setTimeout(o,i))};o()})}(o,{delayMs:2e3,maxRetries:10})}catch(e){}}).catch(function(e){o.data.reasonCode=500,o.data.reasonText="Client Error",hs(r)}),n(r)},makeAudioSession:E,makeVideoSession:R,toggleLocalVideoTrack:I,toggleShareScreen:C,rejectSession:function(e){const t=s(e);if(null==t)return;const i=t.sipSession;!i||i instanceof at||(i.state==st.Established?i.bye().catch(function(e){}):i.reject({statusCode:486,reasonPhrase:"Busy Here"}).catch(function(e){}),i.data.terminateBy="us",i.data.reasonCode=486,i.data.reasonText="Busy Here",hs(t))},dialByNumber:function(t,s,n){const o=d().userAgents?.[e];if(!o||!o?.isRegistered())return void alert(`SIP userAgent for ${e} not registered`);if(!a)return void alert("No audio device detected!");const c=new D(i(),s);"audio"===t?E(c,s,n):R(c,s,n??[]),r(e,c)},endSession:function(e){const t=s(e);if(null==t)return;const i=t.sipSession;if(i)switch(i.state){case st.Initial:case st.Establishing:i instanceof at?(i.data.terminateBy="us",i.data.reasonCode=0,i.data.reasonText="Call Cancelled",i.cancel()):(i.reject({statusCode:486,reasonPhrase:"Busy Here"}).catch(function(e){}),i.data.terminateBy="us",i.data.reasonCode=486,i.data.reasonText="Busy Here",hs(t));break;case st.Established:i.bye().catch(function(e){}),i.data.terminateBy="us",i.data.reasonCode=486,i.data.reasonText="Busy Here",hs(t);break;default:hs(t)}},recordSession:function(e){return{start:async function(){const t=s(e);if(!t?.sipSession)return;const i="video"===t.sipSession.data.callType;try{const e=[];let s=null;i&&(s=await navigator.mediaDevices.getDisplayMedia({video:{displaySurface:"monitor"},audio:!0}));const r=new AudioContext,o=r.createMediaStreamDestination();s?.getAudioTracks().length&&r.createMediaStreamSource(new MediaStream(s.getAudioTracks())).connect(o);const a=t.sipSession.sessionDescriptionHandler.peerConnection;a.getSenders().forEach(e=>{"audio"===e.track?.kind&&r.createMediaStreamSource(new MediaStream([e.track])).connect(o)}),a.getReceivers().forEach(e=>{"audio"===e.track?.kind&&r.createMediaStreamSource(new MediaStream([e.track])).connect(o)});const c=new MediaStream([...o.stream.getAudioTracks()]);i&&s?.getVideoTracks().length&&s?.getVideoTracks().forEach(e=>c.addTrack(e));const d=MediaRecorder.isTypeSupported((i?"video":"audio")+"/webm; codecs=vp8,opus")?(i?"video":"audio")+"/webm; codecs=vp8,opus":(i?"video":"audio")+"/webm",h=new MediaRecorder(c,{mimeType:d});h.ondataavailable=t=>{t.data.size>0&&e.push(t.data)},h.onstop=()=>{if(!t?.sipSession?.data.recordMedia)return;t.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},n(t);const s=new Blob(e,{type:d});e.length=0;const r=URL.createObjectURL(s),o=document.createElement("a");o.href=r,o.download=`recording-${i?"video":"audio"}-${Date.now()}.webm`,o.click(),URL.revokeObjectURL(r)},s?.getVideoTracks().length&&(s.getVideoTracks()[0].onended=()=>{h.stop()}),h.start(),t.sipSession.data.recordMedia={recorder:h,recording:!0,startTime:he()},n(t)}catch(e){if(!t?.sipSession?.data.recordMedia)return;t.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},n(t)}},stop:function(){const t=s(e);if(!t?.sipSession)return;const i=t?.sipSession?.data.recordMedia?.recorder;i&&(i.stop(),t.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},n(t))}}},toggleMuteSession:function(e){const t=s(e);if(null==t||null==t.sipSession)return;const i=t.sipSession;if(!i.data.localMediaStreamStatus)return;const r=!i.data.localMediaStreamStatus.soundEnabled;if(i.data.localMediaStreamStatus.soundEnabled=r,i&&i.sessionDescriptionHandler&&i.sessionDescriptionHandler.peerConnection){i.sessionDescriptionHandler.peerConnection.getSenders().forEach(function(e){if(e.track&&"audio"==e.track.kind){const t=e.track;1==t.IsMixedTrack&&i.data.audioSourceTrack&&"audio"==i.data.audioSourceTrack.kind&&(i.data.audioSourceTrack.enabled=r),t.enabled=r}})}ls(i,A.SOUND_TOGGLE,r),n(t)},toggleHoldSession:_,makeTransferSession:function(i,r){_(i,!0),queueMicrotask(()=>{!function(i,r){const o=d().userAgents?.[e];if(!o||!o?.isRegistered())return void alert(`SIP userAgent for ${e} not registered`);const a=String(r);if(""===a)return;const c=s(i);if(!c?.sipSession)return;const h=c.sipSession;if(!h)return;h.data.transfer||(h.data.transfer=[]);h.data.transfer.push({type:"Attended",to:r,transferTime:he(),disposition:"invite",dispositionTime:he(),accept:{complete:null,eventTime:null,disposition:""}});const l=h.data.transfer.length-1,u=navigator.mediaDevices.getSupportedConstraints(),g={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if("object"!=typeof g.sessionDescriptionHandlerOptions.constraints.audio)return;h.data.audioSourceDevice&&"default"!=h.data.audioSourceDevice&&(g.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:h.data.audioSourceDevice});u.autoGainControl&&(g.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=t?.media.autoGainControl);u.echoCancellation&&(g.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=t?.media.echoCancellation);u.noiseSuppression&&(g.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=t?.media.noiseSuppression);if(h.data.localMediaStreamStatus?.videoEnabled){g.sessionDescriptionHandlerOptions.constraints.video={};const e=g.sessionDescriptionHandlerOptions.constraints.video;h.data.videoSourceDevice&&"default"!=h.data.videoSourceDevice&&(e.deviceId={exact:h.data.videoSourceDevice}),u.frameRate&&""!==t?.media.maxFrameRate&&(e.frameRate=String(t?.media.maxFrameRate)),u.height&&""!=t?.media.videoHeight&&(e.height=String(t?.media.videoHeight)),u.aspectRatio&&""!=t?.media.videoAspectRatio&&(e.aspectRatio=String(t?.media.videoAspectRatio)),("object"==typeof g.sessionDescriptionHandlerOptions.constraints.video&&0==Object.keys(g.sessionDescriptionHandlerOptions.constraints.video)?.length||"boolean"==typeof g.sessionDescriptionHandlerOptions.constraints.video)&&(g.sessionDescriptionHandlerOptions.constraints.video=!0)}const p=cs.makeURI("sip:"+a.replace(/#/g,"%23")+"@"+t?.account.domain),f=new at(o,p,g);f.data={},f.delegate={onBye:function(){h.data.transfer&&(h.data.transfer[l].disposition="bye",h.data.transfer[l].dispositionTime=he())},onSessionDescriptionHandler:function(e){b(c,h,e,h?.data?.localMediaStreamStatus?.videoEnabled)}},h.data.childsession=f;const m={requestDelegate:{onTrying:function(){h.data.transfer&&(h.data.transfer[l].disposition="trying",h.data.transfer[l].dispositionTime=he())},onProgress:function(){h.data.transfer&&(h.data.transfer[l].disposition="progress",h.data.transfer[l].dispositionTime=he(),h.data.transfer[l].onCancle=()=>{f.cancel().catch(function(e){}),h.data.transfer&&(h.data.transfer[l].accept.complete=!1,h.data.transfer[l].accept.disposition="cancel",h.data.transfer[l].accept.eventTime=he())})},onRedirect:function(e){},onAccept:function(){if(!h.data.transfer)return;h.data.transfer[l].disposition="accepted",h.data.transfer[l].dispositionTime=he();const e={requestDelegate:{onAccept:function(e){h.data.transfer&&(h.data.terminateBy="us",h.data.reasonCode=202,h.data.reasonText="Attended Transfer",h.data.transfer[l].accept.complete=!0,h.data.transfer[l].accept.disposition=e.message.reasonPhrase??"",h.data.transfer[l].accept.eventTime=he(),h.bye().catch(function(e){}),hs(c))},onReject:function(e){h.data.transfer&&(h.data.transfer[l].accept.complete=!1,h.data.transfer[l].accept.disposition=e.message.reasonPhrase??"",h.data.transfer[l].accept.eventTime=he())}}};h.refer(f,e).catch(function(e){})},onReject:function(e){h.data.transfer&&(h.data.transfer[l].disposition=e.message.reasonPhrase??"",h.data.transfer[l].dispositionTime=he())}}};f.invite(m).catch(function(e){}),n(c)}(i,r)})},cancelTransferSession:function(e,t){if(null==o)return;if(!o.isRegistered())return;if(""===String(t))return;const i=s(e);if(!i?.sipSession)return;const r=i.sipSession;r&&r.data.transfer&&(r.data.transfer.forEach(e=>{e.to===t&&e.onCancle?.()}),_(e,!1),n(i))},cancelSession:function(e){const t=s(e);if(null==t||null==t.sipSession)return;const i=t.sipSession;i instanceof at&&(i.data.terminateBy="us",i.data.reasonCode=0,i.data.reasonText="Call Cancelled",i.state==st.Initial||i.state==st.Establishing?i.cancel():hs(t))},teardownSession:hs}};function hs(e){const{removeLine:t}=d();if(null==e||null==e.sipSession)return;const s=e.sipSession;if(1!=s.data.teardownComplete){if(s.data.teardownComplete=!0,s.data.childsession&&s.data.childsession.dispose().then(function(){s.data.childsession=null}).catch(function(e){s.data.childsession=null}),s.data.audioSourceTrack&&"audio"==s.data.audioSourceTrack.kind&&(s.data.audioSourceTrack.stop(),s.data.audioSourceTrack=null),s.data.earlyMedia&&(s.data.earlyMedia.pause(),s.data.earlyMedia.removeAttribute("src"),s.data.earlyMedia.load(),s.data.earlyMedia=null),s.data.ringerObj&&(s.data.ringerObj.pause(),s.data.ringerObj.removeAttribute("src"),s.data.ringerObj.load(),s.data.ringerObj=null),null!==e.localSoundMeter&&(e.localSoundMeter.stop(),e.localSoundMeter=null),null!==e.remoteSoundMeter&&(e.remoteSoundMeter.stop(),e.remoteSoundMeter=null),s&&s.sessionDescriptionHandler&&s.sessionDescriptionHandler?.peerConnection){s.sessionDescriptionHandler.peerConnection.getSenders().forEach(function(e){"audio"==e?.track?.kind&&e.track.stop()})}t(e.lineNumber)}}async function ls(e,t,s){if(e)try{await e.message({requestDelegate:{onAccept:()=>{},onReject:()=>{}},requestOptions:{body:{contentType:"text/plain",content:JSON.stringify({type:t,value:s}),contentDisposition:"render"}}})}catch(e){}}d().getUsernameByNumber,d().getSessionByNumber;class us{ua;configs;username;constructor(e){this.configs=e,this.username=e.account.username,d().setConfig(this.username,e)}async init(){await this.detectDevices(),await this.createUserAgent()}async detectDevices(){const e=await le(this.username);d().setSipStore({devicesInfo:e})}async createUserAgent(){const e=new cs({uri:cs.makeURI(`sip:${this.username}@${this.configs.account.domain}`),transportOptions:{server:`wss://${this.configs.account.wssServer}:${this.configs.account.webSocketPort}${this.configs.account.serverPath}`,traceSip:!1,connectionTimeout:this.configs.registration.transportConnectionTimeout},authorizationUsername:this.username,authorizationPassword:this.configs.account.password,delegate:{onInvite:ds({username:this.username}).receiveSession,onMessage:()=>{}}});e.isRegistered=()=>e&&e.registerer&&e.registerer.state===ct.Registered,e.sessions=e._sessions,e.registrationCompleted=!1,e.registering=!1,e.transport.reconnectionAttempts=this.configs.registration.transportReconnectionAttempts||0,e.transport.attemptingReconnection=!1,e.BlfSubs=[],e.lastVoicemailCount=0,e.transport.onConnect=()=>R(this.username,e),e.transport.onDisconnect=t=>{t?I(0,this.username,e):function(e,t){t.isReRegister=!1;const{userAgents:s}=d();c({userAgents:{...s,[e]:t}})}(this.username,e)},e.registerer=new ft(e,{logConfiguration:!1,expires:this.configs.registration.registerExpires,extraHeaders:[],extraContactHeaderParams:[],refreshFrequency:75}),e.registerer.stateChange.addListener(t=>{switch(t){case ct.Registered:!function(e,t){t.registrationCompleted=!0,t.isReRegister,t.registering=!1,t.isReRegister=!0;const{userAgents:s,statuses:i}=d();c({userAgents:{...s,[e]:t},statuses:{...i,[e]:"connected"}})}(this.username,e);break;case ct.Unregistered:!function(e,t){t.isReRegister=!1;const{userAgents:s,statuses:i}=d();c({userAgents:{...s,[e]:t},statuses:{...i,[e]:"disconnected"}})}(this.username,e)}}),await e.start().catch(e=>I(0,this.username)),this.ua=e,d().setUserAgent(this.username,e)}getUserAgent(){return this.ua}async stop(){this.ua&&await this.ua.stop()}}exports.AudioStream=({lineNumber:e,...s})=>"local"===s.type?t.jsx("audio",{...s,id:`line-${e}-localAudio`}):t.jsx("div",{...s,id:`line-${e}-remoteAudios`}),exports.SipManager=class{instances=new Map;async add(e){const t=e.account.username;if(this.instances.has(t)&&w(this.instances.get(t)?.config,e))return;this.instances.has(t)&&(e=>{const t=d().configs?.[e.account.username]?.media;if(t&&!w(t,e.media)){const t=e.account.username,s=d().lines[t]??{};Object.values(s).forEach(t=>{t.sipSession?.data.started&&(t.sipSession?.initiateLocalMediaStreams({videoEnabled:t.sipSession.data.localMediaStreamStatus?.videoEnabled,configs:e}),t.sipSession?.initiateRemoteMediaStreams({videoEnabled:t.sipSession.data.localMediaStreamStatus?.videoEnabled,configs:e}))})}})(e);const s=new us(de($,e));await s.init(),this.instances.set(t,{config:e,instance:s})}methods(e){return ds({username:e})}get(e){const{lines:t,statuses:s}=d();return{status:s?.[e]??"disconnected",lines:Object.values(t[e]??[]),watch:u({username:e})}}has(e){return this.instances.has(e)}reconnect(e){C(e)}async stop(e){const t=this.instances.get(e)?.instance;t&&(await t.stop(),this.instances.delete(e),d().remove(e))}async stopAll(){for(const[e,{instance:t}]of this.instances)await t.stop();d().removeAll(),this.instances.clear()}getUsernameByNumber(e){return d().getUsernameByNumber(e)}getSessionByNumber(e){return d().getSessionByNumber(e)}},exports.VideoStream=({lineNumber:e,...s})=>"local"===s.type?t.jsx("video",{...s,id:`line-${e}-${s.type}Video`,muted:"local"===s.type}):t.jsx("div",{...s,id:`line-${e}-remoteVideos`}),exports.useWatchSessionData=function({lineNumber:e,name:t}){const s=d().getUsernameByNumber(e);return o(b(i=>{try{const r=s?i.lines?.[s]?.[e]:null,n=r?.sipSession?.data;return Array.isArray(t)?t.map(e=>n?T(n,e):void 0):"string"==typeof t?n?T(n,t):void 0:r?.sipSession?.data}catch(e){}}))};
|
|
1
|
+
"use strict";var e=require("react"),t=require("react/jsx-runtime");const s={username:"",password:"",domain:"",wssServer:"",webSocketPort:7443,serverPath:"/ws"},i={transportConnectionTimeout:15e3,transportReconnectionAttempts:999,transportReconnectionTimeout:3e3,registerExpires:3600,registerExtraHeaders:"",registerExtraContactParams:"",registerContactParams:"",wssInTransport:!0,ipInContact:!1,bundlePolicy:"balanced",iceStunServerJson:"",iceStunCheckTimeout:5e3,subscribeToYourself:!1,voiceMailSubscribe:!1,voicemailDid:"",subscribeVoicemailExpires:3600,inviteExtraHeaders:"",noAnswerTimeout:120},r={key:s.username,account:s,features:{enableVideo:!0,enableTransfer:!0,enableConference:!0},media:{audioInputDeviceId:"default",audioOutputDeviceId:"default",videoInputDeviceId:"default",ringerOutputDeviceId:"default",maxFrameRate:30,videoHeight:720,videoAspectRatio:1.777,autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,mirrorVideo:"auto",maxVideoBandwidth:2048,startVideoFullScreen:!1},policy:{autoAnswerPolicy:"manual",doNotDisturbPolicy:"off",callWaitingPolicy:"on",callRecordingPolicy:"manual",intercomPolicy:"off"},registration:i,storage:{streamBuffer:50,maxDataStoreDays:0,posterJpegQuality:80},recording:{videoResampleSize:"HD",recordingVideoSize:"HD",recordingVideoFps:12,recordingLayout:"grid"},advanced:{didLength:4,maxDidLength:8,singleInstance:!0,chatEngine:"default"}};var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var a,c={exports:{}};var d,h=(a||(a=1,c.exports=function(){var e=1e3,t=6e4,s=36e5,i="millisecond",r="second",n="minute",o="hour",a="day",c="week",d="month",h="quarter",l="year",u="date",g="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,f=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,m={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(e){var t=["th","st","nd","rd"],s=e%100;return"["+e+(t[(s-20)%10]||t[s]||t[0])+"]"}},v=function(e,t,s){var i=String(e);return!i||i.length>=t?e:""+Array(t+1-i.length).join(s)+e},y={s:v,z:function(e){var t=-e.utcOffset(),s=Math.abs(t),i=Math.floor(s/60),r=s%60;return(t<=0?"+":"-")+v(i,2,"0")+":"+v(r,2,"0")},m:function e(t,s){if(t.date()<s.date())return-e(s,t);var i=12*(s.year()-t.year())+(s.month()-t.month()),r=t.clone().add(i,d),n=s-r<0,o=t.clone().add(i+(n?-1:1),d);return+(-(i+(s-r)/(n?r-o:o-r))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:d,y:l,w:c,d:a,D:u,h:o,m:n,s:r,ms:i,Q:h}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},w="en",b={};b[w]=m;var S="$isDayjsObject",T=function(e){return e instanceof C||!(!e||!e[S])},$=function e(t,s,i){var r;if(!t)return w;if("string"==typeof t){var n=t.toLowerCase();b[n]&&(r=n),s&&(b[n]=s,r=n);var o=t.split("-");if(!r&&o.length>1)return e(o[0])}else{var a=t.name;b[a]=t,r=a}return!i&&r&&(w=r),r||!i&&w},E=function(e,t){if(T(e))return e.clone();var s="object"==typeof t?t:{};return s.date=e,s.args=arguments,new C(s)},R=y;R.l=$,R.i=T,R.w=function(e,t){return E(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var C=function(){function m(e){this.$L=$(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[S]=!0}var v=m.prototype;return v.parse=function(e){this.$d=function(e){var t=e.date,s=e.utc;if(null===t)return new Date(NaN);if(R.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var i=t.match(p);if(i){var r=i[2]-1||0,n=(i[7]||"0").substring(0,3);return s?new Date(Date.UTC(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,n)):new Date(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,n)}}return new Date(t)}(e),this.init()},v.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},v.$utils=function(){return R},v.isValid=function(){return!(this.$d.toString()===g)},v.isSame=function(e,t){var s=E(e);return this.startOf(t)<=s&&s<=this.endOf(t)},v.isAfter=function(e,t){return E(e)<this.startOf(t)},v.isBefore=function(e,t){return this.endOf(t)<E(e)},v.$g=function(e,t,s){return R.u(e)?this[t]:this.set(s,e)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(e,t){var s=this,i=!!R.u(t)||t,h=R.p(e),g=function(e,t){var r=R.w(s.$u?Date.UTC(s.$y,t,e):new Date(s.$y,t,e),s);return i?r:r.endOf(a)},p=function(e,t){return R.w(s.toDate()[e].apply(s.toDate("s"),(i?[0,0,0,0]:[23,59,59,999]).slice(t)),s)},f=this.$W,m=this.$M,v=this.$D,y="set"+(this.$u?"UTC":"");switch(h){case l:return i?g(1,0):g(31,11);case d:return i?g(1,m):g(0,m+1);case c:var w=this.$locale().weekStart||0,b=(f<w?f+7:f)-w;return g(i?v-b:v+(6-b),m);case a:case u:return p(y+"Hours",0);case o:return p(y+"Minutes",1);case n:return p(y+"Seconds",2);case r:return p(y+"Milliseconds",3);default:return this.clone()}},v.endOf=function(e){return this.startOf(e,!1)},v.$set=function(e,t){var s,c=R.p(e),h="set"+(this.$u?"UTC":""),g=(s={},s[a]=h+"Date",s[u]=h+"Date",s[d]=h+"Month",s[l]=h+"FullYear",s[o]=h+"Hours",s[n]=h+"Minutes",s[r]=h+"Seconds",s[i]=h+"Milliseconds",s)[c],p=c===a?this.$D+(t-this.$W):t;if(c===d||c===l){var f=this.clone().set(u,1);f.$d[g](p),f.init(),this.$d=f.set(u,Math.min(this.$D,f.daysInMonth())).$d}else g&&this.$d[g](p);return this.init(),this},v.set=function(e,t){return this.clone().$set(e,t)},v.get=function(e){return this[R.p(e)]()},v.add=function(i,h){var u,g=this;i=Number(i);var p=R.p(h),f=function(e){var t=E(g);return R.w(t.date(t.date()+Math.round(e*i)),g)};if(p===d)return this.set(d,this.$M+i);if(p===l)return this.set(l,this.$y+i);if(p===a)return f(1);if(p===c)return f(7);var m=(u={},u[n]=t,u[o]=s,u[r]=e,u)[p]||1,v=this.$d.getTime()+i*m;return R.w(v,this)},v.subtract=function(e,t){return this.add(-1*e,t)},v.format=function(e){var t=this,s=this.$locale();if(!this.isValid())return s.invalidDate||g;var i=e||"YYYY-MM-DDTHH:mm:ssZ",r=R.z(this),n=this.$H,o=this.$m,a=this.$M,c=s.weekdays,d=s.months,h=s.meridiem,l=function(e,s,r,n){return e&&(e[s]||e(t,i))||r[s].slice(0,n)},u=function(e){return R.s(n%12||12,e,"0")},p=h||function(e,t,s){var i=e<12?"AM":"PM";return s?i.toLowerCase():i};return i.replace(f,function(e,i){return i||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return R.s(t.$y,4,"0");case"M":return a+1;case"MM":return R.s(a+1,2,"0");case"MMM":return l(s.monthsShort,a,d,3);case"MMMM":return l(d,a);case"D":return t.$D;case"DD":return R.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return l(s.weekdaysMin,t.$W,c,2);case"ddd":return l(s.weekdaysShort,t.$W,c,3);case"dddd":return c[t.$W];case"H":return String(n);case"HH":return R.s(n,2,"0");case"h":return u(1);case"hh":return u(2);case"a":return p(n,o,!0);case"A":return p(n,o,!1);case"m":return String(o);case"mm":return R.s(o,2,"0");case"s":return String(t.$s);case"ss":return R.s(t.$s,2,"0");case"SSS":return R.s(t.$ms,3,"0");case"Z":return r}return null}(e)||r.replace(":","")})},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(i,u,g){var p,f=this,m=R.p(u),v=E(i),y=(v.utcOffset()-this.utcOffset())*t,w=this-v,b=function(){return R.m(f,v)};switch(m){case l:p=b()/12;break;case d:p=b();break;case h:p=b()/3;break;case c:p=(w-y)/6048e5;break;case a:p=(w-y)/864e5;break;case o:p=w/s;break;case n:p=w/t;break;case r:p=w/e;break;default:p=w}return g?p:R.a(p)},v.daysInMonth=function(){return this.endOf(d).$D},v.$locale=function(){return b[this.$L]},v.locale=function(e,t){if(!e)return this.$L;var s=this.clone(),i=$(e,t,!0);return i&&(s.$L=i),s},v.clone=function(){return R.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},m}(),I=C.prototype;return E.prototype=I,[["$ms",i],["$s",r],["$m",n],["$H",o],["$W",a],["$M",d],["$y",l],["$D",u]].forEach(function(e){I[e[1]]=function(t){return this.$g(t,e[0],e[1])}}),E.extend=function(e,t){return e.$i||(e(t,C,E),e.$i=!0),E},E.locale=$,E.isDayjs=T,E.unix=function(e){return E(1e3*e)},E.en=b[w],E.Ls=b,E.p={},E}()),c.exports),l=o(h),u={exports:{}};var g,p,f,m,v,y,w,b,S,T,$,E,R,C,I,D,_,A,k,H,x=(d||(d=1,u.exports=(w=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,T=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,$={years:b=31536e6,months:S=2628e6,days:y=864e5,hours:v=36e5,minutes:m=6e4,seconds:f=1e3,milliseconds:1,weeks:6048e5},E=function(e){return e instanceof k},R=function(e,t,s){return new k(e,s,t.$l)},C=function(e){return p.p(e)+"s"},I=function(e){return e<0},D=function(e){return I(e)?Math.ceil(e):Math.floor(e)},_=function(e){return Math.abs(e)},A=function(e,t){return e?I(e)?{negative:!0,format:""+_(e)+t}:{negative:!1,format:""+e+t}:{negative:!1,format:""}},k=function(){function e(e,t,s){var i=this;if(this.$d={},this.$l=s,void 0===e&&(this.$ms=0,this.parseFromMilliseconds()),t)return R(e*$[C(t)],this);if("number"==typeof e)return this.$ms=e,this.parseFromMilliseconds(),this;if("object"==typeof e)return Object.keys(e).forEach(function(t){i.$d[C(t)]=e[t]}),this.calMilliseconds(),this;if("string"==typeof e){var r=e.match(T);if(r){var n=r.slice(2).map(function(e){return null!=e?Number(e):0});return this.$d.years=n[0],this.$d.months=n[1],this.$d.weeks=n[2],this.$d.days=n[3],this.$d.hours=n[4],this.$d.minutes=n[5],this.$d.seconds=n[6],this.calMilliseconds(),this}}return this}var t=e.prototype;return t.calMilliseconds=function(){var e=this;this.$ms=Object.keys(this.$d).reduce(function(t,s){return t+(e.$d[s]||0)*$[s]},0)},t.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=D(e/b),e%=b,this.$d.months=D(e/S),e%=S,this.$d.days=D(e/y),e%=y,this.$d.hours=D(e/v),e%=v,this.$d.minutes=D(e/m),e%=m,this.$d.seconds=D(e/f),e%=f,this.$d.milliseconds=e},t.toISOString=function(){var e=A(this.$d.years,"Y"),t=A(this.$d.months,"M"),s=+this.$d.days||0;this.$d.weeks&&(s+=7*this.$d.weeks);var i=A(s,"D"),r=A(this.$d.hours,"H"),n=A(this.$d.minutes,"M"),o=this.$d.seconds||0;this.$d.milliseconds&&(o+=this.$d.milliseconds/1e3,o=Math.round(1e3*o)/1e3);var a=A(o,"S"),c=e.negative||t.negative||i.negative||r.negative||n.negative||a.negative,d=r.format||n.format||a.format?"T":"",h=(c?"-":"")+"P"+e.format+t.format+i.format+d+r.format+n.format+a.format;return"P"===h||"-P"===h?"P0D":h},t.toJSON=function(){return this.toISOString()},t.format=function(e){var t=e||"YYYY-MM-DDTHH:mm:ss",s={Y:this.$d.years,YY:p.s(this.$d.years,2,"0"),YYYY:p.s(this.$d.years,4,"0"),M:this.$d.months,MM:p.s(this.$d.months,2,"0"),D:this.$d.days,DD:p.s(this.$d.days,2,"0"),H:this.$d.hours,HH:p.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:p.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:p.s(this.$d.seconds,2,"0"),SSS:p.s(this.$d.milliseconds,3,"0")};return t.replace(w,function(e,t){return t||String(s[e])})},t.as=function(e){return this.$ms/$[C(e)]},t.get=function(e){var t=this.$ms,s=C(e);return"milliseconds"===s?t%=1e3:t="weeks"===s?D(t/$[s]):this.$d[s],t||0},t.add=function(e,t,s){var i;return i=t?e*$[C(t)]:E(e)?e.$ms:R(e,this).$ms,R(this.$ms+i*(s?-1:1),this)},t.subtract=function(e,t){return this.add(e,t,!0)},t.locale=function(e){var t=this.clone();return t.$l=e,t},t.clone=function(){return R(this.$ms,this)},t.humanize=function(e){return g().add(this.$ms,"ms").locale(this.$l).fromNow(!e)},t.valueOf=function(){return this.asMilliseconds()},t.milliseconds=function(){return this.get("milliseconds")},t.asMilliseconds=function(){return this.as("milliseconds")},t.seconds=function(){return this.get("seconds")},t.asSeconds=function(){return this.as("seconds")},t.minutes=function(){return this.get("minutes")},t.asMinutes=function(){return this.as("minutes")},t.hours=function(){return this.get("hours")},t.asHours=function(){return this.as("hours")},t.days=function(){return this.get("days")},t.asDays=function(){return this.as("days")},t.weeks=function(){return this.get("weeks")},t.asWeeks=function(){return this.as("weeks")},t.months=function(){return this.get("months")},t.asMonths=function(){return this.as("months")},t.years=function(){return this.get("years")},t.asYears=function(){return this.as("years")},e}(),H=function(e,t,s){return e.add(t.years()*s,"y").add(t.months()*s,"M").add(t.days()*s,"d").add(t.hours()*s,"h").add(t.minutes()*s,"m").add(t.seconds()*s,"s").add(t.milliseconds()*s,"ms")},function(e,t,s){g=s,p=s().$utils(),s.duration=function(e,t){var i=s.locale();return R(e,{$l:i},t)},s.isDuration=E;var i=t.prototype.add,r=t.prototype.subtract;t.prototype.add=function(e,t){return E(e)?H(this,e,1):i.bind(this)(e,t)},t.prototype.subtract=function(e,t){return E(e)?H(this,e,-1):r.bind(this)(e,t)}})),u.exports),P=o(x);l.extend(P);var O,q={exports:{}};var M=(O||(O=1,q.exports=function(){var e="minute",t=/[+-]\d\d(?::?\d\d)?/g,s=/([+-]|\d\d)/g;return function(i,r,n){var o=r.prototype;n.utc=function(e){return new r({date:e,utc:!0,args:arguments})},o.utc=function(t){var s=n(this.toDate(),{locale:this.$L,utc:!0});return t?s.add(this.utcOffset(),e):s},o.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var a=o.parse;o.parse=function(e){e.utc&&(this.$u=!0),this.$utils().u(e.$offset)||(this.$offset=e.$offset),a.call(this,e)};var c=o.init;o.init=function(){if(this.$u){var e=this.$d;this.$y=e.getUTCFullYear(),this.$M=e.getUTCMonth(),this.$D=e.getUTCDate(),this.$W=e.getUTCDay(),this.$H=e.getUTCHours(),this.$m=e.getUTCMinutes(),this.$s=e.getUTCSeconds(),this.$ms=e.getUTCMilliseconds()}else c.call(this)};var d=o.utcOffset;o.utcOffset=function(i,r){var n=this.$utils().u;if(n(i))return this.$u?0:n(this.$offset)?d.call(this):this.$offset;if("string"==typeof i&&(i=function(e){void 0===e&&(e="");var i=e.match(t);if(!i)return null;var r=(""+i[0]).match(s)||["-",0,0],n=r[0],o=60*+r[1]+ +r[2];return 0===o?0:"+"===n?o:-o}(i),null===i))return this;var o=Math.abs(i)<=16?60*i:i,a=this;if(r)return a.$offset=o,a.$u=0===i,a;if(0!==i){var c=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(a=this.local().add(o+c,e)).$offset=o,a.$x.$localOffset=c}else a=this.utc();return a};var h=o.format;o.format=function(e){var t=e||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return h.call(this,t)},o.valueOf=function(){var e=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*e},o.isUTC=function(){return!!this.$u},o.toISOString=function(){return this.toDate().toISOString()},o.toString=function(){return this.toDate().toUTCString()};var l=o.toDate;o.toDate=function(e){return"s"===e&&this.$offset?n(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():l.call(this)};var u=o.diff;o.diff=function(e,t,s){if(e&&this.$u===e.$u)return u.call(this,e,t,s);var i=this.local(),r=n(e).local();return u.call(i,r,t,s)}}}()),q.exports),N=o(M);l.extend(P),l.extend(N);const j=l;function L(e,t){const s={...e};if(e&&"object"==typeof e&&t&&"object"==typeof t)for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=t[e],r=s[e];i&&"object"==typeof i&&!Array.isArray(i)&&r&&"object"==typeof r&&!Array.isArray(r)?s[e]=L(r,i):void 0!==i&&(s[e]=i)}return s}function F(){return j().utc().toISOString()}var U,B={exports:{}};var K=(U||(U=1,function(e,t){var s="__lodash_hash_undefined__",i=9007199254740991,r="[object Arguments]",o="[object Array]",a="[object Boolean]",c="[object Date]",d="[object Error]",h="[object Function]",l="[object Map]",u="[object Number]",g="[object Object]",p="[object Promise]",f="[object RegExp]",m="[object Set]",v="[object String]",y="[object Symbol]",w="[object WeakMap]",b="[object ArrayBuffer]",S="[object DataView]",T=/^\[object .+?Constructor\]$/,$=/^(?:0|[1-9]\d*)$/,E={};E["[object Float32Array]"]=E["[object Float64Array]"]=E["[object Int8Array]"]=E["[object Int16Array]"]=E["[object Int32Array]"]=E["[object Uint8Array]"]=E["[object Uint8ClampedArray]"]=E["[object Uint16Array]"]=E["[object Uint32Array]"]=!0,E[r]=E[o]=E[b]=E[a]=E[S]=E[c]=E[d]=E[h]=E[l]=E[u]=E[g]=E[f]=E[m]=E[v]=E[w]=!1;var R="object"==typeof n&&n&&n.Object===Object&&n,C="object"==typeof self&&self&&self.Object===Object&&self,I=R||C||Function("return this")(),D=t&&!t.nodeType&&t,_=D&&e&&!e.nodeType&&e,A=_&&_.exports===D,k=A&&R.process,H=function(){try{return k&&k.binding&&k.binding("util")}catch(e){}}(),x=H&&H.isTypedArray;function P(e,t){for(var s=-1,i=null==e?0:e.length;++s<i;)if(t(e[s],s,e))return!0;return!1}function O(e){var t=-1,s=Array(e.size);return e.forEach(function(e,i){s[++t]=[i,e]}),s}function q(e){var t=-1,s=Array(e.size);return e.forEach(function(e){s[++t]=e}),s}var M,N,j,L=Array.prototype,F=Function.prototype,U=Object.prototype,B=I["__core-js_shared__"],K=F.toString,G=U.hasOwnProperty,V=(M=/[^.]+$/.exec(B&&B.keys&&B.keys.IE_PROTO||""))?"Symbol(src)_1."+M:"",Y=U.toString,W=RegExp("^"+K.call(G).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),J=A?I.Buffer:void 0,Z=I.Symbol,z=I.Uint8Array,X=U.propertyIsEnumerable,Q=L.splice,ee=Z?Z.toStringTag:void 0,te=Object.getOwnPropertySymbols,se=J?J.isBuffer:void 0,ie=(N=Object.keys,j=Object,function(e){return N(j(e))}),re=He(I,"DataView"),ne=He(I,"Map"),oe=He(I,"Promise"),ae=He(I,"Set"),ce=He(I,"WeakMap"),de=He(Object,"create"),he=qe(re),le=qe(ne),ue=qe(oe),ge=qe(ae),pe=qe(ce),fe=Z?Z.prototype:void 0,me=fe?fe.valueOf:void 0;function ve(e){var t=-1,s=null==e?0:e.length;for(this.clear();++t<s;){var i=e[t];this.set(i[0],i[1])}}function ye(e){var t=-1,s=null==e?0:e.length;for(this.clear();++t<s;){var i=e[t];this.set(i[0],i[1])}}function we(e){var t=-1,s=null==e?0:e.length;for(this.clear();++t<s;){var i=e[t];this.set(i[0],i[1])}}function be(e){var t=-1,s=null==e?0:e.length;for(this.__data__=new we;++t<s;)this.add(e[t])}function Se(e){var t=this.__data__=new ye(e);this.size=t.size}function Te(e,t){var s=je(e),i=!s&&Ne(e),r=!s&&!i&&Le(e),n=!s&&!i&&!r&&Ge(e),o=s||i||r||n,a=o?function(e,t){for(var s=-1,i=Array(e);++s<e;)i[s]=t(s);return i}(e.length,String):[],c=a.length;for(var d in e)!G.call(e,d)||o&&("length"==d||r&&("offset"==d||"parent"==d)||n&&("buffer"==d||"byteLength"==d||"byteOffset"==d)||Oe(d,c))||a.push(d);return a}function $e(e,t){for(var s=e.length;s--;)if(Me(e[s][0],t))return s;return-1}function Ee(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ee&&ee in Object(e)?function(e){var t=G.call(e,ee),s=e[ee];try{e[ee]=void 0;var i=!0}catch(e){}var r=Y.call(e);return i&&(t?e[ee]=s:delete e[ee]),r}(e):function(e){return Y.call(e)}(e)}function Re(e){return Ke(e)&&Ee(e)==r}function Ce(e,t,s,i,n){return e===t||(null==e||null==t||!Ke(e)&&!Ke(t)?e!=e&&t!=t:function(e,t,s,i,n,h){var p=je(e),w=je(t),T=p?o:Pe(e),$=w?o:Pe(t),E=(T=T==r?g:T)==g,R=($=$==r?g:$)==g,C=T==$;if(C&&Le(e)){if(!Le(t))return!1;p=!0,E=!1}if(C&&!E)return h||(h=new Se),p||Ge(e)?_e(e,t,s,i,n,h):function(e,t,s,i,r,n,o){switch(s){case S:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case b:return!(e.byteLength!=t.byteLength||!n(new z(e),new z(t)));case a:case c:case u:return Me(+e,+t);case d:return e.name==t.name&&e.message==t.message;case f:case v:return e==t+"";case l:var h=O;case m:var g=1&i;if(h||(h=q),e.size!=t.size&&!g)return!1;var p=o.get(e);if(p)return p==t;i|=2,o.set(e,t);var w=_e(h(e),h(t),i,r,n,o);return o.delete(e),w;case y:if(me)return me.call(e)==me.call(t)}return!1}(e,t,T,s,i,n,h);if(!(1&s)){var I=E&&G.call(e,"__wrapped__"),D=R&&G.call(t,"__wrapped__");if(I||D){var _=I?e.value():e,A=D?t.value():t;return h||(h=new Se),n(_,A,s,i,h)}}return!!C&&(h||(h=new Se),function(e,t,s,i,r,n){var o=1&s,a=Ae(e),c=a.length,d=Ae(t),h=d.length;if(c!=h&&!o)return!1;for(var l=c;l--;){var u=a[l];if(!(o?u in t:G.call(t,u)))return!1}var g=n.get(e);if(g&&n.get(t))return g==t;var p=!0;n.set(e,t),n.set(t,e);for(var f=o;++l<c;){var m=e[u=a[l]],v=t[u];if(i)var y=o?i(v,m,u,t,e,n):i(m,v,u,e,t,n);if(!(void 0===y?m===v||r(m,v,s,i,n):y)){p=!1;break}f||(f="constructor"==u)}if(p&&!f){var w=e.constructor,b=t.constructor;w==b||!("constructor"in e)||!("constructor"in t)||"function"==typeof w&&w instanceof w&&"function"==typeof b&&b instanceof b||(p=!1)}return n.delete(e),n.delete(t),p}(e,t,s,i,n,h))}(e,t,s,i,Ce,n))}function Ie(e){return!(!Be(e)||function(e){return!!V&&V in e}(e))&&(Fe(e)?W:T).test(qe(e))}function De(e){if(s=(t=e)&&t.constructor,i="function"==typeof s&&s.prototype||U,t!==i)return ie(e);var t,s,i,r=[];for(var n in Object(e))G.call(e,n)&&"constructor"!=n&&r.push(n);return r}function _e(e,t,s,i,r,n){var o=1&s,a=e.length,c=t.length;if(a!=c&&!(o&&c>a))return!1;var d=n.get(e);if(d&&n.get(t))return d==t;var h=-1,l=!0,u=2&s?new be:void 0;for(n.set(e,t),n.set(t,e);++h<a;){var g=e[h],p=t[h];if(i)var f=o?i(p,g,h,t,e,n):i(g,p,h,e,t,n);if(void 0!==f){if(f)continue;l=!1;break}if(u){if(!P(t,function(e,t){if(o=t,!u.has(o)&&(g===e||r(g,e,s,i,n)))return u.push(t);var o})){l=!1;break}}else if(g!==p&&!r(g,p,s,i,n)){l=!1;break}}return n.delete(e),n.delete(t),l}function Ae(e){return function(e,t,s){var i=t(e);return je(e)?i:function(e,t){for(var s=-1,i=t.length,r=e.length;++s<i;)e[r+s]=t[s];return e}(i,s(e))}(e,Ve,xe)}function ke(e,t){var s,i,r=e.__data__;return("string"==(i=typeof(s=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==s:null===s)?r["string"==typeof t?"string":"hash"]:r.map}function He(e,t){var s=function(e,t){return null==e?void 0:e[t]}(e,t);return Ie(s)?s:void 0}ve.prototype.clear=function(){this.__data__=de?de(null):{},this.size=0},ve.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},ve.prototype.get=function(e){var t=this.__data__;if(de){var i=t[e];return i===s?void 0:i}return G.call(t,e)?t[e]:void 0},ve.prototype.has=function(e){var t=this.__data__;return de?void 0!==t[e]:G.call(t,e)},ve.prototype.set=function(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=de&&void 0===t?s:t,this},ye.prototype.clear=function(){this.__data__=[],this.size=0},ye.prototype.delete=function(e){var t=this.__data__,s=$e(t,e);return!(s<0||(s==t.length-1?t.pop():Q.call(t,s,1),--this.size,0))},ye.prototype.get=function(e){var t=this.__data__,s=$e(t,e);return s<0?void 0:t[s][1]},ye.prototype.has=function(e){return $e(this.__data__,e)>-1},ye.prototype.set=function(e,t){var s=this.__data__,i=$e(s,e);return i<0?(++this.size,s.push([e,t])):s[i][1]=t,this},we.prototype.clear=function(){this.size=0,this.__data__={hash:new ve,map:new(ne||ye),string:new ve}},we.prototype.delete=function(e){var t=ke(this,e).delete(e);return this.size-=t?1:0,t},we.prototype.get=function(e){return ke(this,e).get(e)},we.prototype.has=function(e){return ke(this,e).has(e)},we.prototype.set=function(e,t){var s=ke(this,e),i=s.size;return s.set(e,t),this.size+=s.size==i?0:1,this},be.prototype.add=be.prototype.push=function(e){return this.__data__.set(e,s),this},be.prototype.has=function(e){return this.__data__.has(e)},Se.prototype.clear=function(){this.__data__=new ye,this.size=0},Se.prototype.delete=function(e){var t=this.__data__,s=t.delete(e);return this.size=t.size,s},Se.prototype.get=function(e){return this.__data__.get(e)},Se.prototype.has=function(e){return this.__data__.has(e)},Se.prototype.set=function(e,t){var s=this.__data__;if(s instanceof ye){var i=s.__data__;if(!ne||i.length<199)return i.push([e,t]),this.size=++s.size,this;s=this.__data__=new we(i)}return s.set(e,t),this.size=s.size,this};var xe=te?function(e){return null==e?[]:(e=Object(e),function(e,t){for(var s=-1,i=null==e?0:e.length,r=0,n=[];++s<i;){var o=e[s];t(o,s,e)&&(n[r++]=o)}return n}(te(e),function(t){return X.call(e,t)}))}:function(){return[]},Pe=Ee;function Oe(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||$.test(e))&&e>-1&&e%1==0&&e<t}function qe(e){if(null!=e){try{return K.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Me(e,t){return e===t||e!=e&&t!=t}(re&&Pe(new re(new ArrayBuffer(1)))!=S||ne&&Pe(new ne)!=l||oe&&Pe(oe.resolve())!=p||ae&&Pe(new ae)!=m||ce&&Pe(new ce)!=w)&&(Pe=function(e){var t=Ee(e),s=t==g?e.constructor:void 0,i=s?qe(s):"";if(i)switch(i){case he:return S;case le:return l;case ue:return p;case ge:return m;case pe:return w}return t});var Ne=Re(function(){return arguments}())?Re:function(e){return Ke(e)&&G.call(e,"callee")&&!X.call(e,"callee")},je=Array.isArray,Le=se||function(){return!1};function Fe(e){if(!Be(e))return!1;var t=Ee(e);return t==h||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Ue(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}function Be(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Ke(e){return null!=e&&"object"==typeof e}var Ge=x?function(e){return function(t){return e(t)}}(x):function(e){return Ke(e)&&Ue(e.length)&&!!E[Ee(e)]};function Ve(e){return null!=(t=e)&&Ue(t.length)&&!Fe(t)?Te(e):De(e);var t}e.exports=function(e,t){return Ce(e,t)}}(B,B.exports)),B.exports),G=o(K);const V=async e=>async function(){return await navigator.mediaDevices.enumerateDevices()}().then(t=>{let s=!1,i=[],r=!1,n=[],o=!1,a=[];if(t)for(let c=0;c<t.length;++c)if("audioinput"===t[c].kind)s=!0,i.push(t[c]);else if("audiooutput"===t[c].kind)r=!0,n.push(t[c]);else if("videoinput"===t[c].kind){const s=te(e)?.features?.enableVideo;s&&(o=!0,a.push(t[c]))}return{hasAudioDevice:s,audioInputDevices:i,hasSpeakerDevice:r,speakerDevices:n,hasVideoDevice:o,videoInputDevices:a}}),Y=e=>{let t;const s=new Set,i=(e,i)=>{const r="function"==typeof e?e(t):e;if(!Object.is(r,t)){const e=t;t=(null!=i?i:"object"!=typeof r||null===r)?r:Object.assign({},t,r),s.forEach(s=>s(t,e))}},r=()=>t,n={setState:i,getState:r,getInitialState:()=>o,subscribe:e=>(s.add(e),()=>s.delete(e))},o=t=e(i,r,n);return n},W=e=>e;const J=t=>{const s=(e=>e?Y(e):Y)(t),i=t=>function(t,s=W){const i=e.useSyncExternalStore(t.subscribe,()=>s(t.getState()),()=>s(t.getInitialState()));return e.useDebugValue(i),i}(s,t);return Object.assign(i,s),i},Z=(z=(e,t)=>({configs:null,statuses:null,userAgents:void 0,devicesInfo:{hasVideoDevice:!1,hasAudioDevice:!1,hasSpeakerDevice:!1,audioInputDevices:[],videoInputDevices:[],speakerDevices:[]},lines:{},configKeysByLineKey:{},lineKeyByRemoteNumber_ConfigKey:{},setSipStore:t=>e(e=>({...e,...t})),setConfig:(t,s)=>{e(e=>({...e,configs:{...e.configs,[t]:s}}))},setUserAgent:(t,s)=>{e(e=>({...e,userAgents:{...e.userAgents,[t]:s}}))},addLine:s=>{const i=s.configKey;e(e=>({...e,lines:{...e.lines,[i]:{...e.lines?.[i],[s.lineKey]:s}},configKeysByLineKey:{...e.configKeysByLineKey,[s.lineKey]:i},lineKeyByRemoteNumber_ConfigKey:{...e.configKeysByLineKey,[t().remoteNumberConfigKeyResolver({remoteNumber:s.remoteNumber,configKey:s.configKey})]:s.lineKey}}))},updateLine:t=>{const s=t.configKey;if(!s)return null;e(e=>e.lines?.[s]?.[t.lineKey]?{...e,lines:{...e.lines,[s]:{...e.lines?.[s],[t.lineKey]:t}}}:e)},removeLine:s=>{const i=t().getConfigKeyByLineKey(s),r=t().findLineByLineKey(s);if(!i)return null;const n=r?.sipSession?.data.remoteNumber??"";e(e=>{if(!e.lines?.[i]?.[s])return e;const{[s]:r,...o}=e.lines[i],{[s]:a,...c}=e.configKeysByLineKey,{[t().remoteNumberConfigKeyResolver({remoteNumber:n,configKey:i})]:d,...h}=e.lineKeyByRemoteNumber_ConfigKey;return{...e,lines:{...e.lines,[i]:{...o}},configKeysByLineKey:{...c},lineKeyByRemoteNumber_ConfigKey:{...h}}})},remove:t=>{if(!t)return null;e(e=>{if(!e.lines?.[t])return e;const{[t]:s,...i}=e.lines,{[t]:r,...n}=e.configs,{[t]:o,...a}=e.userAgents,{[t]:c,...d}=e.statuses;return{...e,lines:{...i},configs:{...n},userAgents:{...a},statuses:{...d}}})},removeAll:()=>{e(e=>({...e,lines:{},configs:{},userAgents:{},statuses:{}}))},findLineByLineKey:e=>{const s=t().getConfigKeyByLineKey(e);return s?t().lines?.[s]?.[e]??null:null},getSessionByLineKey:e=>{const s=t().getConfigKeyByLineKey(e);return s?t().lines?.[s]?.[e]?.sipSession??null:null},getConfigKeyByLineKey:e=>t().configKeysByLineKey[e]??null,getConfigKeyByRemoteNumber_ConfigKey:({configKey:e,remoteNumber:s})=>{const i=t().lineKeyByRemoteNumber_ConfigKey[t().remoteNumberConfigKeyResolver({configKey:e,remoteNumber:s})]??null;return i?t().getConfigKeyByLineKey(i):null},getLineKeyByRemoteNumber_ConfigKey:({configKey:e,remoteNumber:s})=>t().lineKeyByRemoteNumber_ConfigKey[t().remoteNumberConfigKeyResolver({configKey:e,remoteNumber:s})]??null,getLineBy:({configKey:e,remoteNumber:s})=>{const i=t().lineKeyByRemoteNumber_ConfigKey[t().remoteNumberConfigKeyResolver({configKey:e,remoteNumber:s})]??null;return t().findLineByLineKey(i)},remoteNumberConfigKeyResolver:({configKey:e,remoteNumber:t})=>`${t}:${e}`,getNewLineKey:()=>"undefined"!=typeof crypto&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}),z?J(z):J);var z;const X=e=>{Z.setState(t=>({...t,...e}))},Q=()=>Z.getState(),ee=e=>Z.getState()?.userAgents?.[e]??null,te=e=>Z?.getState()?.configs?.[e]??null;function se(e,t=ee(e)){if(!t)return;if(t?.registering)return;if(t.isRegistered())return;t.registering=!0,t.registerer.register({requestDelegate:{onReject(t){!function(e){const t=ee(e);if(!t)return;t.registering=!1;const{userAgents:s,statuses:i}=Q();X({userAgents:{...s,[e]:t},statuses:{...i,[e]:"disconnected"}})}(e,t.message.reasonPhrase,t.message.statusCode)}}});const{userAgents:s}=Q();X({userAgents:{...s,[e]:t}})}function ie(e,t=ee(e)){if(!t)return;t.isReRegister=!1,t.transport.attemptingReconnection=!1,t.transport.attemptingReconnection||t.registering||window.setTimeout(function(){se(e,t)},500);const{userAgents:s,statuses:r}=Q();t.transport.reconnectionAttempts=te(e)?.registration?.transportReconnectionAttempts||i.transportReconnectionAttempts,X({userAgents:{...s,[e]:t},statuses:{...r,[e]:t.transport.isConnected()?"connected":"connecting"}})}function re(e,t,s=ee(t)){if(!s)return;s.isReRegister=!1;try{s.registerer.unregister()}catch(e){}ne(t,s);const{userAgents:i,statuses:r}=Q();X({userAgents:{...i,[t]:s},statuses:{...r,[t]:"disconnected"}})}function ne(e,t=ee(e),s=!1){if(!t)return;if(t.registering=!1,t.transport&&t.transport.isConnected())return void ie(e,t);setTimeout(function(){t.transport&&t.transport.isConnected()?ie(e,t):(t.transport.reconnectionAttempts>0||s)&&(t.transport.attemptingReconnection=!0,t.reconnect().catch(function(s){t.transport.attemptingReconnection=!1,ne(e,t)}))},te(e)?.registration.transportReconnectionTimeout),t.transport.reconnectionAttempts>0&&--t.transport.reconnectionAttempts;const{userAgents:i,statuses:r}=Q();X({userAgents:{...i,[e]:t},statuses:{...r,[e]:"connecting"}})}function oe({configKey:t}){return()=>{const s=Z(e=>t&&e.lines?.[t]?Object.keys(e.lines?.[t]).length:0),i=Z.getState().lines?.[t]??{},r=e.useMemo(()=>Object.values(i),[s]),n=Z(e=>e?.statuses?.[t])??"connecting";return{status:n,lines:r}}}function ae(t){const s=e.useRef(),i=e.useRef();return e=>{const r=t(e),n=ce(r);return void 0!==i.current&&G(i.current,n)||(i.current=n,s.current=de(r)),s.current}}function ce(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if("function"==typeof e)return"__fn__";if(t.has(e))return"__circular__";if(t.set(e,!0),Array.isArray(e))return e.map(e=>ce(e,t));if(Object.getPrototypeOf(e)!==Object.prototype)return`__${Object.prototype.toString.call(e)}__`;const s={};for(const i in e)try{s[i]=ce(e[i],t)}catch{s[i]="__unclonable__"}return s}function de(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);if("function"==typeof e)return e;if(Array.isArray(e)){const s=[];t.set(e,s);for(const i of e)s.push(de(i,t));return s}if(Object.getPrototypeOf(e)!==Object.prototype)return e;const s={};t.set(e,s);for(const i in e)s[i]=de(e[i],t);return s}function he(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}function le({key:e,name:t}){const s=Q(),i="lineKey"in e?e.lineKey:s.getLineKeyByRemoteNumber_ConfigKey(e);if(!i)return;const r=s.getConfigKeyByLineKey(i);return Z(ae(e=>{try{const s=r?e.lines?.[r]?.[i]:null,n=s?.sipSession?.data;if(!n)return;return Array.isArray(t)?t.map(e=>he(n,e)):"string"==typeof t?he(n,t):n}catch(e){}}))}const ue=()=>Z(ae(e=>Object.values(e.configs??{})));class ge{configKey;lineKey;remoteNumber;username;sipSession;localSoundMeter;remoteSoundMeter;constructor(e,t,s,i){this.configKey=e,this.lineKey=s,this.remoteNumber=i,this.username=t,this.sipSession=null,this.localSoundMeter=null,this.remoteSoundMeter=null}}var pe;!function(e){e.SOUND_TOGGLE="SOUND_TOGGLE",e.VIDEO_TOGGLE="VIDEO_TOGGLE",e.SCREEN_SHARE_TOGGLE="SCREEN_SHARE_TOGGLE",e.VIDEO_TOGGLE_ACK="VIDEO_TOGGLE_ACK"}(pe||(pe={}));const fe=({configKey:e})=>{const{audioInputDevices:t,videoInputDevices:s}=Q().devicesInfo,{media:{audioInputDeviceId:i,videoInputDeviceId:n,autoGainControl:o,maxFrameRate:a,noiseSuppression:c,videoAspectRatio:d,videoHeight:h,echoCancellation:l},registration:{inviteExtraHeaders:u}}=Q().configs?.[e]??r,g=()=>navigator.mediaDevices.getSupportedConstraints(),p={answerAudioSpdOptions:function({option:e}={}){const s=e??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:{exact:"default"}},video:!1}}},r=g(),n=i;if("object"==typeof s.sessionDescriptionHandlerOptions.constraints.audio){if("default"!=n){let e=(e=>{let s=!1;for(let i=0;i<t.length;++i)if(e==t[i].deviceId){s=!0;break}return s})(n);e&&(s.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:n})}return r.autoGainControl&&(s.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=o),r.echoCancellation&&(s.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=l),r.noiseSuppression&&(s.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=c),s}},makeAudioSpdOptions:function({extraHeaders:e}){let t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if(t.extraHeaders=e||[],p.answerAudioSpdOptions({option:t}),u&&""!==u&&"{}"!==u)try{for(const[e,s]of Object.entries(JSON.parse(u)))""==s||t?.extraHeaders?.push(e+": "+s)}catch(e){}return t},answerVideoSpdOptions:function({option:e}={}){const t=e??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}},i=g();p.answerAudioSpdOptions({option:t});const r=n;if("object"==typeof t.sessionDescriptionHandlerOptions.constraints.video){if("default"!=r){let e=(e=>{let t=!1;for(let i=0;i<s.length;++i)if(e===s[i].deviceId){t=!0;break}return t})(r);e&&(t.sessionDescriptionHandlerOptions.constraints.video.deviceId={exact:r})}return i.frameRate&&a&&(t.sessionDescriptionHandlerOptions.constraints.video.frameRate=String(a)),i.height&&h&&(t.sessionDescriptionHandlerOptions.constraints.video.height=String(h)),i.aspectRatio&&d&&(t.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=String(d)),t}},makeVideoSpdOptions:function({extraHeaders:e}){const t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}};if(p.answerVideoSpdOptions({option:t}),t.extraHeaders=e||[],u&&""!==u&&"{}"!==u)try{for(const[e,s]of Object.entries(JSON.parse(u)))""==s||t.extraHeaders.push(e+": "+s)}catch(e){}return t}};return p};class me extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class ve extends me{constructor(e){super(e||"Unsupported content type.")}}class ye extends me{constructor(e){super(e||"Request pending.")}}class we extends me{constructor(e){super(e||"Unspecified session description handler error.")}}class be extends me{constructor(){super("The session has terminated.")}}class Se extends me{constructor(e){super(e||"An error occurred during state transition.")}}class Te{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class $e{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class Ee{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class Re{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class Ce{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class Ie{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class De extends Ie{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new De(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class _e extends Ie{constructor(e="sip",t,s,i,r,n){if(super(r||{}),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:i},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:i}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new _e(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}}function Ae(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){const s=Object.keys(e.parameters),i=Object.keys(t.parameters);return!!s.filter(e=>i.includes(e)).every(s=>e.parameters[s]===t.parameters[s])&&(!!["user","ttl","method","transport"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s))&&!!["maddr"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s)))}(e,t))return!1;const s=Object.keys(e.headers),i=Object.keys(t.headers);if(0!==s.length||0!==i.length){if(s.length!==i.length)return!1;const r=s.filter(e=>i.includes(e));if(r.length!==i.length)return!1;if(!r.every(s=>e.headers[s].length&&t.headers[s].length&&e.headers[s][0]===t.headers[s][0]))return!1}return!0}function ke(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class He extends Error{constructor(e,t,s,i){super(),this.message=e,this.expected=t,this.found=s,this.location=i,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,He.prototype):this.__proto__=He.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,He)}static buildMessage(e,t){function s(e){return e.charCodeAt(0).toString(16).toUpperCase()}function i(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function r(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(e));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(n);let s,i;if(t.sort(),t.length>0){for(s=1,i=1;s<t.length;s++)t[s-1]!==t[s]&&(t[i]=t[s],i++);t.length=i}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((o=t)?'"'+i(o)+'"':"end of input")+" found.");var o}format(e){let t="Error: "+this.message;if(this.location){let s,i=null;for(s=0;s<e.length;s++)if(e[s].source===this.location.source){i=e[s].text.split(/\r\n|\n|\r/g);break}let r=this.location.start,n=this.location.source+":"+r.line+":"+r.column;if(i){let e=this.location.end,s=ke("",r.line.toString().length," "),o=i[r.line-1],a=r.line===e.line?e.column:o.length+1;t+="\n --\x3e "+n+"\n"+s+" |\n"+r.line+" | "+o+"\n"+s+" | "+ke("",r.column-1," ")+ke("",a-r.column,"^")}else t+="\n at "+n}return t}}const xe=function(e,t){const s={},i=(t=void 0!==t?t:{}).grammarSource,r={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let n=119;const o=["\r\n",v("\r\n",!1),/^[0-9]/,y([["0","9"]],!1,!1),/^[a-zA-Z]/,y([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,y([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,y([["\0","ÿ"]],!1,!1),/^["]/,y(['"'],!1,!1)," ",v(" ",!1),"\t",v("\t",!1),/^[a-zA-Z0-9]/,y([["a","z"],["A","Z"],["0","9"]],!1,!1),";",v(";",!1),"/",v("/",!1),"?",v("?",!1),":",v(":",!1),"@",v("@",!1),"&",v("&",!1),"=",v("=",!1),"+",v("+",!1),"$",v("$",!1),",",v(",",!1),"-",v("-",!1),"_",v("_",!1),".",v(".",!1),"!",v("!",!1),"~",v("~",!1),"*",v("*",!1),"'",v("'",!1),"(",v("(",!1),")",v(")",!1),"%",v("%",!1),function(){return" "},function(){return":"},/^[!-~]/,y([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,y([["",""]],!1,!1),/^[\x80-\xBF]/,y([["","¿"]],!1,!1),/^[a-f]/,y([["a","f"]],!1,!1),"`",v("`",!1),"<",v("<",!1),">",v(">",!1),"\\",v("\\",!1),"[",v("[",!1),"]",v("]",!1),"{",v("{",!1),"}",v("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,y([["!","'"]],!1,!1),/^[*-[]/,y([["*","["]],!1,!1),/^[\]-~]/,y([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,y([["#","["]],!1,!1),/^[\0-\t]/,y([["\0","\t"]],!1,!1),/^[\v-\f]/,y([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,y([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new _e(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new _e(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",v("sips",!0),"sip",v("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(f().slice(0,-1))},function(){(t=t||{data:{}}).data.password=f()},function(){return(t=t||{data:{}}).data.host=f(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",f()},/^[a-zA-Z0-9_\-]/,y([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,y([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},"::",v("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},function(){return(t=t||{data:{}}).data.host_type="IPv4",f()},"25",v("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",v("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",v("1",!1),/^[1-9]/,y([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",v("transport=",!0),"udp",v("udp",!0),"tcp",v("tcp",!0),"sctp",v("sctp",!0),"tls",v("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",v("user=",!0),"phone",v("phone",!0),"ip",v("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",v("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",v("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",v("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",v("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new _e(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",v("//",!1),function(){(t=t||{data:{}}).data.scheme=f()},v("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=f()},"INVITE",v("INVITE",!1),"ACK",v("ACK",!1),"VXACH",v("VXACH",!1),"OPTIONS",v("OPTIONS",!1),"BYE",v("BYE",!1),"CANCEL",v("CANCEL",!1),"REGISTER",v("REGISTER",!1),"SUBSCRIBE",v("SUBSCRIBE",!1),"NOTIFY",v("NOTIFY",!1),"REFER",v("REFER",!1),"PUBLISH",v("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=f(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=f()},function(){(t=t||{data:{}}).data=f()},function(){var e,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new De(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(e){'"'===(e=f().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",v("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",v("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",v("0",!1),function(){return parseFloat(f())},function(e,s){(t=t||{data:{}}).data.params||(t.data.params={}),s=null===s?void 0:s[1],t.data.params[e.toLowerCase()]=s},"render",v("render",!0),"session",v("session",!0),"icon",v("icon",!0),"alert",v("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=f().toLowerCase())},"handling",v("handling",!0),"optional",v("optional",!0),"required",v("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=f()},"text",v("text",!0),"image",v("image",!0),"audio",v("audio",!0),"video",v("video",!0),"application",v("application",!0),"message",v("message",!0),"multipart",v("multipart",!0),"x-",v("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new De(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",v("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new De(t.data.uri,t.data.displayName,t.data.params)},"digest",v("Digest",!0),"realm",v("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",v("domain",!0),"nonce",v("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",v("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",v("stale",!0),"true",v("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",v("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",v("algorithm",!0),"md5",v("MD5",!0),"md5-sess",v("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",v("qop",!0),"auth-int",v("auth-int",!0),"auth",v("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new De(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new De(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",v("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",v("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",v("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",v("active",!0),"pending",v("pending",!0),"terminated",v("terminated",!0),function(){(t=t||{data:{}}).data.state=f()},"reason",v("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",v("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",v("deactivated",!0),"probation",v("probation",!0),"rejected",v("rejected",!0),"timeout",v("timeout",!0),"giveup",v("giveup",!0),"noresource",v("noresource",!0),"invariant",v("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new De(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",v("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",v("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",v("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",v("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",v("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},v("UDP",!0),v("TCP",!0),v("TLS",!0),v("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=f()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",v("refresher",!1),"uas",v("uas",!1),"uac",v("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",v("stuns",!0),"stun",v("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",v("?transport=",!1),"turns",v("turns",!0),"turn",v("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=f()},"Referred-By",v("Referred-By",!1),"b",v("b",!1),"cid",v("cid",!1)],a=[T('2 ""6 7!'),T('4"""5!7#'),T('4$""5!7%'),T('4&""5!7\''),T(";'.# &;("),T('4(""5!7)'),T('4*""5!7+'),T('2,""6,7-'),T('2.""6.7/'),T('40""5!71'),T('22""6273. &24""6475.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T(";).# &;,"),T('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),T('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),T('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),T(';.." &"'),T("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),T('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),T('4\\""5!7].# &;3'),T('4^""5!7_'),T('4`""5!7a'),T(';!.) &4b""5!7c'),T('%$;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),T('%$;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),T('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273. &28""6879. &2j""6j7k. &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),T('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),T("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),T("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),T("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),T("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),T("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),T('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),T('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),T("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),T("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),T("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),T("%;//0#;&/'$8\":~\" )(\"'#&'#"),T("%;&/0#;//'$8\":~\" )(\"'#&'#"),T("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),T('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),T("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),T("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:
$!!)($'#(#'#(\"'#&'#"),T(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),T('%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("\'#&\'#'),T("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:$ )($'#(#'#(\"'#&'#"),T("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),T('%3""5$7.) &3""5#7/\' 8!:!! )'),T('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:# )(#\'#("\'#&\'#'),T("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),T('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),T('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:! )'),T('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;U.) &;\\.# &;X/& 8!:! )"),T('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:# )(#\'#("\'#&\'#'),T('$4""5!7/,#0)*4""5!7&&&#'),T('%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("\'#&\'#'),T('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),T('%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),T('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),T("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),T("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),T('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7/,#;!/#$+")("\'#&\'#.# &;!'),T('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),T('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),T(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),T('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),T('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),T('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),T('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),T('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),T('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),T('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),T('%$;j/�#*;j&&&#/"!&,)'),T('%$;j/�#*;j&&&#/"!&,)'),T(";k.) &;+.# &;-"),T('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),T('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),T('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),T("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),T("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),T('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),T(";.# &;r"),T("%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T(";M.# &;t"),T("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),T('%;v.# &;w/J#%26""6677/,#;/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T('%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#\'#("\'#&\'#'),T('%24""6475/,#;{/#$+")("\'#&\'#'),T("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),T(";*.) &;+.# &;-"),T(';+. &;-. &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),T('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),T("$;~0#*;~&"),T(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T('%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),T(";.# &;"),T('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),T('$;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/#0*;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),T("$;y0#*;y&"),T('%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),T('2Õ""6Õ7Ö'),T('2×""6×7Ø'),T('2Ù""6Ù7Ú'),T('2Û""6Û7Ü'),T('2Ý""6Ý7Þ'),T('2ß""6ß7à'),T('2á""6á7â'),T('2ã""6ã7ä'),T('2å""6å7æ'),T('2ç""6ç7è'),T('2é""6é7ê'),T("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),T("%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T("%;/' 8!:ì!! )"),T("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),T("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),T("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),T("%;:.c &%;/Y#$%;A/,#;/#$+\")(\"'#&'#06*%;A/,#;/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),T("%;L.# &;/]#$%;B/,#;/#$+\")(\"'#&'#06*%;B/,#;/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),T("%;.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),T("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),T(";.) &;.# &; "),T("%3ò\"\"5!7ó/:#;</1$;/($8#:ô#! )(#'#(\"'#&'#"),T("%3õ\"\"5'7ö/:#;</1$;/($8#:÷#! )(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ø!! )"),T('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),T('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),T(";6.) &;T.# &;H"),T("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),T(";¥.# &; "),T('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),T("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:Č!! )"),T("%;©/& 8!:č! )"),T("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T(";«.# &;¬"),T('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),T('3Ę""5\'7ę./ &3Ě""5)7ě.# &;'),T(";6.# &;®"),T('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),T(";.# &;6"),T("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),T(";6.# &;H"),T("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),T("%;/' 8!:ğ!! )"),T('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),T('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),T("%;L.# &;/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),T(";¹.# &; "),T("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),T("%;/' 8!:Ħ!! )"),T("%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),T(";¾"),T("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),T("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),T(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),T("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),T("%;I/' 8!:Ĭ!! )"),T("%3ĭ\"\"5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),T(";t.# &;w"),T("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),T("%;I/' 8!:ı!! )"),T("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),T('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),T('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),T('%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),T('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),T("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),T("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),T("%;/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),T('%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),T("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),T("%;/& 8!:Ő! )"),T('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),T('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),T("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),T("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),T("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;/($8#:ū#! )(#'#(\"'#&'#.# &; "),T('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),T(';1." &"'),T('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),T("%;L.# &;/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),T(";¹.# &; "),T("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),T("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),T("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),T("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),T("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),T("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),T("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),T('%3""5#7Ó.# &;6/\' 8!:Ƌ!! )'),T('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),T('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),T('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),T('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),T(";¾"),T('%;/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),T(";ô.# &; "),T('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),T('%;/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),T("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),T("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),T("$;%0#*;%&"),T("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),T('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),T('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),T(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),T('2L""6L7M. &2B""6B7C. &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),T('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),T('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),T('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),T("%;Ą/#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),T("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),T("%;ă/,#;ă/#$+\")(\"'#&'#"),T("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),T("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),T('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),T(";.# &;L"),T("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),T("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,d=0;const h=[{line:1,column:1}];let l,u=0,g=[],p=0;if(void 0!==t.startRule){if(!(t.startRule in r))throw new Error("Can't start parsing from rule \""+t.startRule+'".');n=r[t.startRule]}function f(){return e.substring(d,c)}function m(){return b(d,c)}function v(e,t){return{type:"literal",text:e,ignoreCase:t}}function y(e,t,s){return{type:"class",parts:e,inverted:t,ignoreCase:s}}function w(t){let s,i=h[t];if(i)return i;for(s=t-1;!h[s];)s--;for(i=h[s],i={line:i.line,column:i.column};s<t;)10===e.charCodeAt(s)?(i.line++,i.column=1):i.column++,s++;return h[t]=i,i}function b(e,t){const s=w(e),r=w(t);return{source:i,start:{offset:e,line:s.line,column:s.column},end:{offset:t,line:r.line,column:r.column}}}function S(e){c<u||(c>u&&(u=c,g=[]),g.push(e))}function T(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},l=function t(i){const r=a[i];let n=0;const h=[];let l=r.length;const u=[],g=[];let f;for(;;){for(;n<l;)switch(r[n]){case 0:g.push(o[r[n+1]]),n+=2;break;case 1:g.push(void 0),n++;break;case 2:g.push(null),n++;break;case 3:g.push(s),n++;break;case 4:g.push([]),n++;break;case 5:g.push(c),n++;break;case 6:g.pop(),n++;break;case 7:c=g.pop(),n++;break;case 8:g.length-=r[n+1],n+=2;break;case 9:g.splice(-2,1),n++;break;case 10:g[g.length-2].push(g.pop()),n++;break;case 11:g.push(g.splice(g.length-r[n+1],r[n+1])),n+=2;break;case 12:g.push(e.substring(g.pop(),c)),n++;break;case 13:u.push(l),h.push(n+3+r[n+1]+r[n+2]),g[g.length-1]?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 14:u.push(l),h.push(n+3+r[n+1]+r[n+2]),g[g.length-1]===s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 15:u.push(l),h.push(n+3+r[n+1]+r[n+2]),g[g.length-1]!==s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 16:g[g.length-1]!==s?(u.push(l),h.push(n),l=n+2+r[n+1],n+=2):n+=2+r[n+1];break;case 17:u.push(l),h.push(n+3+r[n+1]+r[n+2]),e.length>c?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 18:u.push(l),h.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length)===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 19:u.push(l),h.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length).toLowerCase()===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 20:u.push(l),h.push(n+4+r[n+2]+r[n+3]),o[r[n+1]].test(e.charAt(c))?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 21:g.push(e.substr(c,r[n+1])),c+=r[n+1],n+=2;break;case 22:g.push(o[r[n+1]]),c+=o[r[n+1]].length,n+=2;break;case 23:g.push(s),0===p&&S(o[r[n+1]]),n+=2;break;case 24:d=g[g.length-1-r[n+1]],n+=2;break;case 25:d=c,n++;break;case 26:f=r.slice(n+4,n+4+r[n+3]).map(function(e){return g[g.length-1-e]}),g.splice(g.length-r[n+2],r[n+2],o[r[n+1]].apply(null,f)),n+=4+r[n+3];break;case 27:g.push(t(r[n+1])),n+=2;break;case 28:p++,n++;break;case 29:p--,n++;break;default:throw new Error("Invalid opcode: "+r[n]+".")}if(!(u.length>0))break;l=u.pop(),n=h.pop()}return g[0]}(n),l!==s&&c===e.length)return l;throw l!==s&&c<e.length&&S({type:"end"}),$=g,E=u<e.length?e.charAt(u):null,R=u<e.length?b(u,u+1):b(u,u),new He(He.buildMessage($,E),$,E,R);var $,E,R};var Pe;!function(e){e.parse=function(e,t){const s={startRule:t};try{xe(e,s)}catch(e){s.data=-1}return s.data},e.nameAddrHeaderParse=function(t){const s=e.parse(t,"Name_Addr_Header");return-1!==s?s:void 0},e.URIParse=function(t){const s=e.parse(t,"SIP_URI");return-1!==s?s:void 0}}(Pe=Pe||(Pe={}));const Oe={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function qe(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function Me(e){return Oe[e]||""}function Ne(){return qe(10)}function je(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}function Le(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class Fe{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=je(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[je(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[je(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[je(e)]}parseHeader(e,t=0){if(e=je(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const s=this.headers[e][t],i=s.raw;if(s.parsed)return s.parsed;const r=Pe.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(s.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[je(e)]=[{raw:t}]}toString(){return this.data}}class Ue extends Fe{constructor(){super()}}class Be extends Fe{constructor(){super()}}class Ke{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=Ke.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=s.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Ne(),this.from=Ke.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=Ke.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+qe(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,s){const i={};return s&&(i.tag=s),new De(e,t,i)}getHeader(e){const t=this.headers[je(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],s=this.headers[je(e)];if(s)for(const e of s)t.push(e);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)s.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[je(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[je(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let s="SIP/2.0/"+t;s+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(s+=";rport"),this.setHeader("via",s),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const s of this.headers[t])e+=t+": "+s+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+Le(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+Le(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function Ge(e){return"application/sdp"===e?"session":"render"}function Ve(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Ge(s),contentType:s,content:t}}function Ye(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function We(e){let t,s,i;if(e instanceof Ue&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof Be&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof Ke&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,i=e.body.body}if(Ye(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=Ge(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var Je,Ze;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(Je=Je||(Je={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(Ze=Ze||(Ze={}));const ze=500,Xe={T1:ze,T2:4e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class Qe extends me{constructor(e){super(e||"Transaction state error.")}}var et;!function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(et=et||(et={}));const tt=[et.ACK,et.BYE,et.CANCEL,et.INFO,et.INVITE,et.MESSAGE,et.NOTIFY,et.OPTIONS,et.PRACK,et.REFER,et.REGISTER,et.SUBSCRIBE];class st{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class it{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class rt{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof De))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&s.push("Replaces: "+decodeURIComponent(i));const r=this.referredBy;return r&&s.push("Referred-By: "+r),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var nt,ot;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(nt=nt||(nt={}));class at{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=nt.Initial,this.delegate=t.delegate,this._stateEventEmitter=new Re,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case nt.Initial:case nt.Establishing:break;case nt.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case nt.Terminating:case nt.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case nt.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case nt.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case nt.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case nt.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case nt.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==nt.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==nt.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new ye("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=We(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(nt.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,i).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===nt.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(nt.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,i).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==nt.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(nt.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==nt.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(nt.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+tt.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==nt.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==nt.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof at&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const s=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return i.extraHeaders=i.extraHeaders?i.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,s,i)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case Je.Initial:case Je.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case Je.AckWait:return this.stateTransition(nt.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(nt.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(nt.Terminated),i(r)}}});case Je.Confirmed:{const i=s.bye(e,t);return this.stateTransition(nt.Terminated),Promise.resolve(i)}case Je.Terminated:throw new Error(`Invalid dialog state ${s.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:i})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==nt.Established&&this.state!==nt.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new Te(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case Ze.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(nt.Terminated),Promise.resolve()}case Ze.Stable:{const i=We(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(nt.Terminated)}):Promise.resolve()}case Ze.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(nt.Terminated),Promise.resolve()}case Ze.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(nt.Terminated),Promise.resolve()}case Ze.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===nt.Established){if(this.delegate&&this.delegate.onBye){const t=new $e(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(nt.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===nt.Established)if(this.delegate&&this.delegate.onInfo){const t=new Ce(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==nt.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=Pe.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const i=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,200)}).catch(t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===Ze.Stable){const t=e.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488))}this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const s=e.reject({statusCode:488});if(this.state!==nt.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(nt.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===nt.Established)if(this.delegate&&this.delegate.onMessage){const t=new st(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===nt.Established){if(this.onNotify){const t=new it(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new it(e);this.delegate.onNotify(t)}else e.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===nt.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==nt.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new rt(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=We(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case Ze.Initial:return this.getOffer(e);case Ze.HaveLocalOffer:return Promise.resolve(void 0);case Ze.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case Ze.Stable:return this.state!==nt.Established?Promise.resolve(void 0):this.getOffer(e);case Ze.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>Ve(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new ve)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new ve)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,r).then(()=>s.getDescription(i,r)).then(e=>Ve(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case nt.Initial:e!==nt.Establishing&&e!==nt.Established&&e!==nt.Terminating&&e!==nt.Terminated&&t();break;case nt.Establishing:e!==nt.Established&&e!==nt.Terminating&&e!==nt.Terminated&&t();break;case nt.Established:e!==nt.Terminating&&e!==nt.Terminated&&t();break;case nt.Terminating:e!==nt.Terminated&&t();break;case nt.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===nt.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let i=Me(e);return!i&&t&&(i=t),"SIP;cause="+s+';text="'+i+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof _e)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${i}?Replaces=${encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`)}>`}return t}}!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(ot=ot||(ot={}));const ct={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0};class dt extends at{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const r=s.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(nt.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===nt.Initial&&(t.reject({statusCode:487}),this.stateTransition(nt.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=Pe.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=s.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case nt.Initial:case nt.Establishing:return this.reject().then(()=>super.dispose());case nt.Established:case nt.Terminating:case nt.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==nt.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(nt.Establishing),this.sendAccept(e).then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(nt.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==nt.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===ot.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==nt.Initial&&this.state!==nt.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:Me(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?Ve(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}),this.stateTransition(nt.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===nt.Initial||this.state===nt.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new Ee(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(nt.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=We(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case Ze.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ze.Stable:return this.setAnswer(t,s).then(()=>{});case Ze.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ze.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case Ze.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof ve?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof we?this.logger.error("A session description handler occurred while sending response"):e instanceof be?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof Qe&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===nt.Initial||this.state===nt.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(nt.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(nt.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?Ve(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let n;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n}))).then(t=>{let a,c;this._dialog=t.session,t.session.delegate={onPrack:s=>{a=s,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(s=>{try{c=a.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:a,prackResponse:c,progressResponse:t})}catch(e){o(e)}}).catch(e=>o(e)))}};const d=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then(()=>o(new be)).catch(e=>o(e)))},64*Xe.T1),h=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n})}catch(e){return this.waitingForPrack=!1,void o(e)}u=setTimeout(h,l*=2)};let l=Xe.T1,u=setTimeout(h,l)}).catch(e=>{this.waitingForPrack=!1,o(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new be),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class ht extends at{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=Ne(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const i=Object.assign({},s);i.params=Object.assign({},s.params);const r=s.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?Pe.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?Pe.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const c=Object.assign({},i.params);c.fromTag=this.fromTag;const d=(i.extraHeaders||[]).slice();r&&e.configuration.uri&&(d.push("P-Preferred-Identity: "+e.configuration.uri.toString()),d.push("Privacy: id")),d.push("Contact: "+n),d.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===ot.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===ot.Required&&d.push("Require: replaces"),i.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(et.INVITE,t,o,a,c,d,undefined),this._contact=n,this._referralInviterOptions=i,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case nt.Initial:case nt.Establishing:return this.cancel().then(()=>super.dispose());case nt.Established:case nt.Terminating:case nt.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==nt.Initial&&this.state!==nt.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(nt.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(Me(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(nt.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==nt.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(nt.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(nt.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==nt.Terminated&&this.stateTransition(nt.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(nt.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof at))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==nt.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Pe.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case Ze.Initial:case Ze.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(nt.Terminated),Promise.reject(new Error("Bad Media Description"));case Ze.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(nt.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(nt.Terminated),t})}case Ze.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(nt.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(nt.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(nt.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(nt.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(nt.Terminated),t})}case Ze.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==nt.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Pe.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const r=s.getHeader("require"),n=s.getHeader("rseq"),o=!!(r&&r.includes("100rel")&&n?Number(n):void 0),a=[];switch(o&&a.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case Ze.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case Ze.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case Ze.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:s})}).catch(e=>{throw this.stateTransition(nt.Terminated),e})}case Ze.Stable:if(o&&e.prack({extraHeaders:a}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(nt.Terminated),e})}return Promise.resolve();case Ze.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===nt.Establishing||this.state===nt.Terminating?this.stateTransition(nt.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===nt.Establishing||this.state===nt.Terminating?this.stateTransition(nt.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===nt.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var lt,ut,gt,pt,ft,mt,vt;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(lt=lt||(lt={}));class yt{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=lt.Initial,this._waiting=!1,this._stateEventEmitter=new Re,this._waitingEventEmitter=new Re,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},yt.defaultOptions()),{registrar:s}),yt.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===Pe.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const i=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(et.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||yt.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||yt.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:yt.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new _e("sip","anonymous","anonymous.invalid"),refreshFrequency:yt.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===lt.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===lt.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new ye("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(i=t.message.parseHeader("contact",r),!i)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&Ae(i.uri,this.userAgent.contact.pubGruu)){s=Number(i.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(i.uri.user===this.userAgent.contact.uri.user){s=Number(i.getParam("expires"));break}}else if(Ae(i.uri,this.userAgent.contact.uri)){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=Pe.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=Pe.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===lt.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==lt.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new ye("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===lt.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==lt.Registered&&this.stateTransition(lt.Registered)}unregistered(){this.clearTimers(),this._state!==lt.Unregistered&&this.stateTransition(lt.Unregistered)}terminated(){this.clearTimers(),this._state!==lt.Terminated&&this.stateTransition(lt.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case lt.Initial:e!==lt.Registered&&e!==lt.Unregistered&&e!==lt.Terminated&&t();break;case lt.Registered:e!==lt.Unregistered&&e!==lt.Terminated&&t();break;case lt.Unregistered:e!==lt.Registered&&e!==lt.Terminated&&t();break;case lt.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===lt.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===lt.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}yt.defaultExpires=600,yt.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(ut=ut||(ut={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(gt=gt||(gt={})),function(e){e.Started="Started",e.Stopped="Stopped"}(pt=pt||(pt={}));class wt{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=wt.hexChars,s=wt.hexOut;let i,r,n,o;for(o=0;o<4;o+=1)for(r=8*o,i=e[o],n=0;n<8;n+=2)s[r+1+n]=t.charAt(15&i),i>>>=4,s[r+0+n]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],i=e[1],r=e[2],n=e[3];s+=(i&r|~i&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[3]-1044525330|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[7]-45705983|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[11]-1990404162|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[15]+1236535329|0,i=(i<<22|i>>>10)+r|0,s+=(i&n|r&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[0]-373897302|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[4]-405537848|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[8]+1163531501|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[12]-1926607734|0,i=(i<<20|i>>>12)+r|0,s+=(i^r^n)+t[5]-378558|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[14]-35309556|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[10]-1094730640|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[6]+76029189|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[2]-995338651|0,i=(i<<23|i>>>9)+r|0,s+=(r^(i|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[5]-57434055|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[1]-2054922799|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[13]+1309151649|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[9]-343485551|0,i=(i<<21|i>>>11)+r|0,e[0]=s+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(wt.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,r,n=this._bufferLength;for(r=0;r<e.length;r+=1){if(i=e.charCodeAt(r),i<128)t[n++]=i;else if(i<2048)t[n++]=(i>>>6)+192,t[n++]=63&i|128;else if(i<55296||i>56319)t[n++]=(i>>>12)+224,t[n++]=i>>>6&63|128,t[n++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++r)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=(i>>>18)+240,t[n++]=i>>>12&63|128,t[n++]=i>>>6&63|128,t[n++]=63&i|128}n>=64&&(this._dataLength+=64,wt._md5cycle(this._state,s),n-=64,s[0]=s[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e.charCodeAt(n++);if(r<64)break;this._dataLength+=64,wt._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e[n++];if(r<64)break;this._dataLength+=64,wt._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}getState(){const e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}}setState(e){const t=e.buffer,s=e.state,i=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,s=this._buffer8,i=this._buffer32,r=1+(t>>2);let n;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(wt.buffer32Identity.subarray(r),r),t>55&&(wt._md5cycle(this._state,i),i.set(wt.buffer32Identity)),n=8*this._dataLength,n<=4294967295)i[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return wt._md5cycle(this._state,i),e?this._state:wt._hex(this._state)}}function bt(e){return wt.hashStr(e)}wt.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),wt.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),wt.hexChars="0123456789abcdef",wt.hexOut=[],wt.onePassHasher=new wt,"5d41402abc4b2a76b9719d911017c592"!==wt.hashStr("hello")&&console.error("Md5 self test failed.");class St{constructor(e,t,s,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=qe(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=bt(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=bt(this.method+":"+this.uri),this.response=bt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=bt(this.method+":"+this.uri+":"+bt(e||"")),this.response=bt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=bt(this.method+":"+this.uri),this.response=bt(t+":"+this.nonce+":"+s))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(ft=ft||(ft={}));class Tt{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(ft.error,e)}warn(e){this.genericLog(ft.warn,e)}log(e){this.genericLog(ft.log,e)}debug(e){this.genericLog(ft.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class $t{constructor(){this.builtinEnabled=!0,this._level=ft.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:ft.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new Tt(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new Tt(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(ft[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case ft.error:console.error(i);break;case ft.warn:console.warn(i);break;case ft.log:console.log(i);break;case ft.debug:console.debug(i)}}}function Et(e,t){const s="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const i=t.reasonPhrase?t.reasonPhrase:Me(t.statusCode);let r="SIP/2.0 "+t.statusCode+" "+i+s;t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+s,o="Call-ID: "+e.callId+s,a="CSeq: "+e.cseq+" "+e.method+s,c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+s,"");let d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Ne()),d+=";tag="+e}d+=s;let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+s);let l="";t.userAgent&&(l="User-Agent: "+t.userAgent+s);let u="";return t.extraHeaders&&(u=t.extraHeaders.reduce((e,t)=>e+t.trim()+s,"")),r+=c,r+=n,r+=d,r+=a,r+=o,r+=h,r+=l,r+=u,t.body?(r+="Content-Type: "+t.body.contentType+s,r+="Content-Length: "+Le(t.body.content)+s+s,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){let s=t,i=0,r=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===i;){if(r=e.indexOf("\r\n",s),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?s=r+2:i=r}return i}function s(e,t,s,i){const r=t.indexOf(":",s),n=t.substring(s,r).trim(),o=t.substring(r+1,i).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=Pe.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=Pe.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof Be&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,i){let r=0,n=e.indexOf("\r\n");if(-1===n)return void i.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=Pe.parse(o,"Request_Response");let c,d;if(-1!==a){for(a.status_code?(c=new Be,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new Ue,c.method=a.method,c.ruri=a.uri),c.data=e,r=n+2;;){if(n=t(e,r),-2===n){d=r+2;break}if(-1===n)return void i.error("malformed message");const o=s(c,e,r,n);if(o&&!0!==o)return void i.error(o.error);r=n+2}return c.hasHeader("content-length")?c.body=e.substr(d,Number(c.getHeader("content-length"))):c.body=e.substring(d),c}i.warn('error parsing first line of SIP message: "'+o+'"')}}(mt=mt||(mt={}));class Rt extends me{constructor(e){super(e||"Unspecified transport error.")}}class Ct{constructor(e,t,s,i,r){this._transport=e,this._user=t,this._id=s,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof Rt)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new Rt(e.message):new Rt,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class It extends Ct{constructor(e,t,s,i,r){super(t,s,e.viaBranch,i,r),this._request=e,this.user=s}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(vt=vt||(vt={}));class Dt extends It{constructor(e,t,s){super(e,t,s,vt.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case vt.Proceeding:if(e.method===et.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case vt.Accepted:if(e.method===et.INVITE)return;break;case vt.Completed:if(e.method===et.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===et.ACK)return void this.stateTransition(vt.Confirmed);break;case vt.Confirmed:case vt.Terminated:if(e.method===et.INVITE||e.method===et.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case vt.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(vt.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(vt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case vt.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case vt.Completed:case vt.Confirmed:case vt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===vt.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case vt.Proceeding:t();break;case vt.Accepted:case vt.Completed:this.state!==vt.Proceeding&&t();break;case vt.Confirmed:this.state!==vt.Completed&&t();break;case vt.Terminated:this.state!==vt.Accepted&&this.state!==vt.Completed&&this.state!==vt.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===vt.Accepted&&(this.L=setTimeout(()=>this.timerL(),Xe.TIMER_L)),e===vt.Completed&&(this.H=setTimeout(()=>this.timerH(),Xe.TIMER_H)),e===vt.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Xe.TIMER_I)),e===vt.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},Xe.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===vt.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(vt.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(vt.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===vt.Accepted&&this.stateTransition(vt.Terminated)}}class _t extends Ct{constructor(e,t,s,i,r){super(t,s,_t.makeId(e),i,r),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class At extends _t{constructor(e,t,s){super(e,t,s,vt.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Xe.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case vt.Trying:if(t>=100&&t<=199)return this.stateTransition(vt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(vt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case vt.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(vt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case vt.Completed:case vt.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(vt.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case vt.Trying:s();break;case vt.Proceeding:this.state!==vt.Trying&&s();break;case vt.Completed:this.state!==vt.Trying&&this.state!==vt.Proceeding&&s();break;case vt.Terminated:this.state!==vt.Trying&&this.state!==vt.Proceeding&&this.state!==vt.Completed&&(t||s());break;default:s()}e===vt.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Xe.TIMER_K)),e===vt.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==vt.Trying&&this.state!==vt.Proceeding||(this.onRequestTimeout(),this.stateTransition(vt.Terminated))}timerK(){this.state===vt.Completed&&this.stateTransition(vt.Terminated)}}class kt{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof De))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const d=e.from.uri,h=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:d,remoteURI:h,remoteTarget:r,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof De))throw new Error("Contact not instance of NameAddrHeader.");const n=r.uri,o=e.cseq,a=e.callId,c=t,d=e.fromTag,h=e.from.uri;return{id:a+c+d,early:s,callId:a,localTag:c,remoteTag:d,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:h,remoteTarget:n,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==et.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,i=this.remoteTag,r=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,d=this.routeSet,h=t&&t.extraHeaders,l=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,s,{callId:o,cseq:a,fromTag:n,toTag:i,routeSet:d},h,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===et.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Ht extends _t{constructor(e,t,s){super(e,t,s,vt.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Xe.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case vt.Calling:if(t>=100&&t<=199)return this.stateTransition(vt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(vt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(vt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case vt.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(vt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(vt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case vt.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case vt.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case vt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(vt.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,i=this.request.cseq,r=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${i} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case vt.Calling:s();break;case vt.Proceeding:this.state!==vt.Calling&&s();break;case vt.Accepted:case vt.Completed:this.state!==vt.Calling&&this.state!==vt.Proceeding&&s();break;case vt.Terminated:this.state!==vt.Calling&&this.state!==vt.Accepted&&this.state!==vt.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),vt.Proceeding,e===vt.Completed&&(this.D=setTimeout(()=>this.timerD(),Xe.TIMER_D)),e===vt.Accepted&&(this.M=setTimeout(()=>this.timerM(),Xe.TIMER_M)),e===vt.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===vt.Calling&&(this.onRequestTimeout(),this.stateTransition(vt.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===vt.Completed&&this.stateTransition(vt.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===vt.Accepted&&this.stateTransition(vt.Terminated)}}class xt{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const s=this.core.makeOutgoingRequestMessage(et.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},t.extraHeaders);return s.branch=this.message.branch,this.message.headers.Route&&(s.headers.Route=this.message.headers.Route),e&&s.setHeader("Reason",e),this.transaction.state===vt.Proceeding?new xt(At,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===vt.Proceeding&&new xt(At,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let i,r;if(401===s?(i=e.parseHeader("www-authenticate"),r="authorization"):(i=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!i)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==i.stale))return this.logger.warn(s+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,i))return!0;this.challenged=!0,i.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new Be;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new Be;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===vt.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}class Pt extends xt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(et.BYE,s);super(At,e.userAgentCore,i,t),e.dispose()}}class Ot extends It{constructor(e,t,s){super(e,t,s,vt.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case vt.Trying:break;case vt.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case vt.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case vt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case vt.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(vt.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(vt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case vt.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(vt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case vt.Completed:return;case vt.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(vt.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case vt.Trying:s();break;case vt.Proceeding:this.state!==vt.Trying&&s();break;case vt.Completed:this.state!==vt.Trying&&this.state!==vt.Proceeding&&s();break;case vt.Terminated:this.state!==vt.Proceeding&&this.state!==vt.Completed&&(t||s());break;default:s()}e===vt.Completed&&(this.J=setTimeout(()=>this.timerJ(),Xe.TIMER_J)),e===vt.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===vt.Completed&&this.stateTransition(vt.Terminated)}}class qt{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:Ne(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new Qe(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new Qe(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new Qe(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError(`Invalid statusCode: ${s}`);const i=new Array;e.forEach(e=>i.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(i);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new Qe(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new Qe(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Dt)return this.transaction.state===vt.Proceeding||this.transaction.state===vt.Accepted;if(this.transaction instanceof Ot)return this.transaction.state===vt.Trying||this.transaction.state===vt.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Dt)return this.transaction.state===vt.Proceeding;if(this.transaction instanceof Ot)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Dt)return this.transaction.state===vt.Proceeding;if(this.transaction instanceof Ot)return this.transaction.state===vt.Trying||this.transaction.state===vt.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Dt)return this.transaction.state===vt.Proceeding;if(this.transaction instanceof Ot)return this.transaction.state===vt.Trying||this.transaction.state===vt.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Dt)return this.transaction.state===vt.Proceeding;if(this.transaction instanceof Ot)return this.transaction.state===vt.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=Et(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===vt.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}class Mt extends qt{constructor(e,t,s){super(Ot,e.userAgentCore,t,s)}}class Nt extends xt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(et.INFO,s);super(At,e.userAgentCore,i,t)}}class jt extends qt{constructor(e,t,s){super(Ot,e.userAgentCore,t,s)}}class Lt extends xt{constructor(e,t,s){super(At,e,t,s)}}class Ft extends qt{constructor(e,t,s){super(Ot,e,t,s)}}class Ut extends xt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(et.NOTIFY,s);super(At,e.userAgentCore,i,t)}}class Bt extends qt{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ot,i,t,s)}}class Kt extends xt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(et.PRACK,s);super(At,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class Gt extends qt{constructor(e,t,s){super(Ot,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Vt extends xt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(et.INVITE,s);super(Ht,e.userAgentCore,i,t),this.delegate=t,e.signalingStateTransition(i),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class Yt extends qt{constructor(e,t,s){super(Dt,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),i}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),i}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class Wt extends xt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(et.REFER,s);super(At,e.userAgentCore,i,t)}}class Jt extends qt{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Ot,i,t,s)}}class Zt extends kt{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=Ze.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof Dt&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=Ze.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?Je.Early:this.ackWait?Je.AckWait:this._signalingState===Ze.Closed?Je.Terminated:Je.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Ht))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(et.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(s),this.signalingStateTransition(s),{message:s}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Dt){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==vt.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new Pt(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Nt(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INVITE request`),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new Vt(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const s=this.createOutgoingRequestMessage(et.MESSAGE,t);return new Lt(this.core,s,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new Ut(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Kt(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new Wt(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==et.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===et.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==Ze.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===et.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof De))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case et.BYE:{const t=new Mt(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case et.INFO:{const t=new jt(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case et.INVITE:{const t=new Yt(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case et.MESSAGE:{const t=new Ft(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case et.NOTIFY:{const t=new Bt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case et.PRACK:{const t=new Gt(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case et.REFER:{const t=new Jt(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Ht)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),i=t&&t.includes("100rel")&&s?Number(s):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0}signalingStateRollback(){this._signalingState!==Ze.HaveLocalOffer&&this.signalingState!==Ze.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Ze.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=We(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===Ze.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Ue)switch(this._signalingState){case Ze.Initial:case Ze.Stable:this._signalingState=Ze.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ze.HaveLocalOffer:this._signalingState=Ze.Stable,this._answer=t;break;case Ze.HaveRemoteOffer:case Ze.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Be)switch(this._signalingState){case Ze.Initial:case Ze.Stable:this._signalingState=Ze.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ze.HaveLocalOffer:this._signalingState=Ze.Stable,this._answer=t;break;case Ze.HaveRemoteOffer:case Ze.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Ke)switch(this._signalingState){case Ze.Initial:case Ze.Stable:this._signalingState=Ze.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ze.HaveLocalOffer:break;case Ze.HaveRemoteOffer:this._signalingState=Ze.Stable,this._answer=t;break;case Ze.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Ye(e))switch(this._signalingState){case Ze.Initial:case Ze.Stable:this._signalingState=Ze.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ze.HaveLocalOffer:break;case Ze.HaveRemoteOffer:this._signalingState=Ze.Stable,this._answer=t;break;case Ze.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Dt){const e=this.initialTransaction;let t=Xe.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Xe.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===vt.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(i)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Dt){const e=this.reinviteUserAgentServer.transaction;let t=Xe.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Xe.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===vt.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class zt extends xt{constructor(e,t,s){super(Ht,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===vt.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=kt.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Zt(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==Ze.Initial&&s.signalingState!==Ze.HaveLocalOffer||s.signalingStateTransition(e);const i=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:i,prack:e=>i.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=kt.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Ht))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Zt(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==Ze.Initial&&s.signalingState!==Ze.HaveLocalOffer||s.signalingStateTransition(e);const i=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:i,ack:e=>{const t=i.ack(e);return this.confirmedDialogAcks.set(i.id,t),t}});else{const e=i.ack();this.confirmedDialogAcks.set(i.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class Xt extends qt{constructor(e,t,s){super(Dt,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new Qe(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof Dt))throw new Error("Transaction not instance of InviteClientTransaction.");const t=kt.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Zt(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact.toString()}`,i="Allow: "+tt.toString();if(!e.body)if(this.confirmedDialog.signalingState===Ze.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Ze.Initial||this.confirmedDialog.signalingState===Ze.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i),e.extraHeaders.push(s);const r=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},r),{session:n});return e.body&&this.confirmedDialog.signalingState!==Ze.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new Qe(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Dt))throw new Error("Transaction not instance of InviteClientTransaction.");const t=kt.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Zt(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const i=super.progress(e),r=this.earlyDialog,n=Object.assign(Object.assign({},i),{session:r});return e.body&&this.earlyDialog.signalingState!==Ze.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class Qt extends xt{constructor(e,t,s){super(At,e,t,s)}}class es extends xt{constructor(e,t,s){super(At,e,t,s)}}class ts extends qt{constructor(e,t,s){super(Ot,e,t,s),this.core=e}}class ss extends xt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(et.SUBSCRIBE,s);super(At,e.userAgentCore,i,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class is extends kt{constructor(e,t,s,i,r,n){super(i,r),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=s,this.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const s=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof De))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:s,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===et.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+tt.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var s;if(this.subscriptionState!==ut.Pending&&this.subscriptionState!==ut.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const i=new ss(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(s=t.extraHeaders)||void 0===s?void 0:s.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),Xe.TIMER_N)),i}terminate(){this.stateTransition(ut.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+tt.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const i=s.state,r=s.expires?Math.max(s.expires,0):void 0;switch(i){case"pending":this.stateTransition(ut.Pending,r);break;case"active":this.stateTransition(ut.Active,r);break;case"terminated":this.stateTransition(ut.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new Bt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case ut.Initial:case ut.NotifyWait:return void s();case ut.Pending:if(this.subscriptionState!==ut.NotifyWait&&this.subscriptionState!==ut.Pending)return void s();break;case ut.Active:case ut.Terminated:if(this.subscriptionState!==ut.NotifyWait&&this.subscriptionState!==ut.Pending&&this.subscriptionState!==ut.Active)return void s();break;default:return void s()}e===ut.Pending&&t&&(this.subscriptionExpires=t),e===ut.Active&&t&&(this.subscriptionExpires=t),e===ut.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==ut.Terminated&&(this.stateTransition(ut.Terminated),this.onTerminated())}}class rs extends xt{constructor(e,t,s){const i=t.getHeader("Event");if(!i)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(At,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=ut.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const i=s.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${i}`),void e.reject({statusCode:489})}if("terminated"!==i){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=ut.Pending;break;case"active":this.subscriptionState=ut.Active;break;case"terminated":this.subscriptionState=ut.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==ut.Terminated){const t=is.initialDialogStateForSubscription(this.message,e.message);this.dialog=new is(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),Xe.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class ns extends qt{constructor(e,t,s){super(Ot,e,t,s),this.core=e}}const os=["application/sdp","application/dtmf-relay"];class as{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new zt(this,e,t)}message(e,t){return new Lt(this,e,t)}publish(e,t){return new Qt(this,e,t)}register(e,t){return new es(this,e,t)}subscribe(e,t){return new rs(this,e,t)}request(e,t){return new xt(At,this,e,t)}makeOutgoingRequestMessage(e,t,s,i,r,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,d=this.configuration.viaForceRport,h=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===et.REGISTER&&l.push("path","gruu"),e===et.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const u={callIdPrefix:a,forceRport:d,fromDisplayName:c,hackViaTcp:h,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},u),r);return new Ke(e,t,s,i,g,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:i});const r=Et(e,t);return this.transport.send(r.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),r}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===et.ACK&&s&&s.transaction.state===vt.Accepted&&s instanceof Xt?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==et.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof Dt&&s.transaction.state===vt.Proceeding&&s instanceof Xt&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!tt.includes(e.method)){const t="Allow: "+tt.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==et.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==et.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===et.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,i=this.subscribers.get(s);if(i){const t=new Bt(this,e);return void i.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===et.OPTIONS){const t="Allow: "+tt.toString(),s="Accept: "+os.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==et.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case et.ACK:break;case et.BYE:this.replyStateless(e,{statusCode:481});break;case et.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case et.INFO:this.replyStateless(e,{statusCode:405});break;case et.INVITE:{const t=new Xt(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case et.MESSAGE:{const t=new Ft(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case et.NOTIFY:{const t=new Bt(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case et.OPTIONS:{const t="Allow: "+tt.toString(),s="Accept: "+os.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case et.REFER:{const t=new Jt(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case et.REGISTER:{const t=new ts(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case et.SUBSCRIBE:{const t=new ns(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class cs{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var s,i;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(r,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const i=s[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,n)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:i},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===r);n?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===r);t&&(t.stop(),s.removeTrack(t),cs.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),cs.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}s.addTrack(e),cs.dispatchAddTrackEvent(s,e)}))},n=e.getAudioTracks();n.length&&r(n[0]);const o=e.getVideoTracks();return o.length&&r(o[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),cs.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),cs.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),cs.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),cs.dispatchAddTrackEvent(t,e))}updateDirection(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");{const t=t=>{switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const s=t(e.direction);e.direction!==s&&(e.direction=s)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),s=(()=>{switch(t){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==s&&(e.direction=s)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const i=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const i=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const i=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${i}`),"complete"===i&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const i=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const s=e.track.kind,i=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${i}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function ds(e){return(t,s)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const i={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==s?void 0:s.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new cs(r,e,i)}}class hs{constructor(e,t){if(this._state=gt.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new Re,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,i=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},hs.defaultOptions),t);const s=this.configuration.server,i=Pe.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===gt.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case gt.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(gt.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case gt.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(gt.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case gt.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(gt.Connecting)}catch(e){if(e instanceof Se)return Promise.reject(e);throw e}break;case gt.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(gt.Connecting)}catch(e){if(e instanceof Se)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(gt.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case gt.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(gt.Disconnecting)}catch(e){if(e instanceof Se)return Promise.reject(e);throw e}break;case gt.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(gt.Disconnecting)}catch(e){if(e instanceof Se)return Promise.reject(e);throw e}break;case gt.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(gt.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case gt.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(gt.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==gt.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,i=this.disconnectPromise?void 0:new Error(s);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(gt.Disconnected,i)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let i;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{i=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e.toString()),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+i+"\n")}else i=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+i+"\n");if(this.state===gt.Connected){if(this.onMessage)try{this.onMessage(i)}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===gt.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(gt.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new Se("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case gt.Connecting:e!==gt.Connected&&e!==gt.Disconnecting&&e!==gt.Disconnected&&s();break;case gt.Connected:e!==gt.Disconnecting&&e!==gt.Disconnected&&s();break;case gt.Disconnecting:e!==gt.Connecting&&e!==gt.Disconnected&&s();break;case gt.Disconnected:e!==gt.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===gt.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===gt.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${i} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===gt.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(i===gt.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===gt.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===gt.Connected?r():n(t||new Error("Connect aborted."))}if(i===gt.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===gt.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}hs.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class ls{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=pt.Stopped,this._stateEventEmitter=new Re,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ls.defaultOptions()),{sipjsId:qe(5)}),{uri:new _e("sip","anonymous."+qe(6),"anonymous.invalid")}),{viaHost:qe(12)+".invalid"}),ls.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new $t,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=ft.error;break;case"warn":this.loggerFactory.level=ft.warn;break;case"log":this.loggerFactory.level=ft.log;break;case"debug":this.loggerFactory.level=ft.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,i=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==i&&(this.options.reconnectionDelay=i),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:ls.newUUID(),-1===Pe.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return Pe.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:ds(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:ot.Unsupported,sipExtensionReplaces:ot.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:hs,transportOptions:{},uri:new _e("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===pt.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===pt.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(pt.Started),this.transport.connect())}async stop(){if(this.state===pt.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(pt.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),r=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in i)i[e]&&await i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await r.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(pt.Stopped)}_makeInviter(e,t){return new ht(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=""!==this.options.contactName?this.options.contactName:qe(8),t=this.options.contactParams,s={pubGruu:void 0,tempGruu:void 0,uri:new _e("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const s=e.anonymous||!1,i=e.outbound||!1,r=e.register||!1;let n="<";return n+=s?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:r?this.contact.uri:this.contact.pubGruu||this.contact.uri,i&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}};return s}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===ot.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===ot.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>ct[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new St(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new as(s,{onInvite:e=>{var t;const s=new dt(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==ot.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const i=t.replaces_to_tag;if("string"!=typeof i)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const n=e+i+r,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+r]||this._sessions[e+i]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new st(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new it(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==pt.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==pt.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=mt.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===pt.Stopped&&t instanceof Ue)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof Ue){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=Le(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof Be){if(!s())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=Le(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof Ue)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof Be))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case pt.Started:e!==pt.Stopped&&s();break;case pt.Stopped:e!==pt.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}const us=({configKey:e})=>{const t=Q().configs?.[e],s=t?.account.username??"",i=Q().findLineByLineKey,r=Q().getNewLineKey,n=Q().addLine,o=Q().updateLine,a=Q().userAgents?.[e],{hasAudioDevice:c,hasVideoDevice:d}=Q().devicesInfo,{onInviteAccepted:h,onInviteCancel:l,onInviteProgress:u,onInviteRejected:g,onSessionDescriptionHandlerCreated:p,onSessionReceivedBye:f,onSessionReceivedMessage:m,onSessionReinvited:v,onTransferSessionDescriptionHandlerCreated:y}=(({configKey:e})=>{const t=Q().updateLine;async function s(s,i){const r=s.sipSession;r&&(r.initiateRemoteMediaStreams=({videoEnabled:n=i,pc:o=Q().getSessionByLineKey(s.lineKey)?.sessionDescriptionHandler.peerConnection??r.sessionDescriptionHandler.peerConnection,configs:a=te(e)}={})=>{const c=a?.media,d=new Map,h=new Map,l=`line-${s.lineKey}-remoteAudios`,u=`line-${s.lineKey}-remoteVideos`,g=document.getElementById(l),p=document.getElementById(u);o.getTransceivers().forEach(e=>{const t=e.receiver?.track;if(!t)return;const s=new MediaStream([t]);"audio"===t.kind&&d.set(t.id,s),n&&"video"===t.kind&&(t.mid=e.mid,h.set(t.id,s))}),g&&(g.innerHTML="",d.forEach((e,t)=>{const i=document.createElement("audio");i.id=`line-${s.lineKey}-audio-${t}`,i.autoplay=!0,i.srcObject=e,i.controls=!1,i.onloadedmetadata=()=>{void 0!==i.sinkId&&c?.audioOutputDeviceId&&i.setSinkId(c?.audioOutputDeviceId).then(()=>{}).catch(e=>{}),i.play().catch(e=>{})},g.appendChild(i)})),p&&(p.innerHTML="",h.forEach((e,t)=>{const i=document.createElement("video");i.id=`line-${s.lineKey}-video-${t}`,i.srcObject=e,i.autoplay=!0,i.playsInline=!0,i.muted=!0,i.onloadedmetadata=()=>{void 0!==i.sinkId&&c?.videoInputDeviceId&&i.setSinkId(c?.videoInputDeviceId).then(()=>{}).catch(e=>{}),i.play().catch(e=>{})},p.appendChild(i)})),t(s)},r.initiateRemoteMediaStreams())}return{onInviteCancel:function(e,t,s){let i=0;const r=t.headers.Reason;if(void 0!==r&&r.length>0)for(let e=0;e<r.length;e++){const t=r[e].raw.toLowerCase().trim(),s=t.split(";");if(s.length>=2&&("sip"===s[0].trim()||"q.850"===s[0].trim())&&s[1].includes("cause")&&t.includes("call completed elsewhere")){i=parseInt(s[1].substring(s[1].indexOf("=")+1).trim());break}}const n=e.sipSession;n&&(n.data.terminateBy="them",n.data.reasonCode=i,n.data.reasonText=0===i?"Call Cancelled":"Call completed elsewhere",n.dispose().catch(function(e){}),s?.())},onInviteAccepted:async function(s,i,r){const n=s.sipSession;if(!n)return;n.data.earlyMedia&&(n.data.earlyMedia.pause(),n.data.earlyMedia.removeAttribute("src"),n.data.earlyMedia.load(),n.data.earlyMedia=null);const o=F();n.data.startTime=o,n.data.started=!0,n.initiateLocalMediaStreams=async({videoEnabled:r=i,pc:o=Q().getSessionByLineKey(s.lineKey)?.sessionDescriptionHandler.peerConnection??n.sessionDescriptionHandler.peerConnection,configs:a=te(e)}={})=>{try{const e=a?.media,i=Q().findLineByLineKey(s.lineKey),n=i?.sipSession?.data.localMediaStreamStatus?.screenShareEnabled;let c;if(n)c=new MediaStream,o.getSenders().forEach(function(e){e.track&&"video"===e.track.kind&&c.addTrack(e.track)});else{const t={audio:!!e?.audioInputDeviceId&&("default"===e.audioInputDeviceId||{deviceId:{exact:e.audioInputDeviceId}}),video:!(!r||!e?.videoInputDeviceId)&&("default"===e.videoInputDeviceId||{deviceId:{exact:e.videoInputDeviceId}})};c=await navigator.mediaDevices.getUserMedia(t)}if(c.getTracks().forEach(e=>{const t=o.getSenders().find(t=>t.track&&t.track.kind===e.kind);t?t.replaceTrack(e):o.addTrack(e,c)}),r){const e=document.getElementById(`line-${s.lineKey}-localVideo`);e&&(e.srcObject=new MediaStream(c.getVideoTracks()),await e.play().catch(()=>{}))}t(s)}catch(e){}},n.initiateLocalMediaStreams(),t(s)},onInviteTrying:function(e,t){},onInviteProgress:function(e,s){e.sipSession&&(180===s.message.statusCode||s.message.statusCode,t(e))},onInviteRejected:function(e,t,s){const i=e.sipSession;i&&(i.data.terminateBy="them",i.data.reasonCode=t.message.statusCode,i.data.reasonText=t.message.reasonPhrase,s?.())},onInviteRedirected:function(e,t){},onSessionReceivedBye:function(e,t,s){e?.sipSession&&(e.sipSession.data.terminateBy="them",e.sipSession.data.reasonCode=16,e.sipSession.data.reasonText="Normal Call clearing",t.accept(),s?.())},onSessionReinvited:function(e,t){const s=t.body,i=e.sipSession;if(!i)return;i.data.videoChannelNames=[];const r=s.split("m=video");if(r.length>=1)for(let e=0;e<r.length;e++)if(r[e].indexOf("a=mid:")>-1&&r[e].indexOf("a=label:")>-1){const t=r[e].split("\r\n");let s="",n="";for(let e=0;e<t.length;e++)0==t[e].indexOf("a=label:")&&(s=t[e].replace("a=label:","")),0==t[e].indexOf("a=mid:")&&(n=t[e].replace("a=mid:",""));i.data.videoChannelNames.push({mid:n,channel:s})}},onSessionReceivedMessage:function(e,s){try{const i=s.request.headers["Content-Type"].length>=1?s.request.headers["Content-Type"][0].parsed:"Unknown";if(i.indexOf("application/x-asterisk-confbridge-event")>-1){const t=JSON.parse(s.request.body),i=e.sipSession;if(!i)return;if(!i.data)return;i.data.confBridgeChannels||(i.data.confBridgeChannels=[]),i.data.confBridgeEvents||(i.data.confBridgeEvents=[]),"ConfbridgeStart"==t.type||("ConfbridgeWelcome"==t.type?(i.data.confBridgeChannels=t.channels,i.data.confBridgeChannels.forEach(function(e){})):"ConfbridgeJoin"==t.type?t.channels.forEach(function(e){let t=!1;i.data.confBridgeChannels?.forEach(function(s){s.id==e.id&&(t=!0)}),t||(i.data.confBridgeChannels?.push(e),i.data.confBridgeEvents?.push({event:e.caller.name+" ("+e.caller.number+") joined the conference",eventTime:F()}))}):"ConfbridgeLeave"==t.type?t.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t,s){t.id==e.id&&(i.data.confBridgeChannels?.splice(s,1),i.data.confBridgeEvents?.push({event:e.caller.name+" ("+e.caller.number+") left the conference",eventTime:F()}))})}):"ConfbridgeTalking"===t.type||("ConfbridgeMute"==t.type?t.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(t.muted=!0)})}):"ConfbridgeUnmute"===t.type?t.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(t.muted=!1)})}):t.type)),s.accept()}else if(i.indexOf("application/x-myphone-confbridge-chat")>-1)s.accept();else if(i.indexOf("text/plain")>-1){if(!e?.sipSession?.data.remoteMediaStreamStatus)return;const t=JSON.parse(s.request.body);switch(t.type){case pe.SOUND_TOGGLE:e.sipSession.data.remoteMediaStreamStatus.soundEnabled=t.value;break;case pe.VIDEO_TOGGLE:e.sipSession.data.remoteMediaStreamStatus.videoEnabled=t.value,ps(e.sipSession,pe.VIDEO_TOGGLE_ACK,"");break;case pe.SCREEN_SHARE_TOGGLE:e.sipSession.data.remoteMediaStreamStatus.screenShareEnabled=t.value;break;case pe.VIDEO_TOGGLE_ACK:e.sipSession.data.videoAckReceived=!0;break;default:s.reject()}s.accept()}else s.reject();t(e)}catch(e){}},onSessionDescriptionHandlerCreated:function(e,t,i,r){t&&t.peerConnection&&(t.peerConnection.ontrack=function(t){s(e,r)})},onTrackAddedEvent:s,onTransferSessionDescriptionHandlerCreated:function(e,t,s,i){s&&s.peerConnection&&(s.peerConnection.ontrack=function(){const r=s.peerConnection,n=new MediaStream,o=new MediaStream;r.getReceivers().forEach(e=>{e.track&&("audio"===e.track.kind&&n.addTrack(e.track),i&&"video"===e.track.kind&&o.addTrack(e.track))});const a=document.createElement("audio");if(a.setAttribute("id",`line-${e.lineKey}-transfer-remoteAudio`),a.srcObject=n,a.onloadedmetadata=function(){void 0!==a.sinkId&&t?.data?.audioOutputDevice&&a.setSinkId(t.data.audioOutputDevice).then(function(){}).catch(function(e){}),a.play()},i&&o.getVideoTracks().length>0){const t=document.createElement("video");o.getVideoTracks().forEach((s,i)=>{const r=new MediaStream;r.trackId=s.id,r.mid=s.mid,r.addTrack(s),t.id=`line-${e.lineKey}-video-${i}`,t.srcObject=r,t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.className="video-element",t.onloadedmetadata=()=>{t.play().catch(e=>{})}})}})}}})({configKey:e}),{makeAudioSpdOptions:w,answerAudioSpdOptions:b,answerVideoSpdOptions:S,makeVideoSpdOptions:T}=fe({configKey:e});function $(e,i,r){if(!a)return;if(!a.isRegistered())return;if(null===e)return;if(!c)return void alert("No audio device detected!");const n=w({extraHeaders:r});if(!n)return;let o=F();const d=ls.makeURI("sip:"+i.replace(/#/g,"%23")+"@"+t?.account.domain);e.sipSession=new ht(a,d,n);const l=e.sipSession;l.data={configKey:e.configKey,lineKey:e.lineKey,callDirection:"outbound",remoteNumber:i,username:s,startTime:o,videoSourceDevice:null,audioSourceDevice:t?.media.audioInputDeviceId,audioOutputDevice:t?.media.audioOutputDeviceId,terminateBy:"them",localMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:c,videoEnabled:!1},remoteMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},earlyReject:!1},l.data.callType="audio",l.delegate={onBye:function(t){f(e,t,()=>gs(e))},onMessage:function(t){m(e,t)},onInvite:function(t){v(e,t)},onSessionDescriptionHandler:function(t,s){p(e,t,s,!1)}};const y={requestDelegate:{onTrying:function(e){},onProgress:function(t){u(e,t)},onRedirect:function(e){},onAccept:function(t){h(e,!1,t)},onReject:function(t){g(e,t,()=>gs(e))}}};l.invite(y).catch(function(e){})}function E(e,i,r){if(null==a)return;if(!a.isRegistered())return;if(null==e)return;if(!c)return void alert("No audio device detected!");if(!d)return void $(e,i);const n=T({extraHeaders:r});if(!n)return;const o=F(),l=ls.makeURI("sip:"+i.replace(/#/g,"%23")+"@"+t?.account.domain);e.sipSession=new ht(a,l,n);const y=e.sipSession;y.data={configKey:e.configKey,lineKey:e.lineKey,callDirection:"outbound",remoteNumber:i,username:s,startTime:o,localMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!0},remoteMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},videoSourceDevice:t?.media.videoInputDeviceId,audioSourceDevice:t?.media.audioInputDeviceId,audioOutputDevice:t?.media.audioOutputDeviceId,terminateBy:"them"},y.data.callType="video",y.data.earlyReject=!1,y.delegate={onBye:function(t){f(e,t,()=>gs(e))},onMessage:function(t){m(e,t)},onInvite:function(t){v(e,t)},onSessionDescriptionHandler:function(t,s){p(e,t,s,!0)}};const w={requestDelegate:{onTrying:function(e){},onProgress:function(t){u(e,t)},onRedirect:function(e){},onAccept:function(t){h(e,!0,t)},onReject:function(t){g(e,t,()=>gs(e))}}};y.invite(w).catch(function(e){})}async function R(e){const t=i(e);if(!t||!t.sipSession||"audio"===t.sipSession.data.callType)return;const s=t.sipSession,r=s.sessionDescriptionHandler?.peerConnection;if(!r||!s.data.localMediaStreamStatus)return;if(s.data.localMediaStreamStatus.screenShareEnabled){const e=r.getSenders().find(e=>"video"===e.track?.kind);if(e?.track){const t=s.data.localMediaStreamStatus.videoEnabled;e.track.enabled=t}try{const t=(await navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0];e?await e.replaceTrack(t):r.addTrack(t)}catch(e){}s.data.localMediaStreamStatus.screenShareEnabled=!1,ps(s,pe.SCREEN_SHARE_TOGGLE,!1)}else try{const t=(await navigator.mediaDevices.getDisplayMedia({video:!0})).getVideoTracks()[0];t.onended=()=>{R(e)};let i=r.getSenders().find(e=>"video"===e.track?.kind);i?await i.replaceTrack(t):(r.addTrack(t),i=r.getSenders().find(e=>e.track===t)),s.data.localMediaStreamStatus.screenShareEnabled=!0,ps(s,pe.SCREEN_SHARE_TOGGLE,!0)}catch(e){return}o(t)}function C(e,t){const s=i(e);if(null==s||null==s.sipSession)return;const r=s.sipSession;if(r.data.isHold===t)return;const n=t??!r.data.isHold,a=r.sessionDescriptionHandlerOptionsReInvite;if(a.hold=n,r.sessionDescriptionHandlerOptionsReInvite=a,r&&r.sessionDescriptionHandler&&r.sessionDescriptionHandler.peerConnection){const e=r.sessionDescriptionHandler.peerConnection;e.getReceivers().forEach(function(e){e.track&&(e.track.enabled=n)}),e.getSenders().forEach(function(e){const t=e.track;e.track&&"audio"==e.track.kind?(1==t.IsMixedTrack&&r.data.audioSourceTrack&&"audio"==r.data.audioSourceTrack.kind&&(r.data.audioSourceTrack.enabled=n),t.enabled=n):t&&"video"==t.kind&&(t.enabled=n)})}r.data.isHold=n,o(s)}return{receiveSession:function(i){let o=i.remoteIdentity.uri.user||i.remoteIdentity.displayName;const a=new ge(e,s,r(),o);a.sipSession=i;const c=a.sipSession;c.data={},c.data.configKey=a.configKey,c.data.lineKey=a.lineKey,c.data.callDirection="inbound",c.data.terminateBy="",c.data.remoteNumber=o,c.data.username=a.username,c.data.earlyReject=!1,c.data.callType="audio",c.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},c.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!1,videoEnabled:!1},t?.features.enableVideo&&c.request.body&&c.request.body.indexOf("m=video")>-1&&(c.data.remoteMediaStreamStatus.videoEnabled=!0,c.data.callType="video");const d="video"===c.data.callType,h=c.incomingInviteRequest.message.headers;if(h["P-Asserted-Identity"]){const e=h["P-Asserted-Identity"][0].raw;if(e.includes("<sip:")){const s=e.split("<sip:");s[1].endsWith(">")&&(s[1]=s[1].slice(0,-1)),s[1].includes(`@${t?.account.domain}`)&&(o=s[1].split("@")[0])}}c.delegate={onBye:function(e){f(a,e,()=>gs(a))},onMessage:function(e){m(a,e)},onInvite:function(e){v(a,e)},onSessionDescriptionHandler:function(e,t){p(a,e,t,d)}},c.incomingInviteRequest.delegate={onCancel:function(e){l(a,e,()=>gs(a))}},n(a)},answerAudioSession:function(e){if(!c)return void alert("No audio device detected!");const s=i(e);if(null===s)return;const r=s.sipSession;if(!r||r instanceof ht)return;r.data.ringerObj&&(r.data.ringerObj.pause(),r.data.ringerObj.removeAttribute("src"),r.data.ringerObj.load(),r.data.ringerObj=null);const n=b();n&&(r.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:c,videoEnabled:!1},r.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},r.data.videoSourceDevice=null,r.data.audioSourceDevice=t?.media.audioInputDeviceId,r.data.audioOutputDevice=t?.media.audioOutputDeviceId,r.accept(n).then(function(){h(s,!1)}).catch(function(e){r.data.reasonCode=500,r.data.reasonText="Client Error",gs(s)}))},answerVideoSession:function(e,s){const r=i(e);if(!r||!t)return;const n=r.sipSession;if(!n||n instanceof ht)return;if(n.data.ringerObj&&(n.data.ringerObj.pause(),n.data.ringerObj.removeAttribute("src"),n.data.ringerObj.load(),n.data.ringerObj=null),!c)return void alert("No audio device detected!");const a=S();n.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:s??!0},n.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!0},n.data.videoSourceDevice=t.media.videoInputDeviceId,n.data.audioSourceDevice=t.media.audioInputDeviceId,n.data.audioOutputDevice=t.media.audioOutputDeviceId,n.accept(a).then(async()=>{try{await h(r,!0),n.data.localMediaStreamStatus?.videoEnabled&&await async function(e,t){const s=t?.maxRetries,i=t?.delayMs;let r=0;return new Promise((t,n)=>{const o=async()=>{if(!e?.data?.lineKey)return;const a=Q().getSessionByLineKey(e?.data?.lineKey)?.data?.videoAckReceived;return a?t():r>=s?n(new Error("ACK timeout")):(await ps(e,pe.VIDEO_TOGGLE,!0),r++,void setTimeout(o,i))};o()})}(n,{delayMs:2e3,maxRetries:10})}catch(e){}}).catch(function(e){n.data.reasonCode=500,n.data.reasonText="Client Error",gs(r)}),o(r)},makeAudioSession:$,makeVideoSession:E,toggleLocalVideoTrack:async e=>{const t=i(e);if(!t||!t.sipSession||"audio"===t.sipSession.data.callType)return;const s=t.sipSession;if(!s.data.localMediaStreamStatus||!s.data.remoteMediaStreamStatus)return;s.data.localMediaStreamStatus.screenShareEnabled&&await R(e);const r=!s.data.localMediaStreamStatus.videoEnabled;s.data.localMediaStreamStatus.videoEnabled=r;const n=s.sessionDescriptionHandler?.peerConnection;if(!n)return;const a=n.getSenders().find(e=>"video"===e.track?.kind);if(a)a.track&&(a.track.enabled=r);else if(r)try{const e=(await navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0];n.addTrack(e)}catch(e){return}await ps(s,pe.VIDEO_TOGGLE,r),o(t)},toggleShareScreen:R,rejectSession:function(e){const t=i(e);if(null==t)return;const s=t.sipSession;!s||s instanceof ht||(s.state==nt.Established?s.bye().catch(function(e){}):s.reject({statusCode:486,reasonPhrase:"Busy Here"}).catch(function(e){}),s.data.terminateBy="us",s.data.reasonCode=486,s.data.reasonText="Busy Here",gs(t))},dialByNumber:function(t,i,o){const a=Q().userAgents?.[e];if(!a||!a?.isRegistered())return void alert(`SIP userAgent for ${e} not registered`);if(!c)return void alert("No audio device detected!");const d=new ge(e,s,r(),i);"audio"===t?$(d,i,o):E(d,i,o??[]),n(d)},endSession:function(e){const t=i(e);if(null==t)return;const s=t.sipSession;if(s)switch(s.state){case nt.Initial:case nt.Establishing:s instanceof ht?(s.data.terminateBy="us",s.data.reasonCode=0,s.data.reasonText="Call Cancelled",s.cancel()):(s.reject({statusCode:486,reasonPhrase:"Busy Here"}).catch(function(e){}),s.data.terminateBy="us",s.data.reasonCode=486,s.data.reasonText="Busy Here",gs(t));break;case nt.Established:s.bye().catch(function(e){}),s.data.terminateBy="us",s.data.reasonCode=486,s.data.reasonText="Busy Here",gs(t);break;default:gs(t)}},recordSession:function(e){return{start:async function(){const t=i(e);if(!t?.sipSession)return;const s="video"===t.sipSession.data.callType;try{const e=[];let i=null;s&&(i=await navigator.mediaDevices.getDisplayMedia({video:{displaySurface:"monitor"},audio:!0}));const r=new AudioContext,n=r.createMediaStreamDestination();i?.getAudioTracks().length&&r.createMediaStreamSource(new MediaStream(i.getAudioTracks())).connect(n);const a=t.sipSession.sessionDescriptionHandler.peerConnection;a.getSenders().forEach(e=>{"audio"===e.track?.kind&&r.createMediaStreamSource(new MediaStream([e.track])).connect(n)}),a.getReceivers().forEach(e=>{"audio"===e.track?.kind&&r.createMediaStreamSource(new MediaStream([e.track])).connect(n)});const c=new MediaStream([...n.stream.getAudioTracks()]);s&&i?.getVideoTracks().length&&i?.getVideoTracks().forEach(e=>c.addTrack(e));const d=MediaRecorder.isTypeSupported((s?"video":"audio")+"/webm; codecs=vp8,opus")?(s?"video":"audio")+"/webm; codecs=vp8,opus":(s?"video":"audio")+"/webm",h=new MediaRecorder(c,{mimeType:d});h.ondataavailable=t=>{t.data.size>0&&e.push(t.data)},h.onstop=()=>{if(!t?.sipSession?.data.recordMedia)return;t.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},o(t);const i=new Blob(e,{type:d});e.length=0;const r=URL.createObjectURL(i),n=document.createElement("a");n.href=r,n.download=`recording-${s?"video":"audio"}-${Date.now()}.webm`,n.click(),URL.revokeObjectURL(r)},i?.getVideoTracks().length&&(i.getVideoTracks()[0].onended=()=>{h.stop()}),h.start(),t.sipSession.data.recordMedia={recorder:h,recording:!0,startTime:F()},o(t)}catch(e){if(!t?.sipSession?.data.recordMedia)return;t.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},o(t)}},stop:function(){const t=i(e);if(!t?.sipSession)return;const s=t?.sipSession?.data.recordMedia?.recorder;s&&(s.stop(),t.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},o(t))}}},toggleMuteSession:function(e){const t=i(e);if(null==t||null==t.sipSession)return;const s=t.sipSession;if(!s.data.localMediaStreamStatus)return;const r=!s.data.localMediaStreamStatus.soundEnabled;if(s.data.localMediaStreamStatus.soundEnabled=r,s&&s.sessionDescriptionHandler&&s.sessionDescriptionHandler.peerConnection){s.sessionDescriptionHandler.peerConnection.getSenders().forEach(function(e){if(e.track&&"audio"==e.track.kind){const t=e.track;1==t.IsMixedTrack&&s.data.audioSourceTrack&&"audio"==s.data.audioSourceTrack.kind&&(s.data.audioSourceTrack.enabled=r),t.enabled=r}})}ps(s,pe.SOUND_TOGGLE,r),o(t)},toggleHoldSession:C,makeTransferSession:function(s,r){C(s,!0),queueMicrotask(()=>{!function(s,r){const n=Q().userAgents?.[e];if(!n||!n?.isRegistered())return void alert(`SIP userAgent for ${e} not registered`);const a=String(r);if(""===a)return;const c=i(s);if(!c?.sipSession)return;const d=c.sipSession;if(!d)return;d.data.transfer||(d.data.transfer=[]);d.data.transfer.push({type:"Attended",to:r,transferTime:F(),disposition:"invite",dispositionTime:F(),accept:{complete:null,eventTime:null,disposition:""}});const h=d.data.transfer.length-1,l=navigator.mediaDevices.getSupportedConstraints(),u={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if("object"!=typeof u.sessionDescriptionHandlerOptions.constraints.audio)return;d.data.audioSourceDevice&&"default"!=d.data.audioSourceDevice&&(u.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:d.data.audioSourceDevice});l.autoGainControl&&(u.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=t?.media.autoGainControl);l.echoCancellation&&(u.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=t?.media.echoCancellation);l.noiseSuppression&&(u.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=t?.media.noiseSuppression);if(d.data.localMediaStreamStatus?.videoEnabled){u.sessionDescriptionHandlerOptions.constraints.video={};const e=u.sessionDescriptionHandlerOptions.constraints.video;d.data.videoSourceDevice&&"default"!=d.data.videoSourceDevice&&(e.deviceId={exact:d.data.videoSourceDevice}),l.frameRate&&""!==t?.media.maxFrameRate&&(e.frameRate=String(t?.media.maxFrameRate)),l.height&&""!=t?.media.videoHeight&&(e.height=String(t?.media.videoHeight)),l.aspectRatio&&""!=t?.media.videoAspectRatio&&(e.aspectRatio=String(t?.media.videoAspectRatio)),("object"==typeof u.sessionDescriptionHandlerOptions.constraints.video&&0==Object.keys(u.sessionDescriptionHandlerOptions.constraints.video)?.length||"boolean"==typeof u.sessionDescriptionHandlerOptions.constraints.video)&&(u.sessionDescriptionHandlerOptions.constraints.video=!0)}const g=ls.makeURI("sip:"+a.replace(/#/g,"%23")+"@"+t?.account.domain),p=new ht(n,g,u);p.data={},p.delegate={onBye:function(){d.data.transfer&&(d.data.transfer[h].disposition="bye",d.data.transfer[h].dispositionTime=F())},onSessionDescriptionHandler:function(e){y(c,d,e,d?.data?.localMediaStreamStatus?.videoEnabled)}},d.data.childsession=p;const f={requestDelegate:{onTrying:function(){d.data.transfer&&(d.data.transfer[h].disposition="trying",d.data.transfer[h].dispositionTime=F())},onProgress:function(){d.data.transfer&&(d.data.transfer[h].disposition="progress",d.data.transfer[h].dispositionTime=F(),d.data.transfer[h].onCancle=()=>{p.cancel().catch(function(e){}),d.data.transfer&&(d.data.transfer[h].accept.complete=!1,d.data.transfer[h].accept.disposition="cancel",d.data.transfer[h].accept.eventTime=F())})},onRedirect:function(e){},onAccept:function(){if(!d.data.transfer)return;d.data.transfer[h].disposition="accepted",d.data.transfer[h].dispositionTime=F();const e={requestDelegate:{onAccept:function(e){d.data.transfer&&(d.data.terminateBy="us",d.data.reasonCode=202,d.data.reasonText="Attended Transfer",d.data.transfer[h].accept.complete=!0,d.data.transfer[h].accept.disposition=e.message.reasonPhrase??"",d.data.transfer[h].accept.eventTime=F(),d.bye().catch(function(e){}),gs(c))},onReject:function(e){d.data.transfer&&(d.data.transfer[h].accept.complete=!1,d.data.transfer[h].accept.disposition=e.message.reasonPhrase??"",d.data.transfer[h].accept.eventTime=F())}}};d.refer(p,e).catch(function(e){})},onReject:function(e){d.data.transfer&&(d.data.transfer[h].disposition=e.message.reasonPhrase??"",d.data.transfer[h].dispositionTime=F())}}};p.invite(f).catch(function(e){}),o(c)}(s,r)})},cancelTransferSession:function(e,t){if(null==a)return;if(!a.isRegistered())return;if(""===String(t))return;const s=i(e);if(!s?.sipSession)return;const r=s.sipSession;r&&r.data.transfer&&(r.data.transfer.forEach(e=>{e.to===t&&e.onCancle?.()}),C(e,!1),o(s))},cancelSession:function(e){const t=i(e);if(null==t||null==t.sipSession)return;const s=t.sipSession;s instanceof ht&&(s.data.terminateBy="us",s.data.reasonCode=0,s.data.reasonText="Call Cancelled",s.state==nt.Initial||s.state==nt.Establishing?s.cancel():gs(t))},teardownSession:gs}};function gs(e){const{removeLine:t}=Q();if(null==e||null==e.sipSession)return;const s=e.sipSession;if(1!=s.data.teardownComplete){if(s.data.teardownComplete=!0,s.data.childsession&&s.data.childsession.dispose().then(function(){s.data.childsession=null}).catch(function(e){s.data.childsession=null}),s.data.audioSourceTrack&&"audio"==s.data.audioSourceTrack.kind&&(s.data.audioSourceTrack.stop(),s.data.audioSourceTrack=null),s.data.earlyMedia&&(s.data.earlyMedia.pause(),s.data.earlyMedia.removeAttribute("src"),s.data.earlyMedia.load(),s.data.earlyMedia=null),s.data.ringerObj&&(s.data.ringerObj.pause(),s.data.ringerObj.removeAttribute("src"),s.data.ringerObj.load(),s.data.ringerObj=null),null!==e.localSoundMeter&&(e.localSoundMeter.stop(),e.localSoundMeter=null),null!==e.remoteSoundMeter&&(e.remoteSoundMeter.stop(),e.remoteSoundMeter=null),s&&s.sessionDescriptionHandler&&s.sessionDescriptionHandler?.peerConnection){s.sessionDescriptionHandler.peerConnection.getSenders().forEach(function(e){"audio"==e?.track?.kind&&e.track.stop()})}t(e.lineKey)}}async function ps(e,t,s){if(e)try{await e.message({requestDelegate:{onAccept:()=>{},onReject:()=>{}},requestOptions:{body:{contentType:"text/plain",content:JSON.stringify({type:t,value:s}),contentDisposition:"render"}}})}catch(e){}}class fs{ua;configs;username;configKey;constructor(e,t){this.configs=e,this.username=e.account.username,this.configKey=t,Q().setConfig(this.configKey,e)}async init(){await this.detectDevices(),await this.createUserAgent()}async detectDevices(){const e=await V(this.configKey);Q().setSipStore({devicesInfo:e})}async createUserAgent(){const e=new ls({uri:ls.makeURI(`sip:${this.username}@${this.configs.account.domain}`),transportOptions:{server:`wss://${this.configs.account.wssServer}:${this.configs.account.webSocketPort}${this.configs.account.serverPath}`,traceSip:!1,connectionTimeout:this.configs.registration.transportConnectionTimeout},authorizationUsername:this.username,authorizationPassword:this.configs.account.password,delegate:{onInvite:us({configKey:this.configKey}).receiveSession,onMessage:()=>{}}});e.isRegistered=()=>e&&e.registerer&&e.registerer.state===lt.Registered,e.sessions=e._sessions,e.registrationCompleted=!1,e.registering=!1,e.transport.reconnectionAttempts=this.configs.registration.transportReconnectionAttempts||0,e.transport.attemptingReconnection=!1,e.BlfSubs=[],e.lastVoicemailCount=0,e.transport.onConnect=()=>ie(this.configKey,e),e.transport.onDisconnect=t=>{t?re(0,this.configKey,e):function(e,t){t.isReRegister=!1;const{userAgents:s}=Q();X({userAgents:{...s,[e]:t}})}(this.configKey,e)},e.registerer=new yt(e,{logConfiguration:!1,expires:this.configs.registration.registerExpires,extraHeaders:[],extraContactHeaderParams:[],refreshFrequency:75}),e.registerer.stateChange.addListener(t=>{switch(t){case lt.Registered:!function(e,t){t.registrationCompleted=!0,t.isReRegister,t.registering=!1,t.isReRegister=!0;const{userAgents:s,statuses:i}=Q();X({userAgents:{...s,[e]:t},statuses:{...i,[e]:"connected"}})}(this.configKey,e);break;case lt.Unregistered:!function(e,t){t.isReRegister=!1;const{userAgents:s,statuses:i}=Q();X({userAgents:{...s,[e]:t},statuses:{...i,[e]:"disconnected"}})}(this.configKey,e)}}),await e.start().catch(e=>re(0,this.configKey)),this.ua=e,Q().setUserAgent(this.configKey,e)}getUserAgent(){return this.ua}async stop(){this.ua&&await this.ua.stop()}}exports.AudioStream=({lineKey:e,...s})=>"local"===s.type?t.jsx("audio",{...s,id:`line-${e}-localAudio`}):t.jsx("div",{...s,id:`line-${e}-remoteAudios`}),exports.SipManager=class{instances=new Map;useWatchSessionData=le;useWatchConfigs=ue;updateConfig(e,t){const{instance:s}=this.instances.get(e);this.instances.set(e,{config:t,instance:s}),Q().setConfig(e,t)}async add(e){const t=e?.key??e.account.username,s=L(r,{...e,key:t});if(this.instances.has(t)&&G(this.instances.get(t)?.config,s))return;if(this.instances.has(t))return(e=>{const t=Q().configs?.[e.key]?.media;if(t&&!G(t,e.media)){const t=e.key,s=Q().lines[t]??{};Object.values(s).forEach(t=>{t.sipSession?.data.started&&(t.sipSession?.initiateLocalMediaStreams({videoEnabled:t.sipSession.data.localMediaStreamStatus?.videoEnabled,configs:e}),t.sipSession?.initiateRemoteMediaStreams({videoEnabled:t.sipSession.data.localMediaStreamStatus?.videoEnabled,configs:e}))})}})(s),void this.updateConfig(t,s);const i=new fs(s,t);await i.init(),this.instances.set(t,{config:s,instance:i})}getSessionMethodsBy(e){const t=Q();let s="";return"configKey"in e&&e.configKey?s=e.configKey:"lineKey"in e&&e.lineKey&&(s=t.getConfigKeyByLineKey(e.lineKey)??""),us({configKey:s})}getAccountBy(e){const t=Q();let s="";return"configKey"in e&&e.configKey?s=e.configKey:"lineKey"in e&&e.lineKey&&(s=t.getConfigKeyByLineKey(e.lineKey)??""),{status:t.statuses?.[s]??"disconnected",lines:Object.values(t.lines[s]??[]),watch:oe({configKey:s})}}has(e){return this.instances.has(e)}reconnect(e){ne(e,void 0,!0)}async stop(e){const t=this.instances.get(e)?.instance;t&&(await t.stop(),this.instances.delete(e),Q().remove(e))}async stopAll(){for(const[e,{instance:t}]of this.instances)await t.stop();Q().removeAll(),this.instances.clear()}getLineBy(e){const t=Q();if("lineKey"in e&&e?.lineKey)return t.findLineByLineKey(e.lineKey);if("remoteNumber"in e&&e?.remoteNumber&&"configKey"in e&&e?.configKey){const s=t.getLineKeyByRemoteNumber_ConfigKey(e);return s?t.findLineByLineKey(s):null}return null}getSessionBy(e){const t=Q();if("lineKey"in e&&e?.lineKey)return t.getSessionByLineKey(e.lineKey);if("remoteNumber"in e&&e?.remoteNumber&&"configKey"in e&&e?.configKey){const s=t.getLineKeyByRemoteNumber_ConfigKey(e);return s?t.getSessionByLineKey(s):null}return null}getConfigKeyBy(e){const t=Q();return"lineKey"in e&&e?.lineKey?t.getConfigKeyByLineKey(e.lineKey):"remoteNumber"in e&&e?.remoteNumber&&"configKey"in e&&e?.configKey?t.getConfigKeyByRemoteNumber_ConfigKey(e):null}},exports.VideoStream=({lineKey:e,...s})=>"local"===s.type?t.jsx("video",{...s,id:`line-${e}-${s.type}Video`,muted:"local"===s.type}):t.jsx("div",{...s,id:`line-${e}-remoteVideos`});
|