react-sip-kit 0.2.3 → 0.3.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,10 +1 @@
1
- import e,{createContext as t,useMemo as s,useEffect as i,useCallback as r,useContext as n}from"react";function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var a,c={exports:{}},d={};var l,h,u={};
2
- /**
3
- * @license React
4
- * react-jsx-runtime.development.js
5
- *
6
- * Copyright (c) Meta Platforms, Inc. and affiliates.
7
- *
8
- * This source code is licensed under the MIT license found in the
9
- * LICENSE file in the root directory of this source tree.
10
- */function g(){return l||(l=1,"production"!==process.env.NODE_ENV&&function(){function t(e){if(null==e)return null;if("function"==typeof e)return e.$$typeof===I?null:e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case p:return"Fragment";case m:return"Profiler";case f:return"StrictMode";case y:return"Suspense";case S:return"SuspenseList";case R:return"Activity"}if("object"==typeof e)switch("number"==typeof e.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case g:return"Portal";case w:return(e.displayName||"Context")+".Provider";case v:return(e._context.displayName||"Context")+".Consumer";case b:var s=e.render;return(e=e.displayName)||(e=""!==(e=s.displayName||s.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case T:return null!==(s=e.displayName||null)?s:t(e.type)||"Memo";case $:s=e._payload,e=e._init;try{return t(e(s))}catch(e){}}return null}function s(e){return""+e}function i(e){try{s(e);var t=!1}catch(e){t=!0}if(t){var i=(t=console).error,r="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",r),s(e)}}function r(e){if(e===p)return"<>";if("object"==typeof e&&null!==e&&e.$$typeof===$)return"<...>";try{var s=t(e);return s?"<"+s+">":"<...>"}catch(e){return"<...>"}}function n(){return Error("react-stack-top-frame")}function o(){var e=t(this.type);return A[e]||(A[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(e=this.props.ref)?e:null}function a(e,s,r,n,a,l,u,g){var p,f=s.children;if(void 0!==f)if(n)if(D(f)){for(n=0;n<f.length;n++)c(f[n]);Object.freeze&&Object.freeze(f)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else c(f);if(E.call(s,"key")){f=t(e);var m=Object.keys(s).filter(function(e){return"key"!==e});n=0<m.length?"{key: someKey, "+m.join(": ..., ")+": ...}":"{key: someKey}",x[f+n]||(m=0<m.length?"{"+m.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',n,f,m,f),x[f+n]=!0)}if(f=null,void 0!==r&&(i(r),f=""+r),function(e){if(E.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(s)&&(i(s.key),f=""+s.key),"key"in s)for(var v in r={},s)"key"!==v&&(r[v]=s[v]);else r=s;return f&&function(e,t){function s(){d||(d=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}s.isReactWarning=!0,Object.defineProperty(e,"key",{get:s,configurable:!0})}(r,"function"==typeof e?e.displayName||e.name||"Unknown":e),function(e,t,s,i,r,n,a,c){return s=n.ref,e={$$typeof:h,type:e,key:t,props:n,_owner:r},null!==(void 0!==s?s:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:o}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:c}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(e,f,l,0,null===(p=C.A)?null:p.getOwner(),r,u,g)}function c(e){"object"==typeof e&&null!==e&&e.$$typeof===h&&e._store&&(e._store.validated=1)}var d,l=e,h=Symbol.for("react.transitional.element"),g=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),m=Symbol.for("react.profiler"),v=Symbol.for("react.consumer"),w=Symbol.for("react.context"),b=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),S=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),R=Symbol.for("react.activity"),I=Symbol.for("react.client.reference"),C=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,E=Object.prototype.hasOwnProperty,D=Array.isArray,k=console.createTask?console.createTask:function(){return null},A={},H=(l={"react-stack-bottom-frame":function(e){return e()}})["react-stack-bottom-frame"].bind(l,n)(),_=k(r(n)),x={};u.Fragment=p,u.jsx=function(e,t,s,i,n){var o=1e4>C.recentlyCreatedOwnerStacks++;return a(e,t,s,!1,0,n,o?Error("react-stack-top-frame"):H,o?k(r(e)):_)},u.jsxs=function(e,t,s,i,n){var o=1e4>C.recentlyCreatedOwnerStacks++;return a(e,t,s,!0,0,n,o?Error("react-stack-top-frame"):H,o?k(r(e)):_)}}()),u}var p=(h||(h=1,"production"===process.env.NODE_ENV?c.exports=function(){if(a)return d;a=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function s(t,s,i){var r=null;if(void 0!==i&&(r=""+i),void 0!==s.key&&(r=""+s.key),"key"in s)for(var n in i={},s)"key"!==n&&(i[n]=s[n]);else i=s;return s=i.ref,{$$typeof:e,type:t,key:r,ref:void 0!==s?s:null,props:i}}return d.Fragment=t,d.jsx=s,d.jsxs=s,d}():c.exports=g()),c.exports);const f={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:1500,startVideoFullScreen:!1},policy:{autoAnswerPolicy:"manual",doNotDisturbPolicy:"off",callWaitingPolicy:"on",callRecordingPolicy:"manual",intercomPolicy:"off"},registration:{transportConnectionTimeout:5e3,transportReconnectionAttempts:3,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:30},storage:{streamBuffer:1024,maxDataStoreDays:30,posterJpegQuality:80},recording:{videoResampleSize:"1280x720",recordingVideoSize:"1280x720",recordingVideoFps:30,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}};class m{lineNumber;displayNumber;metaData;sipSession;localSoundMeter;remoteSoundMeter;constructor(e,t,s){this.lineNumber=e,this.displayNumber=t,this.metaData=s,this.sipSession=null,this.localSoundMeter=null,this.remoteSoundMeter=null}}class v{static instance;audioBlobs;constructor(e){this.audioBlobs={Alert:e?.Alert??{file:"Alert.mp3",url:"./src/assets/media/Alert.mp3"},Ringtone:e?.Ringtone??{file:"Ringtone_1.mp3",url:"./src/assets/media/Ringtone.mp3"},CallWaiting:e?.CallWaiting??{file:"Tone_CallWaiting.mp3",url:"./src/assets/media/CallWaiting.mp3"}}}static getInstance(e){return v.instance||(v.instance=new v(e)),v.instance}getAudios(){return this.audioBlobs}}const w=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},b=e=>e;const y=t=>{const s=(e=>e?w(e):w)(t),i=t=>function(t,s=b){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},S=(T=(e,t)=>({configs:f,userAgent:void 0,devicesInfo:{hasVideoDevice:!1,hasAudioDevice:!1,hasSpeakerDevice:!1,audioInputDevices:[],videoInputDevices:[],speakerDevices:[]},lines:[],audioBlobs:v.getInstance().getAudios(),setSipStore:t=>e(e=>({...e,...t})),setUserAgent:t=>e(e=>({...e,userAgent:t})),addLine:t=>e(e=>({...e,lines:[...e.lines,t]})),updateLine:s=>{const i=t().lines.map(e=>e.lineNumber===s.lineNumber?{...s}:e);e(e=>({...e,lines:i}))},removeLine:s=>{console.log("removeLine");const i=t().lines.filter(e=>e.lineNumber!==s);e(e=>({...e,lines:i}))},findLineByNumber:e=>t().lines.find(t=>t.lineNumber===e)??null,getNewLineNumber:()=>t().lines.length+1,getSessions:()=>{const{userAgent:e}=t();return null==e?(console.warn("userAgent is null"),null):0==e.isRegistered()?(console.warn("userAgent is not registered"),null):e.sessions??null},countIdSessions:e=>{let s=0;return t().userAgent?.sessions?(Object.values(t().userAgent?.sessions??{}).forEach(t=>{e!==t.id&&s++}),s):s}}))?y(T):y;var T;const $=e=>{S.setState(t=>({...t,...e}))},R=()=>S.getState().userAgent,I=()=>S.getState().configs;var C,E={exports:{}};var D=(C||(C=1,function(e){var t=function(){function e(e,t){return null!=t&&e instanceof t}var t,s,i;try{t=Map}catch(e){t=function(){}}try{s=Set}catch(e){s=function(){}}try{i=Promise}catch(e){i=function(){}}function r(n,a,c,d,l){"object"==typeof a&&(c=a.depth,d=a.prototype,l=a.includeNonEnumerable,a=a.circular);var h=[],u=[],g="undefined"!=typeof Buffer;return void 0===a&&(a=!0),void 0===c&&(c=1/0),function n(c,p){if(null===c)return null;if(0===p)return c;var f,m;if("object"!=typeof c)return c;if(e(c,t))f=new t;else if(e(c,s))f=new s;else if(e(c,i))f=new i(function(e,t){c.then(function(t){e(n(t,p-1))},function(e){t(n(e,p-1))})});else if(r.__isArray(c))f=[];else if(r.__isRegExp(c))f=new RegExp(c.source,o(c)),c.lastIndex&&(f.lastIndex=c.lastIndex);else if(r.__isDate(c))f=new Date(c.getTime());else{if(g&&Buffer.isBuffer(c))return f=Buffer.allocUnsafe?Buffer.allocUnsafe(c.length):new Buffer(c.length),c.copy(f),f;e(c,Error)?f=Object.create(c):void 0===d?(m=Object.getPrototypeOf(c),f=Object.create(m)):(f=Object.create(d),m=d)}if(a){var v=h.indexOf(c);if(-1!=v)return u[v];h.push(c),u.push(f)}for(var w in e(c,t)&&c.forEach(function(e,t){var s=n(t,p-1),i=n(e,p-1);f.set(s,i)}),e(c,s)&&c.forEach(function(e){var t=n(e,p-1);f.add(t)}),c){var b;m&&(b=Object.getOwnPropertyDescriptor(m,w)),b&&null==b.set||(f[w]=n(c[w],p-1))}if(Object.getOwnPropertySymbols){var y=Object.getOwnPropertySymbols(c);for(w=0;w<y.length;w++){var S=y[w];(!($=Object.getOwnPropertyDescriptor(c,S))||$.enumerable||l)&&(f[S]=n(c[S],p-1),$.enumerable||Object.defineProperty(f,S,{enumerable:!1}))}}if(l){var T=Object.getOwnPropertyNames(c);for(w=0;w<T.length;w++){var $,R=T[w];($=Object.getOwnPropertyDescriptor(c,R))&&$.enumerable||(f[R]=n(c[R],p-1),Object.defineProperty(f,R,{enumerable:!1}))}}return f}(n,c)}function n(e){return Object.prototype.toString.call(e)}function o(e){var t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),t}return r.clonePrototype=function(e){if(null===e)return null;var t=function(){};return t.prototype=e,new t},r.__objToStr=n,r.__isDate=function(e){return"object"==typeof e&&"[object Date]"===n(e)},r.__isArray=function(e){return"object"==typeof e&&"[object Array]"===n(e)},r.__isRegExp=function(e){return"object"==typeof e&&"[object RegExp]"===n(e)},r.__getRegExpFlags=o,r}();e.exports&&(e.exports=t)}(E)),E.exports),k=o(D);function A(e){const t=k(e);t.registrationCompleted=!0,t.isReRegister?(t.registering=!1,console.log("ReRegistered!")):(console.log("Registered!"),t.registering=!1),t.isReRegister=!0,$({userAgent:t})}function H(e){const t=k(e);t.isReRegister=!1,$({userAgent:t})}function _(e){const t=e??k(R());null!=t&&1!=t.registering&&(t.isRegistered()||(console.log("Sending Registration..."),t.registering=!0,t.registerer.register({requestDelegate:{onReject(e){!function(){const e=R(),t=k(e);t&&(t.registering=!1),$({userAgent:t})}(e.message.reasonPhrase,e.message.statusCode)}}}),e||$({userAgent:t})))}function x(e){console.log("Connected to Web Socket!");const t=e??k(R());t&&(t.isReRegister=!1,t.transport.attemptingReconnection=!1,t.transport.ReconnectionAttempts=I().registration.transportReconnectionAttempts,t.transport.attemptingReconnection&&t.registering?window.setTimeout(function(){_(t)},500):console.warn("onTransportConnected: Register() called, but attemptingReconnection is true or registering is true"),e||$({userAgent:t}))}function P(e,t){console.warn("WebSocket Connection Failed:",e);const s=t??k(R());if(s){s.isReRegister=!1,console.log("Unregister...");try{s.registerer.unregister()}catch(e){}q(s),t||$({userAgent:s})}}function O(e){console.log("Disconnected from Web Socket!");const t=k(e);t.isReRegister=!1,$({userAgent:t})}function q(e){const t=S.getState().configs?.registration?.transportReconnectionTimeout,s=e??k(R());s&&(s.registering=!1,s.transport&&s.transport.isConnected()?x(s):(console.log("Reconnect Transport..."),setTimeout(function(){if(console.log("ReConnecting to WebSocket...",{timeout:1e3*t}),s.transport&&s.transport.isConnected())return console.log("Transport Already Connected..."),void x(s);s.transport.attemptingReconnection=!0,s.reconnect().catch(function(e){s.transport.attemptingReconnection=!1,console.warn("Failed to reconnect",e),q(s)})},1e3*I().registration.transportReconnectionAttempts),console.log("Waiting to Re-connect...",I().registration.transportReconnectionAttempts,"Attempt remaining",s.transport.ReconnectionAttempts),s.transport.ReconnectionAttempts=s.transport.ReconnectionAttempts-1,e||$({userAgent:s})))}var M,N={exports:{}};var j,F=(M||(M=1,N.exports=function(){var e=1e3,t=6e4,s=36e5,i="millisecond",r="second",n="minute",o="hour",a="day",c="week",d="month",l="quarter",h="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:h,w:c,d:a,D:u,h:o,m:n,s:r,ms:i,Q:l}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},b="en",y={};y[b]=m;var S="$isDayjsObject",T=function(e){return e instanceof C||!(!e||!e[S])},$=function e(t,s,i){var r;if(!t)return b;if("string"==typeof t){var n=t.toLowerCase();y[n]&&(r=n),s&&(y[n]=s,r=n);var o=t.split("-");if(!r&&o.length>1)return e(o[0])}else{var a=t.name;y[a]=t,r=a}return!i&&r&&(b=r),r||!i&&b},R=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)},I=w;I.l=$,I.i=T,I.w=function(e,t){return R(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(I.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 I},v.isValid=function(){return!(this.$d.toString()===g)},v.isSame=function(e,t){var s=R(e);return this.startOf(t)<=s&&s<=this.endOf(t)},v.isAfter=function(e,t){return R(e)<this.startOf(t)},v.isBefore=function(e,t){return this.endOf(t)<R(e)},v.$g=function(e,t,s){return I.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=!!I.u(t)||t,l=I.p(e),g=function(e,t){var r=I.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 I.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(l){case h: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,y=(f<b?f+7:f)-b;return g(i?v-y:v+(6-y),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=I.p(e),l="set"+(this.$u?"UTC":""),g=(s={},s[a]=l+"Date",s[u]=l+"Date",s[d]=l+"Month",s[h]=l+"FullYear",s[o]=l+"Hours",s[n]=l+"Minutes",s[r]=l+"Seconds",s[i]=l+"Milliseconds",s)[c],p=c===a?this.$D+(t-this.$W):t;if(c===d||c===h){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[I.p(e)]()},v.add=function(i,l){var u,g=this;i=Number(i);var p=I.p(l),f=function(e){var t=R(g);return I.w(t.date(t.date()+Math.round(e*i)),g)};if(p===d)return this.set(d,this.$M+i);if(p===h)return this.set(h,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 I.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=I.z(this),n=this.$H,o=this.$m,a=this.$M,c=s.weekdays,d=s.months,l=s.meridiem,h=function(e,s,r,n){return e&&(e[s]||e(t,i))||r[s].slice(0,n)},u=function(e){return I.s(n%12||12,e,"0")},p=l||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 I.s(t.$y,4,"0");case"M":return a+1;case"MM":return I.s(a+1,2,"0");case"MMM":return h(s.monthsShort,a,d,3);case"MMMM":return h(d,a);case"D":return t.$D;case"DD":return I.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return h(s.weekdaysMin,t.$W,c,2);case"ddd":return h(s.weekdaysShort,t.$W,c,3);case"dddd":return c[t.$W];case"H":return String(n);case"HH":return I.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 I.s(o,2,"0");case"s":return String(t.$s);case"ss":return I.s(t.$s,2,"0");case"SSS":return I.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=I.p(u),v=R(i),w=(v.utcOffset()-this.utcOffset())*t,b=this-v,y=function(){return I.m(f,v)};switch(m){case h:p=y()/12;break;case d:p=y();break;case l:p=y()/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:I.a(p)},v.daysInMonth=function(){return this.endOf(d).$D},v.$locale=function(){return y[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 I.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}(),E=C.prototype;return R.prototype=E,[["$ms",i],["$s",r],["$m",n],["$H",o],["$W",a],["$M",d],["$y",h],["$D",u]].forEach(function(e){E[e[1]]=function(t){return this.$g(t,e[0],e[1])}}),R.extend=function(e,t){return e.$i||(e(t,C,R),e.$i=!0),R},R.locale=$,R.isDayjs=T,R.unix=function(e){return R(1e3*e)},R.en=y[b],R.Ls=y,R.p={},R}()),N.exports),U=o(F),L={exports:{}};var B,V,G,Y,W,K,J,Z,z,X,Q,ee,te,se,ie,re,ne,oe,ae,ce,de=(j||(j=1,L.exports=(J=/\[([^\]]+)]|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,X=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,Q={years:Z=31536e6,months:z=2628e6,days:K=864e5,hours:W=36e5,minutes:Y=6e4,seconds:G=1e3,milliseconds:1,weeks:6048e5},ee=function(e){return e instanceof ae},te=function(e,t,s){return new ae(e,s,t.$l)},se=function(e){return V.p(e)+"s"},ie=function(e){return e<0},re=function(e){return ie(e)?Math.ceil(e):Math.floor(e)},ne=function(e){return Math.abs(e)},oe=function(e,t){return e?ie(e)?{negative:!0,format:""+ne(e)+t}:{negative:!1,format:""+e+t}:{negative:!1,format:""}},ae=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 te(e*Q[se(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[se(t)]=e[t]}),this.calMilliseconds(),this;if("string"==typeof e){var r=e.match(X);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)*Q[s]},0)},t.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=re(e/Z),e%=Z,this.$d.months=re(e/z),e%=z,this.$d.days=re(e/K),e%=K,this.$d.hours=re(e/W),e%=W,this.$d.minutes=re(e/Y),e%=Y,this.$d.seconds=re(e/G),e%=G,this.$d.milliseconds=e},t.toISOString=function(){var e=oe(this.$d.years,"Y"),t=oe(this.$d.months,"M"),s=+this.$d.days||0;this.$d.weeks&&(s+=7*this.$d.weeks);var i=oe(s,"D"),r=oe(this.$d.hours,"H"),n=oe(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=oe(o,"S"),c=e.negative||t.negative||i.negative||r.negative||n.negative||a.negative,d=r.format||n.format||a.format?"T":"",l=(c?"-":"")+"P"+e.format+t.format+i.format+d+r.format+n.format+a.format;return"P"===l||"-P"===l?"P0D":l},t.toJSON=function(){return this.toISOString()},t.format=function(e){var t=e||"YYYY-MM-DDTHH:mm:ss",s={Y:this.$d.years,YY:V.s(this.$d.years,2,"0"),YYYY:V.s(this.$d.years,4,"0"),M:this.$d.months,MM:V.s(this.$d.months,2,"0"),D:this.$d.days,DD:V.s(this.$d.days,2,"0"),H:this.$d.hours,HH:V.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:V.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:V.s(this.$d.seconds,2,"0"),SSS:V.s(this.$d.milliseconds,3,"0")};return t.replace(J,function(e,t){return t||String(s[e])})},t.as=function(e){return this.$ms/Q[se(e)]},t.get=function(e){var t=this.$ms,s=se(e);return"milliseconds"===s?t%=1e3:t="weeks"===s?re(t/Q[s]):this.$d[s],t||0},t.add=function(e,t,s){var i;return i=t?e*Q[se(t)]:ee(e)?e.$ms:te(e,this).$ms,te(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 te(this.$ms,this)},t.humanize=function(e){return B().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}(),ce=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){B=s,V=s().$utils(),s.duration=function(e,t){var i=s.locale();return te(e,{$l:i},t)},s.isDuration=ee;var i=t.prototype.add,r=t.prototype.subtract;t.prototype.add=function(e,t){return ee(e)?ce(this,e,1):i.bind(this)(e,t)},t.prototype.subtract=function(e,t){return ee(e)?ce(this,e,-1):r.bind(this)(e,t)}})),L.exports),le=o(de);U.extend(le);var he,ue={exports:{}};var ge=(he||(he=1,ue.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 l=o.format;o.format=function(e){var t=e||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return l.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 h=o.toDate;o.toDate=function(e){return"s"===e&&this.$offset?n(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():h.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)}}}()),ue.exports),pe=o(ge);U.extend(le),U.extend(pe);const fe=U;function me(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]=me(r,i):void 0!==i&&(s[e]=i)}return s}function ve(){return fe().utc().format("YYYY-MM-DD HH:mm:ss UTC")}const we=()=>{const e=S(e=>e.updateLine),t=S(e=>e.audioBlobs),{media:{maxVideoBandwidth:s,audioOutputDeviceId:i}}=S(e=>e.configs);function r(t,s){console.log("onTrackAddedEvent");const r=t.sipSession;if(!r)return;const n=r.sessionDescriptionHandler.peerConnection,o=new MediaStream,a=new MediaStream;if(n.getTransceivers().forEach(e=>{const t=e.receiver;t.track&&("audio"===t.track.kind&&(console.log("Adding Remote Audio Track"),o.addTrack(t.track)),s&&"video"===t.track.kind&&e.mid&&(console.log("Adding Remote Video Track",t.track.readyState),t.track.mid=e.mid,a.addTrack(t.track)))}),o.getAudioTracks().length>0){const e=document.getElementById(`line-${t.lineNumber}-remoteAudio`);e.setAttribute("id",`line-${t.lineNumber}-remoteAudio`),e.srcObject=o,e.onloadedmetadata=()=>{void 0!==e.sinkId&&e.setSinkId(i).then(()=>console.log("sinkId applied:",i)).catch(e=>console.warn("Error using setSinkId:",e)),e.play()}}if(s&&a.getVideoTracks().length>0){const e=`line-${t.lineNumber}-remoteVideos`;let s=document.getElementById(e);if(!s)return;s.innerHTML="",a.getVideoTracks().forEach((e,i)=>{const r=new MediaStream;r.trackId=e.id,r.mid=e.mid,r.addTrack(e);const n=document.createElement("video");n.id=`line-${t.lineNumber}-video-${i}`,n.srcObject=r,n.autoplay=!0,n.playsInline=!0,n.muted=!0,n.className="video-element",n.onloadedmetadata=()=>{n.play().catch(e=>{console.error("Error playing video:",e)})},s.appendChild(n)})}else console.warn("No Video Tracks Found");e(t)}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,0===i?(n.data.reasonText="Call Cancelled",console.log("Call canceled by remote party before answer!")):(n.data.reasonText="Call completed elsewhere",console.log("Call completed elsewhere before answer")),n.dispose().catch(function(e){console.log("Failed to dispose the cancel dialog",e)}),s?.())},onInviteAccepted:function(t,i,r){console.log("onInviteAccepted");const n=t.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=fe.utc();if(n.data.startTime=o,n.isOnHold=!1,n.data.started=!0,i){const e=new MediaStream,i=n.sessionDescriptionHandler.peerConnection;i.getSenders().forEach(function(t){t.track&&"video"===t.track.kind&&e.addTrack(t.track)});const r=document.getElementById(`line-${t.lineNumber}-localVideo`);console.log("onInviteAccepted",{localVideo:r,localVideoStream:e}),r&&(r.srcObject=e,r.onloadedmetadata=function(e){console.log("onInviteAccepted","play"),r.play()}),s>-1&&i.getSenders().forEach(function(e){if(e.track&&"video"===e.track.kind){const t=e.getParameters();t.encodings||(t.encodings=[{}]),t.encodings[0].maxBitrate=1e3*s,console.log("Applying limit for Bandwidth to: ",s+"kb per second"),e.setParameters(t).catch(function(e){console.warn("Cannot apply Bandwidth Limits",e)})}})}e(t)},onInviteTrying:function(e,t){},onInviteProgress:function(s,r){console.log("Call Progress:",r.message.statusCode);const n=s.sipSession;if(n){if(180===r.message.statusCode){let e=t.Ringtone;if(console.log({soundFile:e}),console.log("Audio:",e.url),n.data.earlyMedia)console.log("Early Media already playing");else{const t=new Audio(e.url);t.preload="auto",t.loop=!0,t.oncanplaythrough=function(e){void 0!==t.sinkId&&"default"!==i&&t.setSinkId(i).then(function(){console.log("Set sinkId to:",i)}).catch(function(e){console.warn("Failed not apply setSinkId.",e)}),t.play().then(function(){}).catch(function(e){console.warn("Unable to play audio file.",e)})},n.data.earlyMedia=t}}else r.message.statusCode;e(s)}},onInviteRejected:function(e,t,s){console.log("INVITE Rejected:",t.message.reasonPhrase);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){console.log("onInviteRedirected",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})}console.log("videoChannelNames:",i.data.videoChannelNames)}},onSessionReceivedMessage:function(e,t){const s=t.request.headers["Content-Type"].length>=1?t.request.headers["Content-Type"][0].parsed:"Unknown";if(s.indexOf("application/x-asterisk-confbridge-event")>-1){const s=JSON.parse(t.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"==s.type?console.log("ConfbridgeStart!"):"ConfbridgeWelcome"==s.type?(console.log("Welcome to the Asterisk Conference"),console.log("Bridge ID:",s.bridge.id),console.log("Bridge Name:",s.bridge.name),console.log("Created at:",s.bridge.creationtime),console.log("Video Mode:",s.bridge.video_mode),i.data.confBridgeChannels=s.channels,i.data.confBridgeChannels.forEach(function(e){console.log(e.caller.name,"Is in the conference. Muted:",e.muted,"Admin:",e.admin)})):"ConfbridgeJoin"==s.type?s.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:ve()}),console.log(e.caller.name,"Joined the conference. Muted: ",e.muted))}):"ConfbridgeLeave"==s.type?s.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t,s){t.id==e.id&&(i.data.confBridgeChannels?.splice(s,1),console.log(e.caller.name,"Left the conference"),i.data.confBridgeEvents?.push({event:e.caller.name+" ("+e.caller.number+") left the conference",eventTime:ve()}))})}):"ConfbridgeTalking"===s.type||("ConfbridgeMute"==s.type?s.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(console.log(t.caller.name,"is now muted"),t.muted=!0)})}):"ConfbridgeUnmute"===s.type?s.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(console.log(t.caller.name,"is now unmuted"),t.muted=!1)})}):"ConfbridgeEnd"==s.type?console.log("The Asterisk Conference has ended, bye!"):console.warn("Unknown Asterisk Conference Event:",s.type,s)),t.accept()}else s.indexOf("application/x-myphone-confbridge-chat")>-1?(console.log("x-myphone-confbridge-chat",t),t.accept()):(console.warn("Unknown message type"),t.reject())},onSessionDescriptionHandlerCreated:function(e,t,s,i){t?t.peerConnection?(console.log(222,"onSessionDescriptionHandlerCreated",t,{peerConnection:t.peerConnection}),t.peerConnection.ontrack=function(t){console.log(222,{event:t}),r(e,i)}):console.warn("onSessionDescriptionHandler fired without a peerConnection"):console.warn("onSessionDescriptionHandler fired without a sessionDescriptionHandler")},onTrackAddedEvent:r,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&&(console.log("Adding Remote Audio Track"),n.addTrack(e.track)),i&&"video"===e.track.kind&&(console.log("Adding Remote Video Track",e.track.readyState),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(){console.log("sinkId applied: "+t.data.audioOutputDevice)}).catch(function(e){console.warn("Error using setSinkId: ",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=>{console.error("Error playing video:",e)})}})}else console.warn("No Video Tracks Found")}:console.warn("onSessionDescriptionHandler fired without a peerConnection"):console.warn("onSessionDescriptionHandler fired without a sessionDescriptionHandler")}}},be=()=>{const{audioInputDevices:e,videoInputDevices:t}=S(e=>e.devicesInfo),{media:{audioInputDeviceId:s,videoInputDeviceId:i,autoGainControl:r,maxFrameRate:n,noiseSuppression:o,videoAspectRatio:a,videoHeight:c,echoCancellation:d},registration:{inviteExtraHeaders:l}}=S(e=>e.configs),h=()=>navigator.mediaDevices.getSupportedConstraints(),u={answerAudioSpdOptions:function({option:t}={}){console.log({defaultOption:t});const i=t??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:{exact:"default"}},video:!1}}},n=h(),a=s;if("object"==typeof i.sessionDescriptionHandlerOptions.constraints.audio){if("default"!=a){let t=(t=>{let s=!1;for(let i=0;i<e.length;++i)if(t==e[i].deviceId){s=!0;break}return s})(a);t?i.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:a}:(console.warn("The audio device you used before is no longer available, default settings applied."),localStorage.setItem("AudioSrcId","default"))}return n.autoGainControl&&(i.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=r),n.echoCancellation&&(i.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=d),n.noiseSuppression&&(i.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=o),i}},makeAudioSpdOptions:function({extraHeaders:e}){let t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if(t.extraHeaders=e||[],u.answerAudioSpdOptions({option:t}),l&&""!==l&&"{}"!==l)try{for(const[e,s]of Object.entries(JSON.parse(l)))""==s||t?.extraHeaders?.push(e+": "+s)}catch(e){}return t},answerVideoSpdOptions:function({option:e}={}){const s=e??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}},r=h();u.answerAudioSpdOptions({option:s});const o=i;if("object"==typeof s.sessionDescriptionHandlerOptions.constraints.video){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.video.deviceId={exact:o}:(console.warn("The video device you used before is no longer available, default settings applied."),localStorage.setItem("VideoSrcId","default"))}return r.frameRate&&n&&(s.sessionDescriptionHandlerOptions.constraints.video.frameRate=String(n)),r.height&&c&&(s.sessionDescriptionHandlerOptions.constraints.video.height=String(c)),r.aspectRatio&&a&&(s.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=String(a)),s}},makeVideoSpdOptions:function({extraHeaders:e}){const t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}};if(u.answerVideoSpdOptions({option:t}),t.extraHeaders=e||[],l&&""!==l&&"{}"!==l)try{for(const[e,s]of Object.entries(JSON.parse(l)))""==s||t.extraHeaders.push(e+": "+s)}catch(e){}return t}};return u};class ye extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class Se extends ye{constructor(e){super(e||"Unsupported content type.")}}class Te extends ye{constructor(e){super(e||"Request pending.")}}class $e extends ye{constructor(e){super(e||"Unspecified session description handler error.")}}class Re extends ye{constructor(){super("The session has terminated.")}}class Ie extends ye{constructor(e){super(e||"An error occurred during state transition.")}}class Ce{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class Ee{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 De{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class ke{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 Ae{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 He{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 _e extends He{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 _e(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 xe extends He{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 xe(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 Pe(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 Oe(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class qe 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,qe.prototype):this.__proto__=qe.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,qe)}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=Oe("",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+" | "+Oe("",r.column-1," ")+Oe("",a-r.column,"^")}else t+="\n at "+n}return t}}const Me=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 xe(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 xe(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 xe(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 _e(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 _e(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 _e(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 _e(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 _e(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 _e(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#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),T(';.." &"'),T("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),T('%%$;2/&#0#*;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!7œ0)*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ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 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/&#0#*;j&&&#/"!&,)'),T('%$;j/&#0#*;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$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$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("%$;!/&#0#*;!&&&#/' 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("%$;!/&#0#*;!&&&#/' 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("%$;!/&#0#*;!&&&#/' 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("%$;!/&#0#*;!&&&#/' 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/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;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("%$;!/&#0#*;!&&&#/' 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("%$;!/&#0#*;!&&&#/' 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 l=[{line:1,column:1}];let h,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 y(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=l[t];if(i)return i;for(s=t-1;!l[s];)s--;for(i=l[s],i={line:i.line,column:i.column};s<t;)10===e.charCodeAt(s)?(i.line++,i.column=1):i.column++,s++;return l[t]=i,i}function y(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 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={},h=function t(i){const r=a[i];let n=0;const l=[];let h=r.length;const u=[],g=[];let f;for(;;){for(;n<h;)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(h),l.push(n+3+r[n+1]+r[n+2]),g[g.length-1]?(h=n+3+r[n+1],n+=3):(h=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 14:u.push(h),l.push(n+3+r[n+1]+r[n+2]),g[g.length-1]===s?(h=n+3+r[n+1],n+=3):(h=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 15:u.push(h),l.push(n+3+r[n+1]+r[n+2]),g[g.length-1]!==s?(h=n+3+r[n+1],n+=3):(h=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 16:g[g.length-1]!==s?(u.push(h),l.push(n),h=n+2+r[n+1],n+=2):n+=2+r[n+1];break;case 17:u.push(h),l.push(n+3+r[n+1]+r[n+2]),e.length>c?(h=n+3+r[n+1],n+=3):(h=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 18:u.push(h),l.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length)===o[r[n+1]]?(h=n+4+r[n+2],n+=4):(h=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 19:u.push(h),l.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length).toLowerCase()===o[r[n+1]]?(h=n+4+r[n+2],n+=4):(h=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 20:u.push(h),l.push(n+4+r[n+2]+r[n+3]),o[r[n+1]].test(e.charAt(c))?(h=n+4+r[n+2],n+=4):(h=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;h=u.pop(),n=l.pop()}return g[0]}(n),h!==s&&c===e.length)return h;throw h!==s&&c<e.length&&S({type:"end"}),$=g,R=u<e.length?e.charAt(u):null,I=u<e.length?y(u,u+1):y(u,u),new qe(qe.buildMessage($,R),$,R,I);var $,R,I};var Ne;!function(e){e.parse=function(e,t){const s={startRule:t};try{Me(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}}(Ne=Ne||(Ne={}));const je={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 Fe(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function Ue(e){return je[e]||""}function Le(){return Fe(10)}function Be(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 Ve(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class Ge{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=Be(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[Be(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[Be(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[Be(e)]}parseHeader(e,t=0){if(e=Be(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=Ne.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[Be(e)]=[{raw:t}]}toString(){return this.data}}class Ye extends Ge{constructor(){super()}}class We extends Ge{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:Le(),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+Fe(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 _e(e,t,i)}getHeader(e){const t=this.headers[Be(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[Be(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[Be(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[Be(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: "+Ve(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: "+Ve(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 Je(e){return"application/sdp"===e?"session":"render"}function Ze(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Je(s),contentType:s,content:t}}function ze(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function Xe(e){let t,s,i;if(e instanceof Ye&&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 We&&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(ze(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=Je(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var Qe,et;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(Qe=Qe||(Qe={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(et=et||(et={}));const tt=500,st={T1:tt,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 it extends ye{constructor(e){super(e||"Transaction state error.")}}var rt;!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"}(rt=rt||(rt={}));const nt=[rt.ACK,rt.BYE,rt.CANCEL,rt.INFO,rt.INVITE,rt.MESSAGE,rt.NOTIFY,rt.OPTIONS,rt.PRACK,rt.REFER,rt.REGISTER,rt.SUBSCRIBE];class ot{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 at{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 ct{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof _e))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 dt,lt;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(dt=dt||(dt={}));class ht{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=dt.Initial,this.delegate=t.delegate,this._stateEventEmitter=new ke,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 dt.Initial:case dt.Establishing:break;case dt.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case dt.Terminating:case dt.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 dt.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 dt.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 dt.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case dt.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 dt.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!==dt.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!==dt.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new Te("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=Xe(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(dt.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===dt.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(dt.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!==dt.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(dt.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!==dt.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(dt.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: "+nt.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!==dt.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!==dt.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 ht&&!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 Qe.Initial:case Qe.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case Qe.AckWait:return this.stateTransition(dt.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(dt.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(dt.Terminated),i(r)}}});case Qe.Confirmed:{const i=s.bye(e,t);return this.stateTransition(dt.Terminated),Promise.resolve(i)}case Qe.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!==dt.Established&&this.state!==dt.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 Ce(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case et.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(dt.Terminated),Promise.resolve()}case et.Stable:{const i=Xe(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(dt.Terminated)}):Promise.resolve()}case et.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(dt.Terminated),Promise.resolve()}case et.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(dt.Terminated),Promise.resolve()}case et.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===dt.Established){if(this.delegate&&this.delegate.onBye){const t=new Ee(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(dt.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===dt.Established)if(this.delegate&&this.delegate.onInfo){const t=new Ae(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!==dt.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=Ne.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===et.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!==dt.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(dt.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===dt.Established)if(this.delegate&&this.delegate.onMessage){const t=new ot(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===dt.Established){if(this.onNotify){const t=new at(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new at(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===dt.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!==dt.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 ct(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=Xe(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 et.Initial:return this.getOffer(e);case et.HaveLocalOffer:return Promise.resolve(void 0);case et.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 et.Stable:return this.state!==dt.Established?Promise.resolve(void 0):this.getOffer(e);case et.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=>Ze(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 Se)}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 Se)}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=>Ze(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 dt.Initial:e!==dt.Establishing&&e!==dt.Established&&e!==dt.Terminating&&e!==dt.Terminated&&t();break;case dt.Establishing:e!==dt.Established&&e!==dt.Terminating&&e!==dt.Terminated&&t();break;case dt.Established:e!==dt.Terminating&&e!==dt.Terminated&&t();break;case dt.Terminating:e!==dt.Terminated&&t();break;case dt.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===dt.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=Ue(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 xe)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"}(lt=lt||(lt={}));const ut={"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 gt extends ht{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(dt.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===dt.Initial&&(t.reject({statusCode:487}),this.stateTransition(dt.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=Ne.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 dt.Initial:case dt.Establishing:return this.reject().then(()=>super.dispose());case dt.Established:case dt.Terminating:case dt.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!==dt.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(dt.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(dt.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==dt.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===lt.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!==dt.Initial&&this.state!==dt.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:Ue(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?Ze(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(dt.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===dt.Initial||this.state===dt.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new De(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(dt.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=Xe(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 et.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case et.Stable:return this.setAnswer(t,s).then(()=>{});case et.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case et.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case et.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 Se?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof $e?this.logger.error("A session description handler occurred while sending response"):e instanceof Re?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof it&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===dt.Initial||this.state===dt.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(dt.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(dt.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?Ze(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 Re)).catch(e=>o(e)))},64*st.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n})}catch(e){return this.waitingForPrack=!1,void o(e)}u=setTimeout(l,h*=2)};let h=st.T1,u=setTimeout(l,h)}).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 Re),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class pt extends ht{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=Le(),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?Ne.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?Ne.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===lt.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===lt.Required&&d.push("Require: replaces"),i.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(rt.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 dt.Initial:case dt.Establishing:return this.cancel().then(()=>super.dispose());case dt.Established:case dt.Terminating:case dt.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!==dt.Initial&&this.state!==dt.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(dt.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="'+(Ue(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(dt.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==dt.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(dt.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(dt.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==dt.Terminated&&this.stateTransition(dt.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(dt.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 ht))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!==dt.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=Ne.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 et.Initial:case et.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(dt.Terminated),Promise.reject(new Error("Bad Media Description"));case et.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(dt.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(dt.Terminated),t})}case et.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(dt.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(dt.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(dt.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(dt.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(dt.Terminated),t})}case et.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!==dt.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=Ne.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 et.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 et.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case et.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(dt.Terminated),e})}case et.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(dt.Terminated),e})}return Promise.resolve();case et.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===dt.Establishing||this.state===dt.Terminating?this.stateTransition(dt.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===dt.Establishing||this.state===dt.Terminating?this.stateTransition(dt.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===dt.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var ft,mt,vt,wt,bt,yt,St;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(ft=ft||(ft={}));class Tt{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=ft.Initial,this._waiting=!1,this._stateEventEmitter=new ke,this._waitingEventEmitter=new ke,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},Tt.defaultOptions()),{registrar:s}),Tt.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===Ne.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(rt.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||Tt.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||Tt.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:Tt.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new xe("sip","anonymous","anonymous.invalid"),refreshFrequency:Tt.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===ft.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===ft.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 Te("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&&Pe(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(Pe(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=Ne.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=Ne.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===ft.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==ft.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new Te("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===ft.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!==ft.Registered&&this.stateTransition(ft.Registered)}unregistered(){this.clearTimers(),this._state!==ft.Unregistered&&this.stateTransition(ft.Unregistered)}terminated(){this.clearTimers(),this._state!==ft.Terminated&&this.stateTransition(ft.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ft.Initial:e!==ft.Registered&&e!==ft.Unregistered&&e!==ft.Terminated&&t();break;case ft.Registered:e!==ft.Unregistered&&e!==ft.Terminated&&t();break;case ft.Unregistered:e!==ft.Registered&&e!==ft.Terminated&&t();break;case ft.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===ft.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===ft.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)}}Tt.defaultExpires=600,Tt.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(mt=mt||(mt={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(vt=vt||(vt={})),function(e){e.Started="Started",e.Stopped="Stopped"}(wt=wt||(wt={}));class $t{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=$t.hexChars,s=$t.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($t.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,$t._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,$t._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,$t._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($t.buffer32Identity.subarray(r),r),t>55&&($t._md5cycle(this._state,i),i.set($t.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 $t._md5cycle(this._state,i),e?this._state:$t._hex(this._state)}}function Rt(e){return $t.hashStr(e)}$t.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),$t.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),$t.hexChars="0123456789abcdef",$t.hexOut=[],$t.onePassHasher=new $t,"5d41402abc4b2a76b9719d911017c592"!==$t.hashStr("hello")&&console.error("Md5 self test failed.");class It{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=Fe(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=Rt(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=Rt(this.method+":"+this.uri),this.response=Rt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=Rt(this.method+":"+this.uri+":"+Rt(e||"")),this.response=Rt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=Rt(this.method+":"+this.uri),this.response=Rt(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"}(bt=bt||(bt={}));class Ct{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(bt.error,e)}warn(e){this.genericLog(bt.warn,e)}log(e){this.genericLog(bt.log,e)}debug(e){this.genericLog(bt.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 Et{constructor(){this.builtinEnabled=!0,this._level=bt.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:bt.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 Ct(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new Ct(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(bt[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 bt.error:console.error(i);break;case bt.warn:console.warn(i);break;case bt.log:console.log(i);break;case bt.debug:console.debug(i)}}}function Dt(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:Ue(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=Le()),d+=";tag="+e}d+=s;let l="";t.supported&&(l="Supported: "+t.supported.join(", ")+s);let h="";t.userAgent&&(h="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+=l,r+=h,r+=u,t.body?(r+="Content-Type: "+t.body.contentType+s,r+="Content-Length: "+Ve(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=Ne.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=Ne.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 We&&(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=Ne.parse(o,"Request_Response");let c,d;if(-1!==a){for(a.status_code?(c=new We,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new Ye,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+'"')}}(yt=yt||(yt={}));class kt extends ye{constructor(e){super(e||"Unspecified transport error.")}}class At{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 kt)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new kt(e.message):new kt,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 Ht extends At{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"}(St=St||(St={}));class _t extends Ht{constructor(e,t,s){super(e,t,s,St.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 St.Proceeding:if(e.method===rt.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case St.Accepted:if(e.method===rt.INVITE)return;break;case St.Completed:if(e.method===rt.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===rt.ACK)return void this.stateTransition(St.Confirmed);break;case St.Confirmed:case St.Terminated:if(e.method===rt.INVITE||e.method===rt.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 St.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(St.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(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case St.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case St.Completed:case St.Confirmed:case St.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===St.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 St.Proceeding:t();break;case St.Accepted:case St.Completed:this.state!==St.Proceeding&&t();break;case St.Confirmed:this.state!==St.Completed&&t();break;case St.Terminated:this.state!==St.Accepted&&this.state!==St.Completed&&this.state!==St.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===St.Accepted&&(this.L=setTimeout(()=>this.timerL(),st.TIMER_L)),e===St.Completed&&(this.H=setTimeout(()=>this.timerH(),st.TIMER_H)),e===St.Confirmed&&(this.I=setTimeout(()=>this.timerI(),st.TIMER_I)),e===St.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.")})},st.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===St.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(St.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(St.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===St.Accepted&&this.stateTransition(St.Terminated)}}class xt extends At{constructor(e,t,s,i,r){super(t,s,xt.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 Pt extends xt{constructor(e,t,s){super(e,t,s,St.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),st.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 St.Trying:if(t>=100&&t<=199)return this.stateTransition(St.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(St.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(St.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Completed:case St.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(St.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 St.Trying:s();break;case St.Proceeding:this.state!==St.Trying&&s();break;case St.Completed:this.state!==St.Trying&&this.state!==St.Proceeding&&s();break;case St.Terminated:this.state!==St.Trying&&this.state!==St.Proceeding&&this.state!==St.Completed&&(t||s());break;default:s()}e===St.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),st.TIMER_K)),e===St.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==St.Trying&&this.state!==St.Proceeding||(this.onRequestTimeout(),this.stateTransition(St.Terminated))}timerK(){this.state===St.Completed&&this.stateTransition(St.Terminated)}}class Ot{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 _e))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,l=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:l,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 _e))throw new Error("Contact not instance of NameAddrHeader.");const n=r.uri,o=e.cseq,a=e.callId,c=t,d=e.fromTag,l=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:l,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!==rt.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,l=t&&t.extraHeaders,h=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,s,{callId:o,cseq:a,fromTag:n,toTag:i,routeSet:d},l,h)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===rt.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class qt extends xt{constructor(e,t,s){super(e,t,s,St.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),st.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 St.Calling:if(t>=100&&t<=199)return this.stateTransition(St.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(St.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(St.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.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(St.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(St.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.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 St.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case St.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(St.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 St.Calling:s();break;case St.Proceeding:this.state!==St.Calling&&s();break;case St.Accepted:case St.Completed:this.state!==St.Calling&&this.state!==St.Proceeding&&s();break;case St.Terminated:this.state!==St.Calling&&this.state!==St.Accepted&&this.state!==St.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),St.Proceeding,e===St.Completed&&(this.D=setTimeout(()=>this.timerD(),st.TIMER_D)),e===St.Accepted&&(this.M=setTimeout(()=>this.timerM(),st.TIMER_M)),e===St.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===St.Calling&&(this.onRequestTimeout(),this.stateTransition(St.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===St.Completed&&this.stateTransition(St.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===St.Accepted&&this.stateTransition(St.Terminated)}}class Mt{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(rt.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===St.Proceeding?new Mt(Pt,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===St.Proceeding&&new Mt(Pt,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 We;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 We;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===St.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 Nt extends Mt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(rt.BYE,s);super(Pt,e.userAgentCore,i,t),e.dispose()}}class jt extends Ht{constructor(e,t,s){super(e,t,s,St.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 St.Trying:break;case St.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 St.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 St.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 St.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(St.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case St.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case St.Completed:return;case St.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(St.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 St.Trying:s();break;case St.Proceeding:this.state!==St.Trying&&s();break;case St.Completed:this.state!==St.Trying&&this.state!==St.Proceeding&&s();break;case St.Terminated:this.state!==St.Proceeding&&this.state!==St.Completed&&(t||s());break;default:s()}e===St.Completed&&(this.J=setTimeout(()=>this.timerJ(),st.TIMER_J)),e===St.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===St.Completed&&this.stateTransition(St.Terminated)}}class Ft{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:Le(),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 it(`${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 it(`${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 it(`${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 it(`${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 it(`${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 _t)return this.transaction.state===St.Proceeding||this.transaction.state===St.Accepted;if(this.transaction instanceof jt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof _t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof jt)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof _t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof jt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof _t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof jt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof _t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof jt)return this.transaction.state===St.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=Dt(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===St.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 Ut extends Ft{constructor(e,t,s){super(jt,e.userAgentCore,t,s)}}class Lt extends Mt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(rt.INFO,s);super(Pt,e.userAgentCore,i,t)}}class Bt extends Ft{constructor(e,t,s){super(jt,e.userAgentCore,t,s)}}class Vt extends Mt{constructor(e,t,s){super(Pt,e,t,s)}}class Gt extends Ft{constructor(e,t,s){super(jt,e,t,s)}}class Yt extends Mt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(rt.NOTIFY,s);super(Pt,e.userAgentCore,i,t)}}class Wt extends Ft{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(jt,i,t,s)}}class Kt extends Mt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(rt.PRACK,s);super(Pt,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class Jt extends Ft{constructor(e,t,s){super(jt,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 Zt extends Mt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(rt.INVITE,s);super(qt,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 zt extends Ft{constructor(e,t,s){super(_t,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 Xt extends Mt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(rt.REFER,s);super(Pt,e.userAgentCore,i,t)}}class Qt extends Ft{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(jt,i,t,s)}}class es extends Ot{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=et.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof _t&&(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=et.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?Qe.Early:this.ackWait?Qe.AckWait:this._signalingState===et.Closed?Qe.Terminated:Qe.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 qt))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof qt))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(rt.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 _t){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==St.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 Nt(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 Lt(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 Zt(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(rt.MESSAGE,t);return new Vt(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 Yt(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 Xt(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==rt.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===rt.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!==et.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===rt.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case rt.BYE:{const t=new Ut(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case rt.INFO:{const t=new Bt(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case rt.INVITE:{const t=new zt(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case rt.MESSAGE:{const t=new Gt(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case rt.NOTIFY:{const t=new Wt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case rt.PRACK:{const t=new Jt(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case rt.REFER:{const t=new Qt(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 qt)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!==et.HaveLocalOffer&&this.signalingState!==et.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=et.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=Xe(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===et.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Ye)switch(this._signalingState){case et.Initial:case et.Stable:this._signalingState=et.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case et.HaveLocalOffer:this._signalingState=et.Stable,this._answer=t;break;case et.HaveRemoteOffer:case et.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof We)switch(this._signalingState){case et.Initial:case et.Stable:this._signalingState=et.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case et.HaveLocalOffer:this._signalingState=et.Stable,this._answer=t;break;case et.HaveRemoteOffer:case et.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Ke)switch(this._signalingState){case et.Initial:case et.Stable:this._signalingState=et.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case et.HaveLocalOffer:break;case et.HaveRemoteOffer:this._signalingState=et.Stable,this._answer=t;break;case et.Closed:break;default:throw new Error("Unexpected signaling state.")}if(ze(e))switch(this._signalingState){case et.Initial:case et.Stable:this._signalingState=et.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case et.HaveLocalOffer:break;case et.HaveRemoteOffer:this._signalingState=et.Stable,this._answer=t;break;case et.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof _t){const e=this.initialTransaction;let t=st.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,st.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===St.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 _t){const e=this.reinviteUserAgentServer.transaction;let t=st.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,st.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===St.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class ts extends Mt{constructor(e,t,s){super(qt,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===St.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=Ot.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof qt))throw new Error("Transaction not instance of InviteClientTransaction.");s=new es(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!==et.Initial&&s.signalingState!==et.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=Ot.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 qt))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 qt))throw new Error("Transaction not instance of InviteClientTransaction.");s=new es(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==et.Initial&&s.signalingState!==et.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 ss extends Ft{constructor(e,t,s){super(_t,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new it(`${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 _t))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Ot.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new es(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: "+nt.toString();if(!e.body)if(this.confirmedDialog.signalingState===et.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===et.Initial||this.confirmedDialog.signalingState===et.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!==et.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new it(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof _t))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Ot.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new es(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!==et.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 is extends Mt{constructor(e,t,s){super(Pt,e,t,s)}}class rs extends Mt{constructor(e,t,s){super(Pt,e,t,s)}}class ns extends Ft{constructor(e,t,s){super(jt,e,t,s),this.core=e}}class os extends Mt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(rt.SUBSCRIBE,s);super(Pt,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 as extends Ot{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 _e))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===rt.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: "+nt.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!==mt.Pending&&this.subscriptionState!==mt.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 os(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(),st.TIMER_N)),i}terminate(){this.stateTransition(mt.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+nt.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(mt.Pending,r);break;case"active":this.stateTransition(mt.Active,r);break;case"terminated":this.stateTransition(mt.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new Wt(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 mt.Initial:case mt.NotifyWait:return void s();case mt.Pending:if(this.subscriptionState!==mt.NotifyWait&&this.subscriptionState!==mt.Pending)return void s();break;case mt.Active:case mt.Terminated:if(this.subscriptionState!==mt.NotifyWait&&this.subscriptionState!==mt.Pending&&this.subscriptionState!==mt.Active)return void s();break;default:return void s()}e===mt.Pending&&t&&(this.subscriptionExpires=t),e===mt.Active&&t&&(this.subscriptionExpires=t),e===mt.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==mt.Terminated&&(this.stateTransition(mt.Terminated),this.onTerminated())}}class cs extends Mt{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(Pt,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=mt.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=mt.Pending;break;case"active":this.subscriptionState=mt.Active;break;case"terminated":this.subscriptionState=mt.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==mt.Terminated){const t=as.initialDialogStateForSubscription(this.message,e.message);this.dialog=new as(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(),st.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 ds extends Ft{constructor(e,t,s){super(jt,e,t,s),this.core=e}}const ls=["application/sdp","application/dtmf-relay"];class hs{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 ts(this,e,t)}message(e,t){return new Vt(this,e,t)}publish(e,t){return new is(this,e,t)}register(e,t){return new rs(this,e,t)}subscribe(e,t){return new cs(this,e,t)}request(e,t){return new Mt(Pt,this,e,t)}makeOutgoingRequestMessage(e,t,s,i,r,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,d=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===rt.REGISTER&&h.push("path","gruu"),e===rt.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");const u={callIdPrefix:a,forceRport:d,fromDisplayName:c,hackViaTcp:l,optionTags:h,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=Dt(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===rt.ACK&&s&&s.transaction.state===St.Accepted&&s instanceof ss?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==rt.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof _t&&s.transaction.state===St.Proceeding&&s instanceof ss&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!nt.includes(e.method)){const t="Allow: "+nt.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!==rt.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==rt.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===rt.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 Wt(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===rt.OPTIONS){const t="Allow: "+nt.toString(),s="Accept: "+ls.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==rt.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case rt.ACK:break;case rt.BYE:this.replyStateless(e,{statusCode:481});break;case rt.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case rt.INFO:this.replyStateless(e,{statusCode:405});break;case rt.INVITE:{const t=new ss(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case rt.MESSAGE:{const t=new Gt(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case rt.NOTIFY:{const t=new Wt(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case rt.OPTIONS:{const t="Allow: "+nt.toString(),s="Accept: "+ls.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case rt.REFER:{const t=new Qt(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case rt.REGISTER:{const t=new ns(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case rt.SUBSCRIBE:{const t=new ds(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 us{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),us.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),us.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),us.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),us.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),us.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),us.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),us.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 gs(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 us(r,e,i)}}class ps{constructor(e,t){if(this._state=vt.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new ke,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({},ps.defaultOptions),t);const s=this.configuration.server,i=Ne.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===vt.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case vt.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(vt.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case vt.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(vt.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case vt.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(vt.Connecting)}catch(e){if(e instanceof Ie)return Promise.reject(e);throw e}break;case vt.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(vt.Connecting)}catch(e){if(e instanceof Ie)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(vt.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 vt.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(vt.Disconnecting)}catch(e){if(e instanceof Ie)return Promise.reject(e);throw e}break;case vt.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(vt.Disconnecting)}catch(e){if(e instanceof Ie)return Promise.reject(e);throw e}break;case vt.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(vt.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case vt.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(vt.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!==vt.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(vt.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===vt.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===vt.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(vt.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 Ie("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 vt.Connecting:e!==vt.Connected&&e!==vt.Disconnecting&&e!==vt.Disconnected&&s();break;case vt.Connected:e!==vt.Disconnecting&&e!==vt.Disconnected&&s();break;case vt.Disconnecting:e!==vt.Connecting&&e!==vt.Disconnected&&s();break;case vt.Disconnected:e!==vt.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===vt.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===vt.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===vt.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===vt.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===vt.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===vt.Connected?r():n(t||new Error("Connect aborted."))}if(i===vt.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===vt.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}}ps.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class fs{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=wt.Stopped,this._stateEventEmitter=new ke,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},fs.defaultOptions()),{sipjsId:Fe(5)}),{uri:new xe("sip","anonymous."+Fe(6),"anonymous.invalid")}),{viaHost:Fe(12)+".invalid"}),fs.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 Et,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=bt.error;break;case"warn":this.loggerFactory.level=bt.warn;break;case"log":this.loggerFactory.level=bt.log;break;case"debug":this.loggerFactory.level=bt.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:fs.newUUID(),-1===Ne.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return Ne.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:gs(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:lt.Unsupported,sipExtensionReplaces:lt.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:ps,transportOptions:{},uri:new xe("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===wt.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===wt.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(wt.Started),this.transport.connect())}async stop(){if(this.state===wt.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(wt.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(wt.Stopped)}_makeInviter(e,t){return new pt(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:Fe(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new xe("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}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===lt.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===lt.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>ut[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 It(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new hs(s,{onInvite:e=>{var t;const s=new gt(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!==lt.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 ot(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new at(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!==wt.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==wt.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=yt.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===wt.Stopped&&t instanceof Ye)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 Ye){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=Ve(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof We){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=Ve(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 Ye)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof We))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 wt.Started:e!==wt.Stopped&&s();break;case wt.Stopped:e!==wt.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 ms=t(void 0),vs=({children:e,configs:t})=>{const n=S(),{userAgent:o,devicesInfo:{hasAudioDevice:a,hasSpeakerDevice:c,hasVideoDevice:d,audioInputDevices:l,videoInputDevices:h,speakerDevices:u},setSipStore:g}=n,v=s(()=>me(f,t),[t]),w=(()=>{const e=S(e=>e.configs),t=S(e=>e.findLineByNumber),s=S(e=>e.getNewLineNumber),i=S(e=>e.addLine),r=S(e=>e.removeLine),n=S(e=>e.updateLine),o=S(e=>e.countIdSessions),a=S(e=>e.userAgent),c=S(e=>e.audioBlobs),{hasAudioDevice:d,hasVideoDevice:l}=S(e=>e.devicesInfo),{onInviteAccepted:h,onInviteCancel:u,onInviteProgress:g,onInviteRedirected:p,onInviteRejected:f,onInviteTrying:v,onSessionDescriptionHandlerCreated:w,onSessionReceivedBye:b,onSessionReceivedMessage:y,onSessionReinvited:T,onTransferSessionDescriptionHandlerCreated:$}=we(),{answerAudioSpdOptions:R,makeAudioSpdOptions:I,answerVideoSpdOptions:C,makeVideoSpdOptions:E}=be();function D(t,s,i){if(console.log(222,{lineObj:t,dialledNumber:s,extraHeaders:i}),!a)return;if(!a.isRegistered())return;if(null===t)return;if(!d)return void console.error("lang.alert_no_microphone");console.log("makeAudioSession");const r=I({extraHeaders:i});if(!r)return;let n=fe.utc();console.log("INVITE (audio): "+s+"@"+e.account.domain);const o=fs.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);t.sipSession=new pt(a,o,r),t.sipSession.data={},t.sipSession.data.line=t.lineNumber,t.sipSession.data.metaData=t.metaData,t.sipSession.data.callDirection="outbound",t.sipSession.data.dialledNumber=s,t.sipSession.data.callstart=n.format("YYYY-MM-DD HH:mm:ss UTC"),t.sipSession.data.videoSourceDevice=null,t.sipSession.data.audioSourceDevice=e.media.audioInputDeviceId,t.sipSession.data.audioOutputDevice=e.media.audioOutputDeviceId,t.sipSession.data.terminateBy="them",t.sipSession.data.withVideo=!1,t.sipSession.data.earlyReject=!1,t.sipSession.isOnHold=!1,t.sipSession.delegate={onBye:function(e){b(t,e,()=>_(t))},onMessage:function(e){y(t,e)},onInvite:function(e){T(t,e)},onSessionDescriptionHandler:function(e,s){console.log("Session Description Handler created:",{sdh:e}),w(t,e,s,!1)}};const c={requestDelegate:{onTrying:function(e){console.log("makeAudioSession 1"),v(t,e)},onProgress:function(e){console.log("makeAudioSession 2"),g(t,e)},onRedirect:function(e){console.log("makeAudioSession 3"),p(t,e)},onAccept:function(e){console.log("makeAudioSession 4"),h(t,!1,e)},onReject:function(e){console.log("makeAudioSession 5"),f(t,e,()=>_(t))}}};t.sipSession.invite(c).catch(function(e){console.warn("Failed to send INVITE:",e)})}function k(t,s,i){if(null==a)return;if(!a.isRegistered())return;if(null==t)return;if(!d)return void alert("lang.alert_no_microphone");if(0==l)return console.warn("No video devices (webcam) found, switching to audio call."),void D(t,s);const r=E({extraHeaders:i});if(!r)return;const n=fe.utc();console.log("INVITE (video): "+s+"@"+e.account.domain);const o=fs.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);console.log("video",{spdOptions:r}),t.sipSession=new pt(a,o,r),t.sipSession.data={},t.sipSession.data.line=t.lineNumber,t.sipSession.data.metaData=t?.metaData,t.sipSession.data.callDirection="outbound",t.sipSession.data.dialledNumber=s,t.sipSession.data.callstart=n.format("YYYY-MM-DD HH:mm:ss UTC"),t.sipSession.data.videoSourceDevice=e.media.videoInputDeviceId,t.sipSession.data.audioSourceDevice=e.media.audioInputDeviceId,t.sipSession.data.audioOutputDevice=e.media.audioOutputDeviceId,t.sipSession.data.terminateBy="them",t.sipSession.data.withVideo=!0,t.sipSession.data.earlyReject=!1,t.sipSession.isOnHold=!1,t.sipSession.delegate={onBye:function(e){b(t,e,()=>_(t))},onMessage:function(e){y(t,e)},onInvite:function(e){T(t,e)},onSessionDescriptionHandler:function(e,s){w(t,e,s,!0)}};const c={requestDelegate:{onTrying:function(e){v(t,e)},onProgress:function(e){g(t,e)},onRedirect:function(e){p(t,e)},onAccept:function(e){h(t,!0,e)},onReject:function(e){f(t,e,()=>_(t))}}};t.sipSession.invite(c).catch(function(e){console.warn("Failed to send INVITE:",e)})}function A(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;if(1==i.isOnHold)return void console.log("Call is already on hold:",e);console.log("Putting Call on hold:",e),i.isOnHold=!0;const r=i.sessionDescriptionHandlerOptionsReInvite;r.hold=!0,i.sessionDescriptionHandlerOptionsReInvite=r;const o={requestDelegate:{onAccept:function(){if(i&&i.sessionDescriptionHandler&&i.sessionDescriptionHandler.peerConnection){const e=i.sessionDescriptionHandler.peerConnection;e.getReceivers().forEach(function(e){e.track&&(e.track.enabled=!1)}),e.getSenders().forEach(function(e){const t=e.track;e.track&&"audio"==e.track.kind?(1==t.IsMixedTrack&&i.data.audioSourceTrack&&"audio"==i.data.audioSourceTrack.kind&&(console.log("Muting Mixed Audio Track : "+i.data.audioSourceTrack.label),i.data.audioSourceTrack.enabled=!1),console.log("Muting Audio Track : "+t.label),t.enabled=!1):t&&"video"==t.kind&&(t.enabled=!1)})}i.isOnHold=!0,console.log("Call is is on hold:",e),i.data.hold||(i.data.hold=[]),i.data.hold.push({event:"hold",eventTime:ve()}),i.data.isHold=!0},onReject:function(){i.isOnHold=!1,console.warn("Failed to put the call on hold:",e)}}};i.invite(o).catch(function(e){i.isOnHold=!1,console.warn("Error attempting to put the call on hold:",e)}),n(s)}function H(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;if(0==i.isOnHold)return void console.log("Call is already off hold:",e);console.log("Taking call off hold:",e),i.isOnHold=!1;const r=i.sessionDescriptionHandlerOptionsReInvite;r.hold=!1,i.sessionDescriptionHandlerOptionsReInvite=r;const o={requestDelegate:{onAccept:function(){if(i&&i.sessionDescriptionHandler&&i.sessionDescriptionHandler.peerConnection){const e=i.sessionDescriptionHandler.peerConnection;e.getReceivers().forEach(function(e){e.track&&(e.track.enabled=!0)}),e.getSenders().forEach(function(e){const t=e.track;t&&"audio"==t.kind?(1==t.IsMixedTrack&&i.data.audioSourceTrack&&"audio"==i.data.audioSourceTrack.kind&&(console.log("Unmuting Mixed Audio Track : "+i.data.audioSourceTrack.label),i.data.audioSourceTrack.enabled=!0),console.log("Unmuting Audio Track : "+t.label),t.enabled=!0):t&&"video"==t.kind&&(t.enabled=!0)})}i.isOnHold=!1,console.log("Call is off hold:",e),i.data.hold||(i.data.hold=[]),i.data.hold.push({event:"unhold",eventTime:ve()}),i.data.isHold=!1},onReject:function(){i.isOnHold=!0,console.warn("Failed to put the call on hold",e)}}};i.invite(o).catch(function(e){i.isOnHold=!0,console.warn("Error attempting to take to call off hold",e)}),n(s)}function _(e){if(null==e||null==e.sipSession)return;const t=e.sipSession;1!=t.data.teardownComplete&&(t.data.teardownComplete=!0,t.data.childsession&&t.data.childsession.dispose().then(function(){t.data.childsession=null}).catch(function(e){console.error("teardownSession",{error:e}),t.data.childsession=null}),t.data.audioSourceTrack&&"audio"==t.data.audioSourceTrack.kind&&(t.data.audioSourceTrack.stop(),t.data.audioSourceTrack=null),t.data.earlyMedia&&(t.data.earlyMedia.pause(),t.data.earlyMedia.removeAttribute("src"),t.data.earlyMedia.load(),t.data.earlyMedia=null),t.data.ringerObj&&(t.data.ringerObj.pause(),t.data.ringerObj.removeAttribute("src"),t.data.ringerObj.load(),t.data.ringerObj=null),null!==e.localSoundMeter&&(e.localSoundMeter.stop(),e.localSoundMeter=null),null!==e.remoteSoundMeter&&(e.remoteSoundMeter.stop(),e.remoteSoundMeter=null),t&&t.sessionDescriptionHandler&&t.sessionDescriptionHandler?.peerConnection&&t.sessionDescriptionHandler.peerConnection.getSenders().forEach(function(e){"audio"==e?.track?.kind&&e.track.stop()}),"inbound"==t.data.callDirection&&(t.data.earlyReject||"them"==t.data.terminateBy&&null==t.data.startTime&&t.data.reasonCode),r(e.lineNumber))}return{receiveCall:function(t){console.log("receiveCall",{session:t});const r=t.remoteIdentity.displayName||t.remoteIdentity.uri.user||"";let n=t.remoteIdentity.uri.user??"";console.log(`Incoming call from: ${r}`);const a=fe.utc(),d=new m(s(),r,t.data.metaData??{});d.sipSession=t,d.sipSession.data={},d.sipSession.data.line=d.lineNumber,d.sipSession.data.callDirection="inbound",d.sipSession.data.terminateBy="",d.sipSession.data.src=n,d.sipSession.data.metaData=d?.metaData,d.sipSession.data.callstart=a.format("YYYY-MM-DD HH:mm:ss UTC"),d.sipSession.data.earlyReject=!1,d.sipSession.data.withVideo=!1,e.features.enableVideo&&d.sipSession.request.body&&d.sipSession.request.body.indexOf("m=video")>-1&&(d.sipSession.data.withVideo=!0);const l=t.incomingInviteRequest.message.headers;if(l["P-Asserted-Identity"]){const t=l["P-Asserted-Identity"][0].raw;if(t.includes("<sip:")){const s=t.split("<sip:");s[1].endsWith(">")&&(s[1]=s[1].slice(0,-1)),s[1].includes(`@${e.account.domain}`)&&(n=s[1].split("@")[0],console.log("Using P-Asserted-Identity:",n))}}d.sipSession.delegate={onBye:function(e){b(d,e,()=>_(d))},onMessage:function(e){y(d,e)},onInvite:function(e){T(d,e)},onSessionDescriptionHandler:function(e,s){w(d,e,s,t.data.withVideo)}},d.sipSession.incomingInviteRequest.delegate={onCancel:function(e){console.log("onInviteCancel"),u(d,e,()=>_(d))}};const h=o(t.id);if(e.features.enableRingtone)if(h>=1){console.log("Audio:",c.CallWaiting.url);const t=new Audio(c.CallWaiting.url);t.preload="auto",t.loop=!1,t.oncanplaythrough=function(){void 0!==t.sinkId&&"default"!=e.media.ringerOutputDeviceId&&t.setSinkId(e.media.ringerOutputDeviceId).then(function(){console.log("Set sinkId to:",e.media.ringerOutputDeviceId)}).catch(function(e){console.warn("Failed not apply setSinkId.",e)}),t.play().then(function(){}).catch(function(e){console.warn("Unable to play audio file.",e)})},d.sipSession.data.ringerObj=t}else{console.log("Audio:",c.Ringtone.url,c.Ringtone);const t=new Audio(c.Ringtone.blob);t.preload="auto",t.loop=!0,t.oncanplaythrough=function(){void 0!==t.sinkId&&"default"!=e.media.ringerOutputDeviceId&&t.setSinkId(e.media.ringerOutputDeviceId).then(function(){console.log("Set sinkId to:",e.media.ringerOutputDeviceId)}).catch(function(e){console.warn("Failed not apply setSinkId.",e)}),t.play().then(function(){}).catch(function(e){console.warn("Unable to play audio file.",e)})},d.sipSession.data.ringerObj=t}i(d)},answerAudioSession:function(s){if(!d)return void alert("lang.alert_no_microphone");const i=t(s);if(null===i)return void console.warn("Failed to get line ("+s+")");const r=i.sipSession;if(!r||r instanceof pt)return;r.data.ringerObj&&(r.data.ringerObj.pause(),r.data.ringerObj.removeAttribute("src"),r.data.ringerObj.load(),r.data.ringerObj=null);const n=R();if(!n)return console.error("answerAudioSession spdOptions is undefined");r.data.withVideo=!1,r.data.videoSourceDevice=null,r.data.audioSourceDevice=e.media.audioInputDeviceId,r.data.audioOutputDevice=e.media.audioOutputDeviceId,r.accept(n).then(function(){h(i,!1)}).catch(function(e){console.warn("Failed to answer call",e,r),r.data.reasonCode=500,r.data.reasonText="Client Error",_(i)})},answerVideoSession:function(s){const i=t(s);if(null==i)return void console.warn("Failed to get line ("+s+")");const r=i.sipSession;if(!r||r instanceof pt)return;if(r.data.ringerObj&&(r.data.ringerObj.pause(),r.data.ringerObj.removeAttribute("src"),r.data.ringerObj.load(),r.data.ringerObj=null),!d)return void alert("lang.alert_no_microphone");const o=C();r.data.withVideo=!0,r.data.videoSourceDevice=e.media.videoInputDeviceId,r.data.audioSourceDevice=e.media.audioInputDeviceId,r.data.audioOutputDevice=e.media.audioOutputDeviceId,r.accept(o).then(function(){h(i,!0)}).catch(function(e){console.warn("Failed to answer call",e,r),r.data.reasonCode=500,r.data.reasonText="Client Error",_(i)}),n(i)},makeAudioSession:D,makeVideoSession:k,rejectCall:function(e){const s=t(e);if(null==s)return void console.warn("Unable to find line ("+e+")");const i=s.sipSession;!i||i instanceof pt||(i.state==dt.Established?i.bye().catch(function(e){console.warn("Problem in rejectCall(), could not bye() call",e,i)}):i.reject({statusCode:486,reasonPhrase:"Busy Here"}).catch(function(e){console.warn("Problem in rejectCall(), could not reject() call",e,i)}),i.data.terminateBy="us",i.data.reasonCode=486,i.data.reasonText="Busy Here",_(s))},dialByLine:function(e,t,r={},n){if(null==a||0==a.isRegistered())return void alert("userAgent not registered");const o=new m(s(),t,r);"audio"===e?D(o,t,n):k(o,t,n??[]),i(o)},endSession:function(e){const s=t(e);if(null==s)return void console.warn("Unable to find line ("+e+")");const i=s.sipSession;if(i)switch(i.state){case dt.Initial:case dt.Establishing:i instanceof pt?(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){console.warn("Problem in rejectCall(), could not reject() call",e,i)}),i.data.terminateBy="us",i.data.reasonCode=486,i.data.reasonText="Busy Here",_(s));break;case dt.Established:i.bye().catch(function(e){console.warn("Problem in rejectCall(), could not bye() call",e,i)}),i.data.terminateBy="us",i.data.reasonCode=486,i.data.reasonText="Busy Here",_(s);break;default:console.warn("Session not in correct state for cancel.",i.state),console.log("Attempting teardown : "+e),_(s)}},holdSession:A,unholdSession:H,muteSession:function(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;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&&(console.log("Muting Mixed Audio Track : "+i.data.audioSourceTrack.label),i.data.audioSourceTrack.enabled=!1),console.log("Muting Audio Track : "+t.label),t.enabled=!1}}),i.data.mute||(i.data.mute=[]),i.data.mute.push({event:"mute",eventTime:ve()}),i.data.isMute=!0,n(s)},unmuteSession:function(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;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&&(console.log("Unmuting Mixed Audio Track : "+i.data.audioSourceTrack.label),i.data.audioSourceTrack.enabled=!0),console.log("Unmuting Audio Track : "+t.label),t.enabled=!0}}),i.data.mute||(i.data.mute=[]),i.data.mute.push({event:"unmute",eventTime:ve()}),i.data.isMute=!1,n(s)},cancelSession:function(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;i instanceof pt&&(i.data.terminateBy="us",i.data.reasonCode=0,i.data.reasonText="Call Cancelled",console.log("Cancelling session : "+e),i.state==dt.Initial||i.state==dt.Establishing?i.cancel():(console.warn("Session not in correct state for cancel.",s.sipSession.state),console.log("Attempting teardown : "+e),_(s)))},startTransferSession:function(e){A(e)},cancelTransferSession:function(e){const s=t(e);if(console.log("cancelTransferSession",{lineObj:s}),null==s||null==s.sipSession)return void console.warn("Null line or session");const i=s.sipSession;i.data.childsession&&(console.log("Child Transfer call detected:",i.data.childsession.state),i.data.childsession.dispose().then(function(){i.data.childsession=null}).catch(function(e){console.error("cancelTransferSession",{error:e}),i.data.childsession=null})),H(e),n(s)},attendedTransferSession:function(t,s){if(null==a)return;if(!a.isRegistered())return;const i=String(s);if(""===i)return void console.warn("Cannot transfer, no number");let r=t;if(console.log("attendedTransfer lineNumber",a.isRegistered(),i,r),!r?.sipSession)return void console.warn("Null line or session");const o=r.sipSession;if(!o)return;o.data.transfer||(o.data.transfer=[]),o.data.transfer.push({type:"Attended",to:s,transferTime:ve(),disposition:"invite",dispositionTime:ve(),accept:{complete:null,eventTime:null,disposition:""}});const c=o.data.transfer.length-1,d=navigator.mediaDevices.getSupportedConstraints(),l={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if(console.log("attend1"),"object"!=typeof l.sessionDescriptionHandlerOptions.constraints.audio)return;if(o.data.audioSourceDevice&&"default"!=o.data.audioSourceDevice&&(l.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:o.data.audioSourceDevice}),d.autoGainControl&&(l.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=e.media.autoGainControl),d.echoCancellation&&(l.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=e.media.echoCancellation),d.noiseSuppression&&(l.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=e.media.noiseSuppression),o.data.withVideo){l.sessionDescriptionHandlerOptions.constraints.video={};const t=l.sessionDescriptionHandlerOptions.constraints.video;o.data.videoSourceDevice&&"default"!=o.data.videoSourceDevice&&(t.deviceId={exact:o.data.videoSourceDevice}),d.frameRate&&""!==e.media.maxFrameRate&&(t.frameRate=String(e.media.maxFrameRate)),d.height&&""!=e.media.videoHeight&&(t.height=String(e.media.videoHeight)),d.aspectRatio&&""!=e.media.videoAspectRatio&&(t.aspectRatio=String(e.media.videoAspectRatio)),("object"==typeof l.sessionDescriptionHandlerOptions.constraints.video&&0==Object.keys(l.sessionDescriptionHandlerOptions.constraints.video)?.length||"boolean"==typeof l.sessionDescriptionHandlerOptions.constraints.video)&&(l.sessionDescriptionHandlerOptions.constraints.video=!0)}console.log(555,"TRANSFER INVITE: ","sip:"+i+"@"+e.account.domain,l);const h=fs.makeURI("sip:"+i.replace(/#/g,"%23")+"@"+e.account.domain),u=new pt(a,h,l);u.data={},u.delegate={onBye:function(){console.log("New call session ended with BYE"),o.data.transfer&&(o.data.transfer[c].disposition="bye",o.data.transfer[c].dispositionTime=ve())},onSessionDescriptionHandler:function(e){$(r,o,e,o?.data?.withVideo)}},o.data.childsession=u;const g={requestDelegate:{onTrying:function(){o.data.transfer&&(o.data.transfer[c].disposition="trying",o.data.transfer[c].dispositionTime=ve())},onProgress:function(){console.log("onProgress"),o.data.transfer&&(o.data.transfer[c].disposition="progress",o.data.transfer[c].dispositionTime=ve(),o.data.transfer[c].onCancle=()=>{u.cancel().catch(function(e){console.warn("Failed to CANCEL",e)}),o.data.transfer&&(o.data.transfer[c].accept.complete=!1,o.data.transfer[c].accept.disposition="cancel",o.data.transfer[c].accept.eventTime=ve())},console.log("New call session canceled"))},onRedirect:function(e){console.log("Redirect received:",e)},onAccept:function(){if(!o.data.transfer)return;o.data.transfer[c].disposition="accepted",o.data.transfer[c].dispositionTime=ve();const e={requestDelegate:{onAccept:function(e){console.log("Attended transfer Accepted"),o.data.transfer&&(o.data.terminateBy="us",o.data.reasonCode=202,o.data.reasonText="Attended Transfer",o.data.transfer[c].accept.complete=!0,o.data.transfer[c].accept.disposition=e.message.reasonPhrase??"",o.data.transfer[c].accept.eventTime=ve(),o.bye().catch(function(e){console.warn("Could not BYE after blind transfer:",e)}),_(r))},onReject:function(e){console.warn("Attended transfer rejected:",e),o.data.transfer&&(o.data.transfer[c].accept.complete=!1,o.data.transfer[c].accept.disposition=e.message.reasonPhrase??"",o.data.transfer[c].accept.eventTime=ve())}}};o.refer(u,e).catch(function(e){console.warn("Failed to REFER",e)})},onReject:function(e){o.data.transfer&&(console.log("New call session rejected: ",e.message.reasonPhrase),o.data.transfer[c].disposition=e.message.reasonPhrase??"",o.data.transfer[c].dispositionTime=ve())}}};u.invite(g).catch(function(e){console.warn("Failed to send INVITE:",e)}),n(r)},cancelAttendedTransferSession:function(e,t){if(null==a)return;if(!a.isRegistered())return;const s=String(t);if(""===s)return void console.warn("Cannot transfer, no number");let i=e;if(console.log("attendedTransfer lineNumber",a.isRegistered(),s,i),!i?.sipSession)return void console.warn("Null line or session");const r=i.sipSession;r&&r.data.transfer&&r.data.transfer.forEach(e=>{e.to===t&&e.onCancle?.()})},teardownSession:_}})(),b=we();i(()=>(g({configs:v}),async function(){await y()}(),()=>{o?.stop()}),[v]);const y=async()=>{await async function(e){const t={audio:!1,video:!1};try{const s=await navigator.mediaDevices.getUserMedia({...t,...e&&{[e]:!0}});return console.log("Media stream obtained:",{stream:s}),s}catch(e){throw"NotAllowedError"===e.name?console.error("Permissions denied by the user."):"NotFoundError"===e.name?console.error("No media devices found."):"OverconstrainedError"===e.name?console.error("Constraints cannot be satisfied by available devices."):console.error("Unknown error:",e),e}}("audio"),$(),T()},T=r(()=>{let e=new fs({uri:fs.makeURI(`sip:${v.account.username}@${v.account.domain}`),transportOptions:{server:`wss://${v.account.wssServer}:${v.account.webSocketPort}${v.account.serverPath}`,traceSip:!1,connectionTimeout:v.registration.transportConnectionTimeout},authorizationUsername:v.account.username,authorizationPassword:v.account.password,delegate:{onInvite:w.receiveCall,onMessage:()=>console.log("Received message")}});e.isRegistered=function(){return e&&e.registerer&&e.registerer.state===ft.Registered},e.sessions=e._sessions,e.registrationCompleted=!1,e.registering=!1,e.transport.ReconnectionAttempts=v.registration.transportReconnectionAttempts||0,e.transport.attemptingReconnection=!1,e.BlfSubs=[],e.lastVoicemailCount=0,e.transport.onConnect=()=>{x(e)},e.transport.onDisconnect=t=>{t?P(t,e):O(e)};const t={logConfiguration:!1,expires:v.registration.registerExpires,extraHeaders:[],extraContactHeaderParams:[],refreshFrequency:75};e.registerer=new Tt(e,t),console.log("Creating Registerer... Done"),e.registerer.stateChange.addListener(function(t){switch(console.log("User Agent Registration State:",t),console.log({"SIP-STATUS":t}),t){case ft.Initial:break;case ft.Registered:A(e);break;case ft.Unregistered:H(e);case ft.Terminated:}}),e.start(),Object.defineProperty(e,"_key",{enumerable:!1,value:1}),console.log("createUserAgent",{ua:e}),R(e)},[v]),$=()=>{var e;e=e=>{if(console.log({deviceInfos:e}),!e)return;let t=a,s=l,i=c,r=u,n=d,o=h;for(let a=0;a<e.length;++a)"audioinput"===e[a].kind?(t=!0,s.push(e[a])):"audiooutput"===e[a].kind?(i=!0,r.push(e[a])):"videoinput"===e[a].kind&&v.features.enableVideo&&(n=!0,o.push(e[a]));g({devicesInfo:{hasAudioDevice:t,audioInputDevices:s,hasSpeakerDevice:i,speakerDevices:r,hasVideoDevice:n,videoInputDevices:o}})},navigator.mediaDevices.enumerateDevices().then(function(t){e(t)}).catch(function(e){console.error("Error enumerating devices",e)})},R=e=>{g({userAgent:e})};return p.jsx(ms.Provider,{value:{lines:n.lines,session:{methods:w,events:b},transport:{reconnectTransport:q}},children:e})},ws=()=>{const e=n(ms);if(!e)throw new Error("useSipProvider must be used within a SipProvider");return e},bs=({lineNumber:e,type:t,...s})=>p.jsx("audio",{...s,id:`line-${e}${t?`-${t}`:""}-remoteAudio`}),ys=({lineNumber:e,...t})=>"local"===t.type?p.jsx("video",{...t,id:`line-${e}-${t.type}Video`,muted:"local"===t.type}):p.jsx("div",{...t,id:`line-${e}-remoteVideos`});export{bs as AudioStream,vs as SipProvider,ys as VideoStream,ws as useSipProvider};
1
+ import e,{createContext as t,useMemo as s,useEffect as i,useCallback as r,useContext as n}from"react";import{jsx as o}from"react/jsx-runtime";class a{lineNumber;displayNumber;sipSession;localSoundMeter;remoteSoundMeter;constructor(e,t){this.lineNumber=e,this.displayNumber=t,this.sipSession=null,this.localSoundMeter=null,this.remoteSoundMeter=null}}class c{static instance;audioBlobs;constructor(e){this.audioBlobs={Alert:e?.Alert??{file:"Alert.mp3",url:"./src/assets/media/Alert.mp3"},Ringtone:e?.Ringtone??{file:"Ringtone_1.mp3",url:"./src/assets/media/Ringtone.mp3"},CallWaiting:e?.CallWaiting??{file:"Tone_CallWaiting.mp3",url:"./src/assets/media/CallWaiting.mp3"}}}static getInstance(e){return c.instance||(c.instance=new c(e)),c.instance}getAudios(){return this.audioBlobs}}const d={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}},h=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},l=e=>e;const u=t=>{const s=(e=>e?h(e):h)(t),i=t=>function(t,s=l){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},g=(p=(e,t)=>({configs:d,userAgent:void 0,devicesInfo:{hasVideoDevice:!1,hasAudioDevice:!1,hasSpeakerDevice:!1,audioInputDevices:[],videoInputDevices:[],speakerDevices:[]},lines:[],audioBlobs:c.getInstance().getAudios(),setSipStore:t=>e(e=>({...e,...t})),setUserAgent:t=>e(e=>({...e,userAgent:t})),addLine:t=>e(e=>({...e,lines:[...e.lines,t]})),updateLine:t=>{e(e=>({...e,lines:e.lines.map(e=>e.lineNumber===t.lineNumber?{...t}:e)}))},removeLine:s=>{const i=t().lines.filter(e=>e.lineNumber!==s);e(e=>({...e,lines:i}))},findLineByNumber:e=>t().lines.find(t=>t.lineNumber===e)??null,getNewLineNumber:()=>t().lines.length+1,getSessions:()=>{const{userAgent:e}=t();return null==e||0==e.isRegistered()?null:e.sessions??null},countIdSessions:e=>{let s=0;return t().userAgent?.sessions?(Object.values(t().userAgent?.sessions??{}).forEach(t=>{e!==t.id&&s++}),s):s}}))?u(p):u;var p;const f=e=>{g.setState(t=>({...t,...e}))},m=()=>g.getState().userAgent;var v;async function w(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){}}async function S(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=g.getState().findLineByNumber(e?.data?.line)?.sipSession?.data?.videoAckReceived;return a?t():r>=s?n(new Error("ACK timeout")):(await w(e,v.VIDEO_TOGGLE,!0),r++,void setTimeout(o,i))};o()})}function b(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}!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"}(v||(v={}));var T,y={exports:{}};var $,E=(T||(T=1,y.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}},S="en",b={};b[S]=m;var T="$isDayjsObject",y=function(e){return e instanceof I||!(!e||!e[T])},$=function e(t,s,i){var r;if(!t)return S;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&&(S=r),r||!i&&S},E=function(e,t){if(y(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=y,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[T]=!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 S=this.$locale().weekStart||0,b=(f<S?f+7:f)-S;return g(i?v-b:v+(6-b),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,S=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=(S-w)/6048e5;break;case a:p=(S-w)/864e5;break;case o:p=S/s;break;case n:p=S/t;break;case r:p=S/e;break;default:p=S}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}(),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=y,E.unix=function(e){return E(1e3*e)},E.en=b[S],E.Ls=b,E.p={},E}()),y.exports),R=b(E),I={exports:{}};var C,D,A,k,H,_,x,P,O,q,M,N,j,F,L,U,B,G,V,Y,W=($||($=1,I.exports=(x=/\[([^\]]+)]|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,q=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,M={years:P=31536e6,months:O=2628e6,days:_=864e5,hours:H=36e5,minutes:k=6e4,seconds:A=1e3,milliseconds:1,weeks:6048e5},N=function(e){return e instanceof V},j=function(e,t,s){return new V(e,s,t.$l)},F=function(e){return D.p(e)+"s"},L=function(e){return e<0},U=function(e){return L(e)?Math.ceil(e):Math.floor(e)},B=function(e){return Math.abs(e)},G=function(e,t){return e?L(e)?{negative:!0,format:""+B(e)+t}:{negative:!1,format:""+e+t}:{negative:!1,format:""}},V=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 j(e*M[F(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[F(t)]=e[t]}),this.calMilliseconds(),this;if("string"==typeof e){var r=e.match(q);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)*M[s]},0)},t.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=U(e/P),e%=P,this.$d.months=U(e/O),e%=O,this.$d.days=U(e/_),e%=_,this.$d.hours=U(e/H),e%=H,this.$d.minutes=U(e/k),e%=k,this.$d.seconds=U(e/A),e%=A,this.$d.milliseconds=e},t.toISOString=function(){var e=G(this.$d.years,"Y"),t=G(this.$d.months,"M"),s=+this.$d.days||0;this.$d.weeks&&(s+=7*this.$d.weeks);var i=G(s,"D"),r=G(this.$d.hours,"H"),n=G(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=G(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:D.s(this.$d.years,2,"0"),YYYY:D.s(this.$d.years,4,"0"),M:this.$d.months,MM:D.s(this.$d.months,2,"0"),D:this.$d.days,DD:D.s(this.$d.days,2,"0"),H:this.$d.hours,HH:D.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:D.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:D.s(this.$d.seconds,2,"0"),SSS:D.s(this.$d.milliseconds,3,"0")};return t.replace(x,function(e,t){return t||String(s[e])})},t.as=function(e){return this.$ms/M[F(e)]},t.get=function(e){var t=this.$ms,s=F(e);return"milliseconds"===s?t%=1e3:t="weeks"===s?U(t/M[s]):this.$d[s],t||0},t.add=function(e,t,s){var i;return i=t?e*M[F(t)]:N(e)?e.$ms:j(e,this).$ms,j(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 j(this.$ms,this)},t.humanize=function(e){return C().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}(),Y=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){C=s,D=s().$utils(),s.duration=function(e,t){var i=s.locale();return j(e,{$l:i},t)},s.isDuration=N;var i=t.prototype.add,r=t.prototype.subtract;t.prototype.add=function(e,t){return N(e)?Y(this,e,1):i.bind(this)(e,t)},t.prototype.subtract=function(e,t){return N(e)?Y(this,e,-1):r.bind(this)(e,t)}})),I.exports),K=b(W);R.extend(K);var J,Z={exports:{}};var z=(J||(J=1,Z.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)}}}()),Z.exports),X=b(z);R.extend(K),R.extend(X);const Q=R;function ee(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]=ee(r,i):void 0!==i&&(s[e]=i)}return s}function te(){return Q().utc().format("YYYY-MM-DD HH:mm:ss UTC")}const se=()=>{const e=g(e=>e.updateLine),t=g(e=>e.audioBlobs),{maxVideoBandwidth:s,audioOutputDeviceId:i}=g(e=>e.configs.media);async function r(t,s){const r=t.sipSession;r&&(r.initiateRemoteMediaStreams=(n=s,o=r.sessionDescriptionHandler.peerConnection)=>{const a=new Map,c=new Map,d=`line-${t.lineNumber}-remoteAudios`,h=`line-${t.lineNumber}-remoteVideos`,l=document.getElementById(d),u=document.getElementById(h);o.getTransceivers().forEach(e=>{const t=e.receiver?.track;if(!t)return;const s=new MediaStream([t]);"audio"===t.kind&&a.set(t.id,s),n&&"video"===t.kind&&(t.mid=e.mid,c.set(t.id,s))}),l&&(l.innerHTML="",a.forEach((e,s)=>{const r=document.createElement("audio");r.id=`line-${t.lineNumber}-audio-${s}`,r.autoplay=!0,r.srcObject=e,r.controls=!1,r.onloadedmetadata=()=>{void 0!==r.sinkId&&r.setSinkId(i).then(()=>{}).catch(e=>{}),r.play().catch(e=>{})},l.appendChild(r)})),u&&(u.innerHTML="",c.forEach((e,s)=>{const i=document.createElement("video");i.id=`line-${t.lineNumber}-video-${s}`,i.srcObject=e,i.autoplay=!0,i.playsInline=!0,i.muted=!0,i.onloadedmetadata=()=>{i.play().catch(e=>{})},u.appendChild(i)})),e(t)})}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(t,i,r){const n=t.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=Q.utc().toISOString();n.data.startTime=o,n.isOnHold=!1,n.data.started=!0,n.initiateLocalMediaStreams=(r=i,o=n.sessionDescriptionHandler.peerConnection)=>{if(r){const i=new MediaStream;o.getSenders().forEach(function(e){e.track&&"video"===e.track.kind&&(e.track.contentHint="Shervin",i.addTrack(e.track))});const r=document.getElementById(`line-${t.lineNumber}-localVideo`);r&&(r.srcObject=i,r.onloadedmetadata=function(e){r.play()}),s>-1&&o.getSenders().forEach(function(e){if(e.track&&"video"===e.track.kind){const t=e.getParameters();t.encodings||(t.encodings=[{}]),t.encodings[0].maxBitrate=1e3*s,e.setParameters(t).catch(function(e){})}}),e(t)}},e(t)},onInviteTrying:function(e,t){},onInviteProgress:function(s,r){const n=s.sipSession;if(n){if(180===r.message.statusCode){let e=t.Ringtone;if(n.data.earlyMedia);else{const t=new Audio(e.url);t.preload="auto",t.loop=!0,t.oncanplaythrough=function(e){void 0!==t.sinkId&&"default"!==i&&t.setSinkId(i).then(function(){}).catch(function(e){}),t.play().then(function(){}).catch(function(e){})},n.data.earlyMedia=t}}else r.message.statusCode;e(s)}},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(t,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 e=JSON.parse(s.request.body),i=t.sipSession;if(!i)return;if(!i.data)return;if(i.data.confBridgeChannels||(i.data.confBridgeChannels=[]),i.data.confBridgeEvents||(i.data.confBridgeEvents=[]),"ConfbridgeStart"==e.type);else if("ConfbridgeWelcome"==e.type)i.data.confBridgeChannels=e.channels,i.data.confBridgeChannels.forEach(function(e){});else if("ConfbridgeJoin"==e.type)e.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:te()}))});else if("ConfbridgeLeave"==e.type)e.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:te()}))})});else if("ConfbridgeTalking"===e.type){}else"ConfbridgeMute"==e.type?e.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(t.muted=!0)})}):"ConfbridgeUnmute"===e.type?e.channels.forEach(function(e){i.data.confBridgeChannels?.forEach(function(t){t.id==e.id&&(t.muted=!1)})}):e.type;s.accept()}else if(i.indexOf("application/x-myphone-confbridge-chat")>-1)s.accept();else if(i.indexOf("text/plain")>-1){if(!t?.sipSession?.data.remoteMediaStreamStatus)return;const e=JSON.parse(s.request.body);switch(e.type){case v.SOUND_TOGGLE:t.sipSession.data.remoteMediaStreamStatus.soundEnabled=e.value;break;case v.VIDEO_TOGGLE:t.sipSession.data.remoteMediaStreamStatus.videoEnabled=e.value,w(t.sipSession,v.VIDEO_TOGGLE_ACK,"");break;case v.SCREEN_SHARE_TOGGLE:t.sipSession.data.remoteMediaStreamStatus.screenShareEnabled=e.value;break;case v.VIDEO_TOGGLE_ACK:t.sipSession.data.videoAckReceived=!0;break;default:s.reject()}s.accept()}else s.reject();e(t)}catch(e){}},onSessionDescriptionHandlerCreated:function(e,t,s,i){t&&t.peerConnection&&(t.peerConnection.ontrack=function(t){r(e,i)})},onTrackAddedEvent:r,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=>{})}})}})}}},ie=()=>{const{audioInputDevices:e,videoInputDevices:t}=g(e=>e.devicesInfo),{media:{audioInputDeviceId:s,videoInputDeviceId:i,autoGainControl:r,maxFrameRate:n,noiseSuppression:o,videoAspectRatio:a,videoHeight:c,echoCancellation:d},registration:{inviteExtraHeaders:h}}=g(e=>e.configs),l=()=>navigator.mediaDevices.getSupportedConstraints(),u={answerAudioSpdOptions:function({option:t}={}){const i=t??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:{exact:"default"}},video:!1}}},n=l(),a=s;if("object"==typeof i.sessionDescriptionHandlerOptions.constraints.audio){if("default"!=a){let t=(t=>{let s=!1;for(let i=0;i<e.length;++i)if(t==e[i].deviceId){s=!0;break}return s})(a);t&&(i.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:a})}return n.autoGainControl&&(i.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=r),n.echoCancellation&&(i.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=d),n.noiseSuppression&&(i.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=o),i}},makeAudioSpdOptions:function({extraHeaders:e}){let t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if(t.extraHeaders=e||[],u.answerAudioSpdOptions({option:t}),h&&""!==h&&"{}"!==h)try{for(const[e,s]of Object.entries(JSON.parse(h)))""==s||t?.extraHeaders?.push(e+": "+s)}catch(e){}return t},answerVideoSpdOptions:function({option:e}={}){const s=e??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}},r=l();u.answerAudioSpdOptions({option:s});const o=i;if("object"==typeof s.sessionDescriptionHandlerOptions.constraints.video){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.video.deviceId={exact:o})}return r.frameRate&&n&&(s.sessionDescriptionHandlerOptions.constraints.video.frameRate=String(n)),r.height&&c&&(s.sessionDescriptionHandlerOptions.constraints.video.height=String(c)),r.aspectRatio&&a&&(s.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=String(a)),s}},makeVideoSpdOptions:function({extraHeaders:e}){const t={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}};if(u.answerVideoSpdOptions({option:t}),t.extraHeaders=e||[],h&&""!==h&&"{}"!==h)try{for(const[e,s]of Object.entries(JSON.parse(h)))""==s||t.extraHeaders.push(e+": "+s)}catch(e){}return t}};return u};class re extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class ne extends re{constructor(e){super(e||"Unsupported content type.")}}class oe extends re{constructor(e){super(e||"Request pending.")}}class ae extends re{constructor(e){super(e||"Unspecified session description handler error.")}}class ce extends re{constructor(){super("The session has terminated.")}}class de extends re{constructor(e){super(e||"An error occurred during state transition.")}}class he{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class le{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 ue{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class ge{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 pe{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 fe{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 me extends fe{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 me(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 ve extends fe{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 ve(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 we(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 Se(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class be 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,be.prototype):this.__proto__=be.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,be)}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=Se("",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+" | "+Se("",r.column-1," ")+Se("",a-r.column,"^")}else t+="\n at "+n}return t}}const Te=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 ve(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 ve(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 ve(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 me(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 me(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 me(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 me(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 me(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 me(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=[y('2 ""6 7!'),y('4"""5!7#'),y('4$""5!7%'),y('4&""5!7\''),y(";'.# &;("),y('4(""5!7)'),y('4*""5!7+'),y('2,""6,7-'),y('2.""6.7/'),y('40""5!71'),y('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'),y(";).# &;,"),y('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),y('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),y('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),y(';.." &"'),y("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),y('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),y('4\\""5!7].# &;3'),y('4^""5!7_'),y('4`""5!7a'),y(';!.) &4b""5!7c'),y('%$;).• &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&&&#/"!&,)'),y('%$;).‰ &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&&&#/"!&,)'),y('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.) &;\'.# &;('),y('%$;).ī &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&&&#/"!&,)'),y("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),y("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),y("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),y("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),y("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),y('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),y('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),y("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),y("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),y("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),y("%;//0#;&/'$8\":~\" )(\"'#&'#"),y("%;&/0#;//'$8\":~\" )(\"'#&'#"),y("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),y('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),y("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),y("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),y(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),y('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),y("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),y("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),y('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),y('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),y("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),y('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'),y('%$;+._ &;-.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!:–! )'),y('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),y("%;U.) &;\\.# &;X/& 8!:—! )"),y('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),y('$4™""5!7š/,#0)*4™""5!7š&&&#'),y('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),y('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),y('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),y('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),y("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),y("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),y('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),y('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),y('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),y(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),y('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),y('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),y('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),y('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),y('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),y('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),y('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),y('%$;j/&#0#*;j&&&#/"!&,)'),y('%$;j/&#0#*;j&&&#/"!&,)'),y(";k.) &;+.# &;-"),y('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),y('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),y('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),y("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),y("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),y('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),y(";‘.# &;r"),y("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),y(";M.# &;t"),y("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),y('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),y('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),y('%24""6475/,#;{/#$+")("\'#&\'#'),y("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),y(";*.) &;+.# &;-"),y(';+. &;-.‰ &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'),y('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),y('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),y("$;~0#*;~&"),y(';+.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'),y('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),y(";.# &;‚"),y('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),y('$;+.ƒ &;-.} &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&&&#'),y("$;y0#*;y&"),y('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),y('2Õ""6Õ7Ö'),y('2×""6×7Ø'),y('2Ù""6Ù7Ú'),y('2Û""6Û7Ü'),y('2Ý""6Ý7Þ'),y('2ß""6ß7à'),y('2á""6á7â'),y('2ã""6ã7ä'),y('2å""6å7æ'),y('2ç""6ç7è'),y('2é""6é7ê'),y("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),y("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),y("%;“/' 8!:ì!! )"),y("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),y("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),y("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),y("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),y("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),y("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),y("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),y(";œ.) &;.# &; "),y("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),y("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),y("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),y('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),y('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),y(";6.) &;T.# &;H"),y("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),y(";¥.# &; "),y('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),y("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),y("%;©/& 8!:č! )"),y("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),y(";«.# &;¬"),y('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),y('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),y(";6.# &;®"),y('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),y(";­.# &;6"),y("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),y(";6.# &;H"),y("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),y("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),y("%;ž/' 8!:ğ!! )"),y('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),y('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),y("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),y(";¹.# &; "),y("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),y("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),y("%;ž/' 8!:Ħ!! )"),y("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),y(";¾"),y("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),y("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),y("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),y(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),y("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),y("%;I/' 8!:Ĭ!! )"),y("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),y(";t.# &;w"),y("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),y("%;I/' 8!:ı!! )"),y("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),y('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),y('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),y('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),y('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),y("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),y("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),y("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),y("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),y('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),y("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),y("%;–/& 8!:Ő! )"),y('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),y('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),y("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),y("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),y("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),y('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'),y(';1." &"'),y('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),y("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),y(";¹.# &; "),y("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),y("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),y(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),y("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),y("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),y("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),y("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),y("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),y("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),y('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),y('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),y('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),y("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),y('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),y('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),y(";¾"),y('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),y(";ô.# &; "),y('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),y('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),y("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),y("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),y("$;%0#*;%&"),y("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),y('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),y('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),y("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),y(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),y('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?'),y('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),y('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),y('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),y("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),y("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),y("%;ă/,#;ă/#$+\")(\"'#&'#"),y("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),y("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),y('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),y(";™.# &;L"),y("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),y("%;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 w(e,t,s){return{type:"class",parts:e,inverted:t,ignoreCase:s}}function S(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=S(e),r=S(t);return{source:i,start:{offset:e,line:s.line,column:s.column},end:{offset:t,line:r.line,column:r.column}}}function T(e){c<u||(c>u&&(u=c,g=[]),g.push(e))}function y(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&&T(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&&T({type:"end"}),$=g,E=u<e.length?e.charAt(u):null,R=u<e.length?b(u,u+1):b(u,u),new be(be.buildMessage($,E),$,E,R);var $,E,R};var ye;!function(e){e.parse=function(e,t){const s={startRule:t};try{Te(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}}(ye=ye||(ye={}));const $e={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 Ee(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function Re(e){return $e[e]||""}function Ie(){return Ee(10)}function Ce(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 De(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class Ae{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=Ce(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[Ce(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[Ce(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[Ce(e)]}parseHeader(e,t=0){if(e=Ce(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=ye.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[Ce(e)]=[{raw:t}]}toString(){return this.data}}class ke extends Ae{constructor(){super()}}class He extends Ae{constructor(){super()}}class _e{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=_e.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:Ie(),this.from=_e.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=_e.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+Ee(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 me(e,t,i)}getHeader(e){const t=this.headers[Ce(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[Ce(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[Ce(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[Ce(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: "+De(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: "+De(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 xe(e){return"application/sdp"===e?"session":"render"}function Pe(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:xe(s),contentType:s,content:t}}function Oe(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function qe(e){let t,s,i;if(e instanceof ke&&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 He&&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 _e&&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(Oe(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=xe(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var Me,Ne;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(Me=Me||(Me={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(Ne=Ne||(Ne={}));const je=500,Fe={T1:je,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 Le extends re{constructor(e){super(e||"Transaction state error.")}}var Ue;!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"}(Ue=Ue||(Ue={}));const Be=[Ue.ACK,Ue.BYE,Ue.CANCEL,Ue.INFO,Ue.INVITE,Ue.MESSAGE,Ue.NOTIFY,Ue.OPTIONS,Ue.PRACK,Ue.REFER,Ue.REGISTER,Ue.SUBSCRIBE];class Ge{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 Ve{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 Ye{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof me))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 We,Ke;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(We=We||(We={}));class Je{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=We.Initial,this.delegate=t.delegate,this._stateEventEmitter=new ge,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 We.Initial:case We.Establishing:break;case We.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case We.Terminating:case We.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 We.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 We.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 We.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case We.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 We.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!==We.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!==We.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new oe("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=qe(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(We.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===We.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(We.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!==We.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(We.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!==We.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(We.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: "+Be.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!==We.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!==We.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 Je&&!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 Me.Initial:case Me.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case Me.AckWait:return this.stateTransition(We.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(We.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(We.Terminated),i(r)}}});case Me.Confirmed:{const i=s.bye(e,t);return this.stateTransition(We.Terminated),Promise.resolve(i)}case Me.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!==We.Established&&this.state!==We.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 he(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case Ne.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(We.Terminated),Promise.resolve()}case Ne.Stable:{const i=qe(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(We.Terminated)}):Promise.resolve()}case Ne.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(We.Terminated),Promise.resolve()}case Ne.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(We.Terminated),Promise.resolve()}case Ne.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===We.Established){if(this.delegate&&this.delegate.onBye){const t=new le(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(We.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===We.Established)if(this.delegate&&this.delegate.onInfo){const t=new pe(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!==We.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=ye.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===Ne.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!==We.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(We.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===We.Established)if(this.delegate&&this.delegate.onMessage){const t=new Ge(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===We.Established){if(this.onNotify){const t=new Ve(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new Ve(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===We.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!==We.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 Ye(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=qe(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 Ne.Initial:return this.getOffer(e);case Ne.HaveLocalOffer:return Promise.resolve(void 0);case Ne.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 Ne.Stable:return this.state!==We.Established?Promise.resolve(void 0):this.getOffer(e);case Ne.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=>Pe(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 ne)}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 ne)}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=>Pe(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 We.Initial:e!==We.Establishing&&e!==We.Established&&e!==We.Terminating&&e!==We.Terminated&&t();break;case We.Establishing:e!==We.Established&&e!==We.Terminating&&e!==We.Terminated&&t();break;case We.Established:e!==We.Terminating&&e!==We.Terminated&&t();break;case We.Terminating:e!==We.Terminated&&t();break;case We.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===We.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=Re(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 ve)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"}(Ke=Ke||(Ke={}));const Ze={"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 ze extends Je{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(We.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===We.Initial&&(t.reject({statusCode:487}),this.stateTransition(We.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=ye.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 We.Initial:case We.Establishing:return this.reject().then(()=>super.dispose());case We.Established:case We.Terminating:case We.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!==We.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(We.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(We.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==We.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===Ke.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!==We.Initial&&this.state!==We.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:Re(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?Pe(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(We.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===We.Initial||this.state===We.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new ue(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(We.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=qe(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 Ne.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ne.Stable:return this.setAnswer(t,s).then(()=>{});case Ne.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ne.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case Ne.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 ne?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof ae?this.logger.error("A session description handler occurred while sending response"):e instanceof ce?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof Le&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===We.Initial||this.state===We.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(We.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(We.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?Pe(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 ce)).catch(e=>o(e)))},64*Fe.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=Fe.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 ce),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class Xe extends Je{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=Ie(),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?ye.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?ye.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===Ke.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===Ke.Required&&d.push("Require: replaces"),i.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(Ue.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 We.Initial:case We.Establishing:return this.cancel().then(()=>super.dispose());case We.Established:case We.Terminating:case We.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!==We.Initial&&this.state!==We.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(We.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="'+(Re(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(We.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==We.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(We.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(We.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==We.Terminated&&this.stateTransition(We.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(We.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 Je))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!==We.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=ye.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 Ne.Initial:case Ne.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(We.Terminated),Promise.reject(new Error("Bad Media Description"));case Ne.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(We.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(We.Terminated),t})}case Ne.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(We.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(We.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(We.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(We.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(We.Terminated),t})}case Ne.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!==We.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=ye.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 Ne.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 Ne.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case Ne.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(We.Terminated),e})}case Ne.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(We.Terminated),e})}return Promise.resolve();case Ne.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===We.Establishing||this.state===We.Terminating?this.stateTransition(We.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===We.Establishing||this.state===We.Terminating?this.stateTransition(We.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===We.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var Qe,et,tt,st,it,rt,nt;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(Qe=Qe||(Qe={}));class ot{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=Qe.Initial,this._waiting=!1,this._stateEventEmitter=new ge,this._waitingEventEmitter=new ge,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ot.defaultOptions()),{registrar:s}),ot.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===ye.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(Ue.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||ot.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||ot.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:ot.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new ve("sip","anonymous","anonymous.invalid"),refreshFrequency:ot.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===Qe.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===Qe.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 oe("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&&we(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(we(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=ye.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=ye.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===Qe.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==Qe.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new oe("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===Qe.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!==Qe.Registered&&this.stateTransition(Qe.Registered)}unregistered(){this.clearTimers(),this._state!==Qe.Unregistered&&this.stateTransition(Qe.Unregistered)}terminated(){this.clearTimers(),this._state!==Qe.Terminated&&this.stateTransition(Qe.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case Qe.Initial:e!==Qe.Registered&&e!==Qe.Unregistered&&e!==Qe.Terminated&&t();break;case Qe.Registered:e!==Qe.Unregistered&&e!==Qe.Terminated&&t();break;case Qe.Unregistered:e!==Qe.Registered&&e!==Qe.Terminated&&t();break;case Qe.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===Qe.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===Qe.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)}}ot.defaultExpires=600,ot.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(et=et||(et={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(tt=tt||(tt={})),function(e){e.Started="Started",e.Stopped="Stopped"}(st=st||(st={}));class at{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=at.hexChars,s=at.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(at.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,at._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,at._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,at._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(at.buffer32Identity.subarray(r),r),t>55&&(at._md5cycle(this._state,i),i.set(at.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 at._md5cycle(this._state,i),e?this._state:at._hex(this._state)}}function ct(e){return at.hashStr(e)}at.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),at.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),at.hexChars="0123456789abcdef",at.hexOut=[],at.onePassHasher=new at,"5d41402abc4b2a76b9719d911017c592"!==at.hashStr("hello")&&console.error("Md5 self test failed.");class dt{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=Ee(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=ct(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=ct(this.method+":"+this.uri),this.response=ct(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=ct(this.method+":"+this.uri+":"+ct(e||"")),this.response=ct(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=ct(this.method+":"+this.uri),this.response=ct(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"}(it=it||(it={}));class ht{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(it.error,e)}warn(e){this.genericLog(it.warn,e)}log(e){this.genericLog(it.log,e)}debug(e){this.genericLog(it.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 lt{constructor(){this.builtinEnabled=!0,this._level=it.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:it.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 ht(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new ht(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(it[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 it.error:console.error(i);break;case it.warn:console.warn(i);break;case it.log:console.log(i);break;case it.debug:console.debug(i)}}}function ut(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:Re(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=Ie()),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: "+De(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=ye.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=ye.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 He&&(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=ye.parse(o,"Request_Response");let c,d;if(-1!==a){for(a.status_code?(c=new He,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new ke,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+'"')}}(rt=rt||(rt={}));class gt extends re{constructor(e){super(e||"Unspecified transport error.")}}class pt{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 gt)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new gt(e.message):new gt,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 ft extends pt{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"}(nt=nt||(nt={}));class mt extends ft{constructor(e,t,s){super(e,t,s,nt.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 nt.Proceeding:if(e.method===Ue.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case nt.Accepted:if(e.method===Ue.INVITE)return;break;case nt.Completed:if(e.method===Ue.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===Ue.ACK)return void this.stateTransition(nt.Confirmed);break;case nt.Confirmed:case nt.Terminated:if(e.method===Ue.INVITE||e.method===Ue.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 nt.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(nt.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(nt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case nt.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case nt.Completed:case nt.Confirmed:case nt.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===nt.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 nt.Proceeding:t();break;case nt.Accepted:case nt.Completed:this.state!==nt.Proceeding&&t();break;case nt.Confirmed:this.state!==nt.Completed&&t();break;case nt.Terminated:this.state!==nt.Accepted&&this.state!==nt.Completed&&this.state!==nt.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===nt.Accepted&&(this.L=setTimeout(()=>this.timerL(),Fe.TIMER_L)),e===nt.Completed&&(this.H=setTimeout(()=>this.timerH(),Fe.TIMER_H)),e===nt.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Fe.TIMER_I)),e===nt.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.")})},Fe.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===nt.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(nt.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(nt.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===nt.Accepted&&this.stateTransition(nt.Terminated)}}class vt extends pt{constructor(e,t,s,i,r){super(t,s,vt.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 wt extends vt{constructor(e,t,s){super(e,t,s,nt.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Fe.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 nt.Trying:if(t>=100&&t<=199)return this.stateTransition(nt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(nt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case nt.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(nt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case nt.Completed:case nt.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(nt.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 nt.Trying:s();break;case nt.Proceeding:this.state!==nt.Trying&&s();break;case nt.Completed:this.state!==nt.Trying&&this.state!==nt.Proceeding&&s();break;case nt.Terminated:this.state!==nt.Trying&&this.state!==nt.Proceeding&&this.state!==nt.Completed&&(t||s());break;default:s()}e===nt.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Fe.TIMER_K)),e===nt.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==nt.Trying&&this.state!==nt.Proceeding||(this.onRequestTimeout(),this.stateTransition(nt.Terminated))}timerK(){this.state===nt.Completed&&this.stateTransition(nt.Terminated)}}class St{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 me))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 me))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!==Ue.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===Ue.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class bt extends vt{constructor(e,t,s){super(e,t,s,nt.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Fe.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 nt.Calling:if(t>=100&&t<=199)return this.stateTransition(nt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(nt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(nt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case nt.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(nt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(nt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case nt.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 nt.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case nt.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(nt.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 nt.Calling:s();break;case nt.Proceeding:this.state!==nt.Calling&&s();break;case nt.Accepted:case nt.Completed:this.state!==nt.Calling&&this.state!==nt.Proceeding&&s();break;case nt.Terminated:this.state!==nt.Calling&&this.state!==nt.Accepted&&this.state!==nt.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),nt.Proceeding,e===nt.Completed&&(this.D=setTimeout(()=>this.timerD(),Fe.TIMER_D)),e===nt.Accepted&&(this.M=setTimeout(()=>this.timerM(),Fe.TIMER_M)),e===nt.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===nt.Calling&&(this.onRequestTimeout(),this.stateTransition(nt.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===nt.Completed&&this.stateTransition(nt.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===nt.Accepted&&this.stateTransition(nt.Terminated)}}class Tt{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(Ue.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===nt.Proceeding?new Tt(wt,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===nt.Proceeding&&new Tt(wt,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 He;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 He;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===nt.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 yt extends Tt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ue.BYE,s);super(wt,e.userAgentCore,i,t),e.dispose()}}class $t extends ft{constructor(e,t,s){super(e,t,s,nt.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 nt.Trying:break;case nt.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 nt.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 nt.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 nt.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(nt.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(nt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case nt.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(nt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case nt.Completed:return;case nt.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(nt.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 nt.Trying:s();break;case nt.Proceeding:this.state!==nt.Trying&&s();break;case nt.Completed:this.state!==nt.Trying&&this.state!==nt.Proceeding&&s();break;case nt.Terminated:this.state!==nt.Proceeding&&this.state!==nt.Completed&&(t||s());break;default:s()}e===nt.Completed&&(this.J=setTimeout(()=>this.timerJ(),Fe.TIMER_J)),e===nt.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===nt.Completed&&this.stateTransition(nt.Terminated)}}class Et{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:Ie(),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 Le(`${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 Le(`${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 Le(`${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 Le(`${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 Le(`${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 mt)return this.transaction.state===nt.Proceeding||this.transaction.state===nt.Accepted;if(this.transaction instanceof $t)return this.transaction.state===nt.Trying||this.transaction.state===nt.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof mt)return this.transaction.state===nt.Proceeding;if(this.transaction instanceof $t)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof mt)return this.transaction.state===nt.Proceeding;if(this.transaction instanceof $t)return this.transaction.state===nt.Trying||this.transaction.state===nt.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof mt)return this.transaction.state===nt.Proceeding;if(this.transaction instanceof $t)return this.transaction.state===nt.Trying||this.transaction.state===nt.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof mt)return this.transaction.state===nt.Proceeding;if(this.transaction instanceof $t)return this.transaction.state===nt.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=ut(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===nt.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 Rt extends Et{constructor(e,t,s){super($t,e.userAgentCore,t,s)}}class It extends Tt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ue.INFO,s);super(wt,e.userAgentCore,i,t)}}class Ct extends Et{constructor(e,t,s){super($t,e.userAgentCore,t,s)}}class Dt extends Tt{constructor(e,t,s){super(wt,e,t,s)}}class At extends Et{constructor(e,t,s){super($t,e,t,s)}}class kt extends Tt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ue.NOTIFY,s);super(wt,e.userAgentCore,i,t)}}class Ht extends Et{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super($t,i,t,s)}}class _t extends Tt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ue.PRACK,s);super(wt,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class xt extends Et{constructor(e,t,s){super($t,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 Pt extends Tt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ue.INVITE,s);super(bt,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 Ot extends Et{constructor(e,t,s){super(mt,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 qt extends Tt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ue.REFER,s);super(wt,e.userAgentCore,i,t)}}class Mt extends Et{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super($t,i,t,s)}}class Nt extends St{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=Ne.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof mt&&(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=Ne.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?Me.Early:this.ackWait?Me.AckWait:this._signalingState===Ne.Closed?Me.Terminated:Me.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 bt))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof bt))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(Ue.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 mt){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==nt.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 yt(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 It(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 Pt(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(Ue.MESSAGE,t);return new Dt(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 kt(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new _t(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 qt(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==Ue.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===Ue.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!==Ne.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===Ue.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof me))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case Ue.BYE:{const t=new Rt(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case Ue.INFO:{const t=new Ct(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case Ue.INVITE:{const t=new Ot(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case Ue.MESSAGE:{const t=new At(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ue.NOTIFY:{const t=new Ht(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case Ue.PRACK:{const t=new xt(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case Ue.REFER:{const t=new Mt(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 bt)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!==Ne.HaveLocalOffer&&this.signalingState!==Ne.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Ne.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=qe(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===Ne.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof ke)switch(this._signalingState){case Ne.Initial:case Ne.Stable:this._signalingState=Ne.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ne.HaveLocalOffer:this._signalingState=Ne.Stable,this._answer=t;break;case Ne.HaveRemoteOffer:case Ne.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof He)switch(this._signalingState){case Ne.Initial:case Ne.Stable:this._signalingState=Ne.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ne.HaveLocalOffer:this._signalingState=Ne.Stable,this._answer=t;break;case Ne.HaveRemoteOffer:case Ne.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof _e)switch(this._signalingState){case Ne.Initial:case Ne.Stable:this._signalingState=Ne.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ne.HaveLocalOffer:break;case Ne.HaveRemoteOffer:this._signalingState=Ne.Stable,this._answer=t;break;case Ne.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Oe(e))switch(this._signalingState){case Ne.Initial:case Ne.Stable:this._signalingState=Ne.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ne.HaveLocalOffer:break;case Ne.HaveRemoteOffer:this._signalingState=Ne.Stable,this._answer=t;break;case Ne.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof mt){const e=this.initialTransaction;let t=Fe.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Fe.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===nt.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 mt){const e=this.reinviteUserAgentServer.transaction;let t=Fe.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Fe.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===nt.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class jt extends Tt{constructor(e,t,s){super(bt,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===nt.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=St.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof bt))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Nt(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!==Ne.Initial&&s.signalingState!==Ne.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=St.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 bt))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 bt))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Nt(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==Ne.Initial&&s.signalingState!==Ne.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 Ft extends Et{constructor(e,t,s){super(mt,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new Le(`${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 mt))throw new Error("Transaction not instance of InviteClientTransaction.");const t=St.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Nt(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: "+Be.toString();if(!e.body)if(this.confirmedDialog.signalingState===Ne.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Ne.Initial||this.confirmedDialog.signalingState===Ne.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!==Ne.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new Le(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof mt))throw new Error("Transaction not instance of InviteClientTransaction.");const t=St.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Nt(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!==Ne.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 Lt extends Tt{constructor(e,t,s){super(wt,e,t,s)}}class Ut extends Tt{constructor(e,t,s){super(wt,e,t,s)}}class Bt extends Et{constructor(e,t,s){super($t,e,t,s),this.core=e}}class Gt extends Tt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ue.SUBSCRIBE,s);super(wt,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 Vt extends St{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 me))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===Ue.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: "+Be.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!==et.Pending&&this.subscriptionState!==et.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 Gt(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(),Fe.TIMER_N)),i}terminate(){this.stateTransition(et.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+Be.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(et.Pending,r);break;case"active":this.stateTransition(et.Active,r);break;case"terminated":this.stateTransition(et.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new Ht(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 et.Initial:case et.NotifyWait:return void s();case et.Pending:if(this.subscriptionState!==et.NotifyWait&&this.subscriptionState!==et.Pending)return void s();break;case et.Active:case et.Terminated:if(this.subscriptionState!==et.NotifyWait&&this.subscriptionState!==et.Pending&&this.subscriptionState!==et.Active)return void s();break;default:return void s()}e===et.Pending&&t&&(this.subscriptionExpires=t),e===et.Active&&t&&(this.subscriptionExpires=t),e===et.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==et.Terminated&&(this.stateTransition(et.Terminated),this.onTerminated())}}class Yt extends Tt{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(wt,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=et.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=et.Pending;break;case"active":this.subscriptionState=et.Active;break;case"terminated":this.subscriptionState=et.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==et.Terminated){const t=Vt.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Vt(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(),Fe.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 Wt extends Et{constructor(e,t,s){super($t,e,t,s),this.core=e}}const Kt=["application/sdp","application/dtmf-relay"];class Jt{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 jt(this,e,t)}message(e,t){return new Dt(this,e,t)}publish(e,t){return new Lt(this,e,t)}register(e,t){return new Ut(this,e,t)}subscribe(e,t){return new Yt(this,e,t)}request(e,t){return new Tt(wt,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===Ue.REGISTER&&l.push("path","gruu"),e===Ue.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 _e(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=ut(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===Ue.ACK&&s&&s.transaction.state===nt.Accepted&&s instanceof Ft?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==Ue.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof mt&&s.transaction.state===nt.Proceeding&&s instanceof Ft&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!Be.includes(e.method)){const t="Allow: "+Be.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!==Ue.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==Ue.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===Ue.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 Ht(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===Ue.OPTIONS){const t="Allow: "+Be.toString(),s="Accept: "+Kt.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==Ue.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case Ue.ACK:break;case Ue.BYE:this.replyStateless(e,{statusCode:481});break;case Ue.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case Ue.INFO:this.replyStateless(e,{statusCode:405});break;case Ue.INVITE:{const t=new Ft(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case Ue.MESSAGE:{const t=new At(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ue.NOTIFY:{const t=new Ht(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case Ue.OPTIONS:{const t="Allow: "+Be.toString(),s="Accept: "+Kt.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case Ue.REFER:{const t=new Mt(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case Ue.REGISTER:{const t=new Bt(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case Ue.SUBSCRIBE:{const t=new Wt(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 Zt{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),Zt.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),Zt.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),Zt.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),Zt.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),Zt.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),Zt.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),Zt.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 zt(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 Zt(r,e,i)}}class Xt{constructor(e,t){if(this._state=tt.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new ge,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({},Xt.defaultOptions),t);const s=this.configuration.server,i=ye.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===tt.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case tt.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(tt.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case tt.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(tt.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case tt.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(tt.Connecting)}catch(e){if(e instanceof de)return Promise.reject(e);throw e}break;case tt.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(tt.Connecting)}catch(e){if(e instanceof de)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(tt.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 tt.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(tt.Disconnecting)}catch(e){if(e instanceof de)return Promise.reject(e);throw e}break;case tt.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(tt.Disconnecting)}catch(e){if(e instanceof de)return Promise.reject(e);throw e}break;case tt.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(tt.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case tt.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(tt.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!==tt.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(tt.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===tt.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===tt.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(tt.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 de("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 tt.Connecting:e!==tt.Connected&&e!==tt.Disconnecting&&e!==tt.Disconnected&&s();break;case tt.Connected:e!==tt.Disconnecting&&e!==tt.Disconnected&&s();break;case tt.Disconnecting:e!==tt.Connecting&&e!==tt.Disconnected&&s();break;case tt.Disconnected:e!==tt.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===tt.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===tt.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===tt.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===tt.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===tt.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===tt.Connected?r():n(t||new Error("Connect aborted."))}if(i===tt.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===tt.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}}Xt.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class Qt{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=st.Stopped,this._stateEventEmitter=new ge,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Qt.defaultOptions()),{sipjsId:Ee(5)}),{uri:new ve("sip","anonymous."+Ee(6),"anonymous.invalid")}),{viaHost:Ee(12)+".invalid"}),Qt.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 lt,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=it.error;break;case"warn":this.loggerFactory.level=it.warn;break;case"log":this.loggerFactory.level=it.log;break;case"debug":this.loggerFactory.level=it.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:Qt.newUUID(),-1===ye.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return ye.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:zt(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:Ke.Unsupported,sipExtensionReplaces:Ke.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Xt,transportOptions:{},uri:new ve("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===st.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===st.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(st.Started),this.transport.connect())}async stop(){if(this.state===st.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(st.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(st.Stopped)}_makeInviter(e,t){return new Xe(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:Ee(8),t=this.options.contactParams,s={pubGruu:void 0,tempGruu:void 0,uri:new ve("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===Ke.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===Ke.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>Ze[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 dt(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new Jt(s,{onInvite:e=>{var t;const s=new ze(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!==Ke.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 Ge(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new Ve(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!==st.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==st.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=rt.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===st.Stopped&&t instanceof ke)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 ke){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=De(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof He){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=De(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 ke)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof He))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 st.Started:e!==st.Stopped&&s();break;case st.Stopped:e!==st.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 es=()=>{const e=g(e=>e.configs),t=g(e=>e.findLineByNumber),s=g(e=>e.getNewLineNumber),i=g(e=>e.addLine),r=g(e=>e.removeLine),n=g(e=>e.updateLine),o=g(e=>e.countIdSessions),c=g(e=>e.userAgent),d=g(e=>e.audioBlobs),{hasAudioDevice:h,hasVideoDevice:l}=g(e=>e.devicesInfo),{onInviteAccepted:u,onInviteCancel:p,onInviteProgress:f,onInviteRedirected:m,onInviteRejected:b,onInviteTrying:T,onSessionDescriptionHandlerCreated:y,onSessionReceivedBye:$,onSessionReceivedMessage:E,onSessionReinvited:R,onTransferSessionDescriptionHandlerCreated:I}=se(),{makeAudioSpdOptions:C,answerAudioSpdOptions:D,answerVideoSpdOptions:A,makeVideoSpdOptions:k}=ie();function H(t,s,i){if(!c)return;if(!c.isRegistered())return;if(null===t)return;if(!h)return;const r=C({extraHeaders:i});if(!r)return;let n=Q.utc().toISOString();const o=Qt.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);t.sipSession=new Xe(c,o,r);const a=t.sipSession;a.data={line:t.lineNumber,callDirection:"outbound",dialledNumber:s,startTime:n,videoSourceDevice:null,audioSourceDevice:e.media.audioInputDeviceId,audioOutputDevice:e.media.audioOutputDeviceId,terminateBy:"them",localMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:h,videoEnabled:!1},remoteMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},earlyReject:!1},a.callType="audio",a.isOnHold=!1,a.delegate={onBye:function(e){$(t,e,()=>q(t))},onMessage:function(e){E(t,e)},onInvite:function(e){R(t,e)},onSessionDescriptionHandler:function(e,s){y(t,e,s,!1)}};const d={requestDelegate:{onTrying:function(e){T(t,e)},onProgress:function(e){f(t,e)},onRedirect:function(e){m(t,e)},onAccept:function(e){u(t,!1,e)},onReject:function(e){b(t,e,()=>q(t))}}};a.invite(d).catch(function(e){})}function _(t,s,i){if(null==c)return;if(!c.isRegistered())return;if(null==t)return;if(!h)return void alert("lang.alert_no_microphone");if(!l)return void H(t,s);const r=k({extraHeaders:i});if(!r)return;const n=Q.utc().toISOString(),o=Qt.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);t.sipSession=new Xe(c,o,r);const a=t.sipSession;a.data={line:t.lineNumber,callDirection:"outbound",dialledNumber:s,startTime:n,localMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!0},remoteMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},videoSourceDevice:e.media.videoInputDeviceId,audioSourceDevice:e.media.audioInputDeviceId,audioOutputDevice:e.media.audioOutputDeviceId,terminateBy:"them"},a.callType="video",a.data.earlyReject=!1,a.isOnHold=!1,a.delegate={onBye:function(e){$(t,e,()=>q(t))},onMessage:function(e){E(t,e)},onInvite:function(e){R(t,e)},onSessionDescriptionHandler:function(e,s){y(t,e,s,!0)}};const d={requestDelegate:{onTrying:function(e){T(t,e)},onProgress:function(e){f(t,e)},onRedirect:function(e){m(t,e)},onAccept:function(e){u(t,!0,e)},onReject:function(e){b(t,e,()=>q(t))}}};a.invite(d).catch(function(e){})}const x=async e=>{const s=t(e);if(!s||!s.sipSession||"audio"===s.sipSession.callType)return;const i=s.sipSession;if(!i.data.localMediaStreamStatus||!i.data.remoteMediaStreamStatus)return;i.data.localMediaStreamStatus.screenShareEnabled&&await P(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 w(i,v.VIDEO_TOGGLE,r),n(s)};async function P(e){const s=t(e);if(!s||!s.sipSession||"audio"===s.sipSession.callType)return;const i=s.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,w(i,v.SCREEN_SHARE_TOGGLE,!1)}else try{const t=(await navigator.mediaDevices.getDisplayMedia({video:!0})).getVideoTracks()[0];t.onended=()=>{P(e)};const s=r.getSenders().find(e=>"video"===e.track?.kind);i.data.localMediaStreamStatus.videoEnabled&&await x(e),s?await s.replaceTrack(t):r.addTrack(t),i.data.localMediaStreamStatus.screenShareEnabled=!0,w(i,v.SCREEN_SHARE_TOGGLE,!0)}catch(e){return}n(s)}async function O(e,s){const i=t(e);if(null==i||null==i.sipSession)return;const r=i.sipSession;if(r.isOnHold===s)return;const o=s??!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)}function q(e){if(null==e||null==e.sipSession)return;const t=e.sipSession;if(1!=t.data.teardownComplete){if(t.data.teardownComplete=!0,t.data.recordMedia?.recording&&t.data.recordMedia.recorder?.stop(),t.data.childsession&&t.data.childsession.dispose().then(function(){t.data.childsession=null}).catch(function(e){t.data.childsession=null}),t.data.audioSourceTrack&&"audio"==t.data.audioSourceTrack.kind&&(t.data.audioSourceTrack.stop(),t.data.audioSourceTrack=null),t.data.earlyMedia&&(t.data.earlyMedia.pause(),t.data.earlyMedia.removeAttribute("src"),t.data.earlyMedia.load(),t.data.earlyMedia=null),t.data.ringerObj&&(t.data.ringerObj.pause(),t.data.ringerObj.removeAttribute("src"),t.data.ringerObj.load(),t.data.ringerObj=null),null!==e.localSoundMeter&&(e.localSoundMeter.stop(),e.localSoundMeter=null),null!==e.remoteSoundMeter&&(e.remoteSoundMeter.stop(),e.remoteSoundMeter=null),t&&t.sessionDescriptionHandler&&t.sessionDescriptionHandler?.peerConnection){t.sessionDescriptionHandler.peerConnection.getSenders().forEach(function(e){"audio"==e?.track?.kind&&e.track.stop()})}"inbound"==t.data.callDirection&&(t.data.earlyReject||"them"==t.data.terminateBy&&null==t.data.startTime&&t.data.reasonCode),r(e.lineNumber)}}return{receiveSession:function(t){const r=t.remoteIdentity.displayName||t.remoteIdentity.uri.user||"";let n=t.remoteIdentity.uri.user??"";const c=new a(s(),r);c.sipSession=t;const h=c.sipSession;h.data={},h.data.line=c.lineNumber,h.data.callDirection="inbound",h.data.terminateBy="",h.data.src=n,h.data.earlyReject=!1,h.callType="audio",h.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},h.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!1,videoEnabled:!1},e.features.enableVideo&&h.request.body&&h.request.body.indexOf("m=video")>-1&&(h.data.remoteMediaStreamStatus.videoEnabled=!0,h.callType="video");const l="video"===h.callType,u=h.incomingInviteRequest.message.headers;if(u["P-Asserted-Identity"]){const t=u["P-Asserted-Identity"][0].raw;if(t.includes("<sip:")){const s=t.split("<sip:");s[1].endsWith(">")&&(s[1]=s[1].slice(0,-1)),s[1].includes(`@${e.account.domain}`)&&(n=s[1].split("@")[0])}}h.delegate={onBye:function(e){$(c,e,()=>q(c))},onMessage:function(e){E(c,e)},onInvite:function(e){R(c,e)},onSessionDescriptionHandler:function(e,t){y(c,e,t,l)}},h.incomingInviteRequest.delegate={onCancel:function(e){p(c,e,()=>q(c))}};const g=o(h.id);if(e.features.enableRingtone)if(g>=1){const t=new Audio(d.CallWaiting.url);t.preload="auto",t.loop=!1,t.oncanplaythrough=function(){void 0!==t.sinkId&&"default"!=e.media.ringerOutputDeviceId&&t.setSinkId(e.media.ringerOutputDeviceId).then(function(){}).catch(function(e){}),t.play().then(function(){}).catch(function(e){})},h.data.ringerObj=t}else{const t=new Audio(d.Ringtone.blob);t.preload="auto",t.loop=!0,t.oncanplaythrough=function(){void 0!==t.sinkId&&"default"!=e.media.ringerOutputDeviceId&&t.setSinkId(e.media.ringerOutputDeviceId).then(function(){}).catch(function(e){}),t.play().then(function(){}).catch(function(e){})},h.data.ringerObj=t}i(c)},answerAudioSession:function(s){if(!h)return void alert("lang.alert_no_microphone");const i=t(s);if(null===i)return;const r=i.sipSession;if(!r||r instanceof Xe)return;r.data.ringerObj&&(r.data.ringerObj.pause(),r.data.ringerObj.removeAttribute("src"),r.data.ringerObj.load(),r.data.ringerObj=null);const n=D();n&&(r.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:h,videoEnabled:!1},r.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},r.data.videoSourceDevice=null,r.data.audioSourceDevice=e.media.audioInputDeviceId,r.data.audioOutputDevice=e.media.audioOutputDeviceId,r.accept(n).then(function(){u(i,!1)}).catch(function(e){r.data.reasonCode=500,r.data.reasonText="Client Error",q(i)}))},answerVideoSession:function(s,i){const r=t(s);if(null==r)return;const o=r.sipSession;if(!o||o instanceof Xe)return;if(o.data.ringerObj&&(o.data.ringerObj.pause(),o.data.ringerObj.removeAttribute("src"),o.data.ringerObj.load(),o.data.ringerObj=null),!h)return void alert("lang.alert_no_microphone");const a=A();o.data.localMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:i??!0},o.data.remoteMediaStreamStatus={screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!0},o.data.videoSourceDevice=e.media.videoInputDeviceId,o.data.audioSourceDevice=e.media.audioInputDeviceId,o.data.audioOutputDevice=e.media.audioOutputDeviceId,o.accept(a).then(async()=>{try{await u(r,!0),o.data.localMediaStreamStatus?.videoEnabled&&await S(o,{delayMs:2e3,maxRetries:10})}catch(e){}}).catch(function(e){o.data.reasonCode=500,o.data.reasonText="Client Error",q(r)}),n(r)},makeAudioSession:H,makeVideoSession:_,toggleLocalVideoTrack:x,toggleShareScreen:P,rejectSession:function(e){const s=t(e);if(null==s)return;const i=s.sipSession;!i||i instanceof Xe||(i.state==We.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",q(s))},dialByNumber:function(e,t,r){if(null==c||0==c.isRegistered())return void alert("SIP userAgent not registered");const n=new a(s(),t);"audio"===e?H(n,t,r):_(n,t,r??[]),i(n)},makeConferenceSession:function(t,s){if(!c||!c.isRegistered()||!t)return;if(!h)return void alert("lang.alert_no_microphone");const i=k({extraHeaders:s});if(!i)return;const r=Q.utc().toISOString(),n=Qt.makeURI(`sip:700@${e.account.domain}`);t.sipSession=new Xe(c,n,i);const o=t.sipSession;o.data={line:t.lineNumber,callDirection:"outbound",dialledNumber:"700",startTime:r,videoSourceDevice:e.media.videoInputDeviceId,audioSourceDevice:e.media.audioInputDeviceId,audioOutputDevice:e.media.audioOutputDeviceId,terminateBy:"them",localMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!!l},remoteMediaStreamStatus:{screenShareEnabled:!1,soundEnabled:!0,videoEnabled:!1},earlyReject:!1},o.callType=l?"video":"audio",o.isOnHold=!1,o.delegate={onBye:e=>$(t,e,()=>q(t)),onMessage:e=>E(t,e),onInvite:e=>R(t,e),onSessionDescriptionHandler:(e,s)=>y(t,e,s,!0)};const a={requestDelegate:{onTrying:e=>T(t,e),onProgress:e=>f(t,e),onRedirect:e=>m(t,e),onAccept:e=>u(t,!0,e),onReject:e=>b(t,e,()=>q(t))}};o.invite(a).catch(e=>{})},endSession:function(e){const s=t(e);if(null==s)return;const i=s.sipSession;if(i)switch(i.state){case We.Initial:case We.Establishing:i instanceof Xe?(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",q(s));break;case We.Established:i.bye().catch(function(e){}),i.data.terminateBy="us",i.data.reasonCode=486,i.data.reasonText="Busy Here",q(s);break;default:q(s)}},recordSession:function(e){return{start:async function(){const s=t(e);if(!s?.sipSession)return;const i="video"===s.sipSession.callType;try{const e=[];let t=null;i&&(t=await navigator.mediaDevices.getDisplayMedia({video:{displaySurface:"monitor"},audio:!0}));const r=new AudioContext,o=r.createMediaStreamDestination();t?.getAudioTracks().length&&r.createMediaStreamSource(new MediaStream(t.getAudioTracks())).connect(o);const a=s.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&&t?.getVideoTracks().length&&t?.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(!s?.sipSession?.data.recordMedia)return;s.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},n(s);const t=new Blob(e,{type:d});e.length=0;const r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`recording-${i?"video":"audio"}-${Date.now()}.webm`,o.click(),URL.revokeObjectURL(r)},t?.getVideoTracks().length&&(t.getVideoTracks()[0].onended=()=>{h.stop()}),h.start(),s.sipSession.data.recordMedia={recorder:h,recording:!0,startTime:Q.utc().toISOString()},n(s)}catch(e){if(!s?.sipSession?.data.recordMedia)return;s.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},n(s)}},stop:function(){const s=t(e);if(!s?.sipSession)return;const i=s?.sipSession?.data.recordMedia?.recorder;i&&(i.stop(),s.sipSession.data.recordMedia={recorder:null,recording:!1,startTime:null},n(s))}}},toggleMuteSession:function(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.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}})}w(i,v.SOUND_TOGGLE,r),n(s)},toggleHoldSession:O,cancelSession:function(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;i instanceof Xe&&(i.data.terminateBy="us",i.data.reasonCode=0,i.data.reasonText="Call Cancelled",i.state==We.Initial||i.state==We.Establishing?i.cancel():q(s))},startTransferSession:function(e){O(e,!0)},cancelTransferSession:function(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;i.data.childsession&&i.data.childsession.dispose().then(function(){i.data.childsession=null}).catch(function(e){i.data.childsession=null}),O(e,!1),n(s)},attendedTransferSession:function(t,s){if(null==c)return;if(!c.isRegistered())return;const i=String(s);if(""===i)return;let r=t;if(!r?.sipSession)return;const o=r.sipSession;if(!o)return;o.data.transfer||(o.data.transfer=[]),o.data.transfer.push({type:"Attended",to:s,transferTime:te(),disposition:"invite",dispositionTime:te(),accept:{complete:null,eventTime:null,disposition:""}});const a=o.data.transfer.length-1,d=navigator.mediaDevices.getSupportedConstraints(),h={earlyMedia:!0,sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};if("object"!=typeof h.sessionDescriptionHandlerOptions.constraints.audio)return;if(o.data.audioSourceDevice&&"default"!=o.data.audioSourceDevice&&(h.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:o.data.audioSourceDevice}),d.autoGainControl&&(h.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=e.media.autoGainControl),d.echoCancellation&&(h.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=e.media.echoCancellation),d.noiseSuppression&&(h.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=e.media.noiseSuppression),o.data.localMediaStreamStatus?.videoEnabled){h.sessionDescriptionHandlerOptions.constraints.video={};const t=h.sessionDescriptionHandlerOptions.constraints.video;o.data.videoSourceDevice&&"default"!=o.data.videoSourceDevice&&(t.deviceId={exact:o.data.videoSourceDevice}),d.frameRate&&""!==e.media.maxFrameRate&&(t.frameRate=String(e.media.maxFrameRate)),d.height&&""!=e.media.videoHeight&&(t.height=String(e.media.videoHeight)),d.aspectRatio&&""!=e.media.videoAspectRatio&&(t.aspectRatio=String(e.media.videoAspectRatio)),("object"==typeof h.sessionDescriptionHandlerOptions.constraints.video&&0==Object.keys(h.sessionDescriptionHandlerOptions.constraints.video)?.length||"boolean"==typeof h.sessionDescriptionHandlerOptions.constraints.video)&&(h.sessionDescriptionHandlerOptions.constraints.video=!0)}const l=Qt.makeURI("sip:"+i.replace(/#/g,"%23")+"@"+e.account.domain),u=new Xe(c,l,h);u.data={},u.delegate={onBye:function(){o.data.transfer&&(o.data.transfer[a].disposition="bye",o.data.transfer[a].dispositionTime=te())},onSessionDescriptionHandler:function(e){I(r,o,e,o?.data?.localMediaStreamStatus?.videoEnabled)}},o.data.childsession=u;const g={requestDelegate:{onTrying:function(){o.data.transfer&&(o.data.transfer[a].disposition="trying",o.data.transfer[a].dispositionTime=te())},onProgress:function(){o.data.transfer&&(o.data.transfer[a].disposition="progress",o.data.transfer[a].dispositionTime=te(),o.data.transfer[a].onCancle=()=>{u.cancel().catch(function(e){}),o.data.transfer&&(o.data.transfer[a].accept.complete=!1,o.data.transfer[a].accept.disposition="cancel",o.data.transfer[a].accept.eventTime=te())})},onRedirect:function(e){},onAccept:function(){if(!o.data.transfer)return;o.data.transfer[a].disposition="accepted",o.data.transfer[a].dispositionTime=te();const e={requestDelegate:{onAccept:function(e){o.data.transfer&&(o.data.terminateBy="us",o.data.reasonCode=202,o.data.reasonText="Attended Transfer",o.data.transfer[a].accept.complete=!0,o.data.transfer[a].accept.disposition=e.message.reasonPhrase??"",o.data.transfer[a].accept.eventTime=te(),o.bye().catch(function(e){}),q(r))},onReject:function(e){o.data.transfer&&(o.data.transfer[a].accept.complete=!1,o.data.transfer[a].accept.disposition=e.message.reasonPhrase??"",o.data.transfer[a].accept.eventTime=te())}}};o.refer(u,e).catch(function(e){})},onReject:function(e){o.data.transfer&&(o.data.transfer[a].disposition=e.message.reasonPhrase??"",o.data.transfer[a].dispositionTime=te())}}};u.invite(g).catch(function(e){}),n(r)},cancelAttendedTransferSession:function(e,t){if(null==c)return;if(!c.isRegistered())return;if(""===String(t))return;let s=e;if(!s?.sipSession)return;const i=s.sipSession;i&&i.data.transfer&&i.data.transfer.forEach(e=>{e.to===t&&e.onCancle?.()})},teardownSession:q}};function ts(e){e.registrationCompleted=!0,e.isReRegister,e.registering=!1,e.isReRegister=!0,f({userAgent:e})}function ss(e){e.isReRegister=!1,f({userAgent:e})}function is(e=m()){e&&1!=e.registering&&(e.isRegistered()||(e.registering=!0,e.registerer.register({requestDelegate:{onReject(e){!function(){const e=m();e&&(e.registering=!1,f({userAgent:e}))}(e.message.reasonPhrase,e.message.statusCode)}}}),f({userAgent:e})))}function rs(e=m()){e&&(e.isReRegister=!1,e.transport.attemptingReconnection=!1,e.transport.reconnectionAttempts=d.registration.transportReconnectionAttempts,e.transport.attemptingReconnection||e.registering||window.setTimeout(function(){is(e)},500),f({userAgent:e}))}function ns(e,t=m()){if(t){t.isReRegister=!1;try{t.registerer.unregister()}catch(e){}as(t),f({userAgent:t})}}function os(e){e.isReRegister=!1,f({userAgent:e})}function as(e=m()){e&&(e.registering=!1,e.transport&&e.transport.isConnected()?rs(e):(setTimeout(function(){e.transport&&e.transport.isConnected()?rs(e):e.transport.reconnectionAttempts>0&&(e.transport.attemptingReconnection=!0,e.reconnect().catch(function(t){e.transport.attemptingReconnection=!1,as(e)}))},g.getState().configs.registration.transportReconnectionTimeout),e.transport.reconnectionAttempts=e.transport.reconnectionAttempts-1,f({userAgent:e})))}const cs=()=>{const e=g(e=>e.configs.features.enableVideo);return{getDevices:async()=>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)"audioinput"===t[c].kind?(s=!0,i.push(t[c])):"audiooutput"===t[c].kind?(r=!0,n.push(t[c])):"videoinput"===t[c].kind&&e&&(o=!0,a.push(t[c]));return{hasAudioDevice:s,audioInputDevices:i,hasSpeakerDevice:r,speakerDevices:n,hasVideoDevice:o,videoInputDevices:a}})}},ds=t(void 0),hs=({children:e,configs:t})=>{const n=g(e=>e.userAgent),a=g(e=>e.lines),c=g(e=>e.setSipStore),{getDevices:h}=cs(),l=s(()=>ee(d,t),[t]),{receiveSession:u}=es();i(()=>(c({configs:l}),async function(){await p()}(),()=>{n?.stop()}),[l]);const p=async()=>{await async function(e){const t={audio:!1,video:!1};try{return await navigator.mediaDevices.getUserMedia({...t,...e&&{[e]:!0}})}catch(e){throw"NotAllowedError"===e.name||"NotFoundError"===e.name||e.name,e}}("audio"),await m(),await f()},f=r(async()=>{let e=new Qt({uri:Qt.makeURI(`sip:${l.account.username}@${l.account.domain}`),transportOptions:{server:`wss://${l.account.wssServer}:${l.account.webSocketPort}${l.account.serverPath}`,traceSip:!1,connectionTimeout:l.registration.transportConnectionTimeout},authorizationUsername:l.account.username,authorizationPassword:l.account.password,delegate:{onInvite:u,onMessage:()=>{}}});e.isRegistered=function(){return e&&e.registerer&&e.registerer.state===Qe.Registered},e.sessions=e._sessions,e.registrationCompleted=!1,e.registering=!1,e.transport.reconnectionAttempts=l.registration.transportReconnectionAttempts||0,e.transport.attemptingReconnection=!1,e.BlfSubs=[],e.lastVoicemailCount=0,e.transport.onConnect=()=>{rs(e)},e.transport.onDisconnect=t=>{t?ns(0,e):os(e)};const t={logConfiguration:!1,expires:l.registration.registerExpires,extraHeaders:[],extraContactHeaderParams:[],refreshFrequency:75};e.registerer=new ot(e,t),e.registerer.stateChange.addListener(function(t){switch(t){case Qe.Initial:break;case Qe.Registered:ts(e);break;case Qe.Unregistered:ss(e);case Qe.Terminated:}}),await e.start().catch(function(e){ns()}),v(e)},[l]),m=async()=>{c({devicesInfo:await h()})},v=e=>{c({userAgent:e})};return o(ds.Provider,{value:{status:n?.isConnected()?"connected":"disconnected",lines:a,transport:{reconnectTransport:as}},children:e})},ls=()=>{const e=n(ds);if(!e)throw new Error("useSipProvider must be used within a SipProvider");return e},us=({lineNumber:e,...t})=>"local"===t.type?o("audio",{...t,id:`line-${e}-localAudio`}):o("div",{...t,id:`line-${e}-remoteAudios`}),gs=({lineNumber:e,...t})=>"local"===t.type?o("video",{...t,id:`line-${e}-${t.type}Video`,muted:"local"===t.type}):o("div",{...t,id:`line-${e}-remoteVideos`});export{us as AudioStream,hs as SipProvider,gs as VideoStream,se as useSessionEvents,es as useSessionMethods,ls as useSipProvider};