react-sip-kit 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +105 -105
- package/dist/index.cjs +10 -1
- package/dist/index.mjs +10 -1
- package/package.json +98 -98
package/dist/index.cjs
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("react");const s={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 i{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 r{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 r.instance||(r.instance=new r(e)),r.instance}getAudios(){return this.audioBlobs}}const n=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},o=e=>e;const a=e=>{const s=(e=>e?n(e):n)(e),i=e=>function(e,s=o){const i=t.useSyncExternalStore(e.subscribe,()=>s(e.getState()),()=>s(e.getInitialState()));return t.useDebugValue(i),i}(s,e);return Object.assign(i,s),i},c=(d=(e,t)=>({configs:s,userAgent:void 0,devicesInfo:{hasVideoDevice:!1,hasAudioDevice:!1,hasSpeakerDevice:!1,audioInputDevices:[],videoInputDevices:[],speakerDevices:[]},lines:[],audioBlobs:r.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}}))?a(d):a;var d;const l=e=>{c.setState(t=>({...t,...e}))},h=()=>c.getState().userAgent,u=()=>c.getState().configs;function g(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var p,f={exports:{}};var m=(p||(p=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 S=Object.getOwnPropertySymbols(c);for(w=0;w<S.length;w++){var T=S[w];(!($=Object.getOwnPropertyDescriptor(c,T))||$.enumerable||l)&&(f[T]=n(c[T],p-1),$.enumerable||Object.defineProperty(f,T,{enumerable:!1}))}}if(l){var y=Object.getOwnPropertyNames(c);for(w=0;w<y.length;w++){var $,I=y[w];($=Object.getOwnPropertyDescriptor(c,I))&&$.enumerable||(f[I]=n(c[I],p-1),Object.defineProperty(f,I,{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)}(f)),f.exports),v=g(m);function w(e){const t=v(e);t.registrationCompleted=!0,t.isReRegister?(t.registering=!1,console.log("ReRegistered!")):(console.log("Registered!"),t.registering=!1),t.isReRegister=!0,l({userAgent:t})}function b(e){const t=v(e);t.isReRegister=!1,l({userAgent:t})}function S(e){const t=e??v(h());null!=t&&1!=t.registering&&(t.isRegistered()||(console.log("Sending Registration..."),t.registering=!0,t.registerer.register({requestDelegate:{onReject(e){!function(){const e=h(),t=v(e);t&&(t.registering=!1),l({userAgent:t})}(e.message.reasonPhrase,e.message.statusCode)}}}),e||l({userAgent:t})))}function T(e){console.log("Connected to Web Socket!");const t=e??v(h());t&&(t.isReRegister=!1,t.transport.attemptingReconnection=!1,t.transport.ReconnectionAttempts=u().registration.transportReconnectionAttempts,t.transport.attemptingReconnection&&t.registering?window.setTimeout(function(){S(t)},500):console.warn("onTransportConnected: Register() called, but attemptingReconnection is true or registering is true"),e||l({userAgent:t}))}function y(e,t){console.warn("WebSocket Connection Failed:",e);const s=t??v(h());if(s){s.isReRegister=!1,console.log("Unregister...");try{s.registerer.unregister()}catch(e){}I(s),t||l({userAgent:s})}}function $(e){console.log("Disconnected from Web Socket!");const t=v(e);t.isReRegister=!1,l({userAgent:t})}function I(e){const t=c.getState().configs?.registration?.transportReconnectionTimeout,s=e??v(h());s&&(s.registering=!1,s.transport&&s.transport.isConnected()?T(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 T(s);s.transport.attemptingReconnection=!0,s.reconnect().catch(function(e){s.transport.attemptingReconnection=!1,console.warn("Failed to reconnect",e),I(s)})},1e3*u().registration.transportReconnectionAttempts),console.log("Waiting to Re-connect...",u().registration.transportReconnectionAttempts,"Attempt remaining",s.transport.ReconnectionAttempts),s.transport.ReconnectionAttempts=s.transport.ReconnectionAttempts-1,e||l({userAgent:s})))}var R,C={exports:{}};var E,D=(R||(R=1,C.exports=function(){var e=1e3,t=6e4,s=36e5,i="millisecond",r="second",n="minute",o="hour",a="day",c="week",d="month",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",S={};S[b]=m;var T="$isDayjsObject",y=function(e){return e instanceof C||!(!e||!e[T])},$=function e(t,s,i){var r;if(!t)return b;if("string"==typeof t){var n=t.toLowerCase();S[n]&&(r=n),s&&(S[n]=s,r=n);var o=t.split("-");if(!r&&o.length>1)return e(o[0])}else{var a=t.name;S[a]=t,r=a}return!i&&r&&(b=r),r||!i&&b},I=function(e,t){if(y(e))return e.clone();var s="object"==typeof t?t:{};return s.date=e,s.args=arguments,new C(s)},R=w;R.l=$,R.i=y,R.w=function(e,t){return I(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[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=I(e);return this.startOf(t)<=s&&s<=this.endOf(t)},v.isAfter=function(e,t){return I(e)<this.startOf(t)},v.isBefore=function(e,t){return this.endOf(t)<I(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,l=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(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,S=(f<b?f+7:f)-b;return g(i?v-S:v+(6-S),m);case a:case u:return p(w+"Hours",0);case o:return p(w+"Minutes",1);case n:return p(w+"Seconds",2);case r:return p(w+"Milliseconds",3);default:return this.clone()}},v.endOf=function(e){return this.startOf(e,!1)},v.$set=function(e,t){var s,c=R.p(e),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[R.p(e)]()},v.add=function(i,l){var u,g=this;i=Number(i);var p=R.p(l),f=function(e){var t=I(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===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 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,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 R.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 R.s(t.$y,4,"0");case"M":return a+1;case"MM":return R.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 R.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 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=I(i),w=(v.utcOffset()-this.utcOffset())*t,b=this-v,S=function(){return R.m(f,v)};switch(m){case h:p=S()/12;break;case d:p=S();break;case l:p=S()/3;break;case c:p=(b-w)/6048e5;break;case a:p=(b-w)/864e5;break;case o:p=b/s;break;case n:p=b/t;break;case r:p=b/e;break;default:p=b}return g?p:R.a(p)},v.daysInMonth=function(){return this.endOf(d).$D},v.$locale=function(){return S[this.$L]},v.locale=function(e,t){if(!e)return this.$L;var s=this.clone(),i=$(e,t,!0);return i&&(s.$L=i),s},v.clone=function(){return R.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},m}(),E=C.prototype;return I.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])}}),I.extend=function(e,t){return e.$i||(e(t,C,I),e.$i=!0),I},I.locale=$,I.isDayjs=y,I.unix=function(e){return I(1e3*e)},I.en=S[b],I.Ls=S,I.p={},I}()),C.exports),A=g(D),k={exports:{}};var H,_,x,P,q,O,M,N,j,F,U,L,B,V,G,Y,W,K,J,Z,z=(E||(E=1,k.exports=(M=/\[([^\]]+)]|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,F=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,U={years:N=31536e6,months:j=2628e6,days:O=864e5,hours:q=36e5,minutes:P=6e4,seconds:x=1e3,milliseconds:1,weeks:6048e5},L=function(e){return e instanceof J},B=function(e,t,s){return new J(e,s,t.$l)},V=function(e){return _.p(e)+"s"},G=function(e){return e<0},Y=function(e){return G(e)?Math.ceil(e):Math.floor(e)},W=function(e){return Math.abs(e)},K=function(e,t){return e?G(e)?{negative:!0,format:""+W(e)+t}:{negative:!1,format:""+e+t}:{negative:!1,format:""}},J=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 B(e*U[V(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[V(t)]=e[t]}),this.calMilliseconds(),this;if("string"==typeof e){var r=e.match(F);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)*U[s]},0)},t.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=Y(e/N),e%=N,this.$d.months=Y(e/j),e%=j,this.$d.days=Y(e/O),e%=O,this.$d.hours=Y(e/q),e%=q,this.$d.minutes=Y(e/P),e%=P,this.$d.seconds=Y(e/x),e%=x,this.$d.milliseconds=e},t.toISOString=function(){var e=K(this.$d.years,"Y"),t=K(this.$d.months,"M"),s=+this.$d.days||0;this.$d.weeks&&(s+=7*this.$d.weeks);var i=K(s,"D"),r=K(this.$d.hours,"H"),n=K(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=K(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:_.s(this.$d.years,2,"0"),YYYY:_.s(this.$d.years,4,"0"),M:this.$d.months,MM:_.s(this.$d.months,2,"0"),D:this.$d.days,DD:_.s(this.$d.days,2,"0"),H:this.$d.hours,HH:_.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:_.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:_.s(this.$d.seconds,2,"0"),SSS:_.s(this.$d.milliseconds,3,"0")};return t.replace(M,function(e,t){return t||String(s[e])})},t.as=function(e){return this.$ms/U[V(e)]},t.get=function(e){var t=this.$ms,s=V(e);return"milliseconds"===s?t%=1e3:t="weeks"===s?Y(t/U[s]):this.$d[s],t||0},t.add=function(e,t,s){var i;return i=t?e*U[V(t)]:L(e)?e.$ms:B(e,this).$ms,B(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 B(this.$ms,this)},t.humanize=function(e){return H().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}(),Z=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){H=s,_=s().$utils(),s.duration=function(e,t){var i=s.locale();return B(e,{$l:i},t)},s.isDuration=L;var i=t.prototype.add,r=t.prototype.subtract;t.prototype.add=function(e,t){return L(e)?Z(this,e,1):i.bind(this)(e,t)},t.prototype.subtract=function(e,t){return L(e)?Z(this,e,-1):r.bind(this)(e,t)}})),k.exports),X=g(z);A.extend(X);var Q,ee={exports:{}};var te=(Q||(Q=1,ee.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)}}}()),ee.exports),se=g(te);A.extend(X),A.extend(se);const ie=A;function re(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]=re(r,i):void 0!==i&&(s[e]=i)}return s}function ne(){return ie().utc().format("YYYY-MM-DD HH:mm:ss UTC")}const oe=()=>{const e=c(e=>e.updateLine),t=c(e=>e.audioBlobs),{media:{maxVideoBandwidth:s,audioOutputDeviceId:i}}=c(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=ie.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:ne()}),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:ne()}))})}):"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")}}},ae=()=>{const{audioInputDevices:e,videoInputDevices:t}=c(e=>e.devicesInfo),{media:{audioInputDeviceId:s,videoInputDeviceId:i,autoGainControl:r,maxFrameRate:n,noiseSuppression:o,videoAspectRatio:a,videoHeight:d,echoCancellation:l},registration:{inviteExtraHeaders:h}}=c(e=>e.configs),u=()=>navigator.mediaDevices.getSupportedConstraints(),g={answerAudioSpdOptions:function({option:t}={}){console.log({defaultOption:t});const i=t??{sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:{exact:"default"}},video:!1}}},n=u(),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=l),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||[],g.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=u();g.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&&d&&(s.sessionDescriptionHandlerOptions.constraints.video.height=String(d)),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(g.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 g};class ce extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class de extends ce{constructor(e){super(e||"Unsupported content type.")}}class le extends ce{constructor(e){super(e||"Request pending.")}}class he extends ce{constructor(e){super(e||"Unspecified session description handler error.")}}class ue extends ce{constructor(){super("The session has terminated.")}}class ge extends ce{constructor(e){super(e||"An error occurred during state transition.")}}class pe{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class fe{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 me{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class ve{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 we{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 be{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 Se extends be{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 Se(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 Te extends be{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 Te(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 ye(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 $e(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class Ie 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,Ie.prototype):this.__proto__=Ie.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ie)}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=$e("",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+" | "+$e("",r.column-1," ")+$e("",a-r.column,"^")}else t+="\n at "+n}return t}}const Re=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 Te(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 Te(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 Te(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 Se(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 Se(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 Se(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 Se(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 Se(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 Se(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#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),y(';.." &"'),y("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),y('%%$;2/�#*;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!70)*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""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),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/�#*;j&&&#/"!&,)'),y('%$;j/�#*;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$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$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("%$;!/�#*;!&&&#/' 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("%$;!/�#*;!&&&#/' 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("%$;!/�#*;!&&&#/' 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("%$;!/�#*;!&&&#/' 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/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;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("%$;!/�#*;!&&&#/' 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("%$;!/�#*;!&&&#/' 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 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 S(d,c)}function v(e,t){return{type:"literal",text:e,ignoreCase:t}}function w(e,t,s){return{type:"class",parts:e,inverted:t,ignoreCase:s}}function b(t){let s,i=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 S(e,t){const s=b(e),r=b(t);return{source:i,start:{offset:e,line:s.line,column:s.column},end:{offset:t,line:r.line,column:r.column}}}function 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={},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&&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;h=u.pop(),n=l.pop()}return g[0]}(n),h!==s&&c===e.length)return h;throw h!==s&&c<e.length&&T({type:"end"}),$=g,I=u<e.length?e.charAt(u):null,R=u<e.length?S(u,u+1):S(u,u),new Ie(Ie.buildMessage($,I),$,I,R);var $,I,R};var Ce;!function(e){e.parse=function(e,t){const s={startRule:t};try{Re(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}}(Ce=Ce||(Ce={}));const Ee={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 De(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function Ae(e){return Ee[e]||""}function ke(){return De(10)}function He(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 _e(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class xe{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=He(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[He(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[He(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[He(e)]}parseHeader(e,t=0){if(e=He(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=Ce.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[He(e)]=[{raw:t}]}toString(){return this.data}}class Pe extends xe{constructor(){super()}}class qe extends xe{constructor(){super()}}class Oe{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=Oe.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:ke(),this.from=Oe.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=Oe.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+De(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 Se(e,t,i)}getHeader(e){const t=this.headers[He(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[He(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[He(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[He(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: "+_e(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: "+_e(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 Me(e){return"application/sdp"===e?"session":"render"}function Ne(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Me(s),contentType:s,content:t}}function je(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function Fe(e){let t,s,i;if(e instanceof Pe&&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 qe&&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 Oe&&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(je(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=Me(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var Ue,Le;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(Ue=Ue||(Ue={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(Le=Le||(Le={}));const Be=500,Ve={T1:Be,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 Ge extends ce{constructor(e){super(e||"Transaction state error.")}}var Ye;!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"}(Ye=Ye||(Ye={}));const We=[Ye.ACK,Ye.BYE,Ye.CANCEL,Ye.INFO,Ye.INVITE,Ye.MESSAGE,Ye.NOTIFY,Ye.OPTIONS,Ye.PRACK,Ye.REFER,Ye.REGISTER,Ye.SUBSCRIBE];class Ke{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 Je{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 Ze{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof Se))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 ze,Xe;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(ze=ze||(ze={}));class Qe{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=ze.Initial,this.delegate=t.delegate,this._stateEventEmitter=new ve,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 ze.Initial:case ze.Establishing:break;case ze.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case ze.Terminating:case ze.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 ze.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 ze.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 ze.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case ze.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 ze.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!==ze.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!==ze.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new le("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=Fe(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(ze.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===ze.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(ze.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!==ze.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(ze.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!==ze.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(ze.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: "+We.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!==ze.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!==ze.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 Qe&&!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 Ue.Initial:case Ue.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case Ue.AckWait:return this.stateTransition(ze.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(ze.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(ze.Terminated),i(r)}}});case Ue.Confirmed:{const i=s.bye(e,t);return this.stateTransition(ze.Terminated),Promise.resolve(i)}case Ue.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!==ze.Established&&this.state!==ze.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 pe(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case Le.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(ze.Terminated),Promise.resolve()}case Le.Stable:{const i=Fe(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(ze.Terminated)}):Promise.resolve()}case Le.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(ze.Terminated),Promise.resolve()}case Le.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(ze.Terminated),Promise.resolve()}case Le.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===ze.Established){if(this.delegate&&this.delegate.onBye){const t=new fe(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(ze.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===ze.Established)if(this.delegate&&this.delegate.onInfo){const t=new we(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!==ze.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=Ce.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===Le.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!==ze.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(ze.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===ze.Established)if(this.delegate&&this.delegate.onMessage){const t=new Ke(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===ze.Established){if(this.onNotify){const t=new Je(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new Je(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===ze.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!==ze.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 Ze(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=Fe(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 Le.Initial:return this.getOffer(e);case Le.HaveLocalOffer:return Promise.resolve(void 0);case Le.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 Le.Stable:return this.state!==ze.Established?Promise.resolve(void 0):this.getOffer(e);case Le.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=>Ne(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 de)}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 de)}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=>Ne(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 ze.Initial:e!==ze.Establishing&&e!==ze.Established&&e!==ze.Terminating&&e!==ze.Terminated&&t();break;case ze.Establishing:e!==ze.Established&&e!==ze.Terminating&&e!==ze.Terminated&&t();break;case ze.Established:e!==ze.Terminating&&e!==ze.Terminated&&t();break;case ze.Terminating:e!==ze.Terminated&&t();break;case ze.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===ze.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=Ae(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 Te)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"}(Xe=Xe||(Xe={}));const et={"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 tt extends Qe{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(ze.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===ze.Initial&&(t.reject({statusCode:487}),this.stateTransition(ze.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=Ce.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 ze.Initial:case ze.Establishing:return this.reject().then(()=>super.dispose());case ze.Established:case ze.Terminating:case ze.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!==ze.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(ze.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(ze.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==ze.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===Xe.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!==ze.Initial&&this.state!==ze.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:Ae(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?Ne(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(ze.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===ze.Initial||this.state===ze.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new me(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(ze.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=Fe(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 Le.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Le.Stable:return this.setAnswer(t,s).then(()=>{});case Le.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Le.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case Le.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 de?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof he?this.logger.error("A session description handler occurred while sending response"):e instanceof ue?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof Ge&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===ze.Initial||this.state===ze.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(ze.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(ze.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?Ne(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 ue)).catch(e=>o(e)))},64*Ve.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=Ve.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 ue),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class st extends Qe{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=ke(),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?Ce.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?Ce.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===Xe.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===Xe.Required&&d.push("Require: replaces"),i.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(Ye.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 ze.Initial:case ze.Establishing:return this.cancel().then(()=>super.dispose());case ze.Established:case ze.Terminating:case ze.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!==ze.Initial&&this.state!==ze.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(ze.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="'+(Ae(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(ze.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==ze.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(ze.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(ze.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==ze.Terminated&&this.stateTransition(ze.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(ze.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 Qe))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!==ze.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=Ce.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 Le.Initial:case Le.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(ze.Terminated),Promise.reject(new Error("Bad Media Description"));case Le.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(ze.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(ze.Terminated),t})}case Le.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(ze.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(ze.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(ze.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(ze.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(ze.Terminated),t})}case Le.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!==ze.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=Ce.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 Le.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 Le.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case Le.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(ze.Terminated),e})}case Le.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(ze.Terminated),e})}return Promise.resolve();case Le.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===ze.Establishing||this.state===ze.Terminating?this.stateTransition(ze.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===ze.Establishing||this.state===ze.Terminating?this.stateTransition(ze.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===ze.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var it,rt,nt,ot,at,ct,dt;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(it=it||(it={}));class lt{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=it.Initial,this._waiting=!1,this._stateEventEmitter=new ve,this._waitingEventEmitter=new ve,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},lt.defaultOptions()),{registrar:s}),lt.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===Ce.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(Ye.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||lt.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||lt.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:lt.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new Te("sip","anonymous","anonymous.invalid"),refreshFrequency:lt.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===it.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===it.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 le("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&&ye(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(ye(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=Ce.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=Ce.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===it.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==it.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new le("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===it.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!==it.Registered&&this.stateTransition(it.Registered)}unregistered(){this.clearTimers(),this._state!==it.Unregistered&&this.stateTransition(it.Unregistered)}terminated(){this.clearTimers(),this._state!==it.Terminated&&this.stateTransition(it.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case it.Initial:e!==it.Registered&&e!==it.Unregistered&&e!==it.Terminated&&t();break;case it.Registered:e!==it.Unregistered&&e!==it.Terminated&&t();break;case it.Unregistered:e!==it.Registered&&e!==it.Terminated&&t();break;case it.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===it.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===it.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)}}lt.defaultExpires=600,lt.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(rt=rt||(rt={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(nt=nt||(nt={})),function(e){e.Started="Started",e.Stopped="Stopped"}(ot=ot||(ot={}));class ht{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=ht.hexChars,s=ht.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(ht.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,ht._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,ht._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,ht._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(ht.buffer32Identity.subarray(r),r),t>55&&(ht._md5cycle(this._state,i),i.set(ht.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 ht._md5cycle(this._state,i),e?this._state:ht._hex(this._state)}}function ut(e){return ht.hashStr(e)}ht.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),ht.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),ht.hexChars="0123456789abcdef",ht.hexOut=[],ht.onePassHasher=new ht,"5d41402abc4b2a76b9719d911017c592"!==ht.hashStr("hello")&&console.error("Md5 self test failed.");class gt{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=De(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=ut(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=ut(this.method+":"+this.uri),this.response=ut(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=ut(this.method+":"+this.uri+":"+ut(e||"")),this.response=ut(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=ut(this.method+":"+this.uri),this.response=ut(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"}(at=at||(at={}));class pt{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(at.error,e)}warn(e){this.genericLog(at.warn,e)}log(e){this.genericLog(at.log,e)}debug(e){this.genericLog(at.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 ft{constructor(){this.builtinEnabled=!0,this._level=at.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:at.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 pt(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new pt(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(at[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 at.error:console.error(i);break;case at.warn:console.warn(i);break;case at.log:console.log(i);break;case at.debug:console.debug(i)}}}function mt(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:Ae(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=ke()),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: "+_e(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=Ce.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=Ce.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 qe&&(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=Ce.parse(o,"Request_Response");let c,d;if(-1!==a){for(a.status_code?(c=new qe,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new Pe,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+'"')}}(ct=ct||(ct={}));class vt extends ce{constructor(e){super(e||"Unspecified transport error.")}}class wt{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 vt)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new vt(e.message):new vt,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 bt extends wt{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"}(dt=dt||(dt={}));class St extends bt{constructor(e,t,s){super(e,t,s,dt.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 dt.Proceeding:if(e.method===Ye.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case dt.Accepted:if(e.method===Ye.INVITE)return;break;case dt.Completed:if(e.method===Ye.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===Ye.ACK)return void this.stateTransition(dt.Confirmed);break;case dt.Confirmed:case dt.Terminated:if(e.method===Ye.INVITE||e.method===Ye.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 dt.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(dt.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(dt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case dt.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case dt.Completed:case dt.Confirmed:case dt.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===dt.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 dt.Proceeding:t();break;case dt.Accepted:case dt.Completed:this.state!==dt.Proceeding&&t();break;case dt.Confirmed:this.state!==dt.Completed&&t();break;case dt.Terminated:this.state!==dt.Accepted&&this.state!==dt.Completed&&this.state!==dt.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===dt.Accepted&&(this.L=setTimeout(()=>this.timerL(),Ve.TIMER_L)),e===dt.Completed&&(this.H=setTimeout(()=>this.timerH(),Ve.TIMER_H)),e===dt.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Ve.TIMER_I)),e===dt.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.")})},Ve.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===dt.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(dt.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(dt.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===dt.Accepted&&this.stateTransition(dt.Terminated)}}class Tt extends wt{constructor(e,t,s,i,r){super(t,s,Tt.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 yt extends Tt{constructor(e,t,s){super(e,t,s,dt.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Ve.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 dt.Trying:if(t>=100&&t<=199)return this.stateTransition(dt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(dt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case dt.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(dt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case dt.Completed:case dt.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(dt.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 dt.Trying:s();break;case dt.Proceeding:this.state!==dt.Trying&&s();break;case dt.Completed:this.state!==dt.Trying&&this.state!==dt.Proceeding&&s();break;case dt.Terminated:this.state!==dt.Trying&&this.state!==dt.Proceeding&&this.state!==dt.Completed&&(t||s());break;default:s()}e===dt.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Ve.TIMER_K)),e===dt.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==dt.Trying&&this.state!==dt.Proceeding||(this.onRequestTimeout(),this.stateTransition(dt.Terminated))}timerK(){this.state===dt.Completed&&this.stateTransition(dt.Terminated)}}class $t{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 Se))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 Se))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!==Ye.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===Ye.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class It extends Tt{constructor(e,t,s){super(e,t,s,dt.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Ve.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 dt.Calling:if(t>=100&&t<=199)return this.stateTransition(dt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(dt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(dt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case dt.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(dt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(dt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case dt.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 dt.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case dt.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(dt.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 dt.Calling:s();break;case dt.Proceeding:this.state!==dt.Calling&&s();break;case dt.Accepted:case dt.Completed:this.state!==dt.Calling&&this.state!==dt.Proceeding&&s();break;case dt.Terminated:this.state!==dt.Calling&&this.state!==dt.Accepted&&this.state!==dt.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),dt.Proceeding,e===dt.Completed&&(this.D=setTimeout(()=>this.timerD(),Ve.TIMER_D)),e===dt.Accepted&&(this.M=setTimeout(()=>this.timerM(),Ve.TIMER_M)),e===dt.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===dt.Calling&&(this.onRequestTimeout(),this.stateTransition(dt.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===dt.Completed&&this.stateTransition(dt.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===dt.Accepted&&this.stateTransition(dt.Terminated)}}class Rt{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(Ye.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===dt.Proceeding?new Rt(yt,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===dt.Proceeding&&new Rt(yt,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 qe;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 qe;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===dt.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 Ct extends Rt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ye.BYE,s);super(yt,e.userAgentCore,i,t),e.dispose()}}class Et extends bt{constructor(e,t,s){super(e,t,s,dt.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 dt.Trying:break;case dt.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 dt.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 dt.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 dt.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(dt.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(dt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case dt.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(dt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case dt.Completed:return;case dt.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(dt.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 dt.Trying:s();break;case dt.Proceeding:this.state!==dt.Trying&&s();break;case dt.Completed:this.state!==dt.Trying&&this.state!==dt.Proceeding&&s();break;case dt.Terminated:this.state!==dt.Proceeding&&this.state!==dt.Completed&&(t||s());break;default:s()}e===dt.Completed&&(this.J=setTimeout(()=>this.timerJ(),Ve.TIMER_J)),e===dt.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===dt.Completed&&this.stateTransition(dt.Terminated)}}class Dt{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:ke(),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 Ge(`${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 Ge(`${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 Ge(`${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 Ge(`${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 Ge(`${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 St)return this.transaction.state===dt.Proceeding||this.transaction.state===dt.Accepted;if(this.transaction instanceof Et)return this.transaction.state===dt.Trying||this.transaction.state===dt.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof St)return this.transaction.state===dt.Proceeding;if(this.transaction instanceof Et)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof St)return this.transaction.state===dt.Proceeding;if(this.transaction instanceof Et)return this.transaction.state===dt.Trying||this.transaction.state===dt.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof St)return this.transaction.state===dt.Proceeding;if(this.transaction instanceof Et)return this.transaction.state===dt.Trying||this.transaction.state===dt.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof St)return this.transaction.state===dt.Proceeding;if(this.transaction instanceof Et)return this.transaction.state===dt.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=mt(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===dt.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 At extends Dt{constructor(e,t,s){super(Et,e.userAgentCore,t,s)}}class kt extends Rt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ye.INFO,s);super(yt,e.userAgentCore,i,t)}}class Ht extends Dt{constructor(e,t,s){super(Et,e.userAgentCore,t,s)}}class _t extends Rt{constructor(e,t,s){super(yt,e,t,s)}}class xt extends Dt{constructor(e,t,s){super(Et,e,t,s)}}class Pt extends Rt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ye.NOTIFY,s);super(yt,e.userAgentCore,i,t)}}class qt extends Dt{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Et,i,t,s)}}class Ot extends Rt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ye.PRACK,s);super(yt,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class Mt extends Dt{constructor(e,t,s){super(Et,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 Nt extends Rt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ye.INVITE,s);super(It,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 jt extends Dt{constructor(e,t,s){super(St,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 Ft extends Rt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ye.REFER,s);super(yt,e.userAgentCore,i,t)}}class Ut extends Dt{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Et,i,t,s)}}class Lt extends $t{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=Le.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof St&&(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=Le.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?Ue.Early:this.ackWait?Ue.AckWait:this._signalingState===Le.Closed?Ue.Terminated:Ue.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 It))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof It))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(Ye.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 St){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==dt.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 Ct(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 kt(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 Nt(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(Ye.MESSAGE,t);return new _t(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 Pt(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Ot(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 Ft(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==Ye.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===Ye.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!==Le.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===Ye.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case Ye.BYE:{const t=new At(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case Ye.INFO:{const t=new Ht(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case Ye.INVITE:{const t=new jt(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case Ye.MESSAGE:{const t=new xt(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ye.NOTIFY:{const t=new qt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case Ye.PRACK:{const t=new Mt(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case Ye.REFER:{const t=new Ut(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 It)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!==Le.HaveLocalOffer&&this.signalingState!==Le.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Le.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=Fe(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===Le.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Pe)switch(this._signalingState){case Le.Initial:case Le.Stable:this._signalingState=Le.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Le.HaveLocalOffer:this._signalingState=Le.Stable,this._answer=t;break;case Le.HaveRemoteOffer:case Le.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof qe)switch(this._signalingState){case Le.Initial:case Le.Stable:this._signalingState=Le.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Le.HaveLocalOffer:this._signalingState=Le.Stable,this._answer=t;break;case Le.HaveRemoteOffer:case Le.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Oe)switch(this._signalingState){case Le.Initial:case Le.Stable:this._signalingState=Le.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Le.HaveLocalOffer:break;case Le.HaveRemoteOffer:this._signalingState=Le.Stable,this._answer=t;break;case Le.Closed:break;default:throw new Error("Unexpected signaling state.")}if(je(e))switch(this._signalingState){case Le.Initial:case Le.Stable:this._signalingState=Le.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Le.HaveLocalOffer:break;case Le.HaveRemoteOffer:this._signalingState=Le.Stable,this._answer=t;break;case Le.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof St){const e=this.initialTransaction;let t=Ve.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Ve.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===dt.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 St){const e=this.reinviteUserAgentServer.transaction;let t=Ve.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Ve.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===dt.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class Bt extends Rt{constructor(e,t,s){super(It,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===dt.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=$t.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof It))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Lt(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!==Le.Initial&&s.signalingState!==Le.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=$t.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 It))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 It))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Lt(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==Le.Initial&&s.signalingState!==Le.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 Vt extends Dt{constructor(e,t,s){super(St,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new Ge(`${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 St))throw new Error("Transaction not instance of InviteClientTransaction.");const t=$t.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Lt(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: "+We.toString();if(!e.body)if(this.confirmedDialog.signalingState===Le.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Le.Initial||this.confirmedDialog.signalingState===Le.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!==Le.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new Ge(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof St))throw new Error("Transaction not instance of InviteClientTransaction.");const t=$t.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Lt(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!==Le.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 Gt extends Rt{constructor(e,t,s){super(yt,e,t,s)}}class Yt extends Rt{constructor(e,t,s){super(yt,e,t,s)}}class Wt extends Dt{constructor(e,t,s){super(Et,e,t,s),this.core=e}}class Kt extends Rt{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Ye.SUBSCRIBE,s);super(yt,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 Jt extends $t{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 Se))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===Ye.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: "+We.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!==rt.Pending&&this.subscriptionState!==rt.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 Kt(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(),Ve.TIMER_N)),i}terminate(){this.stateTransition(rt.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+We.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(rt.Pending,r);break;case"active":this.stateTransition(rt.Active,r);break;case"terminated":this.stateTransition(rt.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new qt(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 rt.Initial:case rt.NotifyWait:return void s();case rt.Pending:if(this.subscriptionState!==rt.NotifyWait&&this.subscriptionState!==rt.Pending)return void s();break;case rt.Active:case rt.Terminated:if(this.subscriptionState!==rt.NotifyWait&&this.subscriptionState!==rt.Pending&&this.subscriptionState!==rt.Active)return void s();break;default:return void s()}e===rt.Pending&&t&&(this.subscriptionExpires=t),e===rt.Active&&t&&(this.subscriptionExpires=t),e===rt.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==rt.Terminated&&(this.stateTransition(rt.Terminated),this.onTerminated())}}class Zt extends Rt{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(yt,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=rt.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=rt.Pending;break;case"active":this.subscriptionState=rt.Active;break;case"terminated":this.subscriptionState=rt.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==rt.Terminated){const t=Jt.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Jt(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(),Ve.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 zt extends Dt{constructor(e,t,s){super(Et,e,t,s),this.core=e}}const Xt=["application/sdp","application/dtmf-relay"];class Qt{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 Bt(this,e,t)}message(e,t){return new _t(this,e,t)}publish(e,t){return new Gt(this,e,t)}register(e,t){return new Yt(this,e,t)}subscribe(e,t){return new Zt(this,e,t)}request(e,t){return new Rt(yt,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===Ye.REGISTER&&h.push("path","gruu"),e===Ye.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 Oe(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=mt(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===Ye.ACK&&s&&s.transaction.state===dt.Accepted&&s instanceof Vt?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==Ye.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof St&&s.transaction.state===dt.Proceeding&&s instanceof Vt&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!We.includes(e.method)){const t="Allow: "+We.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!==Ye.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==Ye.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===Ye.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 qt(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===Ye.OPTIONS){const t="Allow: "+We.toString(),s="Accept: "+Xt.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==Ye.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case Ye.ACK:break;case Ye.BYE:this.replyStateless(e,{statusCode:481});break;case Ye.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case Ye.INFO:this.replyStateless(e,{statusCode:405});break;case Ye.INVITE:{const t=new Vt(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case Ye.MESSAGE:{const t=new xt(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ye.NOTIFY:{const t=new qt(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case Ye.OPTIONS:{const t="Allow: "+We.toString(),s="Accept: "+Xt.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case Ye.REFER:{const t=new Ut(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case Ye.REGISTER:{const t=new Wt(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case Ye.SUBSCRIBE:{const t=new zt(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 es{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),es.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),es.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),es.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),es.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),es.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),es.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),es.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 ts(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 es(r,e,i)}}class ss{constructor(e,t){if(this._state=nt.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new ve,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({},ss.defaultOptions),t);const s=this.configuration.server,i=Ce.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===nt.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case nt.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(nt.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case nt.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(nt.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case nt.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(nt.Connecting)}catch(e){if(e instanceof ge)return Promise.reject(e);throw e}break;case nt.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(nt.Connecting)}catch(e){if(e instanceof ge)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(nt.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 nt.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(nt.Disconnecting)}catch(e){if(e instanceof ge)return Promise.reject(e);throw e}break;case nt.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(nt.Disconnecting)}catch(e){if(e instanceof ge)return Promise.reject(e);throw e}break;case nt.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(nt.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case nt.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(nt.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!==nt.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(nt.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===nt.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===nt.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(nt.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 ge("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 nt.Connecting:e!==nt.Connected&&e!==nt.Disconnecting&&e!==nt.Disconnected&&s();break;case nt.Connected:e!==nt.Disconnecting&&e!==nt.Disconnected&&s();break;case nt.Disconnecting:e!==nt.Connecting&&e!==nt.Disconnected&&s();break;case nt.Disconnected:e!==nt.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===nt.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===nt.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===nt.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===nt.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===nt.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===nt.Connected?r():n(t||new Error("Connect aborted."))}if(i===nt.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===nt.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}}ss.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class is{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=ot.Stopped,this._stateEventEmitter=new ve,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},is.defaultOptions()),{sipjsId:De(5)}),{uri:new Te("sip","anonymous."+De(6),"anonymous.invalid")}),{viaHost:De(12)+".invalid"}),is.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 ft,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=at.error;break;case"warn":this.loggerFactory.level=at.warn;break;case"log":this.loggerFactory.level=at.log;break;case"debug":this.loggerFactory.level=at.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:is.newUUID(),-1===Ce.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return Ce.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:ts(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:Xe.Unsupported,sipExtensionReplaces:Xe.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:ss,transportOptions:{},uri:new Te("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===ot.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===ot.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(ot.Started),this.transport.connect())}async stop(){if(this.state===ot.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(ot.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(ot.Stopped)}_makeInviter(e,t){return new st(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:De(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new Te("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===Xe.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===Xe.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>et[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 gt(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new Qt(s,{onInvite:e=>{var t;const s=new tt(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!==Xe.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 Ke(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new Je(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!==ot.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==ot.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=ct.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===ot.Stopped&&t instanceof Pe)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 Pe){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=_e(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof qe){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=_e(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 Pe)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof qe))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 ot.Started:e!==ot.Stopped&&s();break;case ot.Stopped:e!==ot.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 rs=t.createContext(void 0);exports.AudioStream=({lineNumber:t,type:s,...i})=>e.jsx("audio",{...i,id:`line-${t}${s?`-${s}`:""}-remoteAudio`}),exports.SipProvider=({children:s,configs:r})=>{const n=c(),{userAgent:o,configs:a,devicesInfo:{hasAudioDevice:d,hasSpeakerDevice:l,hasVideoDevice:h,audioInputDevices:u,videoInputDevices:g,speakerDevices:p},setSipStore:f}=n,m=t.useMemo(()=>re(a,r),[r,a]),v=(()=>{const e=c(e=>e.configs),t=c(e=>e.findLineByNumber),s=c(e=>e.getNewLineNumber),r=c(e=>e.addLine),n=c(e=>e.removeLine),o=c(e=>e.updateLine),a=c(e=>e.countIdSessions),d=c(e=>e.userAgent),l=c(e=>e.audioBlobs),{hasAudioDevice:h,hasVideoDevice:u}=c(e=>e.devicesInfo),{onInviteAccepted:g,onInviteCancel:p,onInviteProgress:f,onInviteRedirected:m,onInviteRejected:v,onInviteTrying:w,onSessionDescriptionHandlerCreated:b,onSessionReceivedBye:S,onSessionReceivedMessage:T,onSessionReinvited:y,onTransferSessionDescriptionHandlerCreated:$}=oe(),{answerAudioSpdOptions:I,makeAudioSpdOptions:R,answerVideoSpdOptions:C,makeVideoSpdOptions:E}=ae();function D(t,s,i){if(console.log(222,{lineObj:t,dialledNumber:s,extraHeaders:i}),!d)return;if(!d.isRegistered())return;if(null===t)return;if(!h)return void console.error("lang.alert_no_microphone");console.log("makeAudioSession");const r=R({extraHeaders:i});if(!r)return;let n=ie.utc();console.log("INVITE (audio): "+s+"@"+e.account.domain);const o=is.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);t.sipSession=new st(d,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){S(t,e,()=>_(t))},onMessage:function(e){T(t,e)},onInvite:function(e){y(t,e)},onSessionDescriptionHandler:function(e,s){console.log("Session Description Handler created:",{sdh:e}),b(t,e,s,!1)}};const a={requestDelegate:{onTrying:function(e){console.log("makeAudioSession 1"),w(t,e)},onProgress:function(e){console.log("makeAudioSession 2"),f(t,e)},onRedirect:function(e){console.log("makeAudioSession 3"),m(t,e)},onAccept:function(e){console.log("makeAudioSession 4"),g(t,!1,e)},onReject:function(e){console.log("makeAudioSession 5"),v(t,e,()=>_(t))}}};t.sipSession.invite(a).catch(function(e){console.warn("Failed to send INVITE:",e)})}function A(t,s,i){if(null==d)return;if(!d.isRegistered())return;if(null==t)return;if(!h)return void alert("lang.alert_no_microphone");if(0==u)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=ie.utc();console.log("INVITE (video): "+s+"@"+e.account.domain);const o=is.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);console.log("video",{spdOptions:r}),t.sipSession=new st(d,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){S(t,e,()=>_(t))},onMessage:function(e){T(t,e)},onInvite:function(e){y(t,e)},onSessionDescriptionHandler:function(e,s){b(t,e,s,!0)}};const a={requestDelegate:{onTrying:function(e){w(t,e)},onProgress:function(e){f(t,e)},onRedirect:function(e){m(t,e)},onAccept:function(e){g(t,!0,e)},onReject:function(e){v(t,e,()=>_(t))}}};t.sipSession.invite(a).catch(function(e){console.warn("Failed to send INVITE:",e)})}function k(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 n={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:ne()}),i.data.isHold=!0},onReject:function(){i.isOnHold=!1,console.warn("Failed to put the call on hold:",e)}}};i.invite(n).catch(function(e){i.isOnHold=!1,console.warn("Error attempting to put the call on hold:",e)}),o(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 n={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:ne()}),i.data.isHold=!1},onReject:function(){i.isOnHold=!0,console.warn("Failed to put the call on hold",e)}}};i.invite(n).catch(function(e){i.isOnHold=!0,console.warn("Error attempting to take to call off hold",e)}),o(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),n(e.lineNumber))}return{receiveCall:function(t){console.log("receiveCall",{session:t});const n=t.remoteIdentity.displayName||t.remoteIdentity.uri.user||"";let o=t.remoteIdentity.uri.user??"";console.log(`Incoming call from: ${n}`);const c=ie.utc(),d=new i(s(),n,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=o,d.sipSession.data.metaData=d?.metaData,d.sipSession.data.callstart=c.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 h=t.incomingInviteRequest.message.headers;if(h["P-Asserted-Identity"]){const t=h["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}`)&&(o=s[1].split("@")[0],console.log("Using P-Asserted-Identity:",o))}}d.sipSession.delegate={onBye:function(e){S(d,e,()=>_(d))},onMessage:function(e){T(d,e)},onInvite:function(e){y(d,e)},onSessionDescriptionHandler:function(e,s){b(d,e,s,t.data.withVideo)}},d.sipSession.incomingInviteRequest.delegate={onCancel:function(e){console.log("onInviteCancel"),p(d,e,()=>_(d))}};const u=a(t.id);if(e.features.enableRingtone)if(u>=1){console.log("Audio:",l.CallWaiting.url);const t=new Audio(l.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:",l.Ringtone.url,l.Ringtone);const t=new Audio(l.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}r(d)},answerAudioSession:function(s){if(!h)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 st)return;r.data.ringerObj&&(r.data.ringerObj.pause(),r.data.ringerObj.removeAttribute("src"),r.data.ringerObj.load(),r.data.ringerObj=null);const n=I();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(){g(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 st)return;if(r.data.ringerObj&&(r.data.ringerObj.pause(),r.data.ringerObj.removeAttribute("src"),r.data.ringerObj.load(),r.data.ringerObj=null),!h)return void alert("lang.alert_no_microphone");const n=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(n).then(function(){g(i,!0)}).catch(function(e){console.warn("Failed to answer call",e,r),r.data.reasonCode=500,r.data.reasonText="Client Error",_(i)}),o(i)},makeAudioSession:D,makeVideoSession:A,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 st||(i.state==ze.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,n={},o){if(null==d||0==d.isRegistered())return void alert("userAgent not registered");const a=new i(s(),t,n);"audio"===e?D(a,t,o):A(a,t,o??[]),r(a)},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 ze.Initial:case ze.Establishing:i instanceof st?(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 ze.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:k,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:ne()}),i.data.isMute=!0,o(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:ne()}),i.data.isMute=!1,o(s)},cancelSession:function(e){const s=t(e);if(null==s||null==s.sipSession)return;const i=s.sipSession;i instanceof st&&(i.data.terminateBy="us",i.data.reasonCode=0,i.data.reasonText="Call Cancelled",console.log("Cancelling session : "+e),i.state==ze.Initial||i.state==ze.Establishing?i.cancel():(console.warn("Session not in correct state for cancel.",s.sipSession.state),console.log("Attempting teardown : "+e),_(s)))},startTransferSession:function(e){k(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),o(s)},attendedTransferSession:function(t,s){if(null==d)return;if(!d.isRegistered())return;const i=String(s);if(""===i)return void console.warn("Cannot transfer, no number");let r=t;if(console.log("attendedTransfer lineNumber",d.isRegistered(),i,r),!r?.sipSession)return void console.warn("Null line or session");const n=r.sipSession;if(!n)return;n.data.transfer||(n.data.transfer=[]),n.data.transfer.push({type:"Attended",to:s,transferTime:ne(),disposition:"invite",dispositionTime:ne(),accept:{complete:null,eventTime:null,disposition:""}});const a=n.data.transfer.length-1,c=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(n.data.audioSourceDevice&&"default"!=n.data.audioSourceDevice&&(l.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:n.data.audioSourceDevice}),c.autoGainControl&&(l.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=e.media.autoGainControl),c.echoCancellation&&(l.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=e.media.echoCancellation),c.noiseSuppression&&(l.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=e.media.noiseSuppression),n.data.withVideo){l.sessionDescriptionHandlerOptions.constraints.video={};const t=l.sessionDescriptionHandlerOptions.constraints.video;n.data.videoSourceDevice&&"default"!=n.data.videoSourceDevice&&(t.deviceId={exact:n.data.videoSourceDevice}),c.frameRate&&""!==e.media.maxFrameRate&&(t.frameRate=String(e.media.maxFrameRate)),c.height&&""!=e.media.videoHeight&&(t.height=String(e.media.videoHeight)),c.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=is.makeURI("sip:"+i.replace(/#/g,"%23")+"@"+e.account.domain),u=new st(d,h,l);u.data={},u.delegate={onBye:function(){console.log("New call session ended with BYE"),n.data.transfer&&(n.data.transfer[a].disposition="bye",n.data.transfer[a].dispositionTime=ne())},onSessionDescriptionHandler:function(e){$(r,n,e,n?.data?.withVideo)}},n.data.childsession=u;const g={requestDelegate:{onTrying:function(){n.data.transfer&&(n.data.transfer[a].disposition="trying",n.data.transfer[a].dispositionTime=ne())},onProgress:function(){console.log("onProgress"),n.data.transfer&&(n.data.transfer[a].disposition="progress",n.data.transfer[a].dispositionTime=ne(),n.data.transfer[a].onCancle=()=>{u.cancel().catch(function(e){console.warn("Failed to CANCEL",e)}),n.data.transfer&&(n.data.transfer[a].accept.complete=!1,n.data.transfer[a].accept.disposition="cancel",n.data.transfer[a].accept.eventTime=ne())},console.log("New call session canceled"))},onRedirect:function(e){console.log("Redirect received:",e)},onAccept:function(){if(!n.data.transfer)return;n.data.transfer[a].disposition="accepted",n.data.transfer[a].dispositionTime=ne();const e={requestDelegate:{onAccept:function(e){console.log("Attended transfer Accepted"),n.data.transfer&&(n.data.terminateBy="us",n.data.reasonCode=202,n.data.reasonText="Attended Transfer",n.data.transfer[a].accept.complete=!0,n.data.transfer[a].accept.disposition=e.message.reasonPhrase??"",n.data.transfer[a].accept.eventTime=ne(),n.bye().catch(function(e){console.warn("Could not BYE after blind transfer:",e)}),_(r))},onReject:function(e){console.warn("Attended transfer rejected:",e),n.data.transfer&&(n.data.transfer[a].accept.complete=!1,n.data.transfer[a].accept.disposition=e.message.reasonPhrase??"",n.data.transfer[a].accept.eventTime=ne())}}};n.refer(u,e).catch(function(e){console.warn("Failed to REFER",e)})},onReject:function(e){n.data.transfer&&(console.log("New call session rejected: ",e.message.reasonPhrase),n.data.transfer[a].disposition=e.message.reasonPhrase??"",n.data.transfer[a].dispositionTime=ne())}}};u.invite(g).catch(function(e){console.warn("Failed to send INVITE:",e)}),o(r)},cancelAttendedTransferSession:function(e,t){if(null==d)return;if(!d.isRegistered())return;const s=String(t);if(""===s)return void console.warn("Cannot transfer, no number");let i=e;if(console.log("attendedTransfer lineNumber",d.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:_}})(),S=oe();t.useEffect(()=>(f({configs:m}),async function(){await R()}(),()=>{o?.stop()}),[m]);const R=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"),E(),C()},C=t.useCallback(()=>{let e=new is({uri:is.makeURI(`sip:${m.account.username}@${m.account.domain}`),transportOptions:{server:`wss://${m.account.wssServer}:${m.account.webSocketPort}${m.account.serverPath}`,traceSip:!1,connectionTimeout:m.registration.transportConnectionTimeout},authorizationUsername:m.account.username,authorizationPassword:m.account.password,delegate:{onInvite:v.receiveCall,onMessage:()=>console.log("Received message")}});e.isRegistered=function(){return e&&e.registerer&&e.registerer.state===it.Registered},e.sessions=e._sessions,e.registrationCompleted=!1,e.registering=!1,e.transport.ReconnectionAttempts=m.registration.transportReconnectionAttempts||0,e.transport.attemptingReconnection=!1,e.BlfSubs=[],e.lastVoicemailCount=0,e.transport.onConnect=()=>{T(e)},e.transport.onDisconnect=t=>{t?y(t,e):$(e)};const t={logConfiguration:!1,expires:m.registration.registerExpires,extraHeaders:[],extraContactHeaderParams:[],refreshFrequency:75};e.registerer=new lt(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 it.Initial:break;case it.Registered:w(e);break;case it.Unregistered:b(e);case it.Terminated:}}),e.start(),Object.defineProperty(e,"_key",{enumerable:!1,value:1}),console.log("createUserAgent",{ua:e}),D(e)},[m]),E=()=>{var e;e=e=>{if(console.log({deviceInfos:e}),!e)return;let t=d,s=u,i=l,r=p,n=h,o=g;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&&m.features.enableVideo&&(n=!0,o.push(e[a]));f({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)})},D=e=>{f({userAgent:e})};return e.jsx(rs.Provider,{value:{lines:n.lines,session:{methods:v,events:S},transport:{reconnectTransport:I}},children:s})},exports.VideoStream=({lineNumber:t,...s})=>"local"===s.type?e.jsx("video",{...s,id:`line-${t}-${s.type}Video`,muted:"local"===s.type}):e.jsx("div",{...s,id:`line-${t}-remoteVideos`}),exports.useSipProvider=()=>{const e=t.useContext(rs);if(!e)throw new Error("useSipProvider must be used within a SipProvider");return e};
|
|
1
|
+
"use strict";var e=require("react");function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s,i={exports:{}},r={};var n,o,a={};
|
|
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 c(){return n||(n=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 c(e,s,r,n,a,c,h,g){var p,f=s.children;if(void 0!==f)if(n)if(D(f)){for(n=0;n<f.length;n++)d(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 d(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(){l||(l=!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:u,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,c,0,null===(p=C.A)?null:p.getOwner(),r,h,g)}function d(e){"object"==typeof e&&null!==e&&e.$$typeof===u&&e._store&&(e._store.validated=1)}var l,h=e,u=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=h.__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=(h={"react-stack-bottom-frame":function(e){return e()}})["react-stack-bottom-frame"].bind(h,n)(),_=k(r(n)),x={};a.Fragment=p,a.jsx=function(e,t,s,i,n){var o=1e4>C.recentlyCreatedOwnerStacks++;return c(e,t,s,!1,0,n,o?Error("react-stack-top-frame"):H,o?k(r(e)):_)},a.jsxs=function(e,t,s,i,n){var o=1e4>C.recentlyCreatedOwnerStacks++;return c(e,t,s,!0,0,n,o?Error("react-stack-top-frame"):H,o?k(r(e)):_)}}()),a}var d=(o||(o=1,"production"===process.env.NODE_ENV?i.exports=function(){if(s)return r;s=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(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 r.Fragment=t,r.jsx=i,r.jsxs=i,r}():i.exports=c()),i.exports);const l={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 h{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 u{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 u.instance||(u.instance=new u(e)),u.instance}getAudios(){return this.audioBlobs}}const g=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},p=e=>e;const f=t=>{const s=(e=>e?g(e):g)(t),i=t=>function(t,s=p){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},m=(v=(e,t)=>({configs:l,userAgent:void 0,devicesInfo:{hasVideoDevice:!1,hasAudioDevice:!1,hasSpeakerDevice:!1,audioInputDevices:[],videoInputDevices:[],speakerDevices:[]},lines:[],audioBlobs:u.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}}))?f(v):f;var v;const w=e=>{m.setState(t=>({...t,...e}))},b=()=>m.getState().userAgent,y=()=>m.getState().configs;var S,T={exports:{}};var $=(S||(S=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)}(T)),T.exports),R=t($);function I(e){const t=R(e);t.registrationCompleted=!0,t.isReRegister?(t.registering=!1,console.log("ReRegistered!")):(console.log("Registered!"),t.registering=!1),t.isReRegister=!0,w({userAgent:t})}function C(e){const t=R(e);t.isReRegister=!1,w({userAgent:t})}function E(e){const t=e??R(b());null!=t&&1!=t.registering&&(t.isRegistered()||(console.log("Sending Registration..."),t.registering=!0,t.registerer.register({requestDelegate:{onReject(e){!function(){const e=b(),t=R(e);t&&(t.registering=!1),w({userAgent:t})}(e.message.reasonPhrase,e.message.statusCode)}}}),e||w({userAgent:t})))}function D(e){console.log("Connected to Web Socket!");const t=e??R(b());t&&(t.isReRegister=!1,t.transport.attemptingReconnection=!1,t.transport.ReconnectionAttempts=y().registration.transportReconnectionAttempts,t.transport.attemptingReconnection&&t.registering?window.setTimeout(function(){E(t)},500):console.warn("onTransportConnected: Register() called, but attemptingReconnection is true or registering is true"),e||w({userAgent:t}))}function k(e,t){console.warn("WebSocket Connection Failed:",e);const s=t??R(b());if(s){s.isReRegister=!1,console.log("Unregister...");try{s.registerer.unregister()}catch(e){}H(s),t||w({userAgent:s})}}function A(e){console.log("Disconnected from Web Socket!");const t=R(e);t.isReRegister=!1,w({userAgent:t})}function H(e){const t=m.getState().configs?.registration?.transportReconnectionTimeout,s=e??R(b());s&&(s.registering=!1,s.transport&&s.transport.isConnected()?D(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 D(s);s.transport.attemptingReconnection=!0,s.reconnect().catch(function(e){s.transport.attemptingReconnection=!1,console.warn("Failed to reconnect",e),H(s)})},1e3*y().registration.transportReconnectionAttempts),console.log("Waiting to Re-connect...",y().registration.transportReconnectionAttempts,"Attempt remaining",s.transport.ReconnectionAttempts),s.transport.ReconnectionAttempts=s.transport.ReconnectionAttempts-1,e||w({userAgent:s})))}var _,x={exports:{}};var P,O=(_||(_=1,x.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}()),x.exports),q=t(O),M={exports:{}};var N,j,F,U,L,B,V,G,Y,W,K,J,Z,z,X,Q,ee,te,se,ie,re=(P||(P=1,M.exports=(V=/\[([^\]]+)]|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,W=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,K={years:G=31536e6,months:Y=2628e6,days:B=864e5,hours:L=36e5,minutes:U=6e4,seconds:F=1e3,milliseconds:1,weeks:6048e5},J=function(e){return e instanceof se},Z=function(e,t,s){return new se(e,s,t.$l)},z=function(e){return j.p(e)+"s"},X=function(e){return e<0},Q=function(e){return X(e)?Math.ceil(e):Math.floor(e)},ee=function(e){return Math.abs(e)},te=function(e,t){return e?X(e)?{negative:!0,format:""+ee(e)+t}:{negative:!1,format:""+e+t}:{negative:!1,format:""}},se=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 Z(e*K[z(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[z(t)]=e[t]}),this.calMilliseconds(),this;if("string"==typeof e){var r=e.match(W);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)*K[s]},0)},t.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=Q(e/G),e%=G,this.$d.months=Q(e/Y),e%=Y,this.$d.days=Q(e/B),e%=B,this.$d.hours=Q(e/L),e%=L,this.$d.minutes=Q(e/U),e%=U,this.$d.seconds=Q(e/F),e%=F,this.$d.milliseconds=e},t.toISOString=function(){var e=te(this.$d.years,"Y"),t=te(this.$d.months,"M"),s=+this.$d.days||0;this.$d.weeks&&(s+=7*this.$d.weeks);var i=te(s,"D"),r=te(this.$d.hours,"H"),n=te(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=te(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:j.s(this.$d.years,2,"0"),YYYY:j.s(this.$d.years,4,"0"),M:this.$d.months,MM:j.s(this.$d.months,2,"0"),D:this.$d.days,DD:j.s(this.$d.days,2,"0"),H:this.$d.hours,HH:j.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:j.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:j.s(this.$d.seconds,2,"0"),SSS:j.s(this.$d.milliseconds,3,"0")};return t.replace(V,function(e,t){return t||String(s[e])})},t.as=function(e){return this.$ms/K[z(e)]},t.get=function(e){var t=this.$ms,s=z(e);return"milliseconds"===s?t%=1e3:t="weeks"===s?Q(t/K[s]):this.$d[s],t||0},t.add=function(e,t,s){var i;return i=t?e*K[z(t)]:J(e)?e.$ms:Z(e,this).$ms,Z(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 Z(this.$ms,this)},t.humanize=function(e){return N().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}(),ie=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){N=s,j=s().$utils(),s.duration=function(e,t){var i=s.locale();return Z(e,{$l:i},t)},s.isDuration=J;var i=t.prototype.add,r=t.prototype.subtract;t.prototype.add=function(e,t){return J(e)?ie(this,e,1):i.bind(this)(e,t)},t.prototype.subtract=function(e,t){return J(e)?ie(this,e,-1):r.bind(this)(e,t)}})),M.exports),ne=t(re);q.extend(ne);var oe,ae={exports:{}};var ce=(oe||(oe=1,ae.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)}}}()),ae.exports),de=t(ce);q.extend(ne),q.extend(de);const le=q;function he(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]=he(r,i):void 0!==i&&(s[e]=i)}return s}function ue(){return le().utc().format("YYYY-MM-DD HH:mm:ss UTC")}const ge=()=>{const e=m(e=>e.updateLine),t=m(e=>e.audioBlobs),{media:{maxVideoBandwidth:s,audioOutputDeviceId:i}}=m(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=le.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:ue()}),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:ue()}))})}):"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")}}},pe=()=>{const{audioInputDevices:e,videoInputDevices:t}=m(e=>e.devicesInfo),{media:{audioInputDeviceId:s,videoInputDeviceId:i,autoGainControl:r,maxFrameRate:n,noiseSuppression:o,videoAspectRatio:a,videoHeight:c,echoCancellation:d},registration:{inviteExtraHeaders:l}}=m(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 fe extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class me extends fe{constructor(e){super(e||"Unsupported content type.")}}class ve extends fe{constructor(e){super(e||"Request pending.")}}class we extends fe{constructor(e){super(e||"Unspecified session description handler error.")}}class be extends fe{constructor(){super("The session has terminated.")}}class ye extends fe{constructor(e){super(e||"An error occurred during state transition.")}}class Se{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class Te{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 $e{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class Re{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class Ie{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 Ce{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 Ee extends Ce{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 Ee(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 De extends Ce{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 De(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 ke(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 Ae(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class He extends Error{constructor(e,t,s,i){super(),this.message=e,this.expected=t,this.found=s,this.location=i,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,He.prototype):this.__proto__=He.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,He)}static buildMessage(e,t){function s(e){return e.charCodeAt(0).toString(16).toUpperCase()}function i(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function r(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(e));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(n);let s,i;if(t.sort(),t.length>0){for(s=1,i=1;s<t.length;s++)t[s-1]!==t[s]&&(t[i]=t[s],i++);t.length=i}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((o=t)?'"'+i(o)+'"':"end of input")+" found.");var o}format(e){let t="Error: "+this.message;if(this.location){let s,i=null;for(s=0;s<e.length;s++)if(e[s].source===this.location.source){i=e[s].text.split(/\r\n|\n|\r/g);break}let r=this.location.start,n=this.location.source+":"+r.line+":"+r.column;if(i){let e=this.location.end,s=Ae("",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+" | "+Ae("",r.column-1," ")+Ae("",a-r.column,"^")}else t+="\n at "+n}return t}}const _e=function(e,t){const s={},i=(t=void 0!==t?t:{}).grammarSource,r={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let n=119;const o=["\r\n",v("\r\n",!1),/^[0-9]/,w([["0","9"]],!1,!1),/^[a-zA-Z]/,w([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,w([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,w([["\0","ÿ"]],!1,!1),/^["]/,w(['"'],!1,!1)," ",v(" ",!1),"\t",v("\t",!1),/^[a-zA-Z0-9]/,w([["a","z"],["A","Z"],["0","9"]],!1,!1),";",v(";",!1),"/",v("/",!1),"?",v("?",!1),":",v(":",!1),"@",v("@",!1),"&",v("&",!1),"=",v("=",!1),"+",v("+",!1),"$",v("$",!1),",",v(",",!1),"-",v("-",!1),"_",v("_",!1),".",v(".",!1),"!",v("!",!1),"~",v("~",!1),"*",v("*",!1),"'",v("'",!1),"(",v("(",!1),")",v(")",!1),"%",v("%",!1),function(){return" "},function(){return":"},/^[!-~]/,w([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,w([["",""]],!1,!1),/^[\x80-\xBF]/,w([["","¿"]],!1,!1),/^[a-f]/,w([["a","f"]],!1,!1),"`",v("`",!1),"<",v("<",!1),">",v(">",!1),"\\",v("\\",!1),"[",v("[",!1),"]",v("]",!1),"{",v("{",!1),"}",v("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,w([["!","'"]],!1,!1),/^[*-[]/,w([["*","["]],!1,!1),/^[\]-~]/,w([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,w([["#","["]],!1,!1),/^[\0-\t]/,w([["\0","\t"]],!1,!1),/^[\v-\f]/,w([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,w([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new De(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 De(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 De(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 Ee(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 Ee(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 Ee(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 Ee(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 Ee(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 Ee(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",v("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",v("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",v("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",v("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",v("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},v("UDP",!0),v("TCP",!0),v("TLS",!0),v("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=f()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",v("refresher",!1),"uas",v("uas",!1),"uac",v("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",v("stuns",!0),"stun",v("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",v("?transport=",!1),"turns",v("turns",!0),"turn",v("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=f()},"Referred-By",v("Referred-By",!1),"b",v("b",!1),"cid",v("cid",!1)],a=[T('2 ""6 7!'),T('4"""5!7#'),T('4$""5!7%'),T('4&""5!7\''),T(";'.# &;("),T('4(""5!7)'),T('4*""5!7+'),T('2,""6,7-'),T('2.""6.7/'),T('40""5!71'),T('22""6273. &24""6475.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T(";).# &;,"),T('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),T('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),T('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),T(';.." &"'),T("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),T('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),T('4\\""5!7].# &;3'),T('4^""5!7_'),T('4`""5!7a'),T(';!.) &4b""5!7c'),T('%$;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),T('%$;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),T('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273. &28""6879. &2j""6j7k. &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),T('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),T("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),T("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),T("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),T("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),T("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),T('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),T('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),T("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),T("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),T("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),T("%;//0#;&/'$8\":~\" )(\"'#&'#"),T("%;&/0#;//'$8\":~\" )(\"'#&'#"),T("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),T('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),T("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),T("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:
$!!)($'#(#'#(\"'#&'#"),T(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),T('%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("\'#&\'#'),T("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:$ )($'#(#'#(\"'#&'#"),T("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),T('%3""5$7.) &3""5#7/\' 8!:!! )'),T('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:# )(#\'#("\'#&\'#'),T("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),T('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),T('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:! )'),T('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;U.) &;\\.# &;X/& 8!:! )"),T('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:# )(#\'#("\'#&\'#'),T('$4""5!7/,#0)*4""5!7&&&#'),T('%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("\'#&\'#'),T('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),T('%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),T('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),T("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),T("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),T('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7/,#;!/#$+")("\'#&\'#.# &;!'),T('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),T('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),T(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),T('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),T('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),T('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),T('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),T('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),T('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),T('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),T('%$;j/�#*;j&&&#/"!&,)'),T('%$;j/�#*;j&&&#/"!&,)'),T(";k.) &;+.# &;-"),T('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),T('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),T('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),T("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),T("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),T('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),T(";.# &;r"),T("%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T(";M.# &;t"),T("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),T('%;v.# &;w/J#%26""6677/,#;/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T('%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#\'#("\'#&\'#'),T('%24""6475/,#;{/#$+")("\'#&\'#'),T("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),T(";*.) &;+.# &;-"),T(';+. &;-. &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),T('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),T("$;~0#*;~&"),T(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),T('%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),T(";.# &;"),T('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),T('$;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/#0*;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),T("$;y0#*;y&"),T('%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),T('2Õ""6Õ7Ö'),T('2×""6×7Ø'),T('2Ù""6Ù7Ú'),T('2Û""6Û7Ü'),T('2Ý""6Ý7Þ'),T('2ß""6ß7à'),T('2á""6á7â'),T('2ã""6ã7ä'),T('2å""6å7æ'),T('2ç""6ç7è'),T('2é""6é7ê'),T("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),T("%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T("%;/' 8!:ì!! )"),T("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),T("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),T("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),T("%;:.c &%;/Y#$%;A/,#;/#$+\")(\"'#&'#06*%;A/,#;/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),T("%;L.# &;/]#$%;B/,#;/#$+\")(\"'#&'#06*%;B/,#;/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),T("%;.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),T("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),T(";.) &;.# &; "),T("%3ò\"\"5!7ó/:#;</1$;/($8#:ô#! )(#'#(\"'#&'#"),T("%3õ\"\"5'7ö/:#;</1$;/($8#:÷#! )(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ø!! )"),T('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),T('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),T(";6.) &;T.# &;H"),T("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),T(";¥.# &; "),T('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),T("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:Č!! )"),T("%;©/& 8!:č! )"),T("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T(";«.# &;¬"),T('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),T('3Ę""5\'7ę./ &3Ě""5)7ě.# &;'),T(";6.# &;®"),T('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),T(";.# &;6"),T("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),T(";6.# &;H"),T("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),T("%;/' 8!:ğ!! )"),T('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),T('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),T("%;L.# &;/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),T(";¹.# &; "),T("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),T("%;/' 8!:Ħ!! )"),T("%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),T(";¾"),T("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),T("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),T(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),T("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),T("%;I/' 8!:Ĭ!! )"),T("%3ĭ\"\"5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),T(";t.# &;w"),T("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),T("%;I/' 8!:ı!! )"),T("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),T('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),T('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),T('%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),T('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),T("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),T("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),T("%;/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),T('%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),T("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),T("%;/& 8!:Ő! )"),T('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),T('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),T("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),T("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),T("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;/($8#:ū#! )(#'#(\"'#&'#.# &; "),T('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),T(';1." &"'),T('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),T("%;L.# &;/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),T(";¹.# &; "),T("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),T("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),T(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),T("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),T("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),T("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),T("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),T("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),T("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),T('%3""5#7Ó.# &;6/\' 8!:Ƌ!! )'),T('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),T('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),T('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),T('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),T(";¾"),T('%;/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),T(";ô.# &; "),T('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),T('%;/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),T("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),T("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),T("$;%0#*;%&"),T("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),T('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),T('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),T("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),T(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),T('2L""6L7M. &2B""6B7C. &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),T('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),T('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),T('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),T("%;Ą/#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),T("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),T("%;ă/,#;ă/#$+\")(\"'#&'#"),T("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),T("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),T('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),T(";.# &;L"),T("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),T("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,d=0;const 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 He(He.buildMessage($,R),$,R,I);var $,R,I};var xe;!function(e){e.parse=function(e,t){const s={startRule:t};try{_e(e,s)}catch(e){s.data=-1}return s.data},e.nameAddrHeaderParse=function(t){const s=e.parse(t,"Name_Addr_Header");return-1!==s?s:void 0},e.URIParse=function(t){const s=e.parse(t,"SIP_URI");return-1!==s?s:void 0}}(xe=xe||(xe={}));const Pe={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 Oe(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function qe(e){return Pe[e]||""}function Me(){return Oe(10)}function Ne(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 je(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class Fe{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=Ne(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[Ne(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[Ne(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[Ne(e)]}parseHeader(e,t=0){if(e=Ne(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=xe.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[Ne(e)]=[{raw:t}]}toString(){return this.data}}class Ue extends Fe{constructor(){super()}}class Le extends Fe{constructor(){super()}}class Be{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=Be.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:Me(),this.from=Be.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=Be.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+Oe(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 Ee(e,t,i)}getHeader(e){const t=this.headers[Ne(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[Ne(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[Ne(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[Ne(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: "+je(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: "+je(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 Ve(e){return"application/sdp"===e?"session":"render"}function Ge(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Ve(s),contentType:s,content:t}}function Ye(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function We(e){let t,s,i;if(e instanceof Ue&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof Le&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof Be&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,i=e.body.body}if(Ye(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=Ve(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var Ke,Je;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(Ke=Ke||(Ke={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(Je=Je||(Je={}));const Ze=500,ze={T1:Ze,T2:4e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class Xe extends fe{constructor(e){super(e||"Transaction state error.")}}var Qe;!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"}(Qe=Qe||(Qe={}));const et=[Qe.ACK,Qe.BYE,Qe.CANCEL,Qe.INFO,Qe.INVITE,Qe.MESSAGE,Qe.NOTIFY,Qe.OPTIONS,Qe.PRACK,Qe.REFER,Qe.REGISTER,Qe.SUBSCRIBE];class tt{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 st{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 it{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof Ee))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 rt,nt;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(rt=rt||(rt={}));class ot{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=rt.Initial,this.delegate=t.delegate,this._stateEventEmitter=new Re,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case rt.Initial:case rt.Establishing:break;case rt.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case rt.Terminating:case rt.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 rt.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 rt.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 rt.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case rt.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 rt.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!==rt.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!==rt.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new ve("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=We(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(rt.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===rt.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(rt.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!==rt.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(rt.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!==rt.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(rt.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: "+et.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!==rt.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!==rt.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 ot&&!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 Ke.Initial:case Ke.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case Ke.AckWait:return this.stateTransition(rt.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(rt.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(rt.Terminated),i(r)}}});case Ke.Confirmed:{const i=s.bye(e,t);return this.stateTransition(rt.Terminated),Promise.resolve(i)}case Ke.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!==rt.Established&&this.state!==rt.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 Se(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case Je.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(rt.Terminated),Promise.resolve()}case Je.Stable:{const i=We(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(rt.Terminated)}):Promise.resolve()}case Je.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(rt.Terminated),Promise.resolve()}case Je.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(rt.Terminated),Promise.resolve()}case Je.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===rt.Established){if(this.delegate&&this.delegate.onBye){const t=new Te(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(rt.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===rt.Established)if(this.delegate&&this.delegate.onInfo){const t=new Ie(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!==rt.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=xe.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===Je.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!==rt.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(rt.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===rt.Established)if(this.delegate&&this.delegate.onMessage){const t=new tt(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===rt.Established){if(this.onNotify){const t=new st(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new st(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===rt.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!==rt.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 it(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=We(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case Je.Initial:return this.getOffer(e);case Je.HaveLocalOffer:return Promise.resolve(void 0);case Je.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 Je.Stable:return this.state!==rt.Established?Promise.resolve(void 0):this.getOffer(e);case Je.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=>Ge(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 me)}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 me)}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=>Ge(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 rt.Initial:e!==rt.Establishing&&e!==rt.Established&&e!==rt.Terminating&&e!==rt.Terminated&&t();break;case rt.Establishing:e!==rt.Established&&e!==rt.Terminating&&e!==rt.Terminated&&t();break;case rt.Established:e!==rt.Terminating&&e!==rt.Terminated&&t();break;case rt.Terminating:e!==rt.Terminated&&t();break;case rt.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===rt.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=qe(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 De)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"}(nt=nt||(nt={}));const at={"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 ct extends ot{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(rt.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===rt.Initial&&(t.reject({statusCode:487}),this.stateTransition(rt.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=xe.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 rt.Initial:case rt.Establishing:return this.reject().then(()=>super.dispose());case rt.Established:case rt.Terminating:case rt.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!==rt.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(rt.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(rt.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==rt.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===nt.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!==rt.Initial&&this.state!==rt.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:qe(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?Ge(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(rt.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===rt.Initial||this.state===rt.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new $e(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(rt.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=We(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case Je.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Je.Stable:return this.setAnswer(t,s).then(()=>{});case Je.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Je.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case Je.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 me?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof we?this.logger.error("A session description handler occurred while sending response"):e instanceof be?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof Xe&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===rt.Initial||this.state===rt.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(rt.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(rt.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?Ge(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let n;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n}))).then(t=>{let a,c;this._dialog=t.session,t.session.delegate={onPrack:s=>{a=s,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(s=>{try{c=a.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:a,prackResponse:c,progressResponse:t})}catch(e){o(e)}}).catch(e=>o(e)))}};const d=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then(()=>o(new be)).catch(e=>o(e)))},64*ze.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=ze.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 be),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class dt extends ot{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=Me(),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?xe.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?xe.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===nt.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===nt.Required&&d.push("Require: replaces"),i.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(Qe.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 rt.Initial:case rt.Establishing:return this.cancel().then(()=>super.dispose());case rt.Established:case rt.Terminating:case rt.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!==rt.Initial&&this.state!==rt.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(rt.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="'+(qe(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(rt.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==rt.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(rt.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(rt.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==rt.Terminated&&this.stateTransition(rt.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(rt.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 ot))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!==rt.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=xe.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 Je.Initial:case Je.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(rt.Terminated),Promise.reject(new Error("Bad Media Description"));case Je.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(rt.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(rt.Terminated),t})}case Je.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(rt.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(rt.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(rt.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(rt.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(rt.Terminated),t})}case Je.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!==rt.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=xe.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 Je.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 Je.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case Je.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(rt.Terminated),e})}case Je.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(rt.Terminated),e})}return Promise.resolve();case Je.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===rt.Establishing||this.state===rt.Terminating?this.stateTransition(rt.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===rt.Establishing||this.state===rt.Terminating?this.stateTransition(rt.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===rt.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var lt,ht,ut,gt,pt,ft,mt;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(lt=lt||(lt={}));class vt{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=lt.Initial,this._waiting=!1,this._stateEventEmitter=new Re,this._waitingEventEmitter=new Re,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},vt.defaultOptions()),{registrar:s}),vt.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===xe.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(Qe.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||vt.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||vt.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:vt.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new De("sip","anonymous","anonymous.invalid"),refreshFrequency:vt.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===lt.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===lt.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new ve("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&&ke(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(ke(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=xe.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=xe.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===lt.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==lt.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new ve("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===lt.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==lt.Registered&&this.stateTransition(lt.Registered)}unregistered(){this.clearTimers(),this._state!==lt.Unregistered&&this.stateTransition(lt.Unregistered)}terminated(){this.clearTimers(),this._state!==lt.Terminated&&this.stateTransition(lt.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case lt.Initial:e!==lt.Registered&&e!==lt.Unregistered&&e!==lt.Terminated&&t();break;case lt.Registered:e!==lt.Unregistered&&e!==lt.Terminated&&t();break;case lt.Unregistered:e!==lt.Registered&&e!==lt.Terminated&&t();break;case lt.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===lt.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===lt.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}vt.defaultExpires=600,vt.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(ht=ht||(ht={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(ut=ut||(ut={})),function(e){e.Started="Started",e.Stopped="Stopped"}(gt=gt||(gt={}));class wt{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=wt.hexChars,s=wt.hexOut;let i,r,n,o;for(o=0;o<4;o+=1)for(r=8*o,i=e[o],n=0;n<8;n+=2)s[r+1+n]=t.charAt(15&i),i>>>=4,s[r+0+n]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],i=e[1],r=e[2],n=e[3];s+=(i&r|~i&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[3]-1044525330|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[7]-45705983|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[11]-1990404162|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[15]+1236535329|0,i=(i<<22|i>>>10)+r|0,s+=(i&n|r&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[0]-373897302|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[4]-405537848|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[8]+1163531501|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[12]-1926607734|0,i=(i<<20|i>>>12)+r|0,s+=(i^r^n)+t[5]-378558|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[14]-35309556|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[10]-1094730640|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[6]+76029189|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[2]-995338651|0,i=(i<<23|i>>>9)+r|0,s+=(r^(i|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[5]-57434055|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[1]-2054922799|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[13]+1309151649|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[9]-343485551|0,i=(i<<21|i>>>11)+r|0,e[0]=s+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(wt.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,r,n=this._bufferLength;for(r=0;r<e.length;r+=1){if(i=e.charCodeAt(r),i<128)t[n++]=i;else if(i<2048)t[n++]=(i>>>6)+192,t[n++]=63&i|128;else if(i<55296||i>56319)t[n++]=(i>>>12)+224,t[n++]=i>>>6&63|128,t[n++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++r)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=(i>>>18)+240,t[n++]=i>>>12&63|128,t[n++]=i>>>6&63|128,t[n++]=63&i|128}n>=64&&(this._dataLength+=64,wt._md5cycle(this._state,s),n-=64,s[0]=s[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e.charCodeAt(n++);if(r<64)break;this._dataLength+=64,wt._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e[n++];if(r<64)break;this._dataLength+=64,wt._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}getState(){const e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}}setState(e){const t=e.buffer,s=e.state,i=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,s=this._buffer8,i=this._buffer32,r=1+(t>>2);let n;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(wt.buffer32Identity.subarray(r),r),t>55&&(wt._md5cycle(this._state,i),i.set(wt.buffer32Identity)),n=8*this._dataLength,n<=4294967295)i[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return wt._md5cycle(this._state,i),e?this._state:wt._hex(this._state)}}function bt(e){return wt.hashStr(e)}wt.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),wt.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),wt.hexChars="0123456789abcdef",wt.hexOut=[],wt.onePassHasher=new wt,"5d41402abc4b2a76b9719d911017c592"!==wt.hashStr("hello")&&console.error("Md5 self test failed.");class yt{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=Oe(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=bt(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=bt(this.method+":"+this.uri),this.response=bt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=bt(this.method+":"+this.uri+":"+bt(e||"")),this.response=bt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=bt(this.method+":"+this.uri),this.response=bt(t+":"+this.nonce+":"+s))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(pt=pt||(pt={}));class St{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(pt.error,e)}warn(e){this.genericLog(pt.warn,e)}log(e){this.genericLog(pt.log,e)}debug(e){this.genericLog(pt.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 Tt{constructor(){this.builtinEnabled=!0,this._level=pt.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:pt.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 St(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new St(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(pt[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 pt.error:console.error(i);break;case pt.warn:console.warn(i);break;case pt.log:console.log(i);break;case pt.debug:console.debug(i)}}}function $t(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:qe(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=Me()),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: "+je(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=xe.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=xe.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 Le&&(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=xe.parse(o,"Request_Response");let c,d;if(-1!==a){for(a.status_code?(c=new Le,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new Ue,c.method=a.method,c.ruri=a.uri),c.data=e,r=n+2;;){if(n=t(e,r),-2===n){d=r+2;break}if(-1===n)return void i.error("malformed message");const o=s(c,e,r,n);if(o&&!0!==o)return void i.error(o.error);r=n+2}return c.hasHeader("content-length")?c.body=e.substr(d,Number(c.getHeader("content-length"))):c.body=e.substring(d),c}i.warn('error parsing first line of SIP message: "'+o+'"')}}(ft=ft||(ft={}));class Rt extends fe{constructor(e){super(e||"Unspecified transport error.")}}class It{constructor(e,t,s,i,r){this._transport=e,this._user=t,this._id=s,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof Rt)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new Rt(e.message):new Rt,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Ct extends It{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"}(mt=mt||(mt={}));class Et extends Ct{constructor(e,t,s){super(e,t,s,mt.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 mt.Proceeding:if(e.method===Qe.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case mt.Accepted:if(e.method===Qe.INVITE)return;break;case mt.Completed:if(e.method===Qe.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===Qe.ACK)return void this.stateTransition(mt.Confirmed);break;case mt.Confirmed:case mt.Terminated:if(e.method===Qe.INVITE||e.method===Qe.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 mt.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(mt.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(mt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case mt.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case mt.Completed:case mt.Confirmed:case mt.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===mt.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 mt.Proceeding:t();break;case mt.Accepted:case mt.Completed:this.state!==mt.Proceeding&&t();break;case mt.Confirmed:this.state!==mt.Completed&&t();break;case mt.Terminated:this.state!==mt.Accepted&&this.state!==mt.Completed&&this.state!==mt.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===mt.Accepted&&(this.L=setTimeout(()=>this.timerL(),ze.TIMER_L)),e===mt.Completed&&(this.H=setTimeout(()=>this.timerH(),ze.TIMER_H)),e===mt.Confirmed&&(this.I=setTimeout(()=>this.timerI(),ze.TIMER_I)),e===mt.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.")})},ze.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===mt.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(mt.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(mt.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===mt.Accepted&&this.stateTransition(mt.Terminated)}}class Dt extends It{constructor(e,t,s,i,r){super(t,s,Dt.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 kt extends Dt{constructor(e,t,s){super(e,t,s,mt.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),ze.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 mt.Trying:if(t>=100&&t<=199)return this.stateTransition(mt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(mt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case mt.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(mt.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case mt.Completed:case mt.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(mt.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 mt.Trying:s();break;case mt.Proceeding:this.state!==mt.Trying&&s();break;case mt.Completed:this.state!==mt.Trying&&this.state!==mt.Proceeding&&s();break;case mt.Terminated:this.state!==mt.Trying&&this.state!==mt.Proceeding&&this.state!==mt.Completed&&(t||s());break;default:s()}e===mt.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),ze.TIMER_K)),e===mt.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==mt.Trying&&this.state!==mt.Proceeding||(this.onRequestTimeout(),this.stateTransition(mt.Terminated))}timerK(){this.state===mt.Completed&&this.stateTransition(mt.Terminated)}}class At{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 Ee))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 Ee))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!==Qe.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===Qe.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Ht extends Dt{constructor(e,t,s){super(e,t,s,mt.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),ze.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 mt.Calling:if(t>=100&&t<=199)return this.stateTransition(mt.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(mt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(mt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case mt.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(mt.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(mt.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case mt.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 mt.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case mt.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(mt.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 mt.Calling:s();break;case mt.Proceeding:this.state!==mt.Calling&&s();break;case mt.Accepted:case mt.Completed:this.state!==mt.Calling&&this.state!==mt.Proceeding&&s();break;case mt.Terminated:this.state!==mt.Calling&&this.state!==mt.Accepted&&this.state!==mt.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),mt.Proceeding,e===mt.Completed&&(this.D=setTimeout(()=>this.timerD(),ze.TIMER_D)),e===mt.Accepted&&(this.M=setTimeout(()=>this.timerM(),ze.TIMER_M)),e===mt.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===mt.Calling&&(this.onRequestTimeout(),this.stateTransition(mt.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===mt.Completed&&this.stateTransition(mt.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===mt.Accepted&&this.stateTransition(mt.Terminated)}}class _t{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const s=this.core.makeOutgoingRequestMessage(Qe.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===mt.Proceeding?new _t(kt,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===mt.Proceeding&&new _t(kt,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 Le;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 Le;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===mt.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 xt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Qe.BYE,s);super(kt,e.userAgentCore,i,t),e.dispose()}}class Pt extends Ct{constructor(e,t,s){super(e,t,s,mt.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 mt.Trying:break;case mt.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 mt.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 mt.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 mt.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(mt.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(mt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case mt.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(mt.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case mt.Completed:return;case mt.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(mt.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 mt.Trying:s();break;case mt.Proceeding:this.state!==mt.Trying&&s();break;case mt.Completed:this.state!==mt.Trying&&this.state!==mt.Proceeding&&s();break;case mt.Terminated:this.state!==mt.Proceeding&&this.state!==mt.Completed&&(t||s());break;default:s()}e===mt.Completed&&(this.J=setTimeout(()=>this.timerJ(),ze.TIMER_J)),e===mt.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===mt.Completed&&this.stateTransition(mt.Terminated)}}class Ot{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:Me(),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 Xe(`${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 Xe(`${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 Xe(`${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 Xe(`${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 Xe(`${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 Et)return this.transaction.state===mt.Proceeding||this.transaction.state===mt.Accepted;if(this.transaction instanceof Pt)return this.transaction.state===mt.Trying||this.transaction.state===mt.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Et)return this.transaction.state===mt.Proceeding;if(this.transaction instanceof Pt)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Et)return this.transaction.state===mt.Proceeding;if(this.transaction instanceof Pt)return this.transaction.state===mt.Trying||this.transaction.state===mt.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Et)return this.transaction.state===mt.Proceeding;if(this.transaction instanceof Pt)return this.transaction.state===mt.Trying||this.transaction.state===mt.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Et)return this.transaction.state===mt.Proceeding;if(this.transaction instanceof Pt)return this.transaction.state===mt.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=$t(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===mt.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 qt extends Ot{constructor(e,t,s){super(Pt,e.userAgentCore,t,s)}}class Mt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Qe.INFO,s);super(kt,e.userAgentCore,i,t)}}class Nt extends Ot{constructor(e,t,s){super(Pt,e.userAgentCore,t,s)}}class jt extends _t{constructor(e,t,s){super(kt,e,t,s)}}class Ft extends Ot{constructor(e,t,s){super(Pt,e,t,s)}}class Ut extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Qe.NOTIFY,s);super(kt,e.userAgentCore,i,t)}}class Lt extends Ot{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Pt,i,t,s)}}class Bt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Qe.PRACK,s);super(kt,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class Vt extends Ot{constructor(e,t,s){super(Pt,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 Gt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Qe.INVITE,s);super(Ht,e.userAgentCore,i,t),this.delegate=t,e.signalingStateTransition(i),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class Yt extends Ot{constructor(e,t,s){super(Et,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),i}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),i}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class Wt extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Qe.REFER,s);super(kt,e.userAgentCore,i,t)}}class Kt extends Ot{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Pt,i,t,s)}}class Jt extends At{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=Je.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof Et&&(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=Je.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?Ke.Early:this.ackWait?Ke.AckWait:this._signalingState===Je.Closed?Ke.Terminated:Ke.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Ht))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(Qe.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 Et){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==mt.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 xt(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 Mt(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 Gt(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(Qe.MESSAGE,t);return new jt(this.core,s,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new Ut(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Bt(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new Wt(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==Qe.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===Qe.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!==Je.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===Qe.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof Ee))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case Qe.BYE:{const t=new qt(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case Qe.INFO:{const t=new Nt(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case Qe.INVITE:{const t=new Yt(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case Qe.MESSAGE:{const t=new Ft(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Qe.NOTIFY:{const t=new Lt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case Qe.PRACK:{const t=new Vt(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case Qe.REFER:{const t=new Kt(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Ht)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),i=t&&t.includes("100rel")&&s?Number(s):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0}signalingStateRollback(){this._signalingState!==Je.HaveLocalOffer&&this.signalingState!==Je.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Je.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=We(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===Je.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Ue)switch(this._signalingState){case Je.Initial:case Je.Stable:this._signalingState=Je.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Je.HaveLocalOffer:this._signalingState=Je.Stable,this._answer=t;break;case Je.HaveRemoteOffer:case Je.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Le)switch(this._signalingState){case Je.Initial:case Je.Stable:this._signalingState=Je.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Je.HaveLocalOffer:this._signalingState=Je.Stable,this._answer=t;break;case Je.HaveRemoteOffer:case Je.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Be)switch(this._signalingState){case Je.Initial:case Je.Stable:this._signalingState=Je.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Je.HaveLocalOffer:break;case Je.HaveRemoteOffer:this._signalingState=Je.Stable,this._answer=t;break;case Je.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Ye(e))switch(this._signalingState){case Je.Initial:case Je.Stable:this._signalingState=Je.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Je.HaveLocalOffer:break;case Je.HaveRemoteOffer:this._signalingState=Je.Stable,this._answer=t;break;case Je.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Et){const e=this.initialTransaction;let t=ze.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,ze.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===mt.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 Et){const e=this.reinviteUserAgentServer.transaction;let t=ze.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,ze.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===mt.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class Zt extends _t{constructor(e,t,s){super(Ht,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===mt.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=At.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Jt(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!==Je.Initial&&s.signalingState!==Je.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=At.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Ht))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");s=new Jt(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==Je.Initial&&s.signalingState!==Je.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 zt extends Ot{constructor(e,t,s){super(Et,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new Xe(`${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 Et))throw new Error("Transaction not instance of InviteClientTransaction.");const t=At.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Jt(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: "+et.toString();if(!e.body)if(this.confirmedDialog.signalingState===Je.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Je.Initial||this.confirmedDialog.signalingState===Je.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!==Je.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new Xe(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Et))throw new Error("Transaction not instance of InviteClientTransaction.");const t=At.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Jt(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!==Je.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 Xt extends _t{constructor(e,t,s){super(kt,e,t,s)}}class Qt extends _t{constructor(e,t,s){super(kt,e,t,s)}}class es extends Ot{constructor(e,t,s){super(Pt,e,t,s),this.core=e}}class ts extends _t{constructor(e,t,s){const i=e.createOutgoingRequestMessage(Qe.SUBSCRIBE,s);super(kt,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 ss extends At{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 Ee))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===Qe.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: "+et.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!==ht.Pending&&this.subscriptionState!==ht.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 ts(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(),ze.TIMER_N)),i}terminate(){this.stateTransition(ht.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+et.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(ht.Pending,r);break;case"active":this.stateTransition(ht.Active,r);break;case"terminated":this.stateTransition(ht.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new Lt(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 ht.Initial:case ht.NotifyWait:return void s();case ht.Pending:if(this.subscriptionState!==ht.NotifyWait&&this.subscriptionState!==ht.Pending)return void s();break;case ht.Active:case ht.Terminated:if(this.subscriptionState!==ht.NotifyWait&&this.subscriptionState!==ht.Pending&&this.subscriptionState!==ht.Active)return void s();break;default:return void s()}e===ht.Pending&&t&&(this.subscriptionExpires=t),e===ht.Active&&t&&(this.subscriptionExpires=t),e===ht.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==ht.Terminated&&(this.stateTransition(ht.Terminated),this.onTerminated())}}class is extends _t{constructor(e,t,s){const i=t.getHeader("Event");if(!i)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(kt,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=ht.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=ht.Pending;break;case"active":this.subscriptionState=ht.Active;break;case"terminated":this.subscriptionState=ht.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==ht.Terminated){const t=ss.initialDialogStateForSubscription(this.message,e.message);this.dialog=new ss(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(),ze.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 rs extends Ot{constructor(e,t,s){super(Pt,e,t,s),this.core=e}}const ns=["application/sdp","application/dtmf-relay"];class os{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Zt(this,e,t)}message(e,t){return new jt(this,e,t)}publish(e,t){return new Xt(this,e,t)}register(e,t){return new Qt(this,e,t)}subscribe(e,t){return new is(this,e,t)}request(e,t){return new _t(kt,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===Qe.REGISTER&&h.push("path","gruu"),e===Qe.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 Be(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=$t(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===Qe.ACK&&s&&s.transaction.state===mt.Accepted&&s instanceof zt?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==Qe.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof Et&&s.transaction.state===mt.Proceeding&&s instanceof zt&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!et.includes(e.method)){const t="Allow: "+et.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!==Qe.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==Qe.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===Qe.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 Lt(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===Qe.OPTIONS){const t="Allow: "+et.toString(),s="Accept: "+ns.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==Qe.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case Qe.ACK:break;case Qe.BYE:this.replyStateless(e,{statusCode:481});break;case Qe.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case Qe.INFO:this.replyStateless(e,{statusCode:405});break;case Qe.INVITE:{const t=new zt(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case Qe.MESSAGE:{const t=new Ft(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Qe.NOTIFY:{const t=new Lt(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case Qe.OPTIONS:{const t="Allow: "+et.toString(),s="Accept: "+ns.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case Qe.REFER:{const t=new Kt(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case Qe.REGISTER:{const t=new es(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case Qe.SUBSCRIBE:{const t=new rs(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 as{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),as.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),as.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),as.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),as.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),as.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),as.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),as.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 cs(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 as(r,e,i)}}class ds{constructor(e,t){if(this._state=ut.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new Re,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,i=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},ds.defaultOptions),t);const s=this.configuration.server,i=xe.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===ut.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case ut.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ut.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case ut.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ut.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case ut.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ut.Connecting)}catch(e){if(e instanceof ye)return Promise.reject(e);throw e}break;case ut.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ut.Connecting)}catch(e){if(e instanceof ye)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(ut.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 ut.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ut.Disconnecting)}catch(e){if(e instanceof ye)return Promise.reject(e);throw e}break;case ut.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ut.Disconnecting)}catch(e){if(e instanceof ye)return Promise.reject(e);throw e}break;case ut.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ut.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case ut.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ut.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!==ut.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(ut.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===ut.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===ut.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(ut.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 ye("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 ut.Connecting:e!==ut.Connected&&e!==ut.Disconnecting&&e!==ut.Disconnected&&s();break;case ut.Connected:e!==ut.Disconnecting&&e!==ut.Disconnected&&s();break;case ut.Disconnecting:e!==ut.Connecting&&e!==ut.Disconnected&&s();break;case ut.Disconnected:e!==ut.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===ut.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===ut.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===ut.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===ut.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===ut.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===ut.Connected?r():n(t||new Error("Connect aborted."))}if(i===ut.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===ut.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}}ds.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class ls{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=gt.Stopped,this._stateEventEmitter=new Re,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ls.defaultOptions()),{sipjsId:Oe(5)}),{uri:new De("sip","anonymous."+Oe(6),"anonymous.invalid")}),{viaHost:Oe(12)+".invalid"}),ls.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new Tt,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=pt.error;break;case"warn":this.loggerFactory.level=pt.warn;break;case"log":this.loggerFactory.level=pt.log;break;case"debug":this.loggerFactory.level=pt.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,i=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==i&&(this.options.reconnectionDelay=i),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:ls.newUUID(),-1===xe.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return xe.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:cs(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:nt.Unsupported,sipExtensionReplaces:nt.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:ds,transportOptions:{},uri:new De("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===gt.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===gt.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(gt.Started),this.transport.connect())}async stop(){if(this.state===gt.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(gt.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(gt.Stopped)}_makeInviter(e,t){return new dt(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:Oe(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new De("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===nt.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===nt.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>at[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 yt(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport};return new os(s,{onInvite:e=>{var t;const s=new ct(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!==nt.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 tt(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new st(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!==gt.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==gt.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=ft.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===gt.Stopped&&t instanceof Ue)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof Ue){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=je(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof Le){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=je(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof Ue)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof Le))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 gt.Started:e!==gt.Stopped&&s();break;case gt.Stopped:e!==gt.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 hs=e.createContext(void 0);exports.AudioStream=({lineNumber:e,type:t,...s})=>d.jsx("audio",{...s,id:`line-${e}${t?`-${t}`:""}-remoteAudio`}),exports.SipProvider=({children:t,configs:s})=>{const i=m(),{userAgent:r,devicesInfo:{hasAudioDevice:n,hasSpeakerDevice:o,hasVideoDevice:a,audioInputDevices:c,videoInputDevices:u,speakerDevices:g},setSipStore:p}=i,f=e.useMemo(()=>he(l,s),[s]),v=(()=>{const e=m(e=>e.configs),t=m(e=>e.findLineByNumber),s=m(e=>e.getNewLineNumber),i=m(e=>e.addLine),r=m(e=>e.removeLine),n=m(e=>e.updateLine),o=m(e=>e.countIdSessions),a=m(e=>e.userAgent),c=m(e=>e.audioBlobs),{hasAudioDevice:d,hasVideoDevice:l}=m(e=>e.devicesInfo),{onInviteAccepted:u,onInviteCancel:g,onInviteProgress:p,onInviteRedirected:f,onInviteRejected:v,onInviteTrying:w,onSessionDescriptionHandlerCreated:b,onSessionReceivedBye:y,onSessionReceivedMessage:S,onSessionReinvited:T,onTransferSessionDescriptionHandlerCreated:$}=ge(),{answerAudioSpdOptions:R,makeAudioSpdOptions:I,answerVideoSpdOptions:C,makeVideoSpdOptions:E}=pe();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=le.utc();console.log("INVITE (audio): "+s+"@"+e.account.domain);const o=ls.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);t.sipSession=new dt(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){y(t,e,()=>_(t))},onMessage:function(e){S(t,e)},onInvite:function(e){T(t,e)},onSessionDescriptionHandler:function(e,s){console.log("Session Description Handler created:",{sdh:e}),b(t,e,s,!1)}};const c={requestDelegate:{onTrying:function(e){console.log("makeAudioSession 1"),w(t,e)},onProgress:function(e){console.log("makeAudioSession 2"),p(t,e)},onRedirect:function(e){console.log("makeAudioSession 3"),f(t,e)},onAccept:function(e){console.log("makeAudioSession 4"),u(t,!1,e)},onReject:function(e){console.log("makeAudioSession 5"),v(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=le.utc();console.log("INVITE (video): "+s+"@"+e.account.domain);const o=ls.makeURI("sip:"+s.replace(/#/g,"%23")+"@"+e.account.domain);console.log("video",{spdOptions:r}),t.sipSession=new dt(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){y(t,e,()=>_(t))},onMessage:function(e){S(t,e)},onInvite:function(e){T(t,e)},onSessionDescriptionHandler:function(e,s){b(t,e,s,!0)}};const c={requestDelegate:{onTrying:function(e){w(t,e)},onProgress:function(e){p(t,e)},onRedirect:function(e){f(t,e)},onAccept:function(e){u(t,!0,e)},onReject:function(e){v(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:ue()}),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:ue()}),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=le.utc(),d=new h(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){y(d,e,()=>_(d))},onMessage:function(e){S(d,e)},onInvite:function(e){T(d,e)},onSessionDescriptionHandler:function(e,s){b(d,e,s,t.data.withVideo)}},d.sipSession.incomingInviteRequest.delegate={onCancel:function(e){console.log("onInviteCancel"),g(d,e,()=>_(d))}};const u=o(t.id);if(e.features.enableRingtone)if(u>=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 dt)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(){u(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 dt)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(){u(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 dt||(i.state==rt.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 h(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 rt.Initial:case rt.Establishing:i instanceof dt?(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 rt.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:ue()}),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:ue()}),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 dt&&(i.data.terminateBy="us",i.data.reasonCode=0,i.data.reasonText="Call Cancelled",console.log("Cancelling session : "+e),i.state==rt.Initial||i.state==rt.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:ue(),disposition:"invite",dispositionTime:ue(),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=ls.makeURI("sip:"+i.replace(/#/g,"%23")+"@"+e.account.domain),u=new dt(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=ue())},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=ue())},onProgress:function(){console.log("onProgress"),o.data.transfer&&(o.data.transfer[c].disposition="progress",o.data.transfer[c].dispositionTime=ue(),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=ue())},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=ue();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=ue(),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=ue())}}};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=ue())}}};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:_}})(),w=ge();e.useEffect(()=>(p({configs:f}),async function(){await b()}(),()=>{r?.stop()}),[f]);const b=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"),S(),y()},y=e.useCallback(()=>{let e=new ls({uri:ls.makeURI(`sip:${f.account.username}@${f.account.domain}`),transportOptions:{server:`wss://${f.account.wssServer}:${f.account.webSocketPort}${f.account.serverPath}`,traceSip:!1,connectionTimeout:f.registration.transportConnectionTimeout},authorizationUsername:f.account.username,authorizationPassword:f.account.password,delegate:{onInvite:v.receiveCall,onMessage:()=>console.log("Received message")}});e.isRegistered=function(){return e&&e.registerer&&e.registerer.state===lt.Registered},e.sessions=e._sessions,e.registrationCompleted=!1,e.registering=!1,e.transport.ReconnectionAttempts=f.registration.transportReconnectionAttempts||0,e.transport.attemptingReconnection=!1,e.BlfSubs=[],e.lastVoicemailCount=0,e.transport.onConnect=()=>{D(e)},e.transport.onDisconnect=t=>{t?k(t,e):A(e)};const t={logConfiguration:!1,expires:f.registration.registerExpires,extraHeaders:[],extraContactHeaderParams:[],refreshFrequency:75};e.registerer=new vt(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 lt.Initial:break;case lt.Registered:I(e);break;case lt.Unregistered:C(e);case lt.Terminated:}}),e.start(),Object.defineProperty(e,"_key",{enumerable:!1,value:1}),console.log("createUserAgent",{ua:e}),T(e)},[f]),S=()=>{var e;e=e=>{if(console.log({deviceInfos:e}),!e)return;let t=n,s=c,i=o,r=g,d=a,l=u;for(let n=0;n<e.length;++n)"audioinput"===e[n].kind?(t=!0,s.push(e[n])):"audiooutput"===e[n].kind?(i=!0,r.push(e[n])):"videoinput"===e[n].kind&&f.features.enableVideo&&(d=!0,l.push(e[n]));p({devicesInfo:{hasAudioDevice:t,audioInputDevices:s,hasSpeakerDevice:i,speakerDevices:r,hasVideoDevice:d,videoInputDevices:l}})},navigator.mediaDevices.enumerateDevices().then(function(t){e(t)}).catch(function(e){console.error("Error enumerating devices",e)})},T=e=>{p({userAgent:e})};return d.jsx(hs.Provider,{value:{lines:i.lines,session:{methods:v,events:w},transport:{reconnectTransport:H}},children:t})},exports.VideoStream=({lineNumber:e,...t})=>"local"===t.type?d.jsx("video",{...t,id:`line-${e}-${t.type}Video`,muted:"local"===t.type}):d.jsx("div",{...t,id:`line-${e}-remoteVideos`}),exports.useSipProvider=()=>{const t=e.useContext(hs);if(!t)throw new Error("useSipProvider must be used within a SipProvider");return t};
|