@wizai/agent-sip-sdk 0.2.1 → 0.2.2

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.
@@ -3,4 +3,4 @@
3
3
  * eventsource.js
4
4
  * Available under MIT License (MIT)
5
5
  * https://github.com/Yaffle/EventSource/
6
- */!function(e,t){!function(n){var r=n.setTimeout,i=n.clearTimeout,s=n.XMLHttpRequest,o=n.XDomainRequest,a=n.ActiveXObject,l=n.EventSource,u=n.document,c=n.Promise,h=n.fetch,d=n.Response,f=n.TextDecoder,p=n.TextEncoder,g=n.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==g){var m=h;h=function(e,t){var n=t.signal;return m(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return n._reader=t,n._aborted&&n._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},g=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function A(){this.bitsNeeded=0,this.codePoint=0}A.prototype.decode=function(e){function t(e,t,n){if(1===n)return e>=128>>t&&e<<t<=2047;if(2===n)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===n)return e>=65536>>t&&e<<t<=1114111;throw new Error}function n(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var r=65533,i="",s=this.bitsNeeded,o=this.codePoint,a=0;a<e.length;a+=1){var l=e[a];0!==s&&(l<128||l>191||!t(o<<6|63&l,s-6,n(s,o)))&&(s=0,o=r,i+=String.fromCharCode(o)),0===s?(l>=0&&l<=127?(s=0,o=l):l>=192&&l<=223?(s=6,o=31&l):l>=224&&l<=239?(s=12,o=15&l):l>=240&&l<=247?(s=18,o=7&l):(s=0,o=r),0===s||t(o,s,n(s,o))||(s=0,o=r)):(s-=6,o=o<<6|63&l),0===s&&(o<=65535?i+=String.fromCharCode(o):(i+=String.fromCharCode(55296+(o-65535-1>>10)),i+=String.fromCharCode(56320+(o-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=o,i};null!=f&&null!=p&&function(){try{return"test"===(new f).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(f=A);var _=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=_,this.onload=_,this.onerror=_,this.onreadystatechange=_,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=_}function y(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function T(e){for(var t=Object.create(null),n=e.split("\r\n"),r=0;r<n.length;r+=1){var i=n[r].split(": "),s=i.shift(),o=i.join(": ");t[y(s)]=o}this._map=t}function S(){}function E(e){this._headers=e}function C(){}function w(){this._listeners=Object.create(null)}function b(e){r((function(){throw e}),0)}function I(e){this.type=e,this.target=void 0}function R(e,t){I.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function k(e,t){I.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function O(e,t){I.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var n=this,o=this._xhr,a=1,l=0;this._abort=function(e){0!==n._sendTimeout&&(i(n._sendTimeout),n._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,o.onload=_,o.onerror=_,o.onabort=_,o.onprogress=_,o.onreadystatechange=_,o.abort(),0!==l&&(i(l),l=0),e||(n.readyState=4,n.onabort(null),n.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",r=void 0;if("contentType"in o)e=200,t="OK",r=o.contentType;else try{e=o.status,t=o.statusText,r=o.getResponseHeader("Content-Type")}catch(n){e=0,t="",r=void 0}0!==e&&(a=2,n.readyState=2,n.status=e,n.statusText=t,n._contentType=r,n.onreadystatechange())}},c=function(){if(u(),2===a||3===a){a=3;var e="";try{e=o.responseText}catch(e){}n.readyState=3,n.responseText=e,n.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:_}),c(),1===a||2===a||3===a){if(a=4,0!==l&&(i(l),l=0),n.readyState=4,"load"===e)n.onload(t);else if("error"===e)n.onerror(t);else{if("abort"!==e)throw new TypeError;n.onabort(t)}n.onreadystatechange()}},d=function(){l=r((function(){d()}),500),3===o.readyState&&c()};"onload"in o&&(o.onload=function(e){h("load",e)}),"onerror"in o&&(o.onerror=function(e){h("error",e)}),"onabort"in o&&(o.onabort=function(e){h("abort",e)}),"onprogress"in o&&(o.onprogress=c),"onreadystatechange"in o&&(o.onreadystatechange=function(e){!function(e){null!=o&&(4===o.readyState?"onload"in o&&"onerror"in o&&"onabort"in o||h(""===o.responseText?"error":"load",e):3===o.readyState?"onprogress"in o||c():2===o.readyState&&u())}(e)}),!("contentType"in o)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),o.open(e,t,!0),"readyState"in o&&(l=r((function(){d()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var n=this._xhr;"setRequestHeader"in n&&n.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=r((function(){t._sendTimeout=0,t.send()}),4)}},T.prototype.get=function(e){return this._map[y(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),S.prototype.open=function(e,t,n,r,i,o,a){e.open("GET",i);var l=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(l);l+=t.length,n(t)},e.onerror=function(e){e.preventDefault(),r(new Error("NetworkError"))},e.onload=function(){r(null)},e.onabort=function(){r(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var n=e.status,r=e.statusText,i=e.getResponseHeader("Content-Type"),o=e.getAllResponseHeaders();t(n,r,i,new T(o))}},e.withCredentials=o,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},E.prototype.get=function(e){return this._headers.get(e)},C.prototype.open=function(e,t,n,r,i,s,o){var a=null,l=new g,u=l.signal,d=new f;return h(i,{headers:o,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new E(e.headers)),new c((function(e,t){var r=function(){a.read().then((function(t){if(t.done)e(void 0);else{var i=d.decode(t.value,{stream:!0});n(i),r()}})).catch((function(e){t(e)}))};r()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){r(e)})),{abort:function(){null!=a&&a.cancel(),l.abort()}}},w.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var n=t.length,r=0;r<n;r+=1){var i=t[r];try{"function"==typeof i.handleEvent?i.handleEvent(e):i.call(this,e)}catch(e){b(e)}}},w.prototype.addEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];null==r&&(r=[],n[e]=r);for(var i=!1,s=0;s<r.length;s+=1)r[s]===t&&(i=!0);i||r.push(t)},w.prototype.removeEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];if(null!=r){for(var i=[],s=0;s<r.length;s+=1)r[s]!==t&&i.push(r[s]);0===i.length?delete n[e]:n[e]=i}},R.prototype=Object.create(I.prototype),k.prototype=Object.create(I.prototype),O.prototype=Object.create(I.prototype);var D=-1,M=0,N=1,q=2,U=-1,x=0,P=1,L=2,B=3,F=/^text\/event\-stream(;.*)?$/i,H=function(e,t){var n=null==e?t:parseInt(e,10);return n!=n&&(n=t),G(n)},G=function(e){return Math.min(Math.max(e,1e3),18e6)},Y=function(e,t,n){try{"function"==typeof t&&t.call(e,n)}catch(e){b(e)}};function j(e,t){w.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,n){t=String(t);var a=Boolean(n.withCredentials),l=n.lastEventIdQueryParameterName||"lastEventId",u=G(1e3),c=H(n.heartbeatTimeout,45e3),h="",d=u,f=!1,p=0,g=n.headers||{},m=n.Transport,A=Q&&null==m?void 0:new v(null!=m?new m:null!=s&&"withCredentials"in s.prototype||null==o?new s:new o),_=null!=m&&"string"!=typeof m?new m:null==A?new C:new S,y=void 0,T=0,E=D,w="",b="",I="",j="",W=x,K=0,z=0,J=function(t,n,r,i){if(E===M)if(200===t&&null!=r&&F.test(r)){E=N,f=Date.now(),d=u,e.readyState=N;var s=new k("open",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onopen,s)}else{var o="";200!==t?(n&&(n=n.replace(/\s+/g," ")),o="EventSource's response has a status "+t+" "+n+" that is not 200. Aborting the connection."):o="EventSource's response has a Content-Type specifying an unsupported type: "+(null==r?"-":r.replace(/\s+/g," "))+". Aborting the connection.",X();s=new k("error",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onerror,s),console.error(o)}},V=function(t){if(E===N){for(var n=-1,s=0;s<t.length;s+=1){(l=t.charCodeAt(s))!=="\n".charCodeAt(0)&&l!=="\r".charCodeAt(0)||(n=s)}var o=(-1!==n?j:"")+t.slice(0,n+1);j=(-1===n?j:"")+t.slice(n+1),""!==t&&(f=Date.now(),p+=t.length);for(var a=0;a<o.length;a+=1){var l=o.charCodeAt(a);if(W===U&&l==="\n".charCodeAt(0))W=x;else if(W===U&&(W=x),l==="\r".charCodeAt(0)||l==="\n".charCodeAt(0)){if(W!==x){W===P&&(z=a+1);var g=o.slice(K,z-1),m=o.slice(z+(z<a&&o.charCodeAt(z)===" ".charCodeAt(0)?1:0),a);"data"===g?(w+="\n",w+=m):"id"===g?b=m:"event"===g?I=m:"retry"===g?(u=H(m,u),d=u):"heartbeatTimeout"===g&&(c=H(m,c),0!==T&&(i(T),T=r((function(){$()}),c)))}if(W===x){if(""!==w){h=b,""===I&&(I="message");var A=new R(I,{data:w.slice(1),lastEventId:b});if(e.dispatchEvent(A),"open"===I?Y(e,e.onopen,A):"message"===I?Y(e,e.onmessage,A):"error"===I&&Y(e,e.onerror,A),E===q)return}w="",I=""}W=l==="\r".charCodeAt(0)?U:x}else W===x&&(K=a,W=P),W===P?l===":".charCodeAt(0)&&(z=a+1,W=L):W===L&&(W=B)}}},Z=function(t){if(E===N||E===M){E=D,0!==T&&(i(T),T=0),T=r((function(){$()}),d),d=G(Math.min(16*u,2*d)),e.readyState=M;var n=new O("error",{error:t});e.dispatchEvent(n),Y(e,e.onerror,n),null!=t&&console.error(t)}},X=function(){E=q,null!=y&&(y.abort(),y=void 0),0!==T&&(i(T),T=0),e.readyState=q},$=function(){if(T=0,E===D){f=!1,p=0,T=r((function(){$()}),c),E=M,w="",I="",b=h,j="",K=0,z=0,W=x;var n=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var i=t.indexOf("?");n=-1===i?t:t.slice(0,i+1)+t.slice(i+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===l?"":e})),n+=(-1===t.indexOf("?")?"?":"&")+l+"="+encodeURIComponent(h)}var s=e.withCredentials,o={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(o[u]=a[u]);try{y=_.open(A,J,V,Z,n,s,o)}catch(e){throw X(),e}}else if(f||null==y){var d=Math.max((f||Date.now())+c-Date.now(),1);f=!1,T=r((function(){$()}),d)}else Z(new Error("No activity within "+c+" milliseconds. "+(E===M?"No response received.":p+" chars received.")+" Reconnecting.")),null!=y&&(y.abort(),y=void 0)};e.url=t,e.readyState=M,e.withCredentials=a,e.headers=g,e._close=X,$()}(this,e,t)}var Q=null!=h&&null!=d&&"body"in d.prototype;j.prototype=Object.create(w.prototype),j.prototype.CONNECTING=M,j.prototype.OPEN=N,j.prototype.CLOSED=q,j.prototype.close=function(){this._close()},j.CONNECTING=M,j.OPEN=N,j.CLOSED=q,j.prototype.withCredentials=void 0;var W,K=l;null==s||null!=l&&"withCredentials"in l.prototype||(K=j),W=function(e){e.EventSourcePolyfill=j,e.NativeEventSource=l,e.EventSource=K}(t),void 0!==W&&(e.exports=W)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:n:globalThis)}(ul,ul.exports);var cl=ul.exports,hl={exports:{}},dl=r(hl.exports=function(){var e=1e3,t=6e4,n=36e5,r="millisecond",i="second",s="minute",o="hour",a="day",l="week",u="month",c="quarter",h="year",d="date",f="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|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"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},A=function(e,t,n){var r=String(e);return!r||r.length>=t?e:""+Array(t+1-r.length).join(n)+e},_={s:A,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?"+":"-")+A(r,2,"0")+":"+A(i,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,u),s=n-i<0,o=t.clone().add(r+(s?-1:1),u);return+(-(r+(n-i)/(s?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:u,y:h,w:l,d:a,D:d,h:o,m:s,s:i,ms:r,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",y={};y[v]=m;var T="$isDayjsObject",S=function(e){return e instanceof b||!(!e||!e[T])},E=function e(t,n,r){var i;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();y[s]&&(i=s),n&&(y[s]=n,i=s);var o=t.split("-");if(!i&&o.length>1)return e(o[0])}else{var a=t.name;y[a]=t,i=a}return!r&&i&&(v=i),i||!r&&v},C=function(e,t){if(S(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new b(n)},w=_;w.l=E,w.i=S,w.w=function(e,t){return C(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var b=function(){function m(e){this.$L=E(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[T]=!0}var A=m.prototype;return A.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(w.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var r=t.match(p);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(t)}(e),this.init()},A.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()},A.$utils=function(){return w},A.isValid=function(){return!(this.$d.toString()===f)},A.isSame=function(e,t){var n=C(e);return this.startOf(t)<=n&&n<=this.endOf(t)},A.isAfter=function(e,t){return C(e)<this.startOf(t)},A.isBefore=function(e,t){return this.endOf(t)<C(e)},A.$g=function(e,t,n){return w.u(e)?this[t]:this.set(n,e)},A.unix=function(){return Math.floor(this.valueOf()/1e3)},A.valueOf=function(){return this.$d.getTime()},A.startOf=function(e,t){var n=this,r=!!w.u(t)||t,c=w.p(e),f=function(e,t){var i=w.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(a)},p=function(e,t){return w.w(n.toDate()[e].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,m=this.$M,A=this.$D,_="set"+(this.$u?"UTC":"");switch(c){case h:return r?f(1,0):f(31,11);case u:return r?f(1,m):f(0,m+1);case l:var v=this.$locale().weekStart||0,y=(g<v?g+7:g)-v;return f(r?A-y:A+(6-y),m);case a:case d:return p(_+"Hours",0);case o:return p(_+"Minutes",1);case s:return p(_+"Seconds",2);case i:return p(_+"Milliseconds",3);default:return this.clone()}},A.endOf=function(e){return this.startOf(e,!1)},A.$set=function(e,t){var n,l=w.p(e),c="set"+(this.$u?"UTC":""),f=(n={},n[a]=c+"Date",n[d]=c+"Date",n[u]=c+"Month",n[h]=c+"FullYear",n[o]=c+"Hours",n[s]=c+"Minutes",n[i]=c+"Seconds",n[r]=c+"Milliseconds",n)[l],p=l===a?this.$D+(t-this.$W):t;if(l===u||l===h){var g=this.clone().set(d,1);g.$d[f](p),g.init(),this.$d=g.set(d,Math.min(this.$D,g.daysInMonth())).$d}else f&&this.$d[f](p);return this.init(),this},A.set=function(e,t){return this.clone().$set(e,t)},A.get=function(e){return this[w.p(e)]()},A.add=function(r,c){var d,f=this;r=Number(r);var p=w.p(c),g=function(e){var t=C(f);return w.w(t.date(t.date()+Math.round(e*r)),f)};if(p===u)return this.set(u,this.$M+r);if(p===h)return this.set(h,this.$y+r);if(p===a)return g(1);if(p===l)return g(7);var m=(d={},d[s]=t,d[o]=n,d[i]=e,d)[p]||1,A=this.$d.getTime()+r*m;return w.w(A,this)},A.subtract=function(e,t){return this.add(-1*e,t)},A.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||f;var r=e||"YYYY-MM-DDTHH:mm:ssZ",i=w.z(this),s=this.$H,o=this.$m,a=this.$M,l=n.weekdays,u=n.months,c=n.meridiem,h=function(e,n,i,s){return e&&(e[n]||e(t,r))||i[n].slice(0,s)},d=function(e){return w.s(s%12||12,e,"0")},p=c||function(e,t,n){var r=e<12?"AM":"PM";return n?r.toLowerCase():r};return r.replace(g,(function(e,r){return r||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return w.s(t.$y,4,"0");case"M":return a+1;case"MM":return w.s(a+1,2,"0");case"MMM":return h(n.monthsShort,a,u,3);case"MMMM":return h(u,a);case"D":return t.$D;case"DD":return w.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return h(n.weekdaysMin,t.$W,l,2);case"ddd":return h(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return w.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return p(s,o,!0);case"A":return p(s,o,!1);case"m":return String(o);case"mm":return w.s(o,2,"0");case"s":return String(t.$s);case"ss":return w.s(t.$s,2,"0");case"SSS":return w.s(t.$ms,3,"0");case"Z":return i}return null}(e)||i.replace(":","")}))},A.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},A.diff=function(r,d,f){var p,g=this,m=w.p(d),A=C(r),_=(A.utcOffset()-this.utcOffset())*t,v=this-A,y=function(){return w.m(g,A)};switch(m){case h:p=y()/12;break;case u:p=y();break;case c:p=y()/3;break;case l:p=(v-_)/6048e5;break;case a:p=(v-_)/864e5;break;case o:p=v/n;break;case s:p=v/t;break;case i:p=v/e;break;default:p=v}return f?p:w.a(p)},A.daysInMonth=function(){return this.endOf(u).$D},A.$locale=function(){return y[this.$L]},A.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),r=E(e,t,!0);return r&&(n.$L=r),n},A.clone=function(){return w.w(this.$d,this)},A.toDate=function(){return new Date(this.valueOf())},A.toJSON=function(){return this.isValid()?this.toISOString():null},A.toISOString=function(){return this.$d.toISOString()},A.toString=function(){return this.$d.toUTCString()},m}(),I=b.prototype;return C.prototype=I,[["$ms",r],["$s",i],["$m",s],["$H",o],["$W",a],["$M",u],["$y",h],["$D",d]].forEach((function(e){I[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),C.extend=function(e,t){return e.$i||(e(t,b,C),e.$i=!0),C},C.locale=E,C.isDayjs=S,C.unix=function(e){return C(1e3*e)},C.en=y[v],C.Ls=y,C.p={},C}());const fl="0.2.1",pl="aks_agent_token";class gl{setTrack(e){this.track=e}constructor(e){this.baseUrl="",this.eventSource=null,this.retryCount=0,this.retryMap=new Map,this.token="",this.track=()=>{},this.id=e.id,this.getSystemToken=e.getSystemToken,this.resetSSE=null==e?void 0:e.resetSSE,this.retryCount=e.retryCount||0,this.baseUrl=e.baseUrl||""}validateToken(t,n){return e(this,void 0,void 0,(function*(){return fetch(`${this.baseUrl}/iam/token/validate?accountId=${t}`,{method:"GET",headers:{authentication:n}}).then((e=>e.json()))}))}initToken(){return e(this,void 0,void 0,(function*(){try{const e=yield this.getSystemToken();if(!e)return{code:sl.FAILED,data:null,message:"get system token failed"};const t=yield this.validateToken(this.id,e);return t.code===sl.SUCCESS?(this.token=e,sessionStorage.setItem(pl,e),this.executePeriodically(this.refreshToken.bind(this),12e5),{code:sl.SUCCESS,data:null,message:t.message}):{code:sl.FAILED,data:null,message:t.message}}catch(e){return{code:sl.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"}}}))}refreshToken(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/iam/oauth2/refresh`}).then((e=>{var t;e.token?(this.token=e.token,sessionStorage.setItem(pl,e.token),this.eventSource&&(null===(t=this.resetSSE)||void 0===t||t.call(this))):this.track("token.refresh.fail")}))}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/status/list`})}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/getAgentByUserId`})}))}getAgentSetting(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getAgentSetting`,data:t})}))}updateAgentHangup(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent/${t}`,method:"PUT"})}))}updateAgentTicket(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/voipPlatform/agent/ticket`,data:t})}))}sendSSEACK(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat_ack?agentId=${t}`,method:"POST"})}))}registerSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:n,onMessage:r}=t;let i=e=>{};const s=new Promise((e=>{i=e})),o=this.token;return this.eventSource=new cl.EventSourcePolyfill(`${this.baseUrl}/crm/v1/agent_command/regist_agent_event?agentId=${n}`,{headers:{Authentication:o,"Cache-Control":"no-cache",Connection:"keep-alive"},heartbeatTimeout:12e6}),this.eventSource.onmessage=r,this.eventSource.onopen=()=>e(this,void 0,void 0,(function*(){this.track("sse.open"),i(!0)})),this.eventSource.onerror=()=>e(this,void 0,void 0,(function*(){this.track("sse.error.error"),i(!1)})),s}))}closeClientSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=null)}closeSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:e,clearTicket:n}=t;if(this.eventSource)return this.request({url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_close?agentId=${e}&clearTicket=${n}`}).then((e=>(this.closeClientSSE(),e)))}))}sendHeartbeat(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat?agentId=${t}&version=${fl}`})}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){return this.request({method:"PUT",url:`${this.baseUrl}/voipPlatform/agent/agentStatusSwitch`,data:t})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){const{phone:e,line:n}=t;return this.request({url:`${this.baseUrl}/crm/v1/agentOutBoundCall/dialer/startCall/${e}/${n}`,method:"POST"})}))}saveAgentResponseTime(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/call_record/callRecordAgent`,data:t})}))}reportPDSTimeline(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/reportPDSTimeline`,method:"POST",data:t})}))}reportSdkTrace(t,n){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/reportSdkTrace`;let r="";try{r=this.getTokenWithFallback()}catch(e){r=""}try{if((null==n?void 0:n.useBeacon)&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){const n=new FormData;return n.append("timestamp",String(t.timestamp)),n.append("traceId",t.traceId),n.append("agentId",t.agentId),n.append("sdkVersion",t.sdkVersion),n.append("callId",t.callId),n.append("callRecordId",t.callRecordId),n.append("event",t.event),n.append("message",t.message),t.extra&&n.append("extra",JSON.stringify(t.extra)),r&&n.append("authentication",r),navigator.sendBeacon(e,n)}return(yield fetch(e,{method:"POST",keepalive:null==n?void 0:n.keepalive,headers:Object.assign({"Content-Type":"application/json"},r?{authentication:r}:{}),body:JSON.stringify(t)})).ok}catch(e){return!1}}))}getSdkTraceConfig(){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/getSdkTraceConfig`;try{const t=yield fetch(e,{method:"GET"});if(!t.ok)return null;const n=yield t.json();return{collect:Boolean(null==n?void 0:n.collect)}}catch(e){return null}}))}getCallTaskInfo(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getCallTaskName/${t.callTaskId}`})}))}getAfterCallProcessTime(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/predictCall/afterCallProcessTime/${t.callTaskId}`})}))}formatFormData(e){const t=new FormData;for(const n in e)e[n]&&t.append(n,e[n]);return t}agentAbnormalClose(e){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const t=this.formatFormData(e);return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_abnormal_close`,data:t},!0)}sendBeacon(e){if("function"==typeof navigator.sendBeacon&&e.url){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const{url:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["url"]),r=this.formatFormData(n),i=navigator.sendBeacon(t,r);if(!i){e.lastSendResult=i;const t=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");t.push(e),localStorage.setItem("aks_beacon_queue",JSON.stringify(t))}}}clearnSendBeaconQueue(){return e(this,void 0,void 0,(function*(){const e=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");if(e.length){if(!(yield this.waitToken())){if((yield this.initToken()).code!==sl.SUCCESS)return}for(let t=0;t<e.length-1;t++)this.sendBeacon(e[t])}}))}getTokenWithFallback(){if(this.token)return this.token;return sessionStorage.getItem(pl)||""}waitToken(e=3e3,t=200){return new Promise((n=>{const r=setInterval((()=>{((e-=t)<=0||this.token)&&(clearInterval(r),n(Boolean(this.token)))}),200)}))}request(t){return e(this,arguments,void 0,(function*(t,n=!1){var r;if(!this.retryMap.has(t.url)&&this.retryCount&&this.retryMap.set(t.url,this.retryCount),!this.token){if(!(yield this.waitToken())){const e=yield this.initToken();if(e.code!==sl.SUCCESS)return{code:e.code,message:e.message,data:null}}}const i={method:t.method||"GET",headers:Object.assign({"Content-Type":"application/json",authentication:this.token},t.headers)};n?(i.method=t.method,i.headers={authentication:this.token},i.body=t.data):"GET"!==(null===(r=i.method)||void 0===r?void 0:r.toLocaleUpperCase())&&(i.body=JSON.stringify(t.data));const s=t.url.replace(this.baseUrl,"").split("?")[0].replace(/\/\d+/g,"/{id}");return fetch(t.url,i).then((n=>e(this,void 0,void 0,(function*(){if(401===n.status){const e=this.retryMap.get(t.url);if(e){this.retryMap.set(t.url,e-1),this.track("api.retry",{extra:{api:s,remaining:e-1}});const n=yield this.initToken();return n.code===sl.SUCCESS?this.request(t):n}return this.retryCount&&this.retryMap.delete(t.url),this.track("api.unauthorized.warn",{extra:{api:s}}),{code:sl.UNAUTHORIZED,message:"Unauthorized",data:null}}return n.ok||this.track("api.fail",{extra:{api:s,httpStatus:n.status}}),n.json()})))).catch((e=>{try{this.track("api.fail",{message:String(e),extra:{api:s}})}catch(e){}throw e}))}))}executePeriodically(e,t){let n=Date.now()+t;const r=()=>{const i=Date.now();i>=n&&(e(),n+=t);const s=Math.max(0,n-i);setTimeout(r,s)};r()}static getInstance(e){return!gl.instance&&e&&(gl.instance=new gl(e)),gl.instance}}gl.instance=null;const ml=e=>{if("string"!=typeof e)return"";let t=e;return t=t.replace(/https?:\/\/[^\s]+/g,(e=>e.split("?")[0].replace(/\/\d+(?=\/|$)/g,"/{id}"))),t=t.replace(/\d{7,}/g,(e=>`${e.slice(0,3)}****${e.slice(-2)}`)),t.length>1024&&(t=t.slice(0,1024)),t},Al="aks_trace_queue";class _l{constructor(e,t){this.storage=e,this.opts=t}read(){try{const e=this.storage.getItem(Al);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return[]}}enqueue(e){try{const t=this.read();t.push(e);const n=t.length-this.opts.cap;n>0&&t.splice(0,n),this.storage.setItem(Al,JSON.stringify(t))}catch(e){}}drain(){try{const e=this.opts.now()-this.opts.ttlMs,t=this.read().filter((t=>t.timestamp>=e));return this.storage.removeItem(Al),t}catch(e){return[]}}}class vl{constructor(e){var t,n;this.enabled=!1,this.traceId="",this.agentId="",this.lastSent=new Map,this.bucket=20,this.bucketTs=0,this.version=e.version,this.now=null!==(t=e.now)&&void 0!==t?t:()=>Date.now(),this.genId=null!==(n=e.genId)&&void 0!==n?n:()=>Date.now().toString(36)+Math.random().toString(36).slice(2,10),this.report=e.report,this.queue=new _l(e.storage,{cap:200,ttlMs:864e5,now:this.now})}applyConfig(e){this.enabled=Boolean(e)}setAgentId(e){this.agentId=String(null!=e?e:"")}resetTraceId(){try{this.traceId=this.genId()}catch(e){}}track(e,t){var n,r,i;try{if(!this.enabled)return;const s=this.now();if(this.isDeduped(e,s))return;if(!this.takeToken(s))return;this.lastSent.set(e,s),this.traceId||(this.traceId=this.genId());const o=Object.assign({timestamp:s,traceId:this.traceId,agentId:this.agentId,sdkVersion:this.version,callId:null!==(n=null==t?void 0:t.callId)&&void 0!==n?n:"",callRecordId:null!==(r=null==t?void 0:t.callRecordId)&&void 0!==r?r:"",event:e,message:ml(null!==(i=null==t?void 0:t.message)&&void 0!==i?i:"")},(null==t?void 0:t.extra)?{extra:t.extra}:{});this.report(o).then((e=>{e||this.queue.enqueue(o)})).catch((()=>{try{this.queue.enqueue(o)}catch(e){}}))}catch(e){}}flush(){try{if(!this.enabled)return;const e=this.queue.drain(),t="undefined"==typeof fetch;for(const n of e)try{this.report(n,{keepalive:!0,useBeacon:t}).catch((()=>{}))}catch(e){}}catch(e){}}isDeduped(e,t){const n=this.lastSent.get(e);return void 0!==n&&t-n<5e3}takeToken(e){return e-this.bucketTs>=1e3&&(this.bucket=20,this.bucketTs=e),!(this.bucket<=0)&&(this.bucket-=1,!0)}}const yl="aks_trace_config";var Tl,Sl,El;!function(e){e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.HANGUP=4]="HANGUP"}(Tl||(Tl={})),function(e){e[e.ANSWER=1]="ANSWER",e[e.HANGUP=2]="HANGUP"}(Sl||(Sl={})),function(e){e[e.INCOMMING=1]="INCOMMING",e[e.ACW=2]="ACW"}(El||(El={}));const Cl=1e4;module.exports=class{constructor(e){this.sip={},this.api={},this.isSipInit=!1,this.isInitSuccess=!1,this.agentInfo={},this.initEvent={},this.agentEvent={},this.agentWaitingTime=0,this.agentResponseTime=0,this.timer=null,this.callDetails={},this.baseUrl="",this.autoFinishACWTimer=null,this._acwAutoTriggered=!1,this.heartbeatTimer=null,this.heartbeatFailCount=0,this.isHeartbeatRunning=!1,this.baseUrl=(null==e?void 0:e.baseUrl)||"",this.api=gl.getInstance({id:e.id,getSystemToken:e.getSystemToken,retryCount:e.retryCount,baseUrl:this.baseUrl});try{const e=window.localStorage;this.tracker=new vl({report:(e,t)=>this.api.reportSdkTrace(e,t),storage:e,version:fl,genId:()=>t()}),this.tracker.applyConfig(!0===(e=>{try{const t=e.getItem(yl);return"true"===t||"false"!==t&&null}catch(e){return null}})(e)),this.api.setTrack(((e,t)=>this.tracker.track(e,t)))}catch(e){this.tracker={track:()=>{},flush:()=>{},applyConfig:()=>{},setAgentId:()=>{},resetTraceId:()=>{}}}this.sip=new ll({incomingCallCallback:this.incomingCall.bind(this),trackIncomingCallCallback:this.trackIncomingCall.bind(this),getMediaStream:null==e?void 0:e.getMediaStream,applyAnswer:this.answer.bind(this),track:(e,t)=>this.tracker.track(e,t)}),this.sip.attchSessionEvent("ended",this.sessionEnded.bind(this)),this.sip.attchSessionEvent("failed",this.sessionFailed.bind(this)),this.init().then((()=>{this.api.clearnSendBeaconQueue()})),"undefined"!=typeof window&&window.addEventListener("pagehide",(()=>this.tracker.flush()),{once:!0})}init(){return e(this,void 0,void 0,(function*(){this.tracker.resetTraceId();const e=yield this.api.getSdkTraceConfig();if(e){this.tracker.applyConfig(e.collect);try{((e,t)=>{try{e.setItem(yl,t?"true":"false")}catch(e){}})(window.localStorage,e.collect)}catch(e){}}const t=yield this.api.initToken();if(t.code!==sl.SUCCESS){this.tracker.track("init.fail",{message:t.message,extra:{stage:"initToken"}});const e=Object.assign(Object.assign({},t),{code:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const n=yield this.getAgentStatus();if(n.code!==ol.SUCCESS){n.code===ol.LOCKED?this.tracker.track("init.locked",{message:n.message}):this.tracker.track("init.fail",{message:n.message,extra:{stage:"getAgentStatus"}});const e=Object.assign(Object.assign({},n),{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const r={code:ol.SUCCESS,data:null,message:"success"};return this.tracker.track("init.success"),this.emitInitEvent("success",r),this.isInitSuccess=!0,r}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){const e=yield this.api.getAgentStatusList();return e.code===sl.SUCCESS?{code:ol.SUCCESS,data:e.data||[],message:e.message}:{code:ol.FAILED,data:null,message:e.message}}))}getTicket(){let e=window.sessionStorage.getItem("wiz-agent-ticket");return e||(e=t(),window.sessionStorage.setItem("wiz-agent-ticket",e)),e}getHostName(e){try{return new URL(e).hostname}catch(e){return""}}createOpensips(){return e(this,void 0,void 0,(function*(){const e=yield this.waitSIPRegistered(7e3);return e.code!==ol.SUCCESS?(e.code!==ol.MIC_PERMISSION_DENIED&&this.sip.stop(!0),{code:e.code,message:e.message}):{code:ol.SUCCESS,message:"success"}}))}closeSip(){return e(this,void 0,void 0,(function*(){return this.sip.stop(!0),Promise.resolve({code:sl.SUCCESS,message:"failed"})}))}waitSIPRegistered(){return e(this,arguments,void 0,(function*(e=7e3){return new Promise((t=>{let n=!1;const r=e=>{n||(n=!0,t(e))};this.sip.on("registered",(()=>{n||(this.tracker.track("sip.registered"),r({code:ol.SUCCESS,message:"SIP registration successed"}))})),this.sip.on("registrationFailed",(()=>r({code:ol.FAILED,message:"SIP registration failed"}))),setTimeout((()=>{n||(this.tracker.track("sip.registerTimeout.fail"),r({code:ol.FAILED,message:"SIP registration failed"}))}),e),this.sip.start().then((e=>{e||(this.tracker.track("sip.startFail"),r({code:ol.MIC_PERMISSION_DENIED,message:"Microphone permission denied. Please allow microphone access in your browser settings and try again."}))}))}))}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){var e;const t=yield this.api.getAgentInfo();if("code"in t&&t.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:t.message};if(!("data"in t)||!(null===(e=t.data)||void 0===e?void 0:e[0]))return{code:ol.FAILED,data:null,message:"Agent not found"};const n=t.data[0];this.agentInfo=n,this.tracker.setAgentId(n.id);const r=n.id;let i=n.ticket;const s=n.status,o=this.getTicket();if(i){if(s===Tl.OFFLINE){if((yield this.api.updateAgentTicket({agentId:r,ticket:"",type:Tl.OFFLINE})).code!==sl.SUCCESS)return{code:ol.FAILED,message:"Update Agent Ticket failed"};i="",n.ticket="",this.agentInfo.ticket=""}if(s===Tl.ONLINE&&i!==o)return{code:ol.LOCKED,data:n,message:"Agent ticket occupied, unable to perform agent online or offline."}}if(!this.isSipInit){const e=`sip:${n.number}@${this.getHostName(n.realm)}`;this.sip.init({wssuri:n.realm,password:n.password,uri:e}),this.isSipInit=!0}return{code:ol.SUCCESS,data:n,message:t.message}}))}getAgentStatus(){return e(this,void 0,void 0,(function*(){try{const e=yield Promise.allSettled([this.getAgentInfo(),this.api.getAgentSetting({key:"callCenter"})]),[n,r]=e.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value));if("agentWaitingTime"in r&&(this.agentWaitingTime=r.agentWaitingTime||0),"code"in n&&n.code!==ol.SUCCESS)return{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:n.message};if(!("data"in n)||!n.data)return{code:ol.FAILED,data:null,message:"Agent not found"};const i=n.data,s=i.status,o=i.id,a=i.groupId,l={code:ol.SUCCESS,data:{id:o,groupId:a,status:s,subStatus:i.statusName},message:"success"};if(this.agentInfo=i,s===Tl.OFFLINE)return l;if(s===Tl.ONLINE){if(n.code===ol.LOCKED)return{code:ol.LOCKED,data:null,message:n.message};this.tracker.track("agent.abnormalClose"),yield this.api.agentAbnormalClose({id:o,groupId:a,trace:t()});const e=yield this.api.switchAgentStatus({id:o,groupId:a,status:Tl.OFFLINE,subStatus:"offline"});return e.code!==sl.SUCCESS?{code:ol.FAILED,data:null,message:e.message}:(l.data.status=Tl.OFFLINE,l.data.subStatus="Offline",l)}return{code:ol.FAILED,data:null,message:"system error"}}catch(e){return{code:ol.FAILED,data:null,message:"system error"}}}))}onlineAgent(t){return e(this,void 0,void 0,(function*(){const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t});if(e.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.ONLINE,subStatus:t},message:"Agent is already online"};return this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",i),this.startHeartbeat(),i}if(e===Tl.OFFLINE){const{code:e,message:i}=yield this.createOpensips();if(e!==ol.SUCCESS)return{code:e===ol.MIC_PERMISSION_DENIED?ol.MIC_PERMISSION_DENIED:ol.FAILED,data:null,message:i};const s=this.getTicket(),o=yield Promise.allSettled([this.api.updateAgentTicket({agentId:n,ticket:s,type:Tl.ONLINE}),this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t})]),[a,l]=o.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value)),u=a.code===sl.SUCCESS&&l.code===sl.SUCCESS,c=(null==a?void 0:a.code)!==sl.SUCCESS&&(null==l?void 0:l.code)!==sl.SUCCESS;if(!u&&!c){const e=[this.closeSip()];let t="";a.code!==sl.SUCCESS&&(t=a.message,e.push(this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:"Offline"}))),l.code!==sl.SUCCESS&&(t=l.message,e.push(this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE})));try{yield Promise.all(e)}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${t} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:t}}if(c){try{yield this.closeSip()}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${a.message} & ${l.message} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:`${a.message} & ${l.message}`}}const h={code:e,data:{status:Tl.ONLINE,subStatus:t},message:i};return this.agentInfo.status=Tl.ONLINE,this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",h),this.startHeartbeat(),h}return{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}offlineAgent(t){return e(this,void 0,void 0,(function*(){this.stopHeartbeat();const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.OFFLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.agentInfo.statusName=t,this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),i}if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE}),yield this.closeSip();const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName=t,i}return this.tracker.track("agent.offline.fail",{message:"invalid status",extra:{reason:"invalid_status"}}),{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}startHeartbeat(){this.isHeartbeatRunning&&this.stopHeartbeat(),this.isHeartbeatRunning=!0,this.heartbeatFailCount=0,this.executeHeartbeat()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isHeartbeatRunning=!1,this.heartbeatFailCount=0}executeHeartbeat(){return e(this,void 0,void 0,(function*(){if(this.isHeartbeatRunning)try{const{id:e}=this.agentInfo;if(yield this.api.sendHeartbeat(e)){const e=this.heartbeatFailCount;this.heartbeatFailCount=0,e>0&&this.tracker.track("heartbeat.recover"),this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}else if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat failed, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"fail"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}catch(e){if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat exception, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"exception"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("status.switch.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Registration failed. Seat online and offline cannot be performed."};const e=yield this.getAgentInfo();if(e.code!==ol.SUCCESS)return{code:e.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:e.message};const{status:n,subStatus:r}=t;return this.tracker.track("status.switch",{extra:{from:this.agentInfo.status,to:n}}),n===Tl.ONLINE?this.onlineAgent(r):n===Tl.OFFLINE?this.offlineAgent(r):(this.tracker.track("status.switch.fail",{extra:{reason:"invalid"}}),{code:ol.FAILED,data:null,message:"system error"})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Outbound calls cannot be made."};const e=this.agentInfo.outboundLineId;if(!e)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_line"}}),Promise.resolve({code:ol.FAILED,data:null,message:"Agent has no outbound line"});this.sip.setCallType("outboundCall");const n=yield this.api.outboundCall({phone:t,line:e}).catch((e=>{throw this.sip.setCallType(""),e}));return n.code===sl.SUCCESS?(this.tracker.track("call.outbound",{extra:{line:e}}),{code:ol.SUCCESS,data:n.data,message:n.message||n.msg}):(this.sip.setCallType(""),this.tracker.track("call.outbound.fail",{message:n.message||n.msg,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:n.message||n.msg})}))}autoFinishACW(){var e,t;let n=Number(this.callDetails.afterCallProcessTime);this.tracker.track("acw.start",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{seconds:n}});const r=()=>{if(n<=0)return this._acwAutoTriggered=!0,void this.finshACW();n-=1,this.autoFinishACWTimer=setTimeout(r,1e3)};this.autoFinishACWTimer=setTimeout(r,1e3)}finshACW(){return e(this,void 0,void 0,(function*(){var e,t;const n=!this._acwAutoTriggered;this._acwAutoTriggered=!1,this.tracker.track("acw.finish",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{manual:n}}),this.autoFinishACWTimer&&(clearTimeout(this.autoFinishACWTimer),this.autoFinishACWTimer=null),this.api.reportPDSTimeline({callId:this.callDetails.callId,eventType:El.ACW});const{id:r,groupId:i}=this.agentInfo,s=yield this.api.switchAgentStatus({id:r,groupId:i,status:Tl.HANGUP});return{code:s.code===sl.SUCCESS?ol.SUCCESS:ol.FAILED,data:null,message:s.message}}))}sessionEnded(){return e(this,void 0,void 0,(function*(){this.autoFinishACW()}))}sessionFailed(){return e(this,void 0,void 0,(function*(){this.api.updateAgentHangup(this.agentInfo.id)}))}saveAgentResponseTime(e){this.api.saveAgentResponseTime({callId:this.callDetails.callId,agentId:this.agentInfo.id,agentResponseTime:this.agentResponseTime,agentGroupId:this.agentInfo.groupId,resultType:e}),this.timer&&(clearInterval(this.timer),this.agentResponseTime=0)}hangup(){var e,t;this.tracker.track("call.hangup",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.hangup()}timingResTime(){this.timer&&(clearInterval(this.timer),this.timer=null);let e=this.agentWaitingTime;this.agentResponseTime=0,this.timer=setInterval((()=>{if(e<=0)return clearInterval((null==this?void 0:this.timer)||0),this.timer=null,void this.ignore();e-=1,this.agentResponseTime+=1}),1e3)}trackIncomingCall(e){this.api.reportPDSTimeline({callId:e,eventType:El.INCOMMING,timestamp:(new Date).getTime()})}incomingCall(t){return e(this,void 0,void 0,(function*(){var e,n,r,i,s,o;try{const a=t.request,l=(null===(n=null===(e=a.headers["Call-Param"])||void 0===e?void 0:e[0])||void 0===n?void 0:n.raw)||"",u=l?atob(l):"",c=JSON.parse(u||"{}"),h=(null===(i=null===(r=a.headers["Call-ID"])||void 0===r?void 0:r[0])||void 0===i?void 0:i.raw)||null,d=(null===(o=null===(s=a.headers["Call-Record-Id"])||void 0===s?void 0:s[0])||void 0===o?void 0:o.raw)||null,f=Object.fromEntries(Object.entries(c).filter((([e])=>""!==e))),p=t.request.getHeader("Task-Name")||"",g=t.request.getHeader("After-Time")||"";return this.callDetails={callId:d||"",originCallId:h||"",callType:this.sip.getCallType()||"",taskName:p,afterCallProcessTime:g,phone:f.phone||f.Phone||f.PHONE||"",contactId:f.contactId||f.ContactId||f.CONTACT_ID||"",extraJson:f},"outboundCall"!==this.sip.getCallType()&&this.timingResTime(),Promise.resolve({code:ol.SUCCESS,data:this.callDetails,message:"success"})}catch(e){return this.tracker.track("call.incoming.fail",{message:String(e),extra:{errorName:null==e?void 0:e.name}}),Promise.resolve({code:ol.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"})}}))}answer(){var e,t;this.tracker.track("call.answer",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.answer(),this.saveAgentResponseTime(Sl.ANSWER)}ignore(){var e,t;this.tracker.track("call.ignore",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.ignore(),this.saveAgentResponseTime(Sl.HANGUP)}mute(){this.sip.mute()}unmute(){this.sip.unmute()}attachInitEvent(e,t){t&&"function"==typeof t&&(this.initEvent[e]||(this.initEvent[e]=[]),this.initEvent[e].push(t))}removeInitEvent(e,t){const n=this.initEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitInitEvent(e,t){(this.initEvent[e]||[]).forEach((e=>{e(t)}))}attachAgentEvent(e,t){t&&"function"==typeof t&&(this.agentEvent[e]||(this.agentEvent[e]=[]),this.agentEvent[e].push(t))}removeAgentEvent(e,t){const n=this.agentEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitAgentEvent(e,t){(this.agentEvent[e]||[]).forEach((e=>{e(t)}))}attachAnswerEvent(e){this.sip.attachAnswerEvent(e)}removeAnswerEvent(e){this.sip.removeAnswerEvent(e)}attachAutoAnswerEvent(e){this.sip.attachAutoAnswerEvent(e)}removeAutoAnswerEvent(e){this.sip.removeAutoAnswerEvent(e)}attachNewMessageEvent(e){this.sip.attachNewMessageEvent(e)}removeNewMessageEvent(e){this.sip.removeNewMessageEvent(e)}attchSessionEvent(e,t){this.sip.attchSessionEvent(e,t)}removeSessionEvent(e,t){this.sip.removeSessionEvent(e,t)}};
6
+ */!function(e,t){!function(n){var r=n.setTimeout,i=n.clearTimeout,s=n.XMLHttpRequest,o=n.XDomainRequest,a=n.ActiveXObject,l=n.EventSource,u=n.document,c=n.Promise,h=n.fetch,d=n.Response,f=n.TextDecoder,p=n.TextEncoder,g=n.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==g){var m=h;h=function(e,t){var n=t.signal;return m(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return n._reader=t,n._aborted&&n._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},g=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function A(){this.bitsNeeded=0,this.codePoint=0}A.prototype.decode=function(e){function t(e,t,n){if(1===n)return e>=128>>t&&e<<t<=2047;if(2===n)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===n)return e>=65536>>t&&e<<t<=1114111;throw new Error}function n(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var r=65533,i="",s=this.bitsNeeded,o=this.codePoint,a=0;a<e.length;a+=1){var l=e[a];0!==s&&(l<128||l>191||!t(o<<6|63&l,s-6,n(s,o)))&&(s=0,o=r,i+=String.fromCharCode(o)),0===s?(l>=0&&l<=127?(s=0,o=l):l>=192&&l<=223?(s=6,o=31&l):l>=224&&l<=239?(s=12,o=15&l):l>=240&&l<=247?(s=18,o=7&l):(s=0,o=r),0===s||t(o,s,n(s,o))||(s=0,o=r)):(s-=6,o=o<<6|63&l),0===s&&(o<=65535?i+=String.fromCharCode(o):(i+=String.fromCharCode(55296+(o-65535-1>>10)),i+=String.fromCharCode(56320+(o-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=o,i};null!=f&&null!=p&&function(){try{return"test"===(new f).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(f=A);var _=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=_,this.onload=_,this.onerror=_,this.onreadystatechange=_,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=_}function y(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function T(e){for(var t=Object.create(null),n=e.split("\r\n"),r=0;r<n.length;r+=1){var i=n[r].split(": "),s=i.shift(),o=i.join(": ");t[y(s)]=o}this._map=t}function S(){}function E(e){this._headers=e}function C(){}function w(){this._listeners=Object.create(null)}function b(e){r((function(){throw e}),0)}function I(e){this.type=e,this.target=void 0}function R(e,t){I.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function k(e,t){I.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function O(e,t){I.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var n=this,o=this._xhr,a=1,l=0;this._abort=function(e){0!==n._sendTimeout&&(i(n._sendTimeout),n._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,o.onload=_,o.onerror=_,o.onabort=_,o.onprogress=_,o.onreadystatechange=_,o.abort(),0!==l&&(i(l),l=0),e||(n.readyState=4,n.onabort(null),n.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",r=void 0;if("contentType"in o)e=200,t="OK",r=o.contentType;else try{e=o.status,t=o.statusText,r=o.getResponseHeader("Content-Type")}catch(n){e=0,t="",r=void 0}0!==e&&(a=2,n.readyState=2,n.status=e,n.statusText=t,n._contentType=r,n.onreadystatechange())}},c=function(){if(u(),2===a||3===a){a=3;var e="";try{e=o.responseText}catch(e){}n.readyState=3,n.responseText=e,n.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:_}),c(),1===a||2===a||3===a){if(a=4,0!==l&&(i(l),l=0),n.readyState=4,"load"===e)n.onload(t);else if("error"===e)n.onerror(t);else{if("abort"!==e)throw new TypeError;n.onabort(t)}n.onreadystatechange()}},d=function(){l=r((function(){d()}),500),3===o.readyState&&c()};"onload"in o&&(o.onload=function(e){h("load",e)}),"onerror"in o&&(o.onerror=function(e){h("error",e)}),"onabort"in o&&(o.onabort=function(e){h("abort",e)}),"onprogress"in o&&(o.onprogress=c),"onreadystatechange"in o&&(o.onreadystatechange=function(e){!function(e){null!=o&&(4===o.readyState?"onload"in o&&"onerror"in o&&"onabort"in o||h(""===o.responseText?"error":"load",e):3===o.readyState?"onprogress"in o||c():2===o.readyState&&u())}(e)}),!("contentType"in o)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),o.open(e,t,!0),"readyState"in o&&(l=r((function(){d()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var n=this._xhr;"setRequestHeader"in n&&n.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=r((function(){t._sendTimeout=0,t.send()}),4)}},T.prototype.get=function(e){return this._map[y(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),S.prototype.open=function(e,t,n,r,i,o,a){e.open("GET",i);var l=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(l);l+=t.length,n(t)},e.onerror=function(e){e.preventDefault(),r(new Error("NetworkError"))},e.onload=function(){r(null)},e.onabort=function(){r(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var n=e.status,r=e.statusText,i=e.getResponseHeader("Content-Type"),o=e.getAllResponseHeaders();t(n,r,i,new T(o))}},e.withCredentials=o,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},E.prototype.get=function(e){return this._headers.get(e)},C.prototype.open=function(e,t,n,r,i,s,o){var a=null,l=new g,u=l.signal,d=new f;return h(i,{headers:o,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new E(e.headers)),new c((function(e,t){var r=function(){a.read().then((function(t){if(t.done)e(void 0);else{var i=d.decode(t.value,{stream:!0});n(i),r()}})).catch((function(e){t(e)}))};r()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){r(e)})),{abort:function(){null!=a&&a.cancel(),l.abort()}}},w.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var n=t.length,r=0;r<n;r+=1){var i=t[r];try{"function"==typeof i.handleEvent?i.handleEvent(e):i.call(this,e)}catch(e){b(e)}}},w.prototype.addEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];null==r&&(r=[],n[e]=r);for(var i=!1,s=0;s<r.length;s+=1)r[s]===t&&(i=!0);i||r.push(t)},w.prototype.removeEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];if(null!=r){for(var i=[],s=0;s<r.length;s+=1)r[s]!==t&&i.push(r[s]);0===i.length?delete n[e]:n[e]=i}},R.prototype=Object.create(I.prototype),k.prototype=Object.create(I.prototype),O.prototype=Object.create(I.prototype);var D=-1,M=0,N=1,q=2,U=-1,x=0,P=1,L=2,B=3,F=/^text\/event\-stream(;.*)?$/i,H=function(e,t){var n=null==e?t:parseInt(e,10);return n!=n&&(n=t),G(n)},G=function(e){return Math.min(Math.max(e,1e3),18e6)},Y=function(e,t,n){try{"function"==typeof t&&t.call(e,n)}catch(e){b(e)}};function j(e,t){w.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,n){t=String(t);var a=Boolean(n.withCredentials),l=n.lastEventIdQueryParameterName||"lastEventId",u=G(1e3),c=H(n.heartbeatTimeout,45e3),h="",d=u,f=!1,p=0,g=n.headers||{},m=n.Transport,A=Q&&null==m?void 0:new v(null!=m?new m:null!=s&&"withCredentials"in s.prototype||null==o?new s:new o),_=null!=m&&"string"!=typeof m?new m:null==A?new C:new S,y=void 0,T=0,E=D,w="",b="",I="",j="",W=x,K=0,z=0,J=function(t,n,r,i){if(E===M)if(200===t&&null!=r&&F.test(r)){E=N,f=Date.now(),d=u,e.readyState=N;var s=new k("open",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onopen,s)}else{var o="";200!==t?(n&&(n=n.replace(/\s+/g," ")),o="EventSource's response has a status "+t+" "+n+" that is not 200. Aborting the connection."):o="EventSource's response has a Content-Type specifying an unsupported type: "+(null==r?"-":r.replace(/\s+/g," "))+". Aborting the connection.",X();s=new k("error",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onerror,s),console.error(o)}},V=function(t){if(E===N){for(var n=-1,s=0;s<t.length;s+=1){(l=t.charCodeAt(s))!=="\n".charCodeAt(0)&&l!=="\r".charCodeAt(0)||(n=s)}var o=(-1!==n?j:"")+t.slice(0,n+1);j=(-1===n?j:"")+t.slice(n+1),""!==t&&(f=Date.now(),p+=t.length);for(var a=0;a<o.length;a+=1){var l=o.charCodeAt(a);if(W===U&&l==="\n".charCodeAt(0))W=x;else if(W===U&&(W=x),l==="\r".charCodeAt(0)||l==="\n".charCodeAt(0)){if(W!==x){W===P&&(z=a+1);var g=o.slice(K,z-1),m=o.slice(z+(z<a&&o.charCodeAt(z)===" ".charCodeAt(0)?1:0),a);"data"===g?(w+="\n",w+=m):"id"===g?b=m:"event"===g?I=m:"retry"===g?(u=H(m,u),d=u):"heartbeatTimeout"===g&&(c=H(m,c),0!==T&&(i(T),T=r((function(){$()}),c)))}if(W===x){if(""!==w){h=b,""===I&&(I="message");var A=new R(I,{data:w.slice(1),lastEventId:b});if(e.dispatchEvent(A),"open"===I?Y(e,e.onopen,A):"message"===I?Y(e,e.onmessage,A):"error"===I&&Y(e,e.onerror,A),E===q)return}w="",I=""}W=l==="\r".charCodeAt(0)?U:x}else W===x&&(K=a,W=P),W===P?l===":".charCodeAt(0)&&(z=a+1,W=L):W===L&&(W=B)}}},Z=function(t){if(E===N||E===M){E=D,0!==T&&(i(T),T=0),T=r((function(){$()}),d),d=G(Math.min(16*u,2*d)),e.readyState=M;var n=new O("error",{error:t});e.dispatchEvent(n),Y(e,e.onerror,n),null!=t&&console.error(t)}},X=function(){E=q,null!=y&&(y.abort(),y=void 0),0!==T&&(i(T),T=0),e.readyState=q},$=function(){if(T=0,E===D){f=!1,p=0,T=r((function(){$()}),c),E=M,w="",I="",b=h,j="",K=0,z=0,W=x;var n=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var i=t.indexOf("?");n=-1===i?t:t.slice(0,i+1)+t.slice(i+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===l?"":e})),n+=(-1===t.indexOf("?")?"?":"&")+l+"="+encodeURIComponent(h)}var s=e.withCredentials,o={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(o[u]=a[u]);try{y=_.open(A,J,V,Z,n,s,o)}catch(e){throw X(),e}}else if(f||null==y){var d=Math.max((f||Date.now())+c-Date.now(),1);f=!1,T=r((function(){$()}),d)}else Z(new Error("No activity within "+c+" milliseconds. "+(E===M?"No response received.":p+" chars received.")+" Reconnecting.")),null!=y&&(y.abort(),y=void 0)};e.url=t,e.readyState=M,e.withCredentials=a,e.headers=g,e._close=X,$()}(this,e,t)}var Q=null!=h&&null!=d&&"body"in d.prototype;j.prototype=Object.create(w.prototype),j.prototype.CONNECTING=M,j.prototype.OPEN=N,j.prototype.CLOSED=q,j.prototype.close=function(){this._close()},j.CONNECTING=M,j.OPEN=N,j.CLOSED=q,j.prototype.withCredentials=void 0;var W,K=l;null==s||null!=l&&"withCredentials"in l.prototype||(K=j),W=function(e){e.EventSourcePolyfill=j,e.NativeEventSource=l,e.EventSource=K}(t),void 0!==W&&(e.exports=W)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:n:globalThis)}(ul,ul.exports);var cl=ul.exports,hl={exports:{}},dl=r(hl.exports=function(){var e=1e3,t=6e4,n=36e5,r="millisecond",i="second",s="minute",o="hour",a="day",l="week",u="month",c="quarter",h="year",d="date",f="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|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"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},A=function(e,t,n){var r=String(e);return!r||r.length>=t?e:""+Array(t+1-r.length).join(n)+e},_={s:A,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?"+":"-")+A(r,2,"0")+":"+A(i,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,u),s=n-i<0,o=t.clone().add(r+(s?-1:1),u);return+(-(r+(n-i)/(s?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:u,y:h,w:l,d:a,D:d,h:o,m:s,s:i,ms:r,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",y={};y[v]=m;var T="$isDayjsObject",S=function(e){return e instanceof b||!(!e||!e[T])},E=function e(t,n,r){var i;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();y[s]&&(i=s),n&&(y[s]=n,i=s);var o=t.split("-");if(!i&&o.length>1)return e(o[0])}else{var a=t.name;y[a]=t,i=a}return!r&&i&&(v=i),i||!r&&v},C=function(e,t){if(S(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new b(n)},w=_;w.l=E,w.i=S,w.w=function(e,t){return C(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var b=function(){function m(e){this.$L=E(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[T]=!0}var A=m.prototype;return A.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(w.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var r=t.match(p);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(t)}(e),this.init()},A.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()},A.$utils=function(){return w},A.isValid=function(){return!(this.$d.toString()===f)},A.isSame=function(e,t){var n=C(e);return this.startOf(t)<=n&&n<=this.endOf(t)},A.isAfter=function(e,t){return C(e)<this.startOf(t)},A.isBefore=function(e,t){return this.endOf(t)<C(e)},A.$g=function(e,t,n){return w.u(e)?this[t]:this.set(n,e)},A.unix=function(){return Math.floor(this.valueOf()/1e3)},A.valueOf=function(){return this.$d.getTime()},A.startOf=function(e,t){var n=this,r=!!w.u(t)||t,c=w.p(e),f=function(e,t){var i=w.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(a)},p=function(e,t){return w.w(n.toDate()[e].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,m=this.$M,A=this.$D,_="set"+(this.$u?"UTC":"");switch(c){case h:return r?f(1,0):f(31,11);case u:return r?f(1,m):f(0,m+1);case l:var v=this.$locale().weekStart||0,y=(g<v?g+7:g)-v;return f(r?A-y:A+(6-y),m);case a:case d:return p(_+"Hours",0);case o:return p(_+"Minutes",1);case s:return p(_+"Seconds",2);case i:return p(_+"Milliseconds",3);default:return this.clone()}},A.endOf=function(e){return this.startOf(e,!1)},A.$set=function(e,t){var n,l=w.p(e),c="set"+(this.$u?"UTC":""),f=(n={},n[a]=c+"Date",n[d]=c+"Date",n[u]=c+"Month",n[h]=c+"FullYear",n[o]=c+"Hours",n[s]=c+"Minutes",n[i]=c+"Seconds",n[r]=c+"Milliseconds",n)[l],p=l===a?this.$D+(t-this.$W):t;if(l===u||l===h){var g=this.clone().set(d,1);g.$d[f](p),g.init(),this.$d=g.set(d,Math.min(this.$D,g.daysInMonth())).$d}else f&&this.$d[f](p);return this.init(),this},A.set=function(e,t){return this.clone().$set(e,t)},A.get=function(e){return this[w.p(e)]()},A.add=function(r,c){var d,f=this;r=Number(r);var p=w.p(c),g=function(e){var t=C(f);return w.w(t.date(t.date()+Math.round(e*r)),f)};if(p===u)return this.set(u,this.$M+r);if(p===h)return this.set(h,this.$y+r);if(p===a)return g(1);if(p===l)return g(7);var m=(d={},d[s]=t,d[o]=n,d[i]=e,d)[p]||1,A=this.$d.getTime()+r*m;return w.w(A,this)},A.subtract=function(e,t){return this.add(-1*e,t)},A.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||f;var r=e||"YYYY-MM-DDTHH:mm:ssZ",i=w.z(this),s=this.$H,o=this.$m,a=this.$M,l=n.weekdays,u=n.months,c=n.meridiem,h=function(e,n,i,s){return e&&(e[n]||e(t,r))||i[n].slice(0,s)},d=function(e){return w.s(s%12||12,e,"0")},p=c||function(e,t,n){var r=e<12?"AM":"PM";return n?r.toLowerCase():r};return r.replace(g,(function(e,r){return r||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return w.s(t.$y,4,"0");case"M":return a+1;case"MM":return w.s(a+1,2,"0");case"MMM":return h(n.monthsShort,a,u,3);case"MMMM":return h(u,a);case"D":return t.$D;case"DD":return w.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return h(n.weekdaysMin,t.$W,l,2);case"ddd":return h(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return w.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return p(s,o,!0);case"A":return p(s,o,!1);case"m":return String(o);case"mm":return w.s(o,2,"0");case"s":return String(t.$s);case"ss":return w.s(t.$s,2,"0");case"SSS":return w.s(t.$ms,3,"0");case"Z":return i}return null}(e)||i.replace(":","")}))},A.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},A.diff=function(r,d,f){var p,g=this,m=w.p(d),A=C(r),_=(A.utcOffset()-this.utcOffset())*t,v=this-A,y=function(){return w.m(g,A)};switch(m){case h:p=y()/12;break;case u:p=y();break;case c:p=y()/3;break;case l:p=(v-_)/6048e5;break;case a:p=(v-_)/864e5;break;case o:p=v/n;break;case s:p=v/t;break;case i:p=v/e;break;default:p=v}return f?p:w.a(p)},A.daysInMonth=function(){return this.endOf(u).$D},A.$locale=function(){return y[this.$L]},A.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),r=E(e,t,!0);return r&&(n.$L=r),n},A.clone=function(){return w.w(this.$d,this)},A.toDate=function(){return new Date(this.valueOf())},A.toJSON=function(){return this.isValid()?this.toISOString():null},A.toISOString=function(){return this.$d.toISOString()},A.toString=function(){return this.$d.toUTCString()},m}(),I=b.prototype;return C.prototype=I,[["$ms",r],["$s",i],["$m",s],["$H",o],["$W",a],["$M",u],["$y",h],["$D",d]].forEach((function(e){I[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),C.extend=function(e,t){return e.$i||(e(t,b,C),e.$i=!0),C},C.locale=E,C.isDayjs=S,C.unix=function(e){return C(1e3*e)},C.en=y[v],C.Ls=y,C.p={},C}());const fl="0.2.2",pl="aks_agent_token";class gl{setTrack(e){this.track=e}constructor(e){this.baseUrl="",this.eventSource=null,this.retryCount=0,this.retryMap=new Map,this.token="",this.track=()=>{},this.id=e.id,this.getSystemToken=e.getSystemToken,this.resetSSE=null==e?void 0:e.resetSSE,this.retryCount=e.retryCount||0,this.baseUrl=e.baseUrl||""}validateToken(t,n){return e(this,void 0,void 0,(function*(){return fetch(`${this.baseUrl}/iam/token/validate?accountId=${t}`,{method:"GET",headers:{authentication:n}}).then((e=>e.json()))}))}initToken(){return e(this,void 0,void 0,(function*(){try{const e=yield this.getSystemToken();if(!e)return{code:sl.FAILED,data:null,message:"get system token failed"};const t=yield this.validateToken(this.id,e);return t.code===sl.SUCCESS?(this.token=e,sessionStorage.setItem(pl,e),this.executePeriodically(this.refreshToken.bind(this),12e5),{code:sl.SUCCESS,data:null,message:t.message}):{code:sl.FAILED,data:null,message:t.message}}catch(e){return{code:sl.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"}}}))}refreshToken(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/iam/oauth2/refresh`}).then((e=>{var t;e.token?(this.token=e.token,sessionStorage.setItem(pl,e.token),this.eventSource&&(null===(t=this.resetSSE)||void 0===t||t.call(this))):this.track("token.refresh.fail")}))}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/status/list`})}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/getAgentByUserId`})}))}getAgentSetting(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getAgentSetting`,data:t})}))}updateAgentHangup(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent/${t}`,method:"PUT"})}))}updateAgentTicket(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/voipPlatform/agent/ticket`,data:t})}))}sendSSEACK(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat_ack?agentId=${t}`,method:"POST"})}))}registerSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:n,onMessage:r}=t;let i=e=>{};const s=new Promise((e=>{i=e})),o=this.token;return this.eventSource=new cl.EventSourcePolyfill(`${this.baseUrl}/crm/v1/agent_command/regist_agent_event?agentId=${n}`,{headers:{Authentication:o,"Cache-Control":"no-cache",Connection:"keep-alive"},heartbeatTimeout:12e6}),this.eventSource.onmessage=r,this.eventSource.onopen=()=>e(this,void 0,void 0,(function*(){this.track("sse.open"),i(!0)})),this.eventSource.onerror=()=>e(this,void 0,void 0,(function*(){this.track("sse.error.error"),i(!1)})),s}))}closeClientSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=null)}closeSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:e,clearTicket:n}=t;if(this.eventSource)return this.request({url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_close?agentId=${e}&clearTicket=${n}`}).then((e=>(this.closeClientSSE(),e)))}))}sendHeartbeat(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat?agentId=${t}&version=${fl}`})}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){return this.request({method:"PUT",url:`${this.baseUrl}/voipPlatform/agent/agentStatusSwitch`,data:t})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){const{phone:e,line:n}=t;return this.request({url:`${this.baseUrl}/crm/v1/agentOutBoundCall/dialer/startCall/${e}/${n}`,method:"POST"})}))}saveAgentResponseTime(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/call_record/callRecordAgent`,data:t})}))}reportPDSTimeline(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/reportPDSTimeline`,method:"POST",data:t})}))}reportSdkTrace(t,n){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/reportSdkTrace`;let r="";try{r=this.getTokenWithFallback()}catch(e){r=""}try{if((null==n?void 0:n.useBeacon)&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){const n=new FormData;return n.append("timestamp",String(t.timestamp)),n.append("traceId",t.traceId),n.append("agentId",t.agentId),n.append("sdkVersion",t.sdkVersion),n.append("callId",t.callId),n.append("callRecordId",t.callRecordId),n.append("event",t.event),n.append("message",t.message),t.extra&&n.append("extra",JSON.stringify(t.extra)),r&&n.append("authentication",r),navigator.sendBeacon(e,n)}return(yield fetch(e,{method:"POST",keepalive:null==n?void 0:n.keepalive,headers:Object.assign({"Content-Type":"application/json"},r?{authentication:r}:{}),body:JSON.stringify(t)})).ok}catch(e){return!1}}))}getSdkTraceConfig(){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/getSdkTraceConfig`;try{const t=yield fetch(e,{method:"GET"});if(!t.ok)return null;const n=yield t.json();return{collect:Boolean(null==n?void 0:n.collect)}}catch(e){return null}}))}getCallTaskInfo(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getCallTaskName/${t.callTaskId}`})}))}getAfterCallProcessTime(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/predictCall/afterCallProcessTime/${t.callTaskId}`})}))}formatFormData(e){const t=new FormData;for(const n in e)e[n]&&t.append(n,e[n]);return t}agentAbnormalClose(e){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const t=this.formatFormData(e);return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_abnormal_close`,data:t},!0)}sendBeacon(e){if("function"==typeof navigator.sendBeacon&&e.url){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const{url:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["url"]),r=this.formatFormData(n),i=navigator.sendBeacon(t,r);if(!i){e.lastSendResult=i;const t=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");t.push(e),localStorage.setItem("aks_beacon_queue",JSON.stringify(t))}}}clearnSendBeaconQueue(){return e(this,void 0,void 0,(function*(){const e=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");if(e.length){if(!(yield this.waitToken())){if((yield this.initToken()).code!==sl.SUCCESS)return}for(let t=0;t<e.length-1;t++)this.sendBeacon(e[t])}}))}getTokenWithFallback(){if(this.token)return this.token;return sessionStorage.getItem(pl)||""}waitToken(e=3e3,t=200){return new Promise((n=>{const r=setInterval((()=>{((e-=t)<=0||this.token)&&(clearInterval(r),n(Boolean(this.token)))}),200)}))}request(t){return e(this,arguments,void 0,(function*(t,n=!1){var r;if(!this.retryMap.has(t.url)&&this.retryCount&&this.retryMap.set(t.url,this.retryCount),!this.token){if(!(yield this.waitToken())){const e=yield this.initToken();if(e.code!==sl.SUCCESS)return{code:e.code,message:e.message,data:null}}}const i={method:t.method||"GET",headers:Object.assign({"Content-Type":"application/json",authentication:this.token},t.headers)};n?(i.method=t.method,i.headers={authentication:this.token},i.body=t.data):"GET"!==(null===(r=i.method)||void 0===r?void 0:r.toLocaleUpperCase())&&(i.body=JSON.stringify(t.data));const s=t.url.replace(this.baseUrl,"").split("?")[0].replace(/\/\d+/g,"/{id}");return fetch(t.url,i).then((n=>e(this,void 0,void 0,(function*(){if(401===n.status){const e=this.retryMap.get(t.url);if(e){this.retryMap.set(t.url,e-1),this.track("api.retry",{extra:{api:s,remaining:e-1}});const n=yield this.initToken();return n.code===sl.SUCCESS?this.request(t):n}return this.retryCount&&this.retryMap.delete(t.url),this.track("api.unauthorized.warn",{extra:{api:s}}),{code:sl.UNAUTHORIZED,message:"Unauthorized",data:null}}return n.ok||this.track("api.fail",{extra:{api:s,httpStatus:n.status}}),n.json()})))).catch((e=>{try{this.track("api.fail",{message:String(e),extra:{api:s}})}catch(e){}throw e}))}))}executePeriodically(e,t){let n=Date.now()+t;const r=()=>{const i=Date.now();i>=n&&(e(),n+=t);const s=Math.max(0,n-i);setTimeout(r,s)};r()}static getInstance(e){return!gl.instance&&e&&(gl.instance=new gl(e)),gl.instance}}gl.instance=null;const ml=e=>{if("string"!=typeof e)return"";let t=e;return t=t.replace(/https?:\/\/[^\s]+/g,(e=>e.split("?")[0].replace(/\/\d+(?=\/|$)/g,"/{id}"))),t=t.replace(/\d{7,}/g,(e=>`${e.slice(0,3)}****${e.slice(-2)}`)),t.length>1024&&(t=t.slice(0,1024)),t},Al="aks_trace_queue";class _l{constructor(e,t){this.storage=e,this.opts=t}read(){try{const e=this.storage.getItem(Al);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return[]}}enqueue(e){try{const t=this.read();t.push(e);const n=t.length-this.opts.cap;n>0&&t.splice(0,n),this.storage.setItem(Al,JSON.stringify(t))}catch(e){}}drain(){try{const e=this.opts.now()-this.opts.ttlMs,t=this.read().filter((t=>t.timestamp>=e));return this.storage.removeItem(Al),t}catch(e){return[]}}}class vl{constructor(e){var t,n;this.enabled=!1,this.traceId="",this.agentId="",this.lastSent=new Map,this.bucket=20,this.bucketTs=0,this.version=e.version,this.now=null!==(t=e.now)&&void 0!==t?t:()=>Date.now(),this.genId=null!==(n=e.genId)&&void 0!==n?n:()=>Date.now().toString(36)+Math.random().toString(36).slice(2,10),this.report=e.report,this.queue=new _l(e.storage,{cap:200,ttlMs:864e5,now:this.now})}applyConfig(e){this.enabled=Boolean(e)}setAgentId(e){this.agentId=String(null!=e?e:"")}resetTraceId(){try{this.traceId=this.genId()}catch(e){}}track(e,t){var n,r,i;try{if(!this.enabled)return;const s=this.now();if(this.isDeduped(e,s))return;if(!this.takeToken(s))return;this.lastSent.set(e,s),this.traceId||(this.traceId=this.genId());const o=Object.assign({timestamp:s,traceId:this.traceId,agentId:this.agentId,sdkVersion:this.version,callId:null!==(n=null==t?void 0:t.callId)&&void 0!==n?n:"",callRecordId:null!==(r=null==t?void 0:t.callRecordId)&&void 0!==r?r:"",event:e,message:ml(null!==(i=null==t?void 0:t.message)&&void 0!==i?i:"")},(null==t?void 0:t.extra)?{extra:t.extra}:{});this.report(o).then((e=>{e||this.queue.enqueue(o)})).catch((()=>{try{this.queue.enqueue(o)}catch(e){}}))}catch(e){}}flush(){try{if(!this.enabled)return;const e=this.queue.drain(),t="undefined"==typeof fetch;for(const n of e)try{this.report(n,{keepalive:!0,useBeacon:t}).catch((()=>{}))}catch(e){}}catch(e){}}isDeduped(e,t){const n=this.lastSent.get(e);return void 0!==n&&t-n<5e3}takeToken(e){return e-this.bucketTs>=1e3&&(this.bucket=20,this.bucketTs=e),!(this.bucket<=0)&&(this.bucket-=1,!0)}}const yl="aks_trace_config";var Tl,Sl,El;!function(e){e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.HANGUP=4]="HANGUP"}(Tl||(Tl={})),function(e){e[e.ANSWER=1]="ANSWER",e[e.HANGUP=2]="HANGUP"}(Sl||(Sl={})),function(e){e[e.INCOMMING=1]="INCOMMING",e[e.ACW=2]="ACW"}(El||(El={}));const Cl=1e4;module.exports=class{constructor(e){this.sip={},this.api={},this.isSipInit=!1,this.isInitSuccess=!1,this.agentInfo={},this.initEvent={},this.agentEvent={},this.agentWaitingTime=0,this.agentResponseTime=0,this.timer=null,this.callDetails={},this.baseUrl="",this.autoFinishACWTimer=null,this._acwAutoTriggered=!1,this.heartbeatTimer=null,this.heartbeatFailCount=0,this.isHeartbeatRunning=!1,this.baseUrl=(null==e?void 0:e.baseUrl)||"",this.api=gl.getInstance({id:e.id,getSystemToken:e.getSystemToken,retryCount:e.retryCount,baseUrl:this.baseUrl});try{const e=window.localStorage;this.tracker=new vl({report:(e,t)=>this.api.reportSdkTrace(e,t),storage:e,version:fl,genId:()=>t()}),this.tracker.applyConfig(!0===(e=>{try{const t=e.getItem(yl);return"true"===t||"false"!==t&&null}catch(e){return null}})(e)),this.api.setTrack(((e,t)=>this.tracker.track(e,t)))}catch(e){this.tracker={track:()=>{},flush:()=>{},applyConfig:()=>{},setAgentId:()=>{},resetTraceId:()=>{}}}this.sip=new ll({incomingCallCallback:this.incomingCall.bind(this),trackIncomingCallCallback:this.trackIncomingCall.bind(this),getMediaStream:null==e?void 0:e.getMediaStream,applyAnswer:this.answer.bind(this),track:(e,t)=>this.tracker.track(e,t)}),this.sip.attchSessionEvent("ended",this.sessionEnded.bind(this)),this.sip.attchSessionEvent("failed",this.sessionFailed.bind(this)),this.init().then((()=>{this.api.clearnSendBeaconQueue()})),"undefined"!=typeof window&&window.addEventListener("pagehide",(()=>this.tracker.flush()),{once:!0})}init(){return e(this,void 0,void 0,(function*(){this.tracker.resetTraceId();const e=yield this.api.getSdkTraceConfig();if(e){this.tracker.applyConfig(e.collect);try{((e,t)=>{try{e.setItem(yl,t?"true":"false")}catch(e){}})(window.localStorage,e.collect)}catch(e){}}const t=yield this.api.initToken();if(t.code!==sl.SUCCESS){this.tracker.track("init.fail",{message:t.message,extra:{stage:"initToken"}});const e=Object.assign(Object.assign({},t),{code:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const n=yield this.getAgentStatus();if(n.code!==ol.SUCCESS){n.code===ol.LOCKED?this.tracker.track("init.locked",{message:n.message}):this.tracker.track("init.fail",{message:n.message,extra:{stage:"getAgentStatus"}});const e=Object.assign(Object.assign({},n),{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const r={code:ol.SUCCESS,data:null,message:"success"};return this.tracker.track("init.success"),this.emitInitEvent("success",r),this.isInitSuccess=!0,r}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){const e=yield this.api.getAgentStatusList();return e.code===sl.SUCCESS?{code:ol.SUCCESS,data:e.data||[],message:e.message}:{code:ol.FAILED,data:null,message:e.message}}))}getTicket(){let e=window.sessionStorage.getItem("wiz-agent-ticket");return e||(e=t(),window.sessionStorage.setItem("wiz-agent-ticket",e)),e}getHostName(e){try{return new URL(e).hostname}catch(e){return""}}createOpensips(){return e(this,void 0,void 0,(function*(){const e=yield this.waitSIPRegistered(7e3);return e.code!==ol.SUCCESS?(e.code!==ol.MIC_PERMISSION_DENIED&&this.sip.stop(!0),{code:e.code,message:e.message}):{code:ol.SUCCESS,message:"success"}}))}closeSip(){return e(this,void 0,void 0,(function*(){return this.sip.stop(!0),Promise.resolve({code:sl.SUCCESS,message:"failed"})}))}waitSIPRegistered(){return e(this,arguments,void 0,(function*(e=7e3){return new Promise((t=>{let n=!1;const r=e=>{n||(n=!0,t(e))};this.sip.on("registered",(()=>{n||(this.tracker.track("sip.registered"),r({code:ol.SUCCESS,message:"SIP registration successed"}))})),this.sip.on("registrationFailed",(()=>r({code:ol.FAILED,message:"SIP registration failed"}))),setTimeout((()=>{n||(this.tracker.track("sip.registerTimeout.fail"),r({code:ol.FAILED,message:"SIP registration failed"}))}),e),this.sip.start().then((e=>{e||(this.tracker.track("sip.startFail"),r({code:ol.MIC_PERMISSION_DENIED,message:"Microphone permission denied. Please allow microphone access in your browser settings and try again."}))}))}))}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){var e;const t=yield this.api.getAgentInfo();if("code"in t&&t.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:t.message};if(!("data"in t)||!(null===(e=t.data)||void 0===e?void 0:e[0]))return{code:ol.FAILED,data:null,message:"Agent not found"};const n=t.data[0];this.agentInfo=n,this.tracker.setAgentId(n.id);const r=n.id;let i=n.ticket;const s=n.status,o=this.getTicket();if(i){if(s===Tl.OFFLINE){if((yield this.api.updateAgentTicket({agentId:r,ticket:"",type:Tl.OFFLINE})).code!==sl.SUCCESS)return{code:ol.FAILED,message:"Update Agent Ticket failed"};i="",n.ticket="",this.agentInfo.ticket=""}if(s===Tl.ONLINE&&i!==o)return{code:ol.LOCKED,data:n,message:"Agent ticket occupied, unable to perform agent online or offline."}}if(!this.isSipInit){const e=`sip:${n.number}@${this.getHostName(n.realm)}`;this.sip.init({wssuri:n.realm,password:n.password,uri:e}),this.isSipInit=!0}return{code:ol.SUCCESS,data:n,message:t.message}}))}getAgentStatus(){return e(this,void 0,void 0,(function*(){try{const e=yield Promise.allSettled([this.getAgentInfo(),this.api.getAgentSetting({key:"callCenter"})]),[n,r]=e.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value));if("agentWaitingTime"in r&&(this.agentWaitingTime=r.agentWaitingTime||0),"code"in n&&n.code!==ol.SUCCESS)return{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:n.message};if(!("data"in n)||!n.data)return{code:ol.FAILED,data:null,message:"Agent not found"};const i=n.data,s=i.status,o=i.id,a=i.groupId,l={code:ol.SUCCESS,data:{id:o,groupId:a,status:s,subStatus:i.statusName},message:"success"};if(this.agentInfo=i,s===Tl.OFFLINE)return l;if(s===Tl.ONLINE){if(n.code===ol.LOCKED)return{code:ol.LOCKED,data:null,message:n.message};this.tracker.track("agent.abnormalClose"),yield this.api.agentAbnormalClose({id:o,groupId:a,trace:t()});const e=yield this.api.switchAgentStatus({id:o,groupId:a,status:Tl.OFFLINE,subStatus:"offline"});return e.code!==sl.SUCCESS?{code:ol.FAILED,data:null,message:e.message}:(l.data.status=Tl.OFFLINE,l.data.subStatus="Offline",l)}return{code:ol.FAILED,data:null,message:"system error"}}catch(e){return{code:ol.FAILED,data:null,message:"system error"}}}))}onlineAgent(t){return e(this,void 0,void 0,(function*(){const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t});if(e.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.ONLINE,subStatus:t},message:"Agent is already online"};return this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",i),this.startHeartbeat(),i}if(e===Tl.OFFLINE){const{code:e,message:i}=yield this.createOpensips();if(e!==ol.SUCCESS)return{code:e===ol.MIC_PERMISSION_DENIED?ol.MIC_PERMISSION_DENIED:ol.FAILED,data:null,message:i};const s=this.getTicket(),o=yield Promise.allSettled([this.api.updateAgentTicket({agentId:n,ticket:s,type:Tl.ONLINE}),this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t})]),[a,l]=o.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value)),u=a.code===sl.SUCCESS&&l.code===sl.SUCCESS,c=(null==a?void 0:a.code)!==sl.SUCCESS&&(null==l?void 0:l.code)!==sl.SUCCESS;if(!u&&!c){const e=[this.closeSip()];let t="";a.code!==sl.SUCCESS&&(t=a.message,e.push(this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:"Offline"}))),l.code!==sl.SUCCESS&&(t=l.message,e.push(this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE})));try{yield Promise.all(e)}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${t} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:t}}if(c){try{yield this.closeSip()}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${a.message} & ${l.message} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:`${a.message} & ${l.message}`}}const h={code:e,data:{status:Tl.ONLINE,subStatus:t},message:i};return this.agentInfo.status=Tl.ONLINE,this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",h),this.startHeartbeat(),h}return{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}offlineAgent(t){return e(this,void 0,void 0,(function*(){this.stopHeartbeat();const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.OFFLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.agentInfo.statusName=t,this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),i}if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE}),yield this.closeSip();const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName=t,i}return this.tracker.track("agent.offline.fail",{message:"invalid status",extra:{reason:"invalid_status"}}),{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}startHeartbeat(){this.isHeartbeatRunning&&this.stopHeartbeat(),this.isHeartbeatRunning=!0,this.heartbeatFailCount=0,this.executeHeartbeat()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isHeartbeatRunning=!1,this.heartbeatFailCount=0}executeHeartbeat(){return e(this,void 0,void 0,(function*(){if(this.isHeartbeatRunning)try{const{id:e}=this.agentInfo;if(yield this.api.sendHeartbeat(e)){const e=this.heartbeatFailCount;this.heartbeatFailCount=0,e>0&&this.tracker.track("heartbeat.recover"),this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}else if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat failed, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"fail"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}catch(e){if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat exception, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"exception"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("status.switch.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Registration failed. Seat online and offline cannot be performed."};const e=yield this.getAgentInfo();if(e.code!==ol.SUCCESS)return{code:e.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:e.message};const{status:n,subStatus:r}=t;return this.tracker.track("status.switch",{extra:{from:this.agentInfo.status,to:n}}),n===Tl.ONLINE?this.onlineAgent(r):n===Tl.OFFLINE?this.offlineAgent(r):(this.tracker.track("status.switch.fail",{extra:{reason:"invalid"}}),{code:ol.FAILED,data:null,message:"system error"})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Outbound calls cannot be made."};const e=this.agentInfo.outboundLineId;if(!e)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_line"}}),Promise.resolve({code:ol.FAILED,data:null,message:"Agent has no outbound line"});this.sip.setCallType("outboundCall");const n=yield this.api.outboundCall({phone:t,line:e}).catch((e=>{throw this.sip.setCallType(""),e}));return n.code===sl.SUCCESS?(this.tracker.track("call.outbound",{extra:{line:e}}),{code:ol.SUCCESS,data:n.data,message:n.message||n.msg}):(this.sip.setCallType(""),this.tracker.track("call.outbound.fail",{message:n.message||n.msg,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:n.message||n.msg})}))}autoFinishACW(){var e,t;let n=Number(this.callDetails.afterCallProcessTime);this.tracker.track("acw.start",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{seconds:n}});const r=()=>{if(n<=0)return this._acwAutoTriggered=!0,void this.finshACW();n-=1,this.autoFinishACWTimer=setTimeout(r,1e3)};this.autoFinishACWTimer=setTimeout(r,1e3)}finshACW(){return e(this,void 0,void 0,(function*(){var e,t;const n=!this._acwAutoTriggered;this._acwAutoTriggered=!1,this.tracker.track("acw.finish",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{manual:n}}),this.autoFinishACWTimer&&(clearTimeout(this.autoFinishACWTimer),this.autoFinishACWTimer=null),this.api.reportPDSTimeline({callId:this.callDetails.callId,eventType:El.ACW});const{id:r,groupId:i}=this.agentInfo,s=yield this.api.switchAgentStatus({id:r,groupId:i,status:Tl.HANGUP});return{code:s.code===sl.SUCCESS?ol.SUCCESS:ol.FAILED,data:null,message:s.message}}))}sessionEnded(){return e(this,void 0,void 0,(function*(){this.autoFinishACW()}))}sessionFailed(){return e(this,void 0,void 0,(function*(){this.api.updateAgentHangup(this.agentInfo.id)}))}saveAgentResponseTime(e){this.api.saveAgentResponseTime({callId:this.callDetails.callId,agentId:this.agentInfo.id,agentResponseTime:this.agentResponseTime,agentGroupId:this.agentInfo.groupId,resultType:e}),this.timer&&(clearInterval(this.timer),this.agentResponseTime=0)}hangup(){var e,t;this.tracker.track("call.hangup",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.hangup()}timingResTime(){this.timer&&(clearInterval(this.timer),this.timer=null);let e=this.agentWaitingTime;this.agentResponseTime=0,this.timer=setInterval((()=>{if(e<=0)return clearInterval((null==this?void 0:this.timer)||0),this.timer=null,void this.ignore();e-=1,this.agentResponseTime+=1}),1e3)}trackIncomingCall(e){this.api.reportPDSTimeline({callId:e,eventType:El.INCOMMING,timestamp:(new Date).getTime()})}incomingCall(t){return e(this,void 0,void 0,(function*(){var e,n,r,i,s,o;try{const a=t.request,l=(null===(n=null===(e=a.headers["Call-Param"])||void 0===e?void 0:e[0])||void 0===n?void 0:n.raw)||"",u=l?atob(l):"",c=JSON.parse(u||"{}"),h=(null===(i=null===(r=a.headers["Call-ID"])||void 0===r?void 0:r[0])||void 0===i?void 0:i.raw)||null,d=(null===(o=null===(s=a.headers["Call-Record-Id"])||void 0===s?void 0:s[0])||void 0===o?void 0:o.raw)||null,f=Object.fromEntries(Object.entries(c).filter((([e])=>""!==e))),p=t.request.getHeader("Task-Name")||"",g=t.request.getHeader("After-Time")||"";let m=f.phone||f.Phone||f.PHONE||"";return m||(m=t.request.getHeader("Caller")||""),this.callDetails={callId:d||"",originCallId:h||"",callType:this.sip.getCallType()||"",taskName:p,afterCallProcessTime:g,phone:m,contactId:f.contactId||f.ContactId||f.CONTACT_ID||"",extraJson:f},"outboundCall"!==this.sip.getCallType()&&this.timingResTime(),Promise.resolve({code:ol.SUCCESS,data:this.callDetails,message:"success"})}catch(e){return this.tracker.track("call.incoming.fail",{message:String(e),extra:{errorName:null==e?void 0:e.name}}),Promise.resolve({code:ol.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"})}}))}answer(){var e,t;this.tracker.track("call.answer",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.answer(),this.saveAgentResponseTime(Sl.ANSWER)}ignore(){var e,t;this.tracker.track("call.ignore",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.ignore(),this.saveAgentResponseTime(Sl.HANGUP)}mute(){this.sip.mute()}unmute(){this.sip.unmute()}attachInitEvent(e,t){t&&"function"==typeof t&&(this.initEvent[e]||(this.initEvent[e]=[]),this.initEvent[e].push(t))}removeInitEvent(e,t){const n=this.initEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitInitEvent(e,t){(this.initEvent[e]||[]).forEach((e=>{e(t)}))}attachAgentEvent(e,t){t&&"function"==typeof t&&(this.agentEvent[e]||(this.agentEvent[e]=[]),this.agentEvent[e].push(t))}removeAgentEvent(e,t){const n=this.agentEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitAgentEvent(e,t){(this.agentEvent[e]||[]).forEach((e=>{e(t)}))}attachAnswerEvent(e){this.sip.attachAnswerEvent(e)}removeAnswerEvent(e){this.sip.removeAnswerEvent(e)}attachAutoAnswerEvent(e){this.sip.attachAutoAnswerEvent(e)}removeAutoAnswerEvent(e){this.sip.removeAutoAnswerEvent(e)}attachNewMessageEvent(e){this.sip.attachNewMessageEvent(e)}removeNewMessageEvent(e){this.sip.removeNewMessageEvent(e)}attchSessionEvent(e,t){this.sip.attchSessionEvent(e,t)}removeSessionEvent(e,t){this.sip.removeSessionEvent(e,t)}};
@@ -3,4 +3,4 @@ function e(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{
3
3
  * eventsource.js
4
4
  * Available under MIT License (MIT)
5
5
  * https://github.com/Yaffle/EventSource/
6
- */!function(e,t){!function(n){var r=n.setTimeout,i=n.clearTimeout,s=n.XMLHttpRequest,o=n.XDomainRequest,a=n.ActiveXObject,l=n.EventSource,u=n.document,c=n.Promise,h=n.fetch,d=n.Response,f=n.TextDecoder,p=n.TextEncoder,g=n.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==g){var m=h;h=function(e,t){var n=t.signal;return m(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return n._reader=t,n._aborted&&n._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},g=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function A(){this.bitsNeeded=0,this.codePoint=0}A.prototype.decode=function(e){function t(e,t,n){if(1===n)return e>=128>>t&&e<<t<=2047;if(2===n)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===n)return e>=65536>>t&&e<<t<=1114111;throw new Error}function n(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var r=65533,i="",s=this.bitsNeeded,o=this.codePoint,a=0;a<e.length;a+=1){var l=e[a];0!==s&&(l<128||l>191||!t(o<<6|63&l,s-6,n(s,o)))&&(s=0,o=r,i+=String.fromCharCode(o)),0===s?(l>=0&&l<=127?(s=0,o=l):l>=192&&l<=223?(s=6,o=31&l):l>=224&&l<=239?(s=12,o=15&l):l>=240&&l<=247?(s=18,o=7&l):(s=0,o=r),0===s||t(o,s,n(s,o))||(s=0,o=r)):(s-=6,o=o<<6|63&l),0===s&&(o<=65535?i+=String.fromCharCode(o):(i+=String.fromCharCode(55296+(o-65535-1>>10)),i+=String.fromCharCode(56320+(o-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=o,i};null!=f&&null!=p&&function(){try{return"test"===(new f).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(f=A);var _=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=_,this.onload=_,this.onerror=_,this.onreadystatechange=_,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=_}function y(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function T(e){for(var t=Object.create(null),n=e.split("\r\n"),r=0;r<n.length;r+=1){var i=n[r].split(": "),s=i.shift(),o=i.join(": ");t[y(s)]=o}this._map=t}function S(){}function E(e){this._headers=e}function C(){}function w(){this._listeners=Object.create(null)}function b(e){r((function(){throw e}),0)}function I(e){this.type=e,this.target=void 0}function R(e,t){I.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function k(e,t){I.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function O(e,t){I.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var n=this,o=this._xhr,a=1,l=0;this._abort=function(e){0!==n._sendTimeout&&(i(n._sendTimeout),n._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,o.onload=_,o.onerror=_,o.onabort=_,o.onprogress=_,o.onreadystatechange=_,o.abort(),0!==l&&(i(l),l=0),e||(n.readyState=4,n.onabort(null),n.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",r=void 0;if("contentType"in o)e=200,t="OK",r=o.contentType;else try{e=o.status,t=o.statusText,r=o.getResponseHeader("Content-Type")}catch(n){e=0,t="",r=void 0}0!==e&&(a=2,n.readyState=2,n.status=e,n.statusText=t,n._contentType=r,n.onreadystatechange())}},c=function(){if(u(),2===a||3===a){a=3;var e="";try{e=o.responseText}catch(e){}n.readyState=3,n.responseText=e,n.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:_}),c(),1===a||2===a||3===a){if(a=4,0!==l&&(i(l),l=0),n.readyState=4,"load"===e)n.onload(t);else if("error"===e)n.onerror(t);else{if("abort"!==e)throw new TypeError;n.onabort(t)}n.onreadystatechange()}},d=function(){l=r((function(){d()}),500),3===o.readyState&&c()};"onload"in o&&(o.onload=function(e){h("load",e)}),"onerror"in o&&(o.onerror=function(e){h("error",e)}),"onabort"in o&&(o.onabort=function(e){h("abort",e)}),"onprogress"in o&&(o.onprogress=c),"onreadystatechange"in o&&(o.onreadystatechange=function(e){!function(e){null!=o&&(4===o.readyState?"onload"in o&&"onerror"in o&&"onabort"in o||h(""===o.responseText?"error":"load",e):3===o.readyState?"onprogress"in o||c():2===o.readyState&&u())}(e)}),!("contentType"in o)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),o.open(e,t,!0),"readyState"in o&&(l=r((function(){d()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var n=this._xhr;"setRequestHeader"in n&&n.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=r((function(){t._sendTimeout=0,t.send()}),4)}},T.prototype.get=function(e){return this._map[y(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),S.prototype.open=function(e,t,n,r,i,o,a){e.open("GET",i);var l=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(l);l+=t.length,n(t)},e.onerror=function(e){e.preventDefault(),r(new Error("NetworkError"))},e.onload=function(){r(null)},e.onabort=function(){r(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var n=e.status,r=e.statusText,i=e.getResponseHeader("Content-Type"),o=e.getAllResponseHeaders();t(n,r,i,new T(o))}},e.withCredentials=o,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},E.prototype.get=function(e){return this._headers.get(e)},C.prototype.open=function(e,t,n,r,i,s,o){var a=null,l=new g,u=l.signal,d=new f;return h(i,{headers:o,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new E(e.headers)),new c((function(e,t){var r=function(){a.read().then((function(t){if(t.done)e(void 0);else{var i=d.decode(t.value,{stream:!0});n(i),r()}})).catch((function(e){t(e)}))};r()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){r(e)})),{abort:function(){null!=a&&a.cancel(),l.abort()}}},w.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var n=t.length,r=0;r<n;r+=1){var i=t[r];try{"function"==typeof i.handleEvent?i.handleEvent(e):i.call(this,e)}catch(e){b(e)}}},w.prototype.addEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];null==r&&(r=[],n[e]=r);for(var i=!1,s=0;s<r.length;s+=1)r[s]===t&&(i=!0);i||r.push(t)},w.prototype.removeEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];if(null!=r){for(var i=[],s=0;s<r.length;s+=1)r[s]!==t&&i.push(r[s]);0===i.length?delete n[e]:n[e]=i}},R.prototype=Object.create(I.prototype),k.prototype=Object.create(I.prototype),O.prototype=Object.create(I.prototype);var D=-1,M=0,N=1,q=2,U=-1,x=0,P=1,L=2,B=3,F=/^text\/event\-stream(;.*)?$/i,H=function(e,t){var n=null==e?t:parseInt(e,10);return n!=n&&(n=t),G(n)},G=function(e){return Math.min(Math.max(e,1e3),18e6)},Y=function(e,t,n){try{"function"==typeof t&&t.call(e,n)}catch(e){b(e)}};function j(e,t){w.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,n){t=String(t);var a=Boolean(n.withCredentials),l=n.lastEventIdQueryParameterName||"lastEventId",u=G(1e3),c=H(n.heartbeatTimeout,45e3),h="",d=u,f=!1,p=0,g=n.headers||{},m=n.Transport,A=Q&&null==m?void 0:new v(null!=m?new m:null!=s&&"withCredentials"in s.prototype||null==o?new s:new o),_=null!=m&&"string"!=typeof m?new m:null==A?new C:new S,y=void 0,T=0,E=D,w="",b="",I="",j="",W=x,K=0,z=0,J=function(t,n,r,i){if(E===M)if(200===t&&null!=r&&F.test(r)){E=N,f=Date.now(),d=u,e.readyState=N;var s=new k("open",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onopen,s)}else{var o="";200!==t?(n&&(n=n.replace(/\s+/g," ")),o="EventSource's response has a status "+t+" "+n+" that is not 200. Aborting the connection."):o="EventSource's response has a Content-Type specifying an unsupported type: "+(null==r?"-":r.replace(/\s+/g," "))+". Aborting the connection.",X();s=new k("error",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onerror,s),console.error(o)}},V=function(t){if(E===N){for(var n=-1,s=0;s<t.length;s+=1){(l=t.charCodeAt(s))!=="\n".charCodeAt(0)&&l!=="\r".charCodeAt(0)||(n=s)}var o=(-1!==n?j:"")+t.slice(0,n+1);j=(-1===n?j:"")+t.slice(n+1),""!==t&&(f=Date.now(),p+=t.length);for(var a=0;a<o.length;a+=1){var l=o.charCodeAt(a);if(W===U&&l==="\n".charCodeAt(0))W=x;else if(W===U&&(W=x),l==="\r".charCodeAt(0)||l==="\n".charCodeAt(0)){if(W!==x){W===P&&(z=a+1);var g=o.slice(K,z-1),m=o.slice(z+(z<a&&o.charCodeAt(z)===" ".charCodeAt(0)?1:0),a);"data"===g?(w+="\n",w+=m):"id"===g?b=m:"event"===g?I=m:"retry"===g?(u=H(m,u),d=u):"heartbeatTimeout"===g&&(c=H(m,c),0!==T&&(i(T),T=r((function(){$()}),c)))}if(W===x){if(""!==w){h=b,""===I&&(I="message");var A=new R(I,{data:w.slice(1),lastEventId:b});if(e.dispatchEvent(A),"open"===I?Y(e,e.onopen,A):"message"===I?Y(e,e.onmessage,A):"error"===I&&Y(e,e.onerror,A),E===q)return}w="",I=""}W=l==="\r".charCodeAt(0)?U:x}else W===x&&(K=a,W=P),W===P?l===":".charCodeAt(0)&&(z=a+1,W=L):W===L&&(W=B)}}},Z=function(t){if(E===N||E===M){E=D,0!==T&&(i(T),T=0),T=r((function(){$()}),d),d=G(Math.min(16*u,2*d)),e.readyState=M;var n=new O("error",{error:t});e.dispatchEvent(n),Y(e,e.onerror,n),null!=t&&console.error(t)}},X=function(){E=q,null!=y&&(y.abort(),y=void 0),0!==T&&(i(T),T=0),e.readyState=q},$=function(){if(T=0,E===D){f=!1,p=0,T=r((function(){$()}),c),E=M,w="",I="",b=h,j="",K=0,z=0,W=x;var n=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var i=t.indexOf("?");n=-1===i?t:t.slice(0,i+1)+t.slice(i+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===l?"":e})),n+=(-1===t.indexOf("?")?"?":"&")+l+"="+encodeURIComponent(h)}var s=e.withCredentials,o={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(o[u]=a[u]);try{y=_.open(A,J,V,Z,n,s,o)}catch(e){throw X(),e}}else if(f||null==y){var d=Math.max((f||Date.now())+c-Date.now(),1);f=!1,T=r((function(){$()}),d)}else Z(new Error("No activity within "+c+" milliseconds. "+(E===M?"No response received.":p+" chars received.")+" Reconnecting.")),null!=y&&(y.abort(),y=void 0)};e.url=t,e.readyState=M,e.withCredentials=a,e.headers=g,e._close=X,$()}(this,e,t)}var Q=null!=h&&null!=d&&"body"in d.prototype;j.prototype=Object.create(w.prototype),j.prototype.CONNECTING=M,j.prototype.OPEN=N,j.prototype.CLOSED=q,j.prototype.close=function(){this._close()},j.CONNECTING=M,j.OPEN=N,j.CLOSED=q,j.prototype.withCredentials=void 0;var W,K=l;null==s||null!=l&&"withCredentials"in l.prototype||(K=j),W=function(e){e.EventSourcePolyfill=j,e.NativeEventSource=l,e.EventSource=K}(t),void 0!==W&&(e.exports=W)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:n:globalThis)}(ul,ul.exports);var cl=ul.exports,hl={exports:{}},dl=r(hl.exports=function(){var e=1e3,t=6e4,n=36e5,r="millisecond",i="second",s="minute",o="hour",a="day",l="week",u="month",c="quarter",h="year",d="date",f="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|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"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},A=function(e,t,n){var r=String(e);return!r||r.length>=t?e:""+Array(t+1-r.length).join(n)+e},_={s:A,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?"+":"-")+A(r,2,"0")+":"+A(i,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,u),s=n-i<0,o=t.clone().add(r+(s?-1:1),u);return+(-(r+(n-i)/(s?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:u,y:h,w:l,d:a,D:d,h:o,m:s,s:i,ms:r,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",y={};y[v]=m;var T="$isDayjsObject",S=function(e){return e instanceof b||!(!e||!e[T])},E=function e(t,n,r){var i;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();y[s]&&(i=s),n&&(y[s]=n,i=s);var o=t.split("-");if(!i&&o.length>1)return e(o[0])}else{var a=t.name;y[a]=t,i=a}return!r&&i&&(v=i),i||!r&&v},C=function(e,t){if(S(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new b(n)},w=_;w.l=E,w.i=S,w.w=function(e,t){return C(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var b=function(){function m(e){this.$L=E(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[T]=!0}var A=m.prototype;return A.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(w.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var r=t.match(p);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(t)}(e),this.init()},A.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()},A.$utils=function(){return w},A.isValid=function(){return!(this.$d.toString()===f)},A.isSame=function(e,t){var n=C(e);return this.startOf(t)<=n&&n<=this.endOf(t)},A.isAfter=function(e,t){return C(e)<this.startOf(t)},A.isBefore=function(e,t){return this.endOf(t)<C(e)},A.$g=function(e,t,n){return w.u(e)?this[t]:this.set(n,e)},A.unix=function(){return Math.floor(this.valueOf()/1e3)},A.valueOf=function(){return this.$d.getTime()},A.startOf=function(e,t){var n=this,r=!!w.u(t)||t,c=w.p(e),f=function(e,t){var i=w.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(a)},p=function(e,t){return w.w(n.toDate()[e].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,m=this.$M,A=this.$D,_="set"+(this.$u?"UTC":"");switch(c){case h:return r?f(1,0):f(31,11);case u:return r?f(1,m):f(0,m+1);case l:var v=this.$locale().weekStart||0,y=(g<v?g+7:g)-v;return f(r?A-y:A+(6-y),m);case a:case d:return p(_+"Hours",0);case o:return p(_+"Minutes",1);case s:return p(_+"Seconds",2);case i:return p(_+"Milliseconds",3);default:return this.clone()}},A.endOf=function(e){return this.startOf(e,!1)},A.$set=function(e,t){var n,l=w.p(e),c="set"+(this.$u?"UTC":""),f=(n={},n[a]=c+"Date",n[d]=c+"Date",n[u]=c+"Month",n[h]=c+"FullYear",n[o]=c+"Hours",n[s]=c+"Minutes",n[i]=c+"Seconds",n[r]=c+"Milliseconds",n)[l],p=l===a?this.$D+(t-this.$W):t;if(l===u||l===h){var g=this.clone().set(d,1);g.$d[f](p),g.init(),this.$d=g.set(d,Math.min(this.$D,g.daysInMonth())).$d}else f&&this.$d[f](p);return this.init(),this},A.set=function(e,t){return this.clone().$set(e,t)},A.get=function(e){return this[w.p(e)]()},A.add=function(r,c){var d,f=this;r=Number(r);var p=w.p(c),g=function(e){var t=C(f);return w.w(t.date(t.date()+Math.round(e*r)),f)};if(p===u)return this.set(u,this.$M+r);if(p===h)return this.set(h,this.$y+r);if(p===a)return g(1);if(p===l)return g(7);var m=(d={},d[s]=t,d[o]=n,d[i]=e,d)[p]||1,A=this.$d.getTime()+r*m;return w.w(A,this)},A.subtract=function(e,t){return this.add(-1*e,t)},A.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||f;var r=e||"YYYY-MM-DDTHH:mm:ssZ",i=w.z(this),s=this.$H,o=this.$m,a=this.$M,l=n.weekdays,u=n.months,c=n.meridiem,h=function(e,n,i,s){return e&&(e[n]||e(t,r))||i[n].slice(0,s)},d=function(e){return w.s(s%12||12,e,"0")},p=c||function(e,t,n){var r=e<12?"AM":"PM";return n?r.toLowerCase():r};return r.replace(g,(function(e,r){return r||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return w.s(t.$y,4,"0");case"M":return a+1;case"MM":return w.s(a+1,2,"0");case"MMM":return h(n.monthsShort,a,u,3);case"MMMM":return h(u,a);case"D":return t.$D;case"DD":return w.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return h(n.weekdaysMin,t.$W,l,2);case"ddd":return h(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return w.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return p(s,o,!0);case"A":return p(s,o,!1);case"m":return String(o);case"mm":return w.s(o,2,"0");case"s":return String(t.$s);case"ss":return w.s(t.$s,2,"0");case"SSS":return w.s(t.$ms,3,"0");case"Z":return i}return null}(e)||i.replace(":","")}))},A.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},A.diff=function(r,d,f){var p,g=this,m=w.p(d),A=C(r),_=(A.utcOffset()-this.utcOffset())*t,v=this-A,y=function(){return w.m(g,A)};switch(m){case h:p=y()/12;break;case u:p=y();break;case c:p=y()/3;break;case l:p=(v-_)/6048e5;break;case a:p=(v-_)/864e5;break;case o:p=v/n;break;case s:p=v/t;break;case i:p=v/e;break;default:p=v}return f?p:w.a(p)},A.daysInMonth=function(){return this.endOf(u).$D},A.$locale=function(){return y[this.$L]},A.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),r=E(e,t,!0);return r&&(n.$L=r),n},A.clone=function(){return w.w(this.$d,this)},A.toDate=function(){return new Date(this.valueOf())},A.toJSON=function(){return this.isValid()?this.toISOString():null},A.toISOString=function(){return this.$d.toISOString()},A.toString=function(){return this.$d.toUTCString()},m}(),I=b.prototype;return C.prototype=I,[["$ms",r],["$s",i],["$m",s],["$H",o],["$W",a],["$M",u],["$y",h],["$D",d]].forEach((function(e){I[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),C.extend=function(e,t){return e.$i||(e(t,b,C),e.$i=!0),C},C.locale=E,C.isDayjs=S,C.unix=function(e){return C(1e3*e)},C.en=y[v],C.Ls=y,C.p={},C}());const fl="0.2.1",pl="aks_agent_token";class gl{setTrack(e){this.track=e}constructor(e){this.baseUrl="",this.eventSource=null,this.retryCount=0,this.retryMap=new Map,this.token="",this.track=()=>{},this.id=e.id,this.getSystemToken=e.getSystemToken,this.resetSSE=null==e?void 0:e.resetSSE,this.retryCount=e.retryCount||0,this.baseUrl=e.baseUrl||""}validateToken(t,n){return e(this,void 0,void 0,(function*(){return fetch(`${this.baseUrl}/iam/token/validate?accountId=${t}`,{method:"GET",headers:{authentication:n}}).then((e=>e.json()))}))}initToken(){return e(this,void 0,void 0,(function*(){try{const e=yield this.getSystemToken();if(!e)return{code:sl.FAILED,data:null,message:"get system token failed"};const t=yield this.validateToken(this.id,e);return t.code===sl.SUCCESS?(this.token=e,sessionStorage.setItem(pl,e),this.executePeriodically(this.refreshToken.bind(this),12e5),{code:sl.SUCCESS,data:null,message:t.message}):{code:sl.FAILED,data:null,message:t.message}}catch(e){return{code:sl.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"}}}))}refreshToken(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/iam/oauth2/refresh`}).then((e=>{var t;e.token?(this.token=e.token,sessionStorage.setItem(pl,e.token),this.eventSource&&(null===(t=this.resetSSE)||void 0===t||t.call(this))):this.track("token.refresh.fail")}))}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/status/list`})}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/getAgentByUserId`})}))}getAgentSetting(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getAgentSetting`,data:t})}))}updateAgentHangup(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent/${t}`,method:"PUT"})}))}updateAgentTicket(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/voipPlatform/agent/ticket`,data:t})}))}sendSSEACK(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat_ack?agentId=${t}`,method:"POST"})}))}registerSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:n,onMessage:r}=t;let i=e=>{};const s=new Promise((e=>{i=e})),o=this.token;return this.eventSource=new cl.EventSourcePolyfill(`${this.baseUrl}/crm/v1/agent_command/regist_agent_event?agentId=${n}`,{headers:{Authentication:o,"Cache-Control":"no-cache",Connection:"keep-alive"},heartbeatTimeout:12e6}),this.eventSource.onmessage=r,this.eventSource.onopen=()=>e(this,void 0,void 0,(function*(){this.track("sse.open"),i(!0)})),this.eventSource.onerror=()=>e(this,void 0,void 0,(function*(){this.track("sse.error.error"),i(!1)})),s}))}closeClientSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=null)}closeSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:e,clearTicket:n}=t;if(this.eventSource)return this.request({url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_close?agentId=${e}&clearTicket=${n}`}).then((e=>(this.closeClientSSE(),e)))}))}sendHeartbeat(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat?agentId=${t}&version=${fl}`})}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){return this.request({method:"PUT",url:`${this.baseUrl}/voipPlatform/agent/agentStatusSwitch`,data:t})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){const{phone:e,line:n}=t;return this.request({url:`${this.baseUrl}/crm/v1/agentOutBoundCall/dialer/startCall/${e}/${n}`,method:"POST"})}))}saveAgentResponseTime(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/call_record/callRecordAgent`,data:t})}))}reportPDSTimeline(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/reportPDSTimeline`,method:"POST",data:t})}))}reportSdkTrace(t,n){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/reportSdkTrace`;let r="";try{r=this.getTokenWithFallback()}catch(e){r=""}try{if((null==n?void 0:n.useBeacon)&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){const n=new FormData;return n.append("timestamp",String(t.timestamp)),n.append("traceId",t.traceId),n.append("agentId",t.agentId),n.append("sdkVersion",t.sdkVersion),n.append("callId",t.callId),n.append("callRecordId",t.callRecordId),n.append("event",t.event),n.append("message",t.message),t.extra&&n.append("extra",JSON.stringify(t.extra)),r&&n.append("authentication",r),navigator.sendBeacon(e,n)}return(yield fetch(e,{method:"POST",keepalive:null==n?void 0:n.keepalive,headers:Object.assign({"Content-Type":"application/json"},r?{authentication:r}:{}),body:JSON.stringify(t)})).ok}catch(e){return!1}}))}getSdkTraceConfig(){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/getSdkTraceConfig`;try{const t=yield fetch(e,{method:"GET"});if(!t.ok)return null;const n=yield t.json();return{collect:Boolean(null==n?void 0:n.collect)}}catch(e){return null}}))}getCallTaskInfo(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getCallTaskName/${t.callTaskId}`})}))}getAfterCallProcessTime(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/predictCall/afterCallProcessTime/${t.callTaskId}`})}))}formatFormData(e){const t=new FormData;for(const n in e)e[n]&&t.append(n,e[n]);return t}agentAbnormalClose(e){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const t=this.formatFormData(e);return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_abnormal_close`,data:t},!0)}sendBeacon(e){if("function"==typeof navigator.sendBeacon&&e.url){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const{url:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["url"]),r=this.formatFormData(n),i=navigator.sendBeacon(t,r);if(!i){e.lastSendResult=i;const t=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");t.push(e),localStorage.setItem("aks_beacon_queue",JSON.stringify(t))}}}clearnSendBeaconQueue(){return e(this,void 0,void 0,(function*(){const e=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");if(e.length){if(!(yield this.waitToken())){if((yield this.initToken()).code!==sl.SUCCESS)return}for(let t=0;t<e.length-1;t++)this.sendBeacon(e[t])}}))}getTokenWithFallback(){if(this.token)return this.token;return sessionStorage.getItem(pl)||""}waitToken(e=3e3,t=200){return new Promise((n=>{const r=setInterval((()=>{((e-=t)<=0||this.token)&&(clearInterval(r),n(Boolean(this.token)))}),200)}))}request(t){return e(this,arguments,void 0,(function*(t,n=!1){var r;if(!this.retryMap.has(t.url)&&this.retryCount&&this.retryMap.set(t.url,this.retryCount),!this.token){if(!(yield this.waitToken())){const e=yield this.initToken();if(e.code!==sl.SUCCESS)return{code:e.code,message:e.message,data:null}}}const i={method:t.method||"GET",headers:Object.assign({"Content-Type":"application/json",authentication:this.token},t.headers)};n?(i.method=t.method,i.headers={authentication:this.token},i.body=t.data):"GET"!==(null===(r=i.method)||void 0===r?void 0:r.toLocaleUpperCase())&&(i.body=JSON.stringify(t.data));const s=t.url.replace(this.baseUrl,"").split("?")[0].replace(/\/\d+/g,"/{id}");return fetch(t.url,i).then((n=>e(this,void 0,void 0,(function*(){if(401===n.status){const e=this.retryMap.get(t.url);if(e){this.retryMap.set(t.url,e-1),this.track("api.retry",{extra:{api:s,remaining:e-1}});const n=yield this.initToken();return n.code===sl.SUCCESS?this.request(t):n}return this.retryCount&&this.retryMap.delete(t.url),this.track("api.unauthorized.warn",{extra:{api:s}}),{code:sl.UNAUTHORIZED,message:"Unauthorized",data:null}}return n.ok||this.track("api.fail",{extra:{api:s,httpStatus:n.status}}),n.json()})))).catch((e=>{try{this.track("api.fail",{message:String(e),extra:{api:s}})}catch(e){}throw e}))}))}executePeriodically(e,t){let n=Date.now()+t;const r=()=>{const i=Date.now();i>=n&&(e(),n+=t);const s=Math.max(0,n-i);setTimeout(r,s)};r()}static getInstance(e){return!gl.instance&&e&&(gl.instance=new gl(e)),gl.instance}}gl.instance=null;const ml=e=>{if("string"!=typeof e)return"";let t=e;return t=t.replace(/https?:\/\/[^\s]+/g,(e=>e.split("?")[0].replace(/\/\d+(?=\/|$)/g,"/{id}"))),t=t.replace(/\d{7,}/g,(e=>`${e.slice(0,3)}****${e.slice(-2)}`)),t.length>1024&&(t=t.slice(0,1024)),t},Al="aks_trace_queue";class _l{constructor(e,t){this.storage=e,this.opts=t}read(){try{const e=this.storage.getItem(Al);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return[]}}enqueue(e){try{const t=this.read();t.push(e);const n=t.length-this.opts.cap;n>0&&t.splice(0,n),this.storage.setItem(Al,JSON.stringify(t))}catch(e){}}drain(){try{const e=this.opts.now()-this.opts.ttlMs,t=this.read().filter((t=>t.timestamp>=e));return this.storage.removeItem(Al),t}catch(e){return[]}}}class vl{constructor(e){var t,n;this.enabled=!1,this.traceId="",this.agentId="",this.lastSent=new Map,this.bucket=20,this.bucketTs=0,this.version=e.version,this.now=null!==(t=e.now)&&void 0!==t?t:()=>Date.now(),this.genId=null!==(n=e.genId)&&void 0!==n?n:()=>Date.now().toString(36)+Math.random().toString(36).slice(2,10),this.report=e.report,this.queue=new _l(e.storage,{cap:200,ttlMs:864e5,now:this.now})}applyConfig(e){this.enabled=Boolean(e)}setAgentId(e){this.agentId=String(null!=e?e:"")}resetTraceId(){try{this.traceId=this.genId()}catch(e){}}track(e,t){var n,r,i;try{if(!this.enabled)return;const s=this.now();if(this.isDeduped(e,s))return;if(!this.takeToken(s))return;this.lastSent.set(e,s),this.traceId||(this.traceId=this.genId());const o=Object.assign({timestamp:s,traceId:this.traceId,agentId:this.agentId,sdkVersion:this.version,callId:null!==(n=null==t?void 0:t.callId)&&void 0!==n?n:"",callRecordId:null!==(r=null==t?void 0:t.callRecordId)&&void 0!==r?r:"",event:e,message:ml(null!==(i=null==t?void 0:t.message)&&void 0!==i?i:"")},(null==t?void 0:t.extra)?{extra:t.extra}:{});this.report(o).then((e=>{e||this.queue.enqueue(o)})).catch((()=>{try{this.queue.enqueue(o)}catch(e){}}))}catch(e){}}flush(){try{if(!this.enabled)return;const e=this.queue.drain(),t="undefined"==typeof fetch;for(const n of e)try{this.report(n,{keepalive:!0,useBeacon:t}).catch((()=>{}))}catch(e){}}catch(e){}}isDeduped(e,t){const n=this.lastSent.get(e);return void 0!==n&&t-n<5e3}takeToken(e){return e-this.bucketTs>=1e3&&(this.bucket=20,this.bucketTs=e),!(this.bucket<=0)&&(this.bucket-=1,!0)}}const yl="aks_trace_config";var Tl,Sl,El;!function(e){e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.HANGUP=4]="HANGUP"}(Tl||(Tl={})),function(e){e[e.ANSWER=1]="ANSWER",e[e.HANGUP=2]="HANGUP"}(Sl||(Sl={})),function(e){e[e.INCOMMING=1]="INCOMMING",e[e.ACW=2]="ACW"}(El||(El={}));const Cl=1e4;class wl{constructor(e){this.sip={},this.api={},this.isSipInit=!1,this.isInitSuccess=!1,this.agentInfo={},this.initEvent={},this.agentEvent={},this.agentWaitingTime=0,this.agentResponseTime=0,this.timer=null,this.callDetails={},this.baseUrl="",this.autoFinishACWTimer=null,this._acwAutoTriggered=!1,this.heartbeatTimer=null,this.heartbeatFailCount=0,this.isHeartbeatRunning=!1,this.baseUrl=(null==e?void 0:e.baseUrl)||"",this.api=gl.getInstance({id:e.id,getSystemToken:e.getSystemToken,retryCount:e.retryCount,baseUrl:this.baseUrl});try{const e=window.localStorage;this.tracker=new vl({report:(e,t)=>this.api.reportSdkTrace(e,t),storage:e,version:fl,genId:()=>t()}),this.tracker.applyConfig(!0===(e=>{try{const t=e.getItem(yl);return"true"===t||"false"!==t&&null}catch(e){return null}})(e)),this.api.setTrack(((e,t)=>this.tracker.track(e,t)))}catch(e){this.tracker={track:()=>{},flush:()=>{},applyConfig:()=>{},setAgentId:()=>{},resetTraceId:()=>{}}}this.sip=new ll({incomingCallCallback:this.incomingCall.bind(this),trackIncomingCallCallback:this.trackIncomingCall.bind(this),getMediaStream:null==e?void 0:e.getMediaStream,applyAnswer:this.answer.bind(this),track:(e,t)=>this.tracker.track(e,t)}),this.sip.attchSessionEvent("ended",this.sessionEnded.bind(this)),this.sip.attchSessionEvent("failed",this.sessionFailed.bind(this)),this.init().then((()=>{this.api.clearnSendBeaconQueue()})),"undefined"!=typeof window&&window.addEventListener("pagehide",(()=>this.tracker.flush()),{once:!0})}init(){return e(this,void 0,void 0,(function*(){this.tracker.resetTraceId();const e=yield this.api.getSdkTraceConfig();if(e){this.tracker.applyConfig(e.collect);try{((e,t)=>{try{e.setItem(yl,t?"true":"false")}catch(e){}})(window.localStorage,e.collect)}catch(e){}}const t=yield this.api.initToken();if(t.code!==sl.SUCCESS){this.tracker.track("init.fail",{message:t.message,extra:{stage:"initToken"}});const e=Object.assign(Object.assign({},t),{code:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const n=yield this.getAgentStatus();if(n.code!==ol.SUCCESS){n.code===ol.LOCKED?this.tracker.track("init.locked",{message:n.message}):this.tracker.track("init.fail",{message:n.message,extra:{stage:"getAgentStatus"}});const e=Object.assign(Object.assign({},n),{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const r={code:ol.SUCCESS,data:null,message:"success"};return this.tracker.track("init.success"),this.emitInitEvent("success",r),this.isInitSuccess=!0,r}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){const e=yield this.api.getAgentStatusList();return e.code===sl.SUCCESS?{code:ol.SUCCESS,data:e.data||[],message:e.message}:{code:ol.FAILED,data:null,message:e.message}}))}getTicket(){let e=window.sessionStorage.getItem("wiz-agent-ticket");return e||(e=t(),window.sessionStorage.setItem("wiz-agent-ticket",e)),e}getHostName(e){try{return new URL(e).hostname}catch(e){return""}}createOpensips(){return e(this,void 0,void 0,(function*(){const e=yield this.waitSIPRegistered(7e3);return e.code!==ol.SUCCESS?(e.code!==ol.MIC_PERMISSION_DENIED&&this.sip.stop(!0),{code:e.code,message:e.message}):{code:ol.SUCCESS,message:"success"}}))}closeSip(){return e(this,void 0,void 0,(function*(){return this.sip.stop(!0),Promise.resolve({code:sl.SUCCESS,message:"failed"})}))}waitSIPRegistered(){return e(this,arguments,void 0,(function*(e=7e3){return new Promise((t=>{let n=!1;const r=e=>{n||(n=!0,t(e))};this.sip.on("registered",(()=>{n||(this.tracker.track("sip.registered"),r({code:ol.SUCCESS,message:"SIP registration successed"}))})),this.sip.on("registrationFailed",(()=>r({code:ol.FAILED,message:"SIP registration failed"}))),setTimeout((()=>{n||(this.tracker.track("sip.registerTimeout.fail"),r({code:ol.FAILED,message:"SIP registration failed"}))}),e),this.sip.start().then((e=>{e||(this.tracker.track("sip.startFail"),r({code:ol.MIC_PERMISSION_DENIED,message:"Microphone permission denied. Please allow microphone access in your browser settings and try again."}))}))}))}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){var e;const t=yield this.api.getAgentInfo();if("code"in t&&t.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:t.message};if(!("data"in t)||!(null===(e=t.data)||void 0===e?void 0:e[0]))return{code:ol.FAILED,data:null,message:"Agent not found"};const n=t.data[0];this.agentInfo=n,this.tracker.setAgentId(n.id);const r=n.id;let i=n.ticket;const s=n.status,o=this.getTicket();if(i){if(s===Tl.OFFLINE){if((yield this.api.updateAgentTicket({agentId:r,ticket:"",type:Tl.OFFLINE})).code!==sl.SUCCESS)return{code:ol.FAILED,message:"Update Agent Ticket failed"};i="",n.ticket="",this.agentInfo.ticket=""}if(s===Tl.ONLINE&&i!==o)return{code:ol.LOCKED,data:n,message:"Agent ticket occupied, unable to perform agent online or offline."}}if(!this.isSipInit){const e=`sip:${n.number}@${this.getHostName(n.realm)}`;this.sip.init({wssuri:n.realm,password:n.password,uri:e}),this.isSipInit=!0}return{code:ol.SUCCESS,data:n,message:t.message}}))}getAgentStatus(){return e(this,void 0,void 0,(function*(){try{const e=yield Promise.allSettled([this.getAgentInfo(),this.api.getAgentSetting({key:"callCenter"})]),[n,r]=e.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value));if("agentWaitingTime"in r&&(this.agentWaitingTime=r.agentWaitingTime||0),"code"in n&&n.code!==ol.SUCCESS)return{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:n.message};if(!("data"in n)||!n.data)return{code:ol.FAILED,data:null,message:"Agent not found"};const i=n.data,s=i.status,o=i.id,a=i.groupId,l={code:ol.SUCCESS,data:{id:o,groupId:a,status:s,subStatus:i.statusName},message:"success"};if(this.agentInfo=i,s===Tl.OFFLINE)return l;if(s===Tl.ONLINE){if(n.code===ol.LOCKED)return{code:ol.LOCKED,data:null,message:n.message};this.tracker.track("agent.abnormalClose"),yield this.api.agentAbnormalClose({id:o,groupId:a,trace:t()});const e=yield this.api.switchAgentStatus({id:o,groupId:a,status:Tl.OFFLINE,subStatus:"offline"});return e.code!==sl.SUCCESS?{code:ol.FAILED,data:null,message:e.message}:(l.data.status=Tl.OFFLINE,l.data.subStatus="Offline",l)}return{code:ol.FAILED,data:null,message:"system error"}}catch(e){return{code:ol.FAILED,data:null,message:"system error"}}}))}onlineAgent(t){return e(this,void 0,void 0,(function*(){const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t});if(e.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.ONLINE,subStatus:t},message:"Agent is already online"};return this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",i),this.startHeartbeat(),i}if(e===Tl.OFFLINE){const{code:e,message:i}=yield this.createOpensips();if(e!==ol.SUCCESS)return{code:e===ol.MIC_PERMISSION_DENIED?ol.MIC_PERMISSION_DENIED:ol.FAILED,data:null,message:i};const s=this.getTicket(),o=yield Promise.allSettled([this.api.updateAgentTicket({agentId:n,ticket:s,type:Tl.ONLINE}),this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t})]),[a,l]=o.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value)),u=a.code===sl.SUCCESS&&l.code===sl.SUCCESS,c=(null==a?void 0:a.code)!==sl.SUCCESS&&(null==l?void 0:l.code)!==sl.SUCCESS;if(!u&&!c){const e=[this.closeSip()];let t="";a.code!==sl.SUCCESS&&(t=a.message,e.push(this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:"Offline"}))),l.code!==sl.SUCCESS&&(t=l.message,e.push(this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE})));try{yield Promise.all(e)}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${t} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:t}}if(c){try{yield this.closeSip()}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${a.message} & ${l.message} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:`${a.message} & ${l.message}`}}const h={code:e,data:{status:Tl.ONLINE,subStatus:t},message:i};return this.agentInfo.status=Tl.ONLINE,this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",h),this.startHeartbeat(),h}return{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}offlineAgent(t){return e(this,void 0,void 0,(function*(){this.stopHeartbeat();const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.OFFLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.agentInfo.statusName=t,this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),i}if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE}),yield this.closeSip();const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName=t,i}return this.tracker.track("agent.offline.fail",{message:"invalid status",extra:{reason:"invalid_status"}}),{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}startHeartbeat(){this.isHeartbeatRunning&&this.stopHeartbeat(),this.isHeartbeatRunning=!0,this.heartbeatFailCount=0,this.executeHeartbeat()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isHeartbeatRunning=!1,this.heartbeatFailCount=0}executeHeartbeat(){return e(this,void 0,void 0,(function*(){if(this.isHeartbeatRunning)try{const{id:e}=this.agentInfo;if(yield this.api.sendHeartbeat(e)){const e=this.heartbeatFailCount;this.heartbeatFailCount=0,e>0&&this.tracker.track("heartbeat.recover"),this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}else if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat failed, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"fail"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}catch(e){if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat exception, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"exception"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("status.switch.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Registration failed. Seat online and offline cannot be performed."};const e=yield this.getAgentInfo();if(e.code!==ol.SUCCESS)return{code:e.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:e.message};const{status:n,subStatus:r}=t;return this.tracker.track("status.switch",{extra:{from:this.agentInfo.status,to:n}}),n===Tl.ONLINE?this.onlineAgent(r):n===Tl.OFFLINE?this.offlineAgent(r):(this.tracker.track("status.switch.fail",{extra:{reason:"invalid"}}),{code:ol.FAILED,data:null,message:"system error"})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Outbound calls cannot be made."};const e=this.agentInfo.outboundLineId;if(!e)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_line"}}),Promise.resolve({code:ol.FAILED,data:null,message:"Agent has no outbound line"});this.sip.setCallType("outboundCall");const n=yield this.api.outboundCall({phone:t,line:e}).catch((e=>{throw this.sip.setCallType(""),e}));return n.code===sl.SUCCESS?(this.tracker.track("call.outbound",{extra:{line:e}}),{code:ol.SUCCESS,data:n.data,message:n.message||n.msg}):(this.sip.setCallType(""),this.tracker.track("call.outbound.fail",{message:n.message||n.msg,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:n.message||n.msg})}))}autoFinishACW(){var e,t;let n=Number(this.callDetails.afterCallProcessTime);this.tracker.track("acw.start",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{seconds:n}});const r=()=>{if(n<=0)return this._acwAutoTriggered=!0,void this.finshACW();n-=1,this.autoFinishACWTimer=setTimeout(r,1e3)};this.autoFinishACWTimer=setTimeout(r,1e3)}finshACW(){return e(this,void 0,void 0,(function*(){var e,t;const n=!this._acwAutoTriggered;this._acwAutoTriggered=!1,this.tracker.track("acw.finish",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{manual:n}}),this.autoFinishACWTimer&&(clearTimeout(this.autoFinishACWTimer),this.autoFinishACWTimer=null),this.api.reportPDSTimeline({callId:this.callDetails.callId,eventType:El.ACW});const{id:r,groupId:i}=this.agentInfo,s=yield this.api.switchAgentStatus({id:r,groupId:i,status:Tl.HANGUP});return{code:s.code===sl.SUCCESS?ol.SUCCESS:ol.FAILED,data:null,message:s.message}}))}sessionEnded(){return e(this,void 0,void 0,(function*(){this.autoFinishACW()}))}sessionFailed(){return e(this,void 0,void 0,(function*(){this.api.updateAgentHangup(this.agentInfo.id)}))}saveAgentResponseTime(e){this.api.saveAgentResponseTime({callId:this.callDetails.callId,agentId:this.agentInfo.id,agentResponseTime:this.agentResponseTime,agentGroupId:this.agentInfo.groupId,resultType:e}),this.timer&&(clearInterval(this.timer),this.agentResponseTime=0)}hangup(){var e,t;this.tracker.track("call.hangup",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.hangup()}timingResTime(){this.timer&&(clearInterval(this.timer),this.timer=null);let e=this.agentWaitingTime;this.agentResponseTime=0,this.timer=setInterval((()=>{if(e<=0)return clearInterval((null==this?void 0:this.timer)||0),this.timer=null,void this.ignore();e-=1,this.agentResponseTime+=1}),1e3)}trackIncomingCall(e){this.api.reportPDSTimeline({callId:e,eventType:El.INCOMMING,timestamp:(new Date).getTime()})}incomingCall(t){return e(this,void 0,void 0,(function*(){var e,n,r,i,s,o;try{const a=t.request,l=(null===(n=null===(e=a.headers["Call-Param"])||void 0===e?void 0:e[0])||void 0===n?void 0:n.raw)||"",u=l?atob(l):"",c=JSON.parse(u||"{}"),h=(null===(i=null===(r=a.headers["Call-ID"])||void 0===r?void 0:r[0])||void 0===i?void 0:i.raw)||null,d=(null===(o=null===(s=a.headers["Call-Record-Id"])||void 0===s?void 0:s[0])||void 0===o?void 0:o.raw)||null,f=Object.fromEntries(Object.entries(c).filter((([e])=>""!==e))),p=t.request.getHeader("Task-Name")||"",g=t.request.getHeader("After-Time")||"";return this.callDetails={callId:d||"",originCallId:h||"",callType:this.sip.getCallType()||"",taskName:p,afterCallProcessTime:g,phone:f.phone||f.Phone||f.PHONE||"",contactId:f.contactId||f.ContactId||f.CONTACT_ID||"",extraJson:f},"outboundCall"!==this.sip.getCallType()&&this.timingResTime(),Promise.resolve({code:ol.SUCCESS,data:this.callDetails,message:"success"})}catch(e){return this.tracker.track("call.incoming.fail",{message:String(e),extra:{errorName:null==e?void 0:e.name}}),Promise.resolve({code:ol.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"})}}))}answer(){var e,t;this.tracker.track("call.answer",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.answer(),this.saveAgentResponseTime(Sl.ANSWER)}ignore(){var e,t;this.tracker.track("call.ignore",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.ignore(),this.saveAgentResponseTime(Sl.HANGUP)}mute(){this.sip.mute()}unmute(){this.sip.unmute()}attachInitEvent(e,t){t&&"function"==typeof t&&(this.initEvent[e]||(this.initEvent[e]=[]),this.initEvent[e].push(t))}removeInitEvent(e,t){const n=this.initEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitInitEvent(e,t){(this.initEvent[e]||[]).forEach((e=>{e(t)}))}attachAgentEvent(e,t){t&&"function"==typeof t&&(this.agentEvent[e]||(this.agentEvent[e]=[]),this.agentEvent[e].push(t))}removeAgentEvent(e,t){const n=this.agentEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitAgentEvent(e,t){(this.agentEvent[e]||[]).forEach((e=>{e(t)}))}attachAnswerEvent(e){this.sip.attachAnswerEvent(e)}removeAnswerEvent(e){this.sip.removeAnswerEvent(e)}attachAutoAnswerEvent(e){this.sip.attachAutoAnswerEvent(e)}removeAutoAnswerEvent(e){this.sip.removeAutoAnswerEvent(e)}attachNewMessageEvent(e){this.sip.attachNewMessageEvent(e)}removeNewMessageEvent(e){this.sip.removeNewMessageEvent(e)}attchSessionEvent(e,t){this.sip.attchSessionEvent(e,t)}removeSessionEvent(e,t){this.sip.removeSessionEvent(e,t)}}export{wl as default};
6
+ */!function(e,t){!function(n){var r=n.setTimeout,i=n.clearTimeout,s=n.XMLHttpRequest,o=n.XDomainRequest,a=n.ActiveXObject,l=n.EventSource,u=n.document,c=n.Promise,h=n.fetch,d=n.Response,f=n.TextDecoder,p=n.TextEncoder,g=n.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==g){var m=h;h=function(e,t){var n=t.signal;return m(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return n._reader=t,n._aborted&&n._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},g=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function A(){this.bitsNeeded=0,this.codePoint=0}A.prototype.decode=function(e){function t(e,t,n){if(1===n)return e>=128>>t&&e<<t<=2047;if(2===n)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===n)return e>=65536>>t&&e<<t<=1114111;throw new Error}function n(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var r=65533,i="",s=this.bitsNeeded,o=this.codePoint,a=0;a<e.length;a+=1){var l=e[a];0!==s&&(l<128||l>191||!t(o<<6|63&l,s-6,n(s,o)))&&(s=0,o=r,i+=String.fromCharCode(o)),0===s?(l>=0&&l<=127?(s=0,o=l):l>=192&&l<=223?(s=6,o=31&l):l>=224&&l<=239?(s=12,o=15&l):l>=240&&l<=247?(s=18,o=7&l):(s=0,o=r),0===s||t(o,s,n(s,o))||(s=0,o=r)):(s-=6,o=o<<6|63&l),0===s&&(o<=65535?i+=String.fromCharCode(o):(i+=String.fromCharCode(55296+(o-65535-1>>10)),i+=String.fromCharCode(56320+(o-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=o,i};null!=f&&null!=p&&function(){try{return"test"===(new f).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(f=A);var _=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=_,this.onload=_,this.onerror=_,this.onreadystatechange=_,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=_}function y(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function T(e){for(var t=Object.create(null),n=e.split("\r\n"),r=0;r<n.length;r+=1){var i=n[r].split(": "),s=i.shift(),o=i.join(": ");t[y(s)]=o}this._map=t}function S(){}function E(e){this._headers=e}function C(){}function w(){this._listeners=Object.create(null)}function b(e){r((function(){throw e}),0)}function I(e){this.type=e,this.target=void 0}function R(e,t){I.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function k(e,t){I.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function O(e,t){I.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var n=this,o=this._xhr,a=1,l=0;this._abort=function(e){0!==n._sendTimeout&&(i(n._sendTimeout),n._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,o.onload=_,o.onerror=_,o.onabort=_,o.onprogress=_,o.onreadystatechange=_,o.abort(),0!==l&&(i(l),l=0),e||(n.readyState=4,n.onabort(null),n.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",r=void 0;if("contentType"in o)e=200,t="OK",r=o.contentType;else try{e=o.status,t=o.statusText,r=o.getResponseHeader("Content-Type")}catch(n){e=0,t="",r=void 0}0!==e&&(a=2,n.readyState=2,n.status=e,n.statusText=t,n._contentType=r,n.onreadystatechange())}},c=function(){if(u(),2===a||3===a){a=3;var e="";try{e=o.responseText}catch(e){}n.readyState=3,n.responseText=e,n.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:_}),c(),1===a||2===a||3===a){if(a=4,0!==l&&(i(l),l=0),n.readyState=4,"load"===e)n.onload(t);else if("error"===e)n.onerror(t);else{if("abort"!==e)throw new TypeError;n.onabort(t)}n.onreadystatechange()}},d=function(){l=r((function(){d()}),500),3===o.readyState&&c()};"onload"in o&&(o.onload=function(e){h("load",e)}),"onerror"in o&&(o.onerror=function(e){h("error",e)}),"onabort"in o&&(o.onabort=function(e){h("abort",e)}),"onprogress"in o&&(o.onprogress=c),"onreadystatechange"in o&&(o.onreadystatechange=function(e){!function(e){null!=o&&(4===o.readyState?"onload"in o&&"onerror"in o&&"onabort"in o||h(""===o.responseText?"error":"load",e):3===o.readyState?"onprogress"in o||c():2===o.readyState&&u())}(e)}),!("contentType"in o)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),o.open(e,t,!0),"readyState"in o&&(l=r((function(){d()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var n=this._xhr;"setRequestHeader"in n&&n.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=r((function(){t._sendTimeout=0,t.send()}),4)}},T.prototype.get=function(e){return this._map[y(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),S.prototype.open=function(e,t,n,r,i,o,a){e.open("GET",i);var l=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(l);l+=t.length,n(t)},e.onerror=function(e){e.preventDefault(),r(new Error("NetworkError"))},e.onload=function(){r(null)},e.onabort=function(){r(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var n=e.status,r=e.statusText,i=e.getResponseHeader("Content-Type"),o=e.getAllResponseHeaders();t(n,r,i,new T(o))}},e.withCredentials=o,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},E.prototype.get=function(e){return this._headers.get(e)},C.prototype.open=function(e,t,n,r,i,s,o){var a=null,l=new g,u=l.signal,d=new f;return h(i,{headers:o,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new E(e.headers)),new c((function(e,t){var r=function(){a.read().then((function(t){if(t.done)e(void 0);else{var i=d.decode(t.value,{stream:!0});n(i),r()}})).catch((function(e){t(e)}))};r()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){r(e)})),{abort:function(){null!=a&&a.cancel(),l.abort()}}},w.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var n=t.length,r=0;r<n;r+=1){var i=t[r];try{"function"==typeof i.handleEvent?i.handleEvent(e):i.call(this,e)}catch(e){b(e)}}},w.prototype.addEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];null==r&&(r=[],n[e]=r);for(var i=!1,s=0;s<r.length;s+=1)r[s]===t&&(i=!0);i||r.push(t)},w.prototype.removeEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];if(null!=r){for(var i=[],s=0;s<r.length;s+=1)r[s]!==t&&i.push(r[s]);0===i.length?delete n[e]:n[e]=i}},R.prototype=Object.create(I.prototype),k.prototype=Object.create(I.prototype),O.prototype=Object.create(I.prototype);var D=-1,M=0,N=1,q=2,U=-1,x=0,P=1,L=2,B=3,F=/^text\/event\-stream(;.*)?$/i,H=function(e,t){var n=null==e?t:parseInt(e,10);return n!=n&&(n=t),G(n)},G=function(e){return Math.min(Math.max(e,1e3),18e6)},Y=function(e,t,n){try{"function"==typeof t&&t.call(e,n)}catch(e){b(e)}};function j(e,t){w.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,n){t=String(t);var a=Boolean(n.withCredentials),l=n.lastEventIdQueryParameterName||"lastEventId",u=G(1e3),c=H(n.heartbeatTimeout,45e3),h="",d=u,f=!1,p=0,g=n.headers||{},m=n.Transport,A=Q&&null==m?void 0:new v(null!=m?new m:null!=s&&"withCredentials"in s.prototype||null==o?new s:new o),_=null!=m&&"string"!=typeof m?new m:null==A?new C:new S,y=void 0,T=0,E=D,w="",b="",I="",j="",W=x,K=0,z=0,J=function(t,n,r,i){if(E===M)if(200===t&&null!=r&&F.test(r)){E=N,f=Date.now(),d=u,e.readyState=N;var s=new k("open",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onopen,s)}else{var o="";200!==t?(n&&(n=n.replace(/\s+/g," ")),o="EventSource's response has a status "+t+" "+n+" that is not 200. Aborting the connection."):o="EventSource's response has a Content-Type specifying an unsupported type: "+(null==r?"-":r.replace(/\s+/g," "))+". Aborting the connection.",X();s=new k("error",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onerror,s),console.error(o)}},V=function(t){if(E===N){for(var n=-1,s=0;s<t.length;s+=1){(l=t.charCodeAt(s))!=="\n".charCodeAt(0)&&l!=="\r".charCodeAt(0)||(n=s)}var o=(-1!==n?j:"")+t.slice(0,n+1);j=(-1===n?j:"")+t.slice(n+1),""!==t&&(f=Date.now(),p+=t.length);for(var a=0;a<o.length;a+=1){var l=o.charCodeAt(a);if(W===U&&l==="\n".charCodeAt(0))W=x;else if(W===U&&(W=x),l==="\r".charCodeAt(0)||l==="\n".charCodeAt(0)){if(W!==x){W===P&&(z=a+1);var g=o.slice(K,z-1),m=o.slice(z+(z<a&&o.charCodeAt(z)===" ".charCodeAt(0)?1:0),a);"data"===g?(w+="\n",w+=m):"id"===g?b=m:"event"===g?I=m:"retry"===g?(u=H(m,u),d=u):"heartbeatTimeout"===g&&(c=H(m,c),0!==T&&(i(T),T=r((function(){$()}),c)))}if(W===x){if(""!==w){h=b,""===I&&(I="message");var A=new R(I,{data:w.slice(1),lastEventId:b});if(e.dispatchEvent(A),"open"===I?Y(e,e.onopen,A):"message"===I?Y(e,e.onmessage,A):"error"===I&&Y(e,e.onerror,A),E===q)return}w="",I=""}W=l==="\r".charCodeAt(0)?U:x}else W===x&&(K=a,W=P),W===P?l===":".charCodeAt(0)&&(z=a+1,W=L):W===L&&(W=B)}}},Z=function(t){if(E===N||E===M){E=D,0!==T&&(i(T),T=0),T=r((function(){$()}),d),d=G(Math.min(16*u,2*d)),e.readyState=M;var n=new O("error",{error:t});e.dispatchEvent(n),Y(e,e.onerror,n),null!=t&&console.error(t)}},X=function(){E=q,null!=y&&(y.abort(),y=void 0),0!==T&&(i(T),T=0),e.readyState=q},$=function(){if(T=0,E===D){f=!1,p=0,T=r((function(){$()}),c),E=M,w="",I="",b=h,j="",K=0,z=0,W=x;var n=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var i=t.indexOf("?");n=-1===i?t:t.slice(0,i+1)+t.slice(i+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===l?"":e})),n+=(-1===t.indexOf("?")?"?":"&")+l+"="+encodeURIComponent(h)}var s=e.withCredentials,o={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(o[u]=a[u]);try{y=_.open(A,J,V,Z,n,s,o)}catch(e){throw X(),e}}else if(f||null==y){var d=Math.max((f||Date.now())+c-Date.now(),1);f=!1,T=r((function(){$()}),d)}else Z(new Error("No activity within "+c+" milliseconds. "+(E===M?"No response received.":p+" chars received.")+" Reconnecting.")),null!=y&&(y.abort(),y=void 0)};e.url=t,e.readyState=M,e.withCredentials=a,e.headers=g,e._close=X,$()}(this,e,t)}var Q=null!=h&&null!=d&&"body"in d.prototype;j.prototype=Object.create(w.prototype),j.prototype.CONNECTING=M,j.prototype.OPEN=N,j.prototype.CLOSED=q,j.prototype.close=function(){this._close()},j.CONNECTING=M,j.OPEN=N,j.CLOSED=q,j.prototype.withCredentials=void 0;var W,K=l;null==s||null!=l&&"withCredentials"in l.prototype||(K=j),W=function(e){e.EventSourcePolyfill=j,e.NativeEventSource=l,e.EventSource=K}(t),void 0!==W&&(e.exports=W)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:n:globalThis)}(ul,ul.exports);var cl=ul.exports,hl={exports:{}},dl=r(hl.exports=function(){var e=1e3,t=6e4,n=36e5,r="millisecond",i="second",s="minute",o="hour",a="day",l="week",u="month",c="quarter",h="year",d="date",f="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|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"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},A=function(e,t,n){var r=String(e);return!r||r.length>=t?e:""+Array(t+1-r.length).join(n)+e},_={s:A,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?"+":"-")+A(r,2,"0")+":"+A(i,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,u),s=n-i<0,o=t.clone().add(r+(s?-1:1),u);return+(-(r+(n-i)/(s?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:u,y:h,w:l,d:a,D:d,h:o,m:s,s:i,ms:r,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",y={};y[v]=m;var T="$isDayjsObject",S=function(e){return e instanceof b||!(!e||!e[T])},E=function e(t,n,r){var i;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();y[s]&&(i=s),n&&(y[s]=n,i=s);var o=t.split("-");if(!i&&o.length>1)return e(o[0])}else{var a=t.name;y[a]=t,i=a}return!r&&i&&(v=i),i||!r&&v},C=function(e,t){if(S(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new b(n)},w=_;w.l=E,w.i=S,w.w=function(e,t){return C(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var b=function(){function m(e){this.$L=E(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[T]=!0}var A=m.prototype;return A.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(w.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var r=t.match(p);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(t)}(e),this.init()},A.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()},A.$utils=function(){return w},A.isValid=function(){return!(this.$d.toString()===f)},A.isSame=function(e,t){var n=C(e);return this.startOf(t)<=n&&n<=this.endOf(t)},A.isAfter=function(e,t){return C(e)<this.startOf(t)},A.isBefore=function(e,t){return this.endOf(t)<C(e)},A.$g=function(e,t,n){return w.u(e)?this[t]:this.set(n,e)},A.unix=function(){return Math.floor(this.valueOf()/1e3)},A.valueOf=function(){return this.$d.getTime()},A.startOf=function(e,t){var n=this,r=!!w.u(t)||t,c=w.p(e),f=function(e,t){var i=w.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(a)},p=function(e,t){return w.w(n.toDate()[e].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,m=this.$M,A=this.$D,_="set"+(this.$u?"UTC":"");switch(c){case h:return r?f(1,0):f(31,11);case u:return r?f(1,m):f(0,m+1);case l:var v=this.$locale().weekStart||0,y=(g<v?g+7:g)-v;return f(r?A-y:A+(6-y),m);case a:case d:return p(_+"Hours",0);case o:return p(_+"Minutes",1);case s:return p(_+"Seconds",2);case i:return p(_+"Milliseconds",3);default:return this.clone()}},A.endOf=function(e){return this.startOf(e,!1)},A.$set=function(e,t){var n,l=w.p(e),c="set"+(this.$u?"UTC":""),f=(n={},n[a]=c+"Date",n[d]=c+"Date",n[u]=c+"Month",n[h]=c+"FullYear",n[o]=c+"Hours",n[s]=c+"Minutes",n[i]=c+"Seconds",n[r]=c+"Milliseconds",n)[l],p=l===a?this.$D+(t-this.$W):t;if(l===u||l===h){var g=this.clone().set(d,1);g.$d[f](p),g.init(),this.$d=g.set(d,Math.min(this.$D,g.daysInMonth())).$d}else f&&this.$d[f](p);return this.init(),this},A.set=function(e,t){return this.clone().$set(e,t)},A.get=function(e){return this[w.p(e)]()},A.add=function(r,c){var d,f=this;r=Number(r);var p=w.p(c),g=function(e){var t=C(f);return w.w(t.date(t.date()+Math.round(e*r)),f)};if(p===u)return this.set(u,this.$M+r);if(p===h)return this.set(h,this.$y+r);if(p===a)return g(1);if(p===l)return g(7);var m=(d={},d[s]=t,d[o]=n,d[i]=e,d)[p]||1,A=this.$d.getTime()+r*m;return w.w(A,this)},A.subtract=function(e,t){return this.add(-1*e,t)},A.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||f;var r=e||"YYYY-MM-DDTHH:mm:ssZ",i=w.z(this),s=this.$H,o=this.$m,a=this.$M,l=n.weekdays,u=n.months,c=n.meridiem,h=function(e,n,i,s){return e&&(e[n]||e(t,r))||i[n].slice(0,s)},d=function(e){return w.s(s%12||12,e,"0")},p=c||function(e,t,n){var r=e<12?"AM":"PM";return n?r.toLowerCase():r};return r.replace(g,(function(e,r){return r||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return w.s(t.$y,4,"0");case"M":return a+1;case"MM":return w.s(a+1,2,"0");case"MMM":return h(n.monthsShort,a,u,3);case"MMMM":return h(u,a);case"D":return t.$D;case"DD":return w.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return h(n.weekdaysMin,t.$W,l,2);case"ddd":return h(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return w.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return p(s,o,!0);case"A":return p(s,o,!1);case"m":return String(o);case"mm":return w.s(o,2,"0");case"s":return String(t.$s);case"ss":return w.s(t.$s,2,"0");case"SSS":return w.s(t.$ms,3,"0");case"Z":return i}return null}(e)||i.replace(":","")}))},A.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},A.diff=function(r,d,f){var p,g=this,m=w.p(d),A=C(r),_=(A.utcOffset()-this.utcOffset())*t,v=this-A,y=function(){return w.m(g,A)};switch(m){case h:p=y()/12;break;case u:p=y();break;case c:p=y()/3;break;case l:p=(v-_)/6048e5;break;case a:p=(v-_)/864e5;break;case o:p=v/n;break;case s:p=v/t;break;case i:p=v/e;break;default:p=v}return f?p:w.a(p)},A.daysInMonth=function(){return this.endOf(u).$D},A.$locale=function(){return y[this.$L]},A.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),r=E(e,t,!0);return r&&(n.$L=r),n},A.clone=function(){return w.w(this.$d,this)},A.toDate=function(){return new Date(this.valueOf())},A.toJSON=function(){return this.isValid()?this.toISOString():null},A.toISOString=function(){return this.$d.toISOString()},A.toString=function(){return this.$d.toUTCString()},m}(),I=b.prototype;return C.prototype=I,[["$ms",r],["$s",i],["$m",s],["$H",o],["$W",a],["$M",u],["$y",h],["$D",d]].forEach((function(e){I[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),C.extend=function(e,t){return e.$i||(e(t,b,C),e.$i=!0),C},C.locale=E,C.isDayjs=S,C.unix=function(e){return C(1e3*e)},C.en=y[v],C.Ls=y,C.p={},C}());const fl="0.2.2",pl="aks_agent_token";class gl{setTrack(e){this.track=e}constructor(e){this.baseUrl="",this.eventSource=null,this.retryCount=0,this.retryMap=new Map,this.token="",this.track=()=>{},this.id=e.id,this.getSystemToken=e.getSystemToken,this.resetSSE=null==e?void 0:e.resetSSE,this.retryCount=e.retryCount||0,this.baseUrl=e.baseUrl||""}validateToken(t,n){return e(this,void 0,void 0,(function*(){return fetch(`${this.baseUrl}/iam/token/validate?accountId=${t}`,{method:"GET",headers:{authentication:n}}).then((e=>e.json()))}))}initToken(){return e(this,void 0,void 0,(function*(){try{const e=yield this.getSystemToken();if(!e)return{code:sl.FAILED,data:null,message:"get system token failed"};const t=yield this.validateToken(this.id,e);return t.code===sl.SUCCESS?(this.token=e,sessionStorage.setItem(pl,e),this.executePeriodically(this.refreshToken.bind(this),12e5),{code:sl.SUCCESS,data:null,message:t.message}):{code:sl.FAILED,data:null,message:t.message}}catch(e){return{code:sl.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"}}}))}refreshToken(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/iam/oauth2/refresh`}).then((e=>{var t;e.token?(this.token=e.token,sessionStorage.setItem(pl,e.token),this.eventSource&&(null===(t=this.resetSSE)||void 0===t||t.call(this))):this.track("token.refresh.fail")}))}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/status/list`})}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/getAgentByUserId`})}))}getAgentSetting(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getAgentSetting`,data:t})}))}updateAgentHangup(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent/${t}`,method:"PUT"})}))}updateAgentTicket(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/voipPlatform/agent/ticket`,data:t})}))}sendSSEACK(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat_ack?agentId=${t}`,method:"POST"})}))}registerSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:n,onMessage:r}=t;let i=e=>{};const s=new Promise((e=>{i=e})),o=this.token;return this.eventSource=new cl.EventSourcePolyfill(`${this.baseUrl}/crm/v1/agent_command/regist_agent_event?agentId=${n}`,{headers:{Authentication:o,"Cache-Control":"no-cache",Connection:"keep-alive"},heartbeatTimeout:12e6}),this.eventSource.onmessage=r,this.eventSource.onopen=()=>e(this,void 0,void 0,(function*(){this.track("sse.open"),i(!0)})),this.eventSource.onerror=()=>e(this,void 0,void 0,(function*(){this.track("sse.error.error"),i(!1)})),s}))}closeClientSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=null)}closeSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:e,clearTicket:n}=t;if(this.eventSource)return this.request({url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_close?agentId=${e}&clearTicket=${n}`}).then((e=>(this.closeClientSSE(),e)))}))}sendHeartbeat(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat?agentId=${t}&version=${fl}`})}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){return this.request({method:"PUT",url:`${this.baseUrl}/voipPlatform/agent/agentStatusSwitch`,data:t})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){const{phone:e,line:n}=t;return this.request({url:`${this.baseUrl}/crm/v1/agentOutBoundCall/dialer/startCall/${e}/${n}`,method:"POST"})}))}saveAgentResponseTime(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/call_record/callRecordAgent`,data:t})}))}reportPDSTimeline(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/reportPDSTimeline`,method:"POST",data:t})}))}reportSdkTrace(t,n){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/reportSdkTrace`;let r="";try{r=this.getTokenWithFallback()}catch(e){r=""}try{if((null==n?void 0:n.useBeacon)&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){const n=new FormData;return n.append("timestamp",String(t.timestamp)),n.append("traceId",t.traceId),n.append("agentId",t.agentId),n.append("sdkVersion",t.sdkVersion),n.append("callId",t.callId),n.append("callRecordId",t.callRecordId),n.append("event",t.event),n.append("message",t.message),t.extra&&n.append("extra",JSON.stringify(t.extra)),r&&n.append("authentication",r),navigator.sendBeacon(e,n)}return(yield fetch(e,{method:"POST",keepalive:null==n?void 0:n.keepalive,headers:Object.assign({"Content-Type":"application/json"},r?{authentication:r}:{}),body:JSON.stringify(t)})).ok}catch(e){return!1}}))}getSdkTraceConfig(){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/getSdkTraceConfig`;try{const t=yield fetch(e,{method:"GET"});if(!t.ok)return null;const n=yield t.json();return{collect:Boolean(null==n?void 0:n.collect)}}catch(e){return null}}))}getCallTaskInfo(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getCallTaskName/${t.callTaskId}`})}))}getAfterCallProcessTime(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/predictCall/afterCallProcessTime/${t.callTaskId}`})}))}formatFormData(e){const t=new FormData;for(const n in e)e[n]&&t.append(n,e[n]);return t}agentAbnormalClose(e){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const t=this.formatFormData(e);return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_abnormal_close`,data:t},!0)}sendBeacon(e){if("function"==typeof navigator.sendBeacon&&e.url){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const{url:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["url"]),r=this.formatFormData(n),i=navigator.sendBeacon(t,r);if(!i){e.lastSendResult=i;const t=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");t.push(e),localStorage.setItem("aks_beacon_queue",JSON.stringify(t))}}}clearnSendBeaconQueue(){return e(this,void 0,void 0,(function*(){const e=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");if(e.length){if(!(yield this.waitToken())){if((yield this.initToken()).code!==sl.SUCCESS)return}for(let t=0;t<e.length-1;t++)this.sendBeacon(e[t])}}))}getTokenWithFallback(){if(this.token)return this.token;return sessionStorage.getItem(pl)||""}waitToken(e=3e3,t=200){return new Promise((n=>{const r=setInterval((()=>{((e-=t)<=0||this.token)&&(clearInterval(r),n(Boolean(this.token)))}),200)}))}request(t){return e(this,arguments,void 0,(function*(t,n=!1){var r;if(!this.retryMap.has(t.url)&&this.retryCount&&this.retryMap.set(t.url,this.retryCount),!this.token){if(!(yield this.waitToken())){const e=yield this.initToken();if(e.code!==sl.SUCCESS)return{code:e.code,message:e.message,data:null}}}const i={method:t.method||"GET",headers:Object.assign({"Content-Type":"application/json",authentication:this.token},t.headers)};n?(i.method=t.method,i.headers={authentication:this.token},i.body=t.data):"GET"!==(null===(r=i.method)||void 0===r?void 0:r.toLocaleUpperCase())&&(i.body=JSON.stringify(t.data));const s=t.url.replace(this.baseUrl,"").split("?")[0].replace(/\/\d+/g,"/{id}");return fetch(t.url,i).then((n=>e(this,void 0,void 0,(function*(){if(401===n.status){const e=this.retryMap.get(t.url);if(e){this.retryMap.set(t.url,e-1),this.track("api.retry",{extra:{api:s,remaining:e-1}});const n=yield this.initToken();return n.code===sl.SUCCESS?this.request(t):n}return this.retryCount&&this.retryMap.delete(t.url),this.track("api.unauthorized.warn",{extra:{api:s}}),{code:sl.UNAUTHORIZED,message:"Unauthorized",data:null}}return n.ok||this.track("api.fail",{extra:{api:s,httpStatus:n.status}}),n.json()})))).catch((e=>{try{this.track("api.fail",{message:String(e),extra:{api:s}})}catch(e){}throw e}))}))}executePeriodically(e,t){let n=Date.now()+t;const r=()=>{const i=Date.now();i>=n&&(e(),n+=t);const s=Math.max(0,n-i);setTimeout(r,s)};r()}static getInstance(e){return!gl.instance&&e&&(gl.instance=new gl(e)),gl.instance}}gl.instance=null;const ml=e=>{if("string"!=typeof e)return"";let t=e;return t=t.replace(/https?:\/\/[^\s]+/g,(e=>e.split("?")[0].replace(/\/\d+(?=\/|$)/g,"/{id}"))),t=t.replace(/\d{7,}/g,(e=>`${e.slice(0,3)}****${e.slice(-2)}`)),t.length>1024&&(t=t.slice(0,1024)),t},Al="aks_trace_queue";class _l{constructor(e,t){this.storage=e,this.opts=t}read(){try{const e=this.storage.getItem(Al);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return[]}}enqueue(e){try{const t=this.read();t.push(e);const n=t.length-this.opts.cap;n>0&&t.splice(0,n),this.storage.setItem(Al,JSON.stringify(t))}catch(e){}}drain(){try{const e=this.opts.now()-this.opts.ttlMs,t=this.read().filter((t=>t.timestamp>=e));return this.storage.removeItem(Al),t}catch(e){return[]}}}class vl{constructor(e){var t,n;this.enabled=!1,this.traceId="",this.agentId="",this.lastSent=new Map,this.bucket=20,this.bucketTs=0,this.version=e.version,this.now=null!==(t=e.now)&&void 0!==t?t:()=>Date.now(),this.genId=null!==(n=e.genId)&&void 0!==n?n:()=>Date.now().toString(36)+Math.random().toString(36).slice(2,10),this.report=e.report,this.queue=new _l(e.storage,{cap:200,ttlMs:864e5,now:this.now})}applyConfig(e){this.enabled=Boolean(e)}setAgentId(e){this.agentId=String(null!=e?e:"")}resetTraceId(){try{this.traceId=this.genId()}catch(e){}}track(e,t){var n,r,i;try{if(!this.enabled)return;const s=this.now();if(this.isDeduped(e,s))return;if(!this.takeToken(s))return;this.lastSent.set(e,s),this.traceId||(this.traceId=this.genId());const o=Object.assign({timestamp:s,traceId:this.traceId,agentId:this.agentId,sdkVersion:this.version,callId:null!==(n=null==t?void 0:t.callId)&&void 0!==n?n:"",callRecordId:null!==(r=null==t?void 0:t.callRecordId)&&void 0!==r?r:"",event:e,message:ml(null!==(i=null==t?void 0:t.message)&&void 0!==i?i:"")},(null==t?void 0:t.extra)?{extra:t.extra}:{});this.report(o).then((e=>{e||this.queue.enqueue(o)})).catch((()=>{try{this.queue.enqueue(o)}catch(e){}}))}catch(e){}}flush(){try{if(!this.enabled)return;const e=this.queue.drain(),t="undefined"==typeof fetch;for(const n of e)try{this.report(n,{keepalive:!0,useBeacon:t}).catch((()=>{}))}catch(e){}}catch(e){}}isDeduped(e,t){const n=this.lastSent.get(e);return void 0!==n&&t-n<5e3}takeToken(e){return e-this.bucketTs>=1e3&&(this.bucket=20,this.bucketTs=e),!(this.bucket<=0)&&(this.bucket-=1,!0)}}const yl="aks_trace_config";var Tl,Sl,El;!function(e){e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.HANGUP=4]="HANGUP"}(Tl||(Tl={})),function(e){e[e.ANSWER=1]="ANSWER",e[e.HANGUP=2]="HANGUP"}(Sl||(Sl={})),function(e){e[e.INCOMMING=1]="INCOMMING",e[e.ACW=2]="ACW"}(El||(El={}));const Cl=1e4;class wl{constructor(e){this.sip={},this.api={},this.isSipInit=!1,this.isInitSuccess=!1,this.agentInfo={},this.initEvent={},this.agentEvent={},this.agentWaitingTime=0,this.agentResponseTime=0,this.timer=null,this.callDetails={},this.baseUrl="",this.autoFinishACWTimer=null,this._acwAutoTriggered=!1,this.heartbeatTimer=null,this.heartbeatFailCount=0,this.isHeartbeatRunning=!1,this.baseUrl=(null==e?void 0:e.baseUrl)||"",this.api=gl.getInstance({id:e.id,getSystemToken:e.getSystemToken,retryCount:e.retryCount,baseUrl:this.baseUrl});try{const e=window.localStorage;this.tracker=new vl({report:(e,t)=>this.api.reportSdkTrace(e,t),storage:e,version:fl,genId:()=>t()}),this.tracker.applyConfig(!0===(e=>{try{const t=e.getItem(yl);return"true"===t||"false"!==t&&null}catch(e){return null}})(e)),this.api.setTrack(((e,t)=>this.tracker.track(e,t)))}catch(e){this.tracker={track:()=>{},flush:()=>{},applyConfig:()=>{},setAgentId:()=>{},resetTraceId:()=>{}}}this.sip=new ll({incomingCallCallback:this.incomingCall.bind(this),trackIncomingCallCallback:this.trackIncomingCall.bind(this),getMediaStream:null==e?void 0:e.getMediaStream,applyAnswer:this.answer.bind(this),track:(e,t)=>this.tracker.track(e,t)}),this.sip.attchSessionEvent("ended",this.sessionEnded.bind(this)),this.sip.attchSessionEvent("failed",this.sessionFailed.bind(this)),this.init().then((()=>{this.api.clearnSendBeaconQueue()})),"undefined"!=typeof window&&window.addEventListener("pagehide",(()=>this.tracker.flush()),{once:!0})}init(){return e(this,void 0,void 0,(function*(){this.tracker.resetTraceId();const e=yield this.api.getSdkTraceConfig();if(e){this.tracker.applyConfig(e.collect);try{((e,t)=>{try{e.setItem(yl,t?"true":"false")}catch(e){}})(window.localStorage,e.collect)}catch(e){}}const t=yield this.api.initToken();if(t.code!==sl.SUCCESS){this.tracker.track("init.fail",{message:t.message,extra:{stage:"initToken"}});const e=Object.assign(Object.assign({},t),{code:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const n=yield this.getAgentStatus();if(n.code!==ol.SUCCESS){n.code===ol.LOCKED?this.tracker.track("init.locked",{message:n.message}):this.tracker.track("init.fail",{message:n.message,extra:{stage:"getAgentStatus"}});const e=Object.assign(Object.assign({},n),{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const r={code:ol.SUCCESS,data:null,message:"success"};return this.tracker.track("init.success"),this.emitInitEvent("success",r),this.isInitSuccess=!0,r}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){const e=yield this.api.getAgentStatusList();return e.code===sl.SUCCESS?{code:ol.SUCCESS,data:e.data||[],message:e.message}:{code:ol.FAILED,data:null,message:e.message}}))}getTicket(){let e=window.sessionStorage.getItem("wiz-agent-ticket");return e||(e=t(),window.sessionStorage.setItem("wiz-agent-ticket",e)),e}getHostName(e){try{return new URL(e).hostname}catch(e){return""}}createOpensips(){return e(this,void 0,void 0,(function*(){const e=yield this.waitSIPRegistered(7e3);return e.code!==ol.SUCCESS?(e.code!==ol.MIC_PERMISSION_DENIED&&this.sip.stop(!0),{code:e.code,message:e.message}):{code:ol.SUCCESS,message:"success"}}))}closeSip(){return e(this,void 0,void 0,(function*(){return this.sip.stop(!0),Promise.resolve({code:sl.SUCCESS,message:"failed"})}))}waitSIPRegistered(){return e(this,arguments,void 0,(function*(e=7e3){return new Promise((t=>{let n=!1;const r=e=>{n||(n=!0,t(e))};this.sip.on("registered",(()=>{n||(this.tracker.track("sip.registered"),r({code:ol.SUCCESS,message:"SIP registration successed"}))})),this.sip.on("registrationFailed",(()=>r({code:ol.FAILED,message:"SIP registration failed"}))),setTimeout((()=>{n||(this.tracker.track("sip.registerTimeout.fail"),r({code:ol.FAILED,message:"SIP registration failed"}))}),e),this.sip.start().then((e=>{e||(this.tracker.track("sip.startFail"),r({code:ol.MIC_PERMISSION_DENIED,message:"Microphone permission denied. Please allow microphone access in your browser settings and try again."}))}))}))}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){var e;const t=yield this.api.getAgentInfo();if("code"in t&&t.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:t.message};if(!("data"in t)||!(null===(e=t.data)||void 0===e?void 0:e[0]))return{code:ol.FAILED,data:null,message:"Agent not found"};const n=t.data[0];this.agentInfo=n,this.tracker.setAgentId(n.id);const r=n.id;let i=n.ticket;const s=n.status,o=this.getTicket();if(i){if(s===Tl.OFFLINE){if((yield this.api.updateAgentTicket({agentId:r,ticket:"",type:Tl.OFFLINE})).code!==sl.SUCCESS)return{code:ol.FAILED,message:"Update Agent Ticket failed"};i="",n.ticket="",this.agentInfo.ticket=""}if(s===Tl.ONLINE&&i!==o)return{code:ol.LOCKED,data:n,message:"Agent ticket occupied, unable to perform agent online or offline."}}if(!this.isSipInit){const e=`sip:${n.number}@${this.getHostName(n.realm)}`;this.sip.init({wssuri:n.realm,password:n.password,uri:e}),this.isSipInit=!0}return{code:ol.SUCCESS,data:n,message:t.message}}))}getAgentStatus(){return e(this,void 0,void 0,(function*(){try{const e=yield Promise.allSettled([this.getAgentInfo(),this.api.getAgentSetting({key:"callCenter"})]),[n,r]=e.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value));if("agentWaitingTime"in r&&(this.agentWaitingTime=r.agentWaitingTime||0),"code"in n&&n.code!==ol.SUCCESS)return{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:n.message};if(!("data"in n)||!n.data)return{code:ol.FAILED,data:null,message:"Agent not found"};const i=n.data,s=i.status,o=i.id,a=i.groupId,l={code:ol.SUCCESS,data:{id:o,groupId:a,status:s,subStatus:i.statusName},message:"success"};if(this.agentInfo=i,s===Tl.OFFLINE)return l;if(s===Tl.ONLINE){if(n.code===ol.LOCKED)return{code:ol.LOCKED,data:null,message:n.message};this.tracker.track("agent.abnormalClose"),yield this.api.agentAbnormalClose({id:o,groupId:a,trace:t()});const e=yield this.api.switchAgentStatus({id:o,groupId:a,status:Tl.OFFLINE,subStatus:"offline"});return e.code!==sl.SUCCESS?{code:ol.FAILED,data:null,message:e.message}:(l.data.status=Tl.OFFLINE,l.data.subStatus="Offline",l)}return{code:ol.FAILED,data:null,message:"system error"}}catch(e){return{code:ol.FAILED,data:null,message:"system error"}}}))}onlineAgent(t){return e(this,void 0,void 0,(function*(){const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t});if(e.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.ONLINE,subStatus:t},message:"Agent is already online"};return this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",i),this.startHeartbeat(),i}if(e===Tl.OFFLINE){const{code:e,message:i}=yield this.createOpensips();if(e!==ol.SUCCESS)return{code:e===ol.MIC_PERMISSION_DENIED?ol.MIC_PERMISSION_DENIED:ol.FAILED,data:null,message:i};const s=this.getTicket(),o=yield Promise.allSettled([this.api.updateAgentTicket({agentId:n,ticket:s,type:Tl.ONLINE}),this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t})]),[a,l]=o.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value)),u=a.code===sl.SUCCESS&&l.code===sl.SUCCESS,c=(null==a?void 0:a.code)!==sl.SUCCESS&&(null==l?void 0:l.code)!==sl.SUCCESS;if(!u&&!c){const e=[this.closeSip()];let t="";a.code!==sl.SUCCESS&&(t=a.message,e.push(this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:"Offline"}))),l.code!==sl.SUCCESS&&(t=l.message,e.push(this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE})));try{yield Promise.all(e)}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${t} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:t}}if(c){try{yield this.closeSip()}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${a.message} & ${l.message} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:`${a.message} & ${l.message}`}}const h={code:e,data:{status:Tl.ONLINE,subStatus:t},message:i};return this.agentInfo.status=Tl.ONLINE,this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",h),this.startHeartbeat(),h}return{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}offlineAgent(t){return e(this,void 0,void 0,(function*(){this.stopHeartbeat();const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.OFFLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.agentInfo.statusName=t,this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),i}if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE}),yield this.closeSip();const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName=t,i}return this.tracker.track("agent.offline.fail",{message:"invalid status",extra:{reason:"invalid_status"}}),{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}startHeartbeat(){this.isHeartbeatRunning&&this.stopHeartbeat(),this.isHeartbeatRunning=!0,this.heartbeatFailCount=0,this.executeHeartbeat()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isHeartbeatRunning=!1,this.heartbeatFailCount=0}executeHeartbeat(){return e(this,void 0,void 0,(function*(){if(this.isHeartbeatRunning)try{const{id:e}=this.agentInfo;if(yield this.api.sendHeartbeat(e)){const e=this.heartbeatFailCount;this.heartbeatFailCount=0,e>0&&this.tracker.track("heartbeat.recover"),this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}else if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat failed, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"fail"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}catch(e){if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat exception, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"exception"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("status.switch.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Registration failed. Seat online and offline cannot be performed."};const e=yield this.getAgentInfo();if(e.code!==ol.SUCCESS)return{code:e.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:e.message};const{status:n,subStatus:r}=t;return this.tracker.track("status.switch",{extra:{from:this.agentInfo.status,to:n}}),n===Tl.ONLINE?this.onlineAgent(r):n===Tl.OFFLINE?this.offlineAgent(r):(this.tracker.track("status.switch.fail",{extra:{reason:"invalid"}}),{code:ol.FAILED,data:null,message:"system error"})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Outbound calls cannot be made."};const e=this.agentInfo.outboundLineId;if(!e)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_line"}}),Promise.resolve({code:ol.FAILED,data:null,message:"Agent has no outbound line"});this.sip.setCallType("outboundCall");const n=yield this.api.outboundCall({phone:t,line:e}).catch((e=>{throw this.sip.setCallType(""),e}));return n.code===sl.SUCCESS?(this.tracker.track("call.outbound",{extra:{line:e}}),{code:ol.SUCCESS,data:n.data,message:n.message||n.msg}):(this.sip.setCallType(""),this.tracker.track("call.outbound.fail",{message:n.message||n.msg,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:n.message||n.msg})}))}autoFinishACW(){var e,t;let n=Number(this.callDetails.afterCallProcessTime);this.tracker.track("acw.start",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{seconds:n}});const r=()=>{if(n<=0)return this._acwAutoTriggered=!0,void this.finshACW();n-=1,this.autoFinishACWTimer=setTimeout(r,1e3)};this.autoFinishACWTimer=setTimeout(r,1e3)}finshACW(){return e(this,void 0,void 0,(function*(){var e,t;const n=!this._acwAutoTriggered;this._acwAutoTriggered=!1,this.tracker.track("acw.finish",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{manual:n}}),this.autoFinishACWTimer&&(clearTimeout(this.autoFinishACWTimer),this.autoFinishACWTimer=null),this.api.reportPDSTimeline({callId:this.callDetails.callId,eventType:El.ACW});const{id:r,groupId:i}=this.agentInfo,s=yield this.api.switchAgentStatus({id:r,groupId:i,status:Tl.HANGUP});return{code:s.code===sl.SUCCESS?ol.SUCCESS:ol.FAILED,data:null,message:s.message}}))}sessionEnded(){return e(this,void 0,void 0,(function*(){this.autoFinishACW()}))}sessionFailed(){return e(this,void 0,void 0,(function*(){this.api.updateAgentHangup(this.agentInfo.id)}))}saveAgentResponseTime(e){this.api.saveAgentResponseTime({callId:this.callDetails.callId,agentId:this.agentInfo.id,agentResponseTime:this.agentResponseTime,agentGroupId:this.agentInfo.groupId,resultType:e}),this.timer&&(clearInterval(this.timer),this.agentResponseTime=0)}hangup(){var e,t;this.tracker.track("call.hangup",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.hangup()}timingResTime(){this.timer&&(clearInterval(this.timer),this.timer=null);let e=this.agentWaitingTime;this.agentResponseTime=0,this.timer=setInterval((()=>{if(e<=0)return clearInterval((null==this?void 0:this.timer)||0),this.timer=null,void this.ignore();e-=1,this.agentResponseTime+=1}),1e3)}trackIncomingCall(e){this.api.reportPDSTimeline({callId:e,eventType:El.INCOMMING,timestamp:(new Date).getTime()})}incomingCall(t){return e(this,void 0,void 0,(function*(){var e,n,r,i,s,o;try{const a=t.request,l=(null===(n=null===(e=a.headers["Call-Param"])||void 0===e?void 0:e[0])||void 0===n?void 0:n.raw)||"",u=l?atob(l):"",c=JSON.parse(u||"{}"),h=(null===(i=null===(r=a.headers["Call-ID"])||void 0===r?void 0:r[0])||void 0===i?void 0:i.raw)||null,d=(null===(o=null===(s=a.headers["Call-Record-Id"])||void 0===s?void 0:s[0])||void 0===o?void 0:o.raw)||null,f=Object.fromEntries(Object.entries(c).filter((([e])=>""!==e))),p=t.request.getHeader("Task-Name")||"",g=t.request.getHeader("After-Time")||"";let m=f.phone||f.Phone||f.PHONE||"";return m||(m=t.request.getHeader("Caller")||""),this.callDetails={callId:d||"",originCallId:h||"",callType:this.sip.getCallType()||"",taskName:p,afterCallProcessTime:g,phone:m,contactId:f.contactId||f.ContactId||f.CONTACT_ID||"",extraJson:f},"outboundCall"!==this.sip.getCallType()&&this.timingResTime(),Promise.resolve({code:ol.SUCCESS,data:this.callDetails,message:"success"})}catch(e){return this.tracker.track("call.incoming.fail",{message:String(e),extra:{errorName:null==e?void 0:e.name}}),Promise.resolve({code:ol.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"})}}))}answer(){var e,t;this.tracker.track("call.answer",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.answer(),this.saveAgentResponseTime(Sl.ANSWER)}ignore(){var e,t;this.tracker.track("call.ignore",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.ignore(),this.saveAgentResponseTime(Sl.HANGUP)}mute(){this.sip.mute()}unmute(){this.sip.unmute()}attachInitEvent(e,t){t&&"function"==typeof t&&(this.initEvent[e]||(this.initEvent[e]=[]),this.initEvent[e].push(t))}removeInitEvent(e,t){const n=this.initEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitInitEvent(e,t){(this.initEvent[e]||[]).forEach((e=>{e(t)}))}attachAgentEvent(e,t){t&&"function"==typeof t&&(this.agentEvent[e]||(this.agentEvent[e]=[]),this.agentEvent[e].push(t))}removeAgentEvent(e,t){const n=this.agentEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitAgentEvent(e,t){(this.agentEvent[e]||[]).forEach((e=>{e(t)}))}attachAnswerEvent(e){this.sip.attachAnswerEvent(e)}removeAnswerEvent(e){this.sip.removeAnswerEvent(e)}attachAutoAnswerEvent(e){this.sip.attachAutoAnswerEvent(e)}removeAutoAnswerEvent(e){this.sip.removeAutoAnswerEvent(e)}attachNewMessageEvent(e){this.sip.attachNewMessageEvent(e)}removeNewMessageEvent(e){this.sip.removeNewMessageEvent(e)}attchSessionEvent(e,t){this.sip.attchSessionEvent(e,t)}removeSessionEvent(e,t){this.sip.removeSessionEvent(e,t)}}export{wl as default};
@@ -3,4 +3,4 @@
3
3
  * eventsource.js
4
4
  * Available under MIT License (MIT)
5
5
  * https://github.com/Yaffle/EventSource/
6
- */!function(e,t){!function(n){var r=n.setTimeout,i=n.clearTimeout,s=n.XMLHttpRequest,o=n.XDomainRequest,a=n.ActiveXObject,l=n.EventSource,u=n.document,c=n.Promise,h=n.fetch,d=n.Response,f=n.TextDecoder,p=n.TextEncoder,g=n.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==g){var m=h;h=function(e,t){var n=t.signal;return m(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return n._reader=t,n._aborted&&n._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},g=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function A(){this.bitsNeeded=0,this.codePoint=0}A.prototype.decode=function(e){function t(e,t,n){if(1===n)return e>=128>>t&&e<<t<=2047;if(2===n)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===n)return e>=65536>>t&&e<<t<=1114111;throw new Error}function n(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var r=65533,i="",s=this.bitsNeeded,o=this.codePoint,a=0;a<e.length;a+=1){var l=e[a];0!==s&&(l<128||l>191||!t(o<<6|63&l,s-6,n(s,o)))&&(s=0,o=r,i+=String.fromCharCode(o)),0===s?(l>=0&&l<=127?(s=0,o=l):l>=192&&l<=223?(s=6,o=31&l):l>=224&&l<=239?(s=12,o=15&l):l>=240&&l<=247?(s=18,o=7&l):(s=0,o=r),0===s||t(o,s,n(s,o))||(s=0,o=r)):(s-=6,o=o<<6|63&l),0===s&&(o<=65535?i+=String.fromCharCode(o):(i+=String.fromCharCode(55296+(o-65535-1>>10)),i+=String.fromCharCode(56320+(o-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=o,i};null!=f&&null!=p&&function(){try{return"test"===(new f).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(f=A);var _=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=_,this.onload=_,this.onerror=_,this.onreadystatechange=_,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=_}function y(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function T(e){for(var t=Object.create(null),n=e.split("\r\n"),r=0;r<n.length;r+=1){var i=n[r].split(": "),s=i.shift(),o=i.join(": ");t[y(s)]=o}this._map=t}function S(){}function E(e){this._headers=e}function C(){}function b(){this._listeners=Object.create(null)}function w(e){r((function(){throw e}),0)}function I(e){this.type=e,this.target=void 0}function R(e,t){I.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function k(e,t){I.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function O(e,t){I.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var n=this,o=this._xhr,a=1,l=0;this._abort=function(e){0!==n._sendTimeout&&(i(n._sendTimeout),n._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,o.onload=_,o.onerror=_,o.onabort=_,o.onprogress=_,o.onreadystatechange=_,o.abort(),0!==l&&(i(l),l=0),e||(n.readyState=4,n.onabort(null),n.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",r=void 0;if("contentType"in o)e=200,t="OK",r=o.contentType;else try{e=o.status,t=o.statusText,r=o.getResponseHeader("Content-Type")}catch(n){e=0,t="",r=void 0}0!==e&&(a=2,n.readyState=2,n.status=e,n.statusText=t,n._contentType=r,n.onreadystatechange())}},c=function(){if(u(),2===a||3===a){a=3;var e="";try{e=o.responseText}catch(e){}n.readyState=3,n.responseText=e,n.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:_}),c(),1===a||2===a||3===a){if(a=4,0!==l&&(i(l),l=0),n.readyState=4,"load"===e)n.onload(t);else if("error"===e)n.onerror(t);else{if("abort"!==e)throw new TypeError;n.onabort(t)}n.onreadystatechange()}},d=function(){l=r((function(){d()}),500),3===o.readyState&&c()};"onload"in o&&(o.onload=function(e){h("load",e)}),"onerror"in o&&(o.onerror=function(e){h("error",e)}),"onabort"in o&&(o.onabort=function(e){h("abort",e)}),"onprogress"in o&&(o.onprogress=c),"onreadystatechange"in o&&(o.onreadystatechange=function(e){!function(e){null!=o&&(4===o.readyState?"onload"in o&&"onerror"in o&&"onabort"in o||h(""===o.responseText?"error":"load",e):3===o.readyState?"onprogress"in o||c():2===o.readyState&&u())}(e)}),!("contentType"in o)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),o.open(e,t,!0),"readyState"in o&&(l=r((function(){d()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var n=this._xhr;"setRequestHeader"in n&&n.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=r((function(){t._sendTimeout=0,t.send()}),4)}},T.prototype.get=function(e){return this._map[y(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),S.prototype.open=function(e,t,n,r,i,o,a){e.open("GET",i);var l=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(l);l+=t.length,n(t)},e.onerror=function(e){e.preventDefault(),r(new Error("NetworkError"))},e.onload=function(){r(null)},e.onabort=function(){r(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var n=e.status,r=e.statusText,i=e.getResponseHeader("Content-Type"),o=e.getAllResponseHeaders();t(n,r,i,new T(o))}},e.withCredentials=o,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},E.prototype.get=function(e){return this._headers.get(e)},C.prototype.open=function(e,t,n,r,i,s,o){var a=null,l=new g,u=l.signal,d=new f;return h(i,{headers:o,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new E(e.headers)),new c((function(e,t){var r=function(){a.read().then((function(t){if(t.done)e(void 0);else{var i=d.decode(t.value,{stream:!0});n(i),r()}})).catch((function(e){t(e)}))};r()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){r(e)})),{abort:function(){null!=a&&a.cancel(),l.abort()}}},b.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var n=t.length,r=0;r<n;r+=1){var i=t[r];try{"function"==typeof i.handleEvent?i.handleEvent(e):i.call(this,e)}catch(e){w(e)}}},b.prototype.addEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];null==r&&(r=[],n[e]=r);for(var i=!1,s=0;s<r.length;s+=1)r[s]===t&&(i=!0);i||r.push(t)},b.prototype.removeEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];if(null!=r){for(var i=[],s=0;s<r.length;s+=1)r[s]!==t&&i.push(r[s]);0===i.length?delete n[e]:n[e]=i}},R.prototype=Object.create(I.prototype),k.prototype=Object.create(I.prototype),O.prototype=Object.create(I.prototype);var D=-1,M=0,N=1,q=2,U=-1,x=0,P=1,L=2,B=3,F=/^text\/event\-stream(;.*)?$/i,H=function(e,t){var n=null==e?t:parseInt(e,10);return n!=n&&(n=t),G(n)},G=function(e){return Math.min(Math.max(e,1e3),18e6)},Y=function(e,t,n){try{"function"==typeof t&&t.call(e,n)}catch(e){w(e)}};function j(e,t){b.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,n){t=String(t);var a=Boolean(n.withCredentials),l=n.lastEventIdQueryParameterName||"lastEventId",u=G(1e3),c=H(n.heartbeatTimeout,45e3),h="",d=u,f=!1,p=0,g=n.headers||{},m=n.Transport,A=Q&&null==m?void 0:new v(null!=m?new m:null!=s&&"withCredentials"in s.prototype||null==o?new s:new o),_=null!=m&&"string"!=typeof m?new m:null==A?new C:new S,y=void 0,T=0,E=D,b="",w="",I="",j="",W=x,K=0,z=0,J=function(t,n,r,i){if(E===M)if(200===t&&null!=r&&F.test(r)){E=N,f=Date.now(),d=u,e.readyState=N;var s=new k("open",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onopen,s)}else{var o="";200!==t?(n&&(n=n.replace(/\s+/g," ")),o="EventSource's response has a status "+t+" "+n+" that is not 200. Aborting the connection."):o="EventSource's response has a Content-Type specifying an unsupported type: "+(null==r?"-":r.replace(/\s+/g," "))+". Aborting the connection.",X();s=new k("error",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onerror,s),console.error(o)}},V=function(t){if(E===N){for(var n=-1,s=0;s<t.length;s+=1){(l=t.charCodeAt(s))!=="\n".charCodeAt(0)&&l!=="\r".charCodeAt(0)||(n=s)}var o=(-1!==n?j:"")+t.slice(0,n+1);j=(-1===n?j:"")+t.slice(n+1),""!==t&&(f=Date.now(),p+=t.length);for(var a=0;a<o.length;a+=1){var l=o.charCodeAt(a);if(W===U&&l==="\n".charCodeAt(0))W=x;else if(W===U&&(W=x),l==="\r".charCodeAt(0)||l==="\n".charCodeAt(0)){if(W!==x){W===P&&(z=a+1);var g=o.slice(K,z-1),m=o.slice(z+(z<a&&o.charCodeAt(z)===" ".charCodeAt(0)?1:0),a);"data"===g?(b+="\n",b+=m):"id"===g?w=m:"event"===g?I=m:"retry"===g?(u=H(m,u),d=u):"heartbeatTimeout"===g&&(c=H(m,c),0!==T&&(i(T),T=r((function(){$()}),c)))}if(W===x){if(""!==b){h=w,""===I&&(I="message");var A=new R(I,{data:b.slice(1),lastEventId:w});if(e.dispatchEvent(A),"open"===I?Y(e,e.onopen,A):"message"===I?Y(e,e.onmessage,A):"error"===I&&Y(e,e.onerror,A),E===q)return}b="",I=""}W=l==="\r".charCodeAt(0)?U:x}else W===x&&(K=a,W=P),W===P?l===":".charCodeAt(0)&&(z=a+1,W=L):W===L&&(W=B)}}},Z=function(t){if(E===N||E===M){E=D,0!==T&&(i(T),T=0),T=r((function(){$()}),d),d=G(Math.min(16*u,2*d)),e.readyState=M;var n=new O("error",{error:t});e.dispatchEvent(n),Y(e,e.onerror,n),null!=t&&console.error(t)}},X=function(){E=q,null!=y&&(y.abort(),y=void 0),0!==T&&(i(T),T=0),e.readyState=q},$=function(){if(T=0,E===D){f=!1,p=0,T=r((function(){$()}),c),E=M,b="",I="",w=h,j="",K=0,z=0,W=x;var n=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var i=t.indexOf("?");n=-1===i?t:t.slice(0,i+1)+t.slice(i+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===l?"":e})),n+=(-1===t.indexOf("?")?"?":"&")+l+"="+encodeURIComponent(h)}var s=e.withCredentials,o={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(o[u]=a[u]);try{y=_.open(A,J,V,Z,n,s,o)}catch(e){throw X(),e}}else if(f||null==y){var d=Math.max((f||Date.now())+c-Date.now(),1);f=!1,T=r((function(){$()}),d)}else Z(new Error("No activity within "+c+" milliseconds. "+(E===M?"No response received.":p+" chars received.")+" Reconnecting.")),null!=y&&(y.abort(),y=void 0)};e.url=t,e.readyState=M,e.withCredentials=a,e.headers=g,e._close=X,$()}(this,e,t)}var Q=null!=h&&null!=d&&"body"in d.prototype;j.prototype=Object.create(b.prototype),j.prototype.CONNECTING=M,j.prototype.OPEN=N,j.prototype.CLOSED=q,j.prototype.close=function(){this._close()},j.CONNECTING=M,j.OPEN=N,j.CLOSED=q,j.prototype.withCredentials=void 0;var W,K=l;null==s||null!=l&&"withCredentials"in l.prototype||(K=j),W=function(e){e.EventSourcePolyfill=j,e.NativeEventSource=l,e.EventSource=K}(t),void 0!==W&&(e.exports=W)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:n:globalThis)}(ul,ul.exports);var cl=ul.exports,hl={exports:{}};!function(e){e.exports=function(){var e=1e3,t=6e4,n=36e5,r="millisecond",i="second",s="minute",o="hour",a="day",l="week",u="month",c="quarter",h="year",d="date",f="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|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"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},A=function(e,t,n){var r=String(e);return!r||r.length>=t?e:""+Array(t+1-r.length).join(n)+e},_={s:A,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?"+":"-")+A(r,2,"0")+":"+A(i,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,u),s=n-i<0,o=t.clone().add(r+(s?-1:1),u);return+(-(r+(n-i)/(s?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:u,y:h,w:l,d:a,D:d,h:o,m:s,s:i,ms:r,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",y={};y[v]=m;var T="$isDayjsObject",S=function(e){return e instanceof w||!(!e||!e[T])},E=function e(t,n,r){var i;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();y[s]&&(i=s),n&&(y[s]=n,i=s);var o=t.split("-");if(!i&&o.length>1)return e(o[0])}else{var a=t.name;y[a]=t,i=a}return!r&&i&&(v=i),i||!r&&v},C=function(e,t){if(S(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new w(n)},b=_;b.l=E,b.i=S,b.w=function(e,t){return C(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var w=function(){function m(e){this.$L=E(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[T]=!0}var A=m.prototype;return A.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(b.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var r=t.match(p);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(t)}(e),this.init()},A.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()},A.$utils=function(){return b},A.isValid=function(){return!(this.$d.toString()===f)},A.isSame=function(e,t){var n=C(e);return this.startOf(t)<=n&&n<=this.endOf(t)},A.isAfter=function(e,t){return C(e)<this.startOf(t)},A.isBefore=function(e,t){return this.endOf(t)<C(e)},A.$g=function(e,t,n){return b.u(e)?this[t]:this.set(n,e)},A.unix=function(){return Math.floor(this.valueOf()/1e3)},A.valueOf=function(){return this.$d.getTime()},A.startOf=function(e,t){var n=this,r=!!b.u(t)||t,c=b.p(e),f=function(e,t){var i=b.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(a)},p=function(e,t){return b.w(n.toDate()[e].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,m=this.$M,A=this.$D,_="set"+(this.$u?"UTC":"");switch(c){case h:return r?f(1,0):f(31,11);case u:return r?f(1,m):f(0,m+1);case l:var v=this.$locale().weekStart||0,y=(g<v?g+7:g)-v;return f(r?A-y:A+(6-y),m);case a:case d:return p(_+"Hours",0);case o:return p(_+"Minutes",1);case s:return p(_+"Seconds",2);case i:return p(_+"Milliseconds",3);default:return this.clone()}},A.endOf=function(e){return this.startOf(e,!1)},A.$set=function(e,t){var n,l=b.p(e),c="set"+(this.$u?"UTC":""),f=(n={},n[a]=c+"Date",n[d]=c+"Date",n[u]=c+"Month",n[h]=c+"FullYear",n[o]=c+"Hours",n[s]=c+"Minutes",n[i]=c+"Seconds",n[r]=c+"Milliseconds",n)[l],p=l===a?this.$D+(t-this.$W):t;if(l===u||l===h){var g=this.clone().set(d,1);g.$d[f](p),g.init(),this.$d=g.set(d,Math.min(this.$D,g.daysInMonth())).$d}else f&&this.$d[f](p);return this.init(),this},A.set=function(e,t){return this.clone().$set(e,t)},A.get=function(e){return this[b.p(e)]()},A.add=function(r,c){var d,f=this;r=Number(r);var p=b.p(c),g=function(e){var t=C(f);return b.w(t.date(t.date()+Math.round(e*r)),f)};if(p===u)return this.set(u,this.$M+r);if(p===h)return this.set(h,this.$y+r);if(p===a)return g(1);if(p===l)return g(7);var m=(d={},d[s]=t,d[o]=n,d[i]=e,d)[p]||1,A=this.$d.getTime()+r*m;return b.w(A,this)},A.subtract=function(e,t){return this.add(-1*e,t)},A.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||f;var r=e||"YYYY-MM-DDTHH:mm:ssZ",i=b.z(this),s=this.$H,o=this.$m,a=this.$M,l=n.weekdays,u=n.months,c=n.meridiem,h=function(e,n,i,s){return e&&(e[n]||e(t,r))||i[n].slice(0,s)},d=function(e){return b.s(s%12||12,e,"0")},p=c||function(e,t,n){var r=e<12?"AM":"PM";return n?r.toLowerCase():r};return r.replace(g,(function(e,r){return r||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return b.s(t.$y,4,"0");case"M":return a+1;case"MM":return b.s(a+1,2,"0");case"MMM":return h(n.monthsShort,a,u,3);case"MMMM":return h(u,a);case"D":return t.$D;case"DD":return b.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return h(n.weekdaysMin,t.$W,l,2);case"ddd":return h(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return b.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return p(s,o,!0);case"A":return p(s,o,!1);case"m":return String(o);case"mm":return b.s(o,2,"0");case"s":return String(t.$s);case"ss":return b.s(t.$s,2,"0");case"SSS":return b.s(t.$ms,3,"0");case"Z":return i}return null}(e)||i.replace(":","")}))},A.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},A.diff=function(r,d,f){var p,g=this,m=b.p(d),A=C(r),_=(A.utcOffset()-this.utcOffset())*t,v=this-A,y=function(){return b.m(g,A)};switch(m){case h:p=y()/12;break;case u:p=y();break;case c:p=y()/3;break;case l:p=(v-_)/6048e5;break;case a:p=(v-_)/864e5;break;case o:p=v/n;break;case s:p=v/t;break;case i:p=v/e;break;default:p=v}return f?p:b.a(p)},A.daysInMonth=function(){return this.endOf(u).$D},A.$locale=function(){return y[this.$L]},A.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),r=E(e,t,!0);return r&&(n.$L=r),n},A.clone=function(){return b.w(this.$d,this)},A.toDate=function(){return new Date(this.valueOf())},A.toJSON=function(){return this.isValid()?this.toISOString():null},A.toISOString=function(){return this.$d.toISOString()},A.toString=function(){return this.$d.toUTCString()},m}(),I=w.prototype;return C.prototype=I,[["$ms",r],["$s",i],["$m",s],["$H",o],["$W",a],["$M",u],["$y",h],["$D",d]].forEach((function(e){I[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),C.extend=function(e,t){return e.$i||(e(t,w,C),e.$i=!0),C},C.locale=E,C.isDayjs=S,C.unix=function(e){return C(1e3*e)},C.en=y[v],C.Ls=y,C.p={},C}()}(hl);var dl=r(hl.exports);const fl="0.2.1",pl="aks_agent_token";class gl{setTrack(e){this.track=e}constructor(e){this.baseUrl="",this.eventSource=null,this.retryCount=0,this.retryMap=new Map,this.token="",this.track=()=>{},this.id=e.id,this.getSystemToken=e.getSystemToken,this.resetSSE=null==e?void 0:e.resetSSE,this.retryCount=e.retryCount||0,this.baseUrl=e.baseUrl||""}validateToken(t,n){return e(this,void 0,void 0,(function*(){return fetch(`${this.baseUrl}/iam/token/validate?accountId=${t}`,{method:"GET",headers:{authentication:n}}).then((e=>e.json()))}))}initToken(){return e(this,void 0,void 0,(function*(){try{const e=yield this.getSystemToken();if(!e)return{code:sl.FAILED,data:null,message:"get system token failed"};const t=yield this.validateToken(this.id,e);return t.code===sl.SUCCESS?(this.token=e,sessionStorage.setItem(pl,e),this.executePeriodically(this.refreshToken.bind(this),12e5),{code:sl.SUCCESS,data:null,message:t.message}):{code:sl.FAILED,data:null,message:t.message}}catch(e){return{code:sl.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"}}}))}refreshToken(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/iam/oauth2/refresh`}).then((e=>{var t;e.token?(this.token=e.token,sessionStorage.setItem(pl,e.token),this.eventSource&&(null===(t=this.resetSSE)||void 0===t||t.call(this))):this.track("token.refresh.fail")}))}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/status/list`})}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/getAgentByUserId`})}))}getAgentSetting(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getAgentSetting`,data:t})}))}updateAgentHangup(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent/${t}`,method:"PUT"})}))}updateAgentTicket(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/voipPlatform/agent/ticket`,data:t})}))}sendSSEACK(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat_ack?agentId=${t}`,method:"POST"})}))}registerSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:n,onMessage:r}=t;let i=e=>{};const s=new Promise((e=>{i=e})),o=this.token;return this.eventSource=new cl.EventSourcePolyfill(`${this.baseUrl}/crm/v1/agent_command/regist_agent_event?agentId=${n}`,{headers:{Authentication:o,"Cache-Control":"no-cache",Connection:"keep-alive"},heartbeatTimeout:12e6}),this.eventSource.onmessage=r,this.eventSource.onopen=()=>e(this,void 0,void 0,(function*(){this.track("sse.open"),i(!0)})),this.eventSource.onerror=()=>e(this,void 0,void 0,(function*(){this.track("sse.error.error"),i(!1)})),s}))}closeClientSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=null)}closeSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:e,clearTicket:n}=t;if(this.eventSource)return this.request({url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_close?agentId=${e}&clearTicket=${n}`}).then((e=>(this.closeClientSSE(),e)))}))}sendHeartbeat(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat?agentId=${t}&version=${fl}`})}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){return this.request({method:"PUT",url:`${this.baseUrl}/voipPlatform/agent/agentStatusSwitch`,data:t})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){const{phone:e,line:n}=t;return this.request({url:`${this.baseUrl}/crm/v1/agentOutBoundCall/dialer/startCall/${e}/${n}`,method:"POST"})}))}saveAgentResponseTime(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/call_record/callRecordAgent`,data:t})}))}reportPDSTimeline(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/reportPDSTimeline`,method:"POST",data:t})}))}reportSdkTrace(t,n){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/reportSdkTrace`;let r="";try{r=this.getTokenWithFallback()}catch(e){r=""}try{if((null==n?void 0:n.useBeacon)&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){const n=new FormData;return n.append("timestamp",String(t.timestamp)),n.append("traceId",t.traceId),n.append("agentId",t.agentId),n.append("sdkVersion",t.sdkVersion),n.append("callId",t.callId),n.append("callRecordId",t.callRecordId),n.append("event",t.event),n.append("message",t.message),t.extra&&n.append("extra",JSON.stringify(t.extra)),r&&n.append("authentication",r),navigator.sendBeacon(e,n)}return(yield fetch(e,{method:"POST",keepalive:null==n?void 0:n.keepalive,headers:Object.assign({"Content-Type":"application/json"},r?{authentication:r}:{}),body:JSON.stringify(t)})).ok}catch(e){return!1}}))}getSdkTraceConfig(){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/getSdkTraceConfig`;try{const t=yield fetch(e,{method:"GET"});if(!t.ok)return null;const n=yield t.json();return{collect:Boolean(null==n?void 0:n.collect)}}catch(e){return null}}))}getCallTaskInfo(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getCallTaskName/${t.callTaskId}`})}))}getAfterCallProcessTime(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/predictCall/afterCallProcessTime/${t.callTaskId}`})}))}formatFormData(e){const t=new FormData;for(const n in e)e[n]&&t.append(n,e[n]);return t}agentAbnormalClose(e){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const t=this.formatFormData(e);return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_abnormal_close`,data:t},!0)}sendBeacon(e){if("function"==typeof navigator.sendBeacon&&e.url){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const{url:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["url"]),r=this.formatFormData(n),i=navigator.sendBeacon(t,r);if(!i){e.lastSendResult=i;const t=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");t.push(e),localStorage.setItem("aks_beacon_queue",JSON.stringify(t))}}}clearnSendBeaconQueue(){return e(this,void 0,void 0,(function*(){const e=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");if(e.length){if(!(yield this.waitToken())){if((yield this.initToken()).code!==sl.SUCCESS)return}for(let t=0;t<e.length-1;t++)this.sendBeacon(e[t])}}))}getTokenWithFallback(){if(this.token)return this.token;return sessionStorage.getItem(pl)||""}waitToken(e=3e3,t=200){return new Promise((n=>{const r=setInterval((()=>{((e-=t)<=0||this.token)&&(clearInterval(r),n(Boolean(this.token)))}),200)}))}request(t){return e(this,arguments,void 0,(function*(t,n=!1){var r;if(!this.retryMap.has(t.url)&&this.retryCount&&this.retryMap.set(t.url,this.retryCount),!this.token){if(!(yield this.waitToken())){const e=yield this.initToken();if(e.code!==sl.SUCCESS)return{code:e.code,message:e.message,data:null}}}const i={method:t.method||"GET",headers:Object.assign({"Content-Type":"application/json",authentication:this.token},t.headers)};n?(i.method=t.method,i.headers={authentication:this.token},i.body=t.data):"GET"!==(null===(r=i.method)||void 0===r?void 0:r.toLocaleUpperCase())&&(i.body=JSON.stringify(t.data));const s=t.url.replace(this.baseUrl,"").split("?")[0].replace(/\/\d+/g,"/{id}");return fetch(t.url,i).then((n=>e(this,void 0,void 0,(function*(){if(401===n.status){const e=this.retryMap.get(t.url);if(e){this.retryMap.set(t.url,e-1),this.track("api.retry",{extra:{api:s,remaining:e-1}});const n=yield this.initToken();return n.code===sl.SUCCESS?this.request(t):n}return this.retryCount&&this.retryMap.delete(t.url),this.track("api.unauthorized.warn",{extra:{api:s}}),{code:sl.UNAUTHORIZED,message:"Unauthorized",data:null}}return n.ok||this.track("api.fail",{extra:{api:s,httpStatus:n.status}}),n.json()})))).catch((e=>{try{this.track("api.fail",{message:String(e),extra:{api:s}})}catch(e){}throw e}))}))}executePeriodically(e,t){let n=Date.now()+t;const r=()=>{const i=Date.now();i>=n&&(e(),n+=t);const s=Math.max(0,n-i);setTimeout(r,s)};r()}static getInstance(e){return!gl.instance&&e&&(gl.instance=new gl(e)),gl.instance}}gl.instance=null;const ml=e=>{if("string"!=typeof e)return"";let t=e;return t=t.replace(/https?:\/\/[^\s]+/g,(e=>e.split("?")[0].replace(/\/\d+(?=\/|$)/g,"/{id}"))),t=t.replace(/\d{7,}/g,(e=>`${e.slice(0,3)}****${e.slice(-2)}`)),t.length>1024&&(t=t.slice(0,1024)),t},Al="aks_trace_queue";class _l{constructor(e,t){this.storage=e,this.opts=t}read(){try{const e=this.storage.getItem(Al);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return[]}}enqueue(e){try{const t=this.read();t.push(e);const n=t.length-this.opts.cap;n>0&&t.splice(0,n),this.storage.setItem(Al,JSON.stringify(t))}catch(e){}}drain(){try{const e=this.opts.now()-this.opts.ttlMs,t=this.read().filter((t=>t.timestamp>=e));return this.storage.removeItem(Al),t}catch(e){return[]}}}class vl{constructor(e){var t,n;this.enabled=!1,this.traceId="",this.agentId="",this.lastSent=new Map,this.bucket=20,this.bucketTs=0,this.version=e.version,this.now=null!==(t=e.now)&&void 0!==t?t:()=>Date.now(),this.genId=null!==(n=e.genId)&&void 0!==n?n:()=>Date.now().toString(36)+Math.random().toString(36).slice(2,10),this.report=e.report,this.queue=new _l(e.storage,{cap:200,ttlMs:864e5,now:this.now})}applyConfig(e){this.enabled=Boolean(e)}setAgentId(e){this.agentId=String(null!=e?e:"")}resetTraceId(){try{this.traceId=this.genId()}catch(e){}}track(e,t){var n,r,i;try{if(!this.enabled)return;const s=this.now();if(this.isDeduped(e,s))return;if(!this.takeToken(s))return;this.lastSent.set(e,s),this.traceId||(this.traceId=this.genId());const o=Object.assign({timestamp:s,traceId:this.traceId,agentId:this.agentId,sdkVersion:this.version,callId:null!==(n=null==t?void 0:t.callId)&&void 0!==n?n:"",callRecordId:null!==(r=null==t?void 0:t.callRecordId)&&void 0!==r?r:"",event:e,message:ml(null!==(i=null==t?void 0:t.message)&&void 0!==i?i:"")},(null==t?void 0:t.extra)?{extra:t.extra}:{});this.report(o).then((e=>{e||this.queue.enqueue(o)})).catch((()=>{try{this.queue.enqueue(o)}catch(e){}}))}catch(e){}}flush(){try{if(!this.enabled)return;const e=this.queue.drain(),t="undefined"==typeof fetch;for(const n of e)try{this.report(n,{keepalive:!0,useBeacon:t}).catch((()=>{}))}catch(e){}}catch(e){}}isDeduped(e,t){const n=this.lastSent.get(e);return void 0!==n&&t-n<5e3}takeToken(e){return e-this.bucketTs>=1e3&&(this.bucket=20,this.bucketTs=e),!(this.bucket<=0)&&(this.bucket-=1,!0)}}const yl="aks_trace_config";var Tl,Sl,El;!function(e){e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.HANGUP=4]="HANGUP"}(Tl||(Tl={})),function(e){e[e.ANSWER=1]="ANSWER",e[e.HANGUP=2]="HANGUP"}(Sl||(Sl={})),function(e){e[e.INCOMMING=1]="INCOMMING",e[e.ACW=2]="ACW"}(El||(El={}));const Cl=1e4;return class{constructor(e){this.sip={},this.api={},this.isSipInit=!1,this.isInitSuccess=!1,this.agentInfo={},this.initEvent={},this.agentEvent={},this.agentWaitingTime=0,this.agentResponseTime=0,this.timer=null,this.callDetails={},this.baseUrl="",this.autoFinishACWTimer=null,this._acwAutoTriggered=!1,this.heartbeatTimer=null,this.heartbeatFailCount=0,this.isHeartbeatRunning=!1,this.baseUrl=(null==e?void 0:e.baseUrl)||"",this.api=gl.getInstance({id:e.id,getSystemToken:e.getSystemToken,retryCount:e.retryCount,baseUrl:this.baseUrl});try{const e=window.localStorage;this.tracker=new vl({report:(e,t)=>this.api.reportSdkTrace(e,t),storage:e,version:fl,genId:()=>t()}),this.tracker.applyConfig(!0===(e=>{try{const t=e.getItem(yl);return"true"===t||"false"!==t&&null}catch(e){return null}})(e)),this.api.setTrack(((e,t)=>this.tracker.track(e,t)))}catch(e){this.tracker={track:()=>{},flush:()=>{},applyConfig:()=>{},setAgentId:()=>{},resetTraceId:()=>{}}}this.sip=new ll({incomingCallCallback:this.incomingCall.bind(this),trackIncomingCallCallback:this.trackIncomingCall.bind(this),getMediaStream:null==e?void 0:e.getMediaStream,applyAnswer:this.answer.bind(this),track:(e,t)=>this.tracker.track(e,t)}),this.sip.attchSessionEvent("ended",this.sessionEnded.bind(this)),this.sip.attchSessionEvent("failed",this.sessionFailed.bind(this)),this.init().then((()=>{this.api.clearnSendBeaconQueue()})),"undefined"!=typeof window&&window.addEventListener("pagehide",(()=>this.tracker.flush()),{once:!0})}init(){return e(this,void 0,void 0,(function*(){this.tracker.resetTraceId();const e=yield this.api.getSdkTraceConfig();if(e){this.tracker.applyConfig(e.collect);try{((e,t)=>{try{e.setItem(yl,t?"true":"false")}catch(e){}})(window.localStorage,e.collect)}catch(e){}}const t=yield this.api.initToken();if(t.code!==sl.SUCCESS){this.tracker.track("init.fail",{message:t.message,extra:{stage:"initToken"}});const e=Object.assign(Object.assign({},t),{code:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const n=yield this.getAgentStatus();if(n.code!==ol.SUCCESS){n.code===ol.LOCKED?this.tracker.track("init.locked",{message:n.message}):this.tracker.track("init.fail",{message:n.message,extra:{stage:"getAgentStatus"}});const e=Object.assign(Object.assign({},n),{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const r={code:ol.SUCCESS,data:null,message:"success"};return this.tracker.track("init.success"),this.emitInitEvent("success",r),this.isInitSuccess=!0,r}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){const e=yield this.api.getAgentStatusList();return e.code===sl.SUCCESS?{code:ol.SUCCESS,data:e.data||[],message:e.message}:{code:ol.FAILED,data:null,message:e.message}}))}getTicket(){let e=window.sessionStorage.getItem("wiz-agent-ticket");return e||(e=t(),window.sessionStorage.setItem("wiz-agent-ticket",e)),e}getHostName(e){try{return new URL(e).hostname}catch(e){return""}}createOpensips(){return e(this,void 0,void 0,(function*(){const e=yield this.waitSIPRegistered(7e3);return e.code!==ol.SUCCESS?(e.code!==ol.MIC_PERMISSION_DENIED&&this.sip.stop(!0),{code:e.code,message:e.message}):{code:ol.SUCCESS,message:"success"}}))}closeSip(){return e(this,void 0,void 0,(function*(){return this.sip.stop(!0),Promise.resolve({code:sl.SUCCESS,message:"failed"})}))}waitSIPRegistered(){return e(this,arguments,void 0,(function*(e=7e3){return new Promise((t=>{let n=!1;const r=e=>{n||(n=!0,t(e))};this.sip.on("registered",(()=>{n||(this.tracker.track("sip.registered"),r({code:ol.SUCCESS,message:"SIP registration successed"}))})),this.sip.on("registrationFailed",(()=>r({code:ol.FAILED,message:"SIP registration failed"}))),setTimeout((()=>{n||(this.tracker.track("sip.registerTimeout.fail"),r({code:ol.FAILED,message:"SIP registration failed"}))}),e),this.sip.start().then((e=>{e||(this.tracker.track("sip.startFail"),r({code:ol.MIC_PERMISSION_DENIED,message:"Microphone permission denied. Please allow microphone access in your browser settings and try again."}))}))}))}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){var e;const t=yield this.api.getAgentInfo();if("code"in t&&t.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:t.message};if(!("data"in t)||!(null===(e=t.data)||void 0===e?void 0:e[0]))return{code:ol.FAILED,data:null,message:"Agent not found"};const n=t.data[0];this.agentInfo=n,this.tracker.setAgentId(n.id);const r=n.id;let i=n.ticket;const s=n.status,o=this.getTicket();if(i){if(s===Tl.OFFLINE){if((yield this.api.updateAgentTicket({agentId:r,ticket:"",type:Tl.OFFLINE})).code!==sl.SUCCESS)return{code:ol.FAILED,message:"Update Agent Ticket failed"};i="",n.ticket="",this.agentInfo.ticket=""}if(s===Tl.ONLINE&&i!==o)return{code:ol.LOCKED,data:n,message:"Agent ticket occupied, unable to perform agent online or offline."}}if(!this.isSipInit){const e=`sip:${n.number}@${this.getHostName(n.realm)}`;this.sip.init({wssuri:n.realm,password:n.password,uri:e}),this.isSipInit=!0}return{code:ol.SUCCESS,data:n,message:t.message}}))}getAgentStatus(){return e(this,void 0,void 0,(function*(){try{const e=yield Promise.allSettled([this.getAgentInfo(),this.api.getAgentSetting({key:"callCenter"})]),[n,r]=e.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value));if("agentWaitingTime"in r&&(this.agentWaitingTime=r.agentWaitingTime||0),"code"in n&&n.code!==ol.SUCCESS)return{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:n.message};if(!("data"in n)||!n.data)return{code:ol.FAILED,data:null,message:"Agent not found"};const i=n.data,s=i.status,o=i.id,a=i.groupId,l={code:ol.SUCCESS,data:{id:o,groupId:a,status:s,subStatus:i.statusName},message:"success"};if(this.agentInfo=i,s===Tl.OFFLINE)return l;if(s===Tl.ONLINE){if(n.code===ol.LOCKED)return{code:ol.LOCKED,data:null,message:n.message};this.tracker.track("agent.abnormalClose"),yield this.api.agentAbnormalClose({id:o,groupId:a,trace:t()});const e=yield this.api.switchAgentStatus({id:o,groupId:a,status:Tl.OFFLINE,subStatus:"offline"});return e.code!==sl.SUCCESS?{code:ol.FAILED,data:null,message:e.message}:(l.data.status=Tl.OFFLINE,l.data.subStatus="Offline",l)}return{code:ol.FAILED,data:null,message:"system error"}}catch(e){return{code:ol.FAILED,data:null,message:"system error"}}}))}onlineAgent(t){return e(this,void 0,void 0,(function*(){const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t});if(e.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.ONLINE,subStatus:t},message:"Agent is already online"};return this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",i),this.startHeartbeat(),i}if(e===Tl.OFFLINE){const{code:e,message:i}=yield this.createOpensips();if(e!==ol.SUCCESS)return{code:e===ol.MIC_PERMISSION_DENIED?ol.MIC_PERMISSION_DENIED:ol.FAILED,data:null,message:i};const s=this.getTicket(),o=yield Promise.allSettled([this.api.updateAgentTicket({agentId:n,ticket:s,type:Tl.ONLINE}),this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t})]),[a,l]=o.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value)),u=a.code===sl.SUCCESS&&l.code===sl.SUCCESS,c=(null==a?void 0:a.code)!==sl.SUCCESS&&(null==l?void 0:l.code)!==sl.SUCCESS;if(!u&&!c){const e=[this.closeSip()];let t="";a.code!==sl.SUCCESS&&(t=a.message,e.push(this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:"Offline"}))),l.code!==sl.SUCCESS&&(t=l.message,e.push(this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE})));try{yield Promise.all(e)}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${t} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:t}}if(c){try{yield this.closeSip()}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${a.message} & ${l.message} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:`${a.message} & ${l.message}`}}const h={code:e,data:{status:Tl.ONLINE,subStatus:t},message:i};return this.agentInfo.status=Tl.ONLINE,this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",h),this.startHeartbeat(),h}return{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}offlineAgent(t){return e(this,void 0,void 0,(function*(){this.stopHeartbeat();const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.OFFLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.agentInfo.statusName=t,this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),i}if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE}),yield this.closeSip();const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName=t,i}return this.tracker.track("agent.offline.fail",{message:"invalid status",extra:{reason:"invalid_status"}}),{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}startHeartbeat(){this.isHeartbeatRunning&&this.stopHeartbeat(),this.isHeartbeatRunning=!0,this.heartbeatFailCount=0,this.executeHeartbeat()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isHeartbeatRunning=!1,this.heartbeatFailCount=0}executeHeartbeat(){return e(this,void 0,void 0,(function*(){if(this.isHeartbeatRunning)try{const{id:e}=this.agentInfo;if(yield this.api.sendHeartbeat(e)){const e=this.heartbeatFailCount;this.heartbeatFailCount=0,e>0&&this.tracker.track("heartbeat.recover"),this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}else if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat failed, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"fail"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}catch(e){if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat exception, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"exception"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("status.switch.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Registration failed. Seat online and offline cannot be performed."};const e=yield this.getAgentInfo();if(e.code!==ol.SUCCESS)return{code:e.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:e.message};const{status:n,subStatus:r}=t;return this.tracker.track("status.switch",{extra:{from:this.agentInfo.status,to:n}}),n===Tl.ONLINE?this.onlineAgent(r):n===Tl.OFFLINE?this.offlineAgent(r):(this.tracker.track("status.switch.fail",{extra:{reason:"invalid"}}),{code:ol.FAILED,data:null,message:"system error"})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Outbound calls cannot be made."};const e=this.agentInfo.outboundLineId;if(!e)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_line"}}),Promise.resolve({code:ol.FAILED,data:null,message:"Agent has no outbound line"});this.sip.setCallType("outboundCall");const n=yield this.api.outboundCall({phone:t,line:e}).catch((e=>{throw this.sip.setCallType(""),e}));return n.code===sl.SUCCESS?(this.tracker.track("call.outbound",{extra:{line:e}}),{code:ol.SUCCESS,data:n.data,message:n.message||n.msg}):(this.sip.setCallType(""),this.tracker.track("call.outbound.fail",{message:n.message||n.msg,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:n.message||n.msg})}))}autoFinishACW(){var e,t;let n=Number(this.callDetails.afterCallProcessTime);this.tracker.track("acw.start",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{seconds:n}});const r=()=>{if(n<=0)return this._acwAutoTriggered=!0,void this.finshACW();n-=1,this.autoFinishACWTimer=setTimeout(r,1e3)};this.autoFinishACWTimer=setTimeout(r,1e3)}finshACW(){return e(this,void 0,void 0,(function*(){var e,t;const n=!this._acwAutoTriggered;this._acwAutoTriggered=!1,this.tracker.track("acw.finish",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{manual:n}}),this.autoFinishACWTimer&&(clearTimeout(this.autoFinishACWTimer),this.autoFinishACWTimer=null),this.api.reportPDSTimeline({callId:this.callDetails.callId,eventType:El.ACW});const{id:r,groupId:i}=this.agentInfo,s=yield this.api.switchAgentStatus({id:r,groupId:i,status:Tl.HANGUP});return{code:s.code===sl.SUCCESS?ol.SUCCESS:ol.FAILED,data:null,message:s.message}}))}sessionEnded(){return e(this,void 0,void 0,(function*(){this.autoFinishACW()}))}sessionFailed(){return e(this,void 0,void 0,(function*(){this.api.updateAgentHangup(this.agentInfo.id)}))}saveAgentResponseTime(e){this.api.saveAgentResponseTime({callId:this.callDetails.callId,agentId:this.agentInfo.id,agentResponseTime:this.agentResponseTime,agentGroupId:this.agentInfo.groupId,resultType:e}),this.timer&&(clearInterval(this.timer),this.agentResponseTime=0)}hangup(){var e,t;this.tracker.track("call.hangup",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.hangup()}timingResTime(){this.timer&&(clearInterval(this.timer),this.timer=null);let e=this.agentWaitingTime;this.agentResponseTime=0,this.timer=setInterval((()=>{if(e<=0)return clearInterval((null==this?void 0:this.timer)||0),this.timer=null,void this.ignore();e-=1,this.agentResponseTime+=1}),1e3)}trackIncomingCall(e){this.api.reportPDSTimeline({callId:e,eventType:El.INCOMMING,timestamp:(new Date).getTime()})}incomingCall(t){return e(this,void 0,void 0,(function*(){var e,n,r,i,s,o;try{const a=t.request,l=(null===(n=null===(e=a.headers["Call-Param"])||void 0===e?void 0:e[0])||void 0===n?void 0:n.raw)||"",u=l?atob(l):"",c=JSON.parse(u||"{}"),h=(null===(i=null===(r=a.headers["Call-ID"])||void 0===r?void 0:r[0])||void 0===i?void 0:i.raw)||null,d=(null===(o=null===(s=a.headers["Call-Record-Id"])||void 0===s?void 0:s[0])||void 0===o?void 0:o.raw)||null,f=Object.fromEntries(Object.entries(c).filter((([e])=>""!==e))),p=t.request.getHeader("Task-Name")||"",g=t.request.getHeader("After-Time")||"";return this.callDetails={callId:d||"",originCallId:h||"",callType:this.sip.getCallType()||"",taskName:p,afterCallProcessTime:g,phone:f.phone||f.Phone||f.PHONE||"",contactId:f.contactId||f.ContactId||f.CONTACT_ID||"",extraJson:f},"outboundCall"!==this.sip.getCallType()&&this.timingResTime(),Promise.resolve({code:ol.SUCCESS,data:this.callDetails,message:"success"})}catch(e){return this.tracker.track("call.incoming.fail",{message:String(e),extra:{errorName:null==e?void 0:e.name}}),Promise.resolve({code:ol.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"})}}))}answer(){var e,t;this.tracker.track("call.answer",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.answer(),this.saveAgentResponseTime(Sl.ANSWER)}ignore(){var e,t;this.tracker.track("call.ignore",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.ignore(),this.saveAgentResponseTime(Sl.HANGUP)}mute(){this.sip.mute()}unmute(){this.sip.unmute()}attachInitEvent(e,t){t&&"function"==typeof t&&(this.initEvent[e]||(this.initEvent[e]=[]),this.initEvent[e].push(t))}removeInitEvent(e,t){const n=this.initEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitInitEvent(e,t){(this.initEvent[e]||[]).forEach((e=>{e(t)}))}attachAgentEvent(e,t){t&&"function"==typeof t&&(this.agentEvent[e]||(this.agentEvent[e]=[]),this.agentEvent[e].push(t))}removeAgentEvent(e,t){const n=this.agentEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitAgentEvent(e,t){(this.agentEvent[e]||[]).forEach((e=>{e(t)}))}attachAnswerEvent(e){this.sip.attachAnswerEvent(e)}removeAnswerEvent(e){this.sip.removeAnswerEvent(e)}attachAutoAnswerEvent(e){this.sip.attachAutoAnswerEvent(e)}removeAutoAnswerEvent(e){this.sip.removeAutoAnswerEvent(e)}attachNewMessageEvent(e){this.sip.attachNewMessageEvent(e)}removeNewMessageEvent(e){this.sip.removeNewMessageEvent(e)}attchSessionEvent(e,t){this.sip.attchSessionEvent(e,t)}removeSessionEvent(e,t){this.sip.removeSessionEvent(e,t)}}}));
6
+ */!function(e,t){!function(n){var r=n.setTimeout,i=n.clearTimeout,s=n.XMLHttpRequest,o=n.XDomainRequest,a=n.ActiveXObject,l=n.EventSource,u=n.document,c=n.Promise,h=n.fetch,d=n.Response,f=n.TextDecoder,p=n.TextEncoder,g=n.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==g){var m=h;h=function(e,t){var n=t.signal;return m(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return n._reader=t,n._aborted&&n._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},g=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function A(){this.bitsNeeded=0,this.codePoint=0}A.prototype.decode=function(e){function t(e,t,n){if(1===n)return e>=128>>t&&e<<t<=2047;if(2===n)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===n)return e>=65536>>t&&e<<t<=1114111;throw new Error}function n(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var r=65533,i="",s=this.bitsNeeded,o=this.codePoint,a=0;a<e.length;a+=1){var l=e[a];0!==s&&(l<128||l>191||!t(o<<6|63&l,s-6,n(s,o)))&&(s=0,o=r,i+=String.fromCharCode(o)),0===s?(l>=0&&l<=127?(s=0,o=l):l>=192&&l<=223?(s=6,o=31&l):l>=224&&l<=239?(s=12,o=15&l):l>=240&&l<=247?(s=18,o=7&l):(s=0,o=r),0===s||t(o,s,n(s,o))||(s=0,o=r)):(s-=6,o=o<<6|63&l),0===s&&(o<=65535?i+=String.fromCharCode(o):(i+=String.fromCharCode(55296+(o-65535-1>>10)),i+=String.fromCharCode(56320+(o-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=o,i};null!=f&&null!=p&&function(){try{return"test"===(new f).decode((new p).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(f=A);var _=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=_,this.onload=_,this.onerror=_,this.onreadystatechange=_,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=_}function y(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function T(e){for(var t=Object.create(null),n=e.split("\r\n"),r=0;r<n.length;r+=1){var i=n[r].split(": "),s=i.shift(),o=i.join(": ");t[y(s)]=o}this._map=t}function S(){}function E(e){this._headers=e}function C(){}function b(){this._listeners=Object.create(null)}function w(e){r((function(){throw e}),0)}function I(e){this.type=e,this.target=void 0}function R(e,t){I.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function k(e,t){I.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function O(e,t){I.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var n=this,o=this._xhr,a=1,l=0;this._abort=function(e){0!==n._sendTimeout&&(i(n._sendTimeout),n._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,o.onload=_,o.onerror=_,o.onabort=_,o.onprogress=_,o.onreadystatechange=_,o.abort(),0!==l&&(i(l),l=0),e||(n.readyState=4,n.onabort(null),n.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",r=void 0;if("contentType"in o)e=200,t="OK",r=o.contentType;else try{e=o.status,t=o.statusText,r=o.getResponseHeader("Content-Type")}catch(n){e=0,t="",r=void 0}0!==e&&(a=2,n.readyState=2,n.status=e,n.statusText=t,n._contentType=r,n.onreadystatechange())}},c=function(){if(u(),2===a||3===a){a=3;var e="";try{e=o.responseText}catch(e){}n.readyState=3,n.responseText=e,n.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:_}),c(),1===a||2===a||3===a){if(a=4,0!==l&&(i(l),l=0),n.readyState=4,"load"===e)n.onload(t);else if("error"===e)n.onerror(t);else{if("abort"!==e)throw new TypeError;n.onabort(t)}n.onreadystatechange()}},d=function(){l=r((function(){d()}),500),3===o.readyState&&c()};"onload"in o&&(o.onload=function(e){h("load",e)}),"onerror"in o&&(o.onerror=function(e){h("error",e)}),"onabort"in o&&(o.onabort=function(e){h("abort",e)}),"onprogress"in o&&(o.onprogress=c),"onreadystatechange"in o&&(o.onreadystatechange=function(e){!function(e){null!=o&&(4===o.readyState?"onload"in o&&"onerror"in o&&"onabort"in o||h(""===o.responseText?"error":"load",e):3===o.readyState?"onprogress"in o||c():2===o.readyState&&u())}(e)}),!("contentType"in o)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),o.open(e,t,!0),"readyState"in o&&(l=r((function(){d()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var n=this._xhr;"setRequestHeader"in n&&n.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=r((function(){t._sendTimeout=0,t.send()}),4)}},T.prototype.get=function(e){return this._map[y(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),S.prototype.open=function(e,t,n,r,i,o,a){e.open("GET",i);var l=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(l);l+=t.length,n(t)},e.onerror=function(e){e.preventDefault(),r(new Error("NetworkError"))},e.onload=function(){r(null)},e.onabort=function(){r(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var n=e.status,r=e.statusText,i=e.getResponseHeader("Content-Type"),o=e.getAllResponseHeaders();t(n,r,i,new T(o))}},e.withCredentials=o,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},E.prototype.get=function(e){return this._headers.get(e)},C.prototype.open=function(e,t,n,r,i,s,o){var a=null,l=new g,u=l.signal,d=new f;return h(i,{headers:o,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new E(e.headers)),new c((function(e,t){var r=function(){a.read().then((function(t){if(t.done)e(void 0);else{var i=d.decode(t.value,{stream:!0});n(i),r()}})).catch((function(e){t(e)}))};r()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){r(e)})),{abort:function(){null!=a&&a.cancel(),l.abort()}}},b.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var n=t.length,r=0;r<n;r+=1){var i=t[r];try{"function"==typeof i.handleEvent?i.handleEvent(e):i.call(this,e)}catch(e){w(e)}}},b.prototype.addEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];null==r&&(r=[],n[e]=r);for(var i=!1,s=0;s<r.length;s+=1)r[s]===t&&(i=!0);i||r.push(t)},b.prototype.removeEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];if(null!=r){for(var i=[],s=0;s<r.length;s+=1)r[s]!==t&&i.push(r[s]);0===i.length?delete n[e]:n[e]=i}},R.prototype=Object.create(I.prototype),k.prototype=Object.create(I.prototype),O.prototype=Object.create(I.prototype);var D=-1,M=0,N=1,q=2,U=-1,x=0,P=1,L=2,B=3,F=/^text\/event\-stream(;.*)?$/i,H=function(e,t){var n=null==e?t:parseInt(e,10);return n!=n&&(n=t),G(n)},G=function(e){return Math.min(Math.max(e,1e3),18e6)},Y=function(e,t,n){try{"function"==typeof t&&t.call(e,n)}catch(e){w(e)}};function j(e,t){b.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,n){t=String(t);var a=Boolean(n.withCredentials),l=n.lastEventIdQueryParameterName||"lastEventId",u=G(1e3),c=H(n.heartbeatTimeout,45e3),h="",d=u,f=!1,p=0,g=n.headers||{},m=n.Transport,A=Q&&null==m?void 0:new v(null!=m?new m:null!=s&&"withCredentials"in s.prototype||null==o?new s:new o),_=null!=m&&"string"!=typeof m?new m:null==A?new C:new S,y=void 0,T=0,E=D,b="",w="",I="",j="",W=x,K=0,z=0,J=function(t,n,r,i){if(E===M)if(200===t&&null!=r&&F.test(r)){E=N,f=Date.now(),d=u,e.readyState=N;var s=new k("open",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onopen,s)}else{var o="";200!==t?(n&&(n=n.replace(/\s+/g," ")),o="EventSource's response has a status "+t+" "+n+" that is not 200. Aborting the connection."):o="EventSource's response has a Content-Type specifying an unsupported type: "+(null==r?"-":r.replace(/\s+/g," "))+". Aborting the connection.",X();s=new k("error",{status:t,statusText:n,headers:i});e.dispatchEvent(s),Y(e,e.onerror,s),console.error(o)}},V=function(t){if(E===N){for(var n=-1,s=0;s<t.length;s+=1){(l=t.charCodeAt(s))!=="\n".charCodeAt(0)&&l!=="\r".charCodeAt(0)||(n=s)}var o=(-1!==n?j:"")+t.slice(0,n+1);j=(-1===n?j:"")+t.slice(n+1),""!==t&&(f=Date.now(),p+=t.length);for(var a=0;a<o.length;a+=1){var l=o.charCodeAt(a);if(W===U&&l==="\n".charCodeAt(0))W=x;else if(W===U&&(W=x),l==="\r".charCodeAt(0)||l==="\n".charCodeAt(0)){if(W!==x){W===P&&(z=a+1);var g=o.slice(K,z-1),m=o.slice(z+(z<a&&o.charCodeAt(z)===" ".charCodeAt(0)?1:0),a);"data"===g?(b+="\n",b+=m):"id"===g?w=m:"event"===g?I=m:"retry"===g?(u=H(m,u),d=u):"heartbeatTimeout"===g&&(c=H(m,c),0!==T&&(i(T),T=r((function(){$()}),c)))}if(W===x){if(""!==b){h=w,""===I&&(I="message");var A=new R(I,{data:b.slice(1),lastEventId:w});if(e.dispatchEvent(A),"open"===I?Y(e,e.onopen,A):"message"===I?Y(e,e.onmessage,A):"error"===I&&Y(e,e.onerror,A),E===q)return}b="",I=""}W=l==="\r".charCodeAt(0)?U:x}else W===x&&(K=a,W=P),W===P?l===":".charCodeAt(0)&&(z=a+1,W=L):W===L&&(W=B)}}},Z=function(t){if(E===N||E===M){E=D,0!==T&&(i(T),T=0),T=r((function(){$()}),d),d=G(Math.min(16*u,2*d)),e.readyState=M;var n=new O("error",{error:t});e.dispatchEvent(n),Y(e,e.onerror,n),null!=t&&console.error(t)}},X=function(){E=q,null!=y&&(y.abort(),y=void 0),0!==T&&(i(T),T=0),e.readyState=q},$=function(){if(T=0,E===D){f=!1,p=0,T=r((function(){$()}),c),E=M,b="",I="",w=h,j="",K=0,z=0,W=x;var n=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var i=t.indexOf("?");n=-1===i?t:t.slice(0,i+1)+t.slice(i+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===l?"":e})),n+=(-1===t.indexOf("?")?"?":"&")+l+"="+encodeURIComponent(h)}var s=e.withCredentials,o={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(o[u]=a[u]);try{y=_.open(A,J,V,Z,n,s,o)}catch(e){throw X(),e}}else if(f||null==y){var d=Math.max((f||Date.now())+c-Date.now(),1);f=!1,T=r((function(){$()}),d)}else Z(new Error("No activity within "+c+" milliseconds. "+(E===M?"No response received.":p+" chars received.")+" Reconnecting.")),null!=y&&(y.abort(),y=void 0)};e.url=t,e.readyState=M,e.withCredentials=a,e.headers=g,e._close=X,$()}(this,e,t)}var Q=null!=h&&null!=d&&"body"in d.prototype;j.prototype=Object.create(b.prototype),j.prototype.CONNECTING=M,j.prototype.OPEN=N,j.prototype.CLOSED=q,j.prototype.close=function(){this._close()},j.CONNECTING=M,j.OPEN=N,j.CLOSED=q,j.prototype.withCredentials=void 0;var W,K=l;null==s||null!=l&&"withCredentials"in l.prototype||(K=j),W=function(e){e.EventSourcePolyfill=j,e.NativeEventSource=l,e.EventSource=K}(t),void 0!==W&&(e.exports=W)}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:n:globalThis)}(ul,ul.exports);var cl=ul.exports,hl={exports:{}};!function(e){e.exports=function(){var e=1e3,t=6e4,n=36e5,r="millisecond",i="second",s="minute",o="hour",a="day",l="week",u="month",c="quarter",h="year",d="date",f="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|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"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},A=function(e,t,n){var r=String(e);return!r||r.length>=t?e:""+Array(t+1-r.length).join(n)+e},_={s:A,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?"+":"-")+A(r,2,"0")+":"+A(i,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,u),s=n-i<0,o=t.clone().add(r+(s?-1:1),u);return+(-(r+(n-i)/(s?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:u,y:h,w:l,d:a,D:d,h:o,m:s,s:i,ms:r,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",y={};y[v]=m;var T="$isDayjsObject",S=function(e){return e instanceof w||!(!e||!e[T])},E=function e(t,n,r){var i;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();y[s]&&(i=s),n&&(y[s]=n,i=s);var o=t.split("-");if(!i&&o.length>1)return e(o[0])}else{var a=t.name;y[a]=t,i=a}return!r&&i&&(v=i),i||!r&&v},C=function(e,t){if(S(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new w(n)},b=_;b.l=E,b.i=S,b.w=function(e,t){return C(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var w=function(){function m(e){this.$L=E(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[T]=!0}var A=m.prototype;return A.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(b.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var r=t.match(p);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(t)}(e),this.init()},A.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()},A.$utils=function(){return b},A.isValid=function(){return!(this.$d.toString()===f)},A.isSame=function(e,t){var n=C(e);return this.startOf(t)<=n&&n<=this.endOf(t)},A.isAfter=function(e,t){return C(e)<this.startOf(t)},A.isBefore=function(e,t){return this.endOf(t)<C(e)},A.$g=function(e,t,n){return b.u(e)?this[t]:this.set(n,e)},A.unix=function(){return Math.floor(this.valueOf()/1e3)},A.valueOf=function(){return this.$d.getTime()},A.startOf=function(e,t){var n=this,r=!!b.u(t)||t,c=b.p(e),f=function(e,t){var i=b.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(a)},p=function(e,t){return b.w(n.toDate()[e].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,m=this.$M,A=this.$D,_="set"+(this.$u?"UTC":"");switch(c){case h:return r?f(1,0):f(31,11);case u:return r?f(1,m):f(0,m+1);case l:var v=this.$locale().weekStart||0,y=(g<v?g+7:g)-v;return f(r?A-y:A+(6-y),m);case a:case d:return p(_+"Hours",0);case o:return p(_+"Minutes",1);case s:return p(_+"Seconds",2);case i:return p(_+"Milliseconds",3);default:return this.clone()}},A.endOf=function(e){return this.startOf(e,!1)},A.$set=function(e,t){var n,l=b.p(e),c="set"+(this.$u?"UTC":""),f=(n={},n[a]=c+"Date",n[d]=c+"Date",n[u]=c+"Month",n[h]=c+"FullYear",n[o]=c+"Hours",n[s]=c+"Minutes",n[i]=c+"Seconds",n[r]=c+"Milliseconds",n)[l],p=l===a?this.$D+(t-this.$W):t;if(l===u||l===h){var g=this.clone().set(d,1);g.$d[f](p),g.init(),this.$d=g.set(d,Math.min(this.$D,g.daysInMonth())).$d}else f&&this.$d[f](p);return this.init(),this},A.set=function(e,t){return this.clone().$set(e,t)},A.get=function(e){return this[b.p(e)]()},A.add=function(r,c){var d,f=this;r=Number(r);var p=b.p(c),g=function(e){var t=C(f);return b.w(t.date(t.date()+Math.round(e*r)),f)};if(p===u)return this.set(u,this.$M+r);if(p===h)return this.set(h,this.$y+r);if(p===a)return g(1);if(p===l)return g(7);var m=(d={},d[s]=t,d[o]=n,d[i]=e,d)[p]||1,A=this.$d.getTime()+r*m;return b.w(A,this)},A.subtract=function(e,t){return this.add(-1*e,t)},A.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||f;var r=e||"YYYY-MM-DDTHH:mm:ssZ",i=b.z(this),s=this.$H,o=this.$m,a=this.$M,l=n.weekdays,u=n.months,c=n.meridiem,h=function(e,n,i,s){return e&&(e[n]||e(t,r))||i[n].slice(0,s)},d=function(e){return b.s(s%12||12,e,"0")},p=c||function(e,t,n){var r=e<12?"AM":"PM";return n?r.toLowerCase():r};return r.replace(g,(function(e,r){return r||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return b.s(t.$y,4,"0");case"M":return a+1;case"MM":return b.s(a+1,2,"0");case"MMM":return h(n.monthsShort,a,u,3);case"MMMM":return h(u,a);case"D":return t.$D;case"DD":return b.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return h(n.weekdaysMin,t.$W,l,2);case"ddd":return h(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return b.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return p(s,o,!0);case"A":return p(s,o,!1);case"m":return String(o);case"mm":return b.s(o,2,"0");case"s":return String(t.$s);case"ss":return b.s(t.$s,2,"0");case"SSS":return b.s(t.$ms,3,"0");case"Z":return i}return null}(e)||i.replace(":","")}))},A.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},A.diff=function(r,d,f){var p,g=this,m=b.p(d),A=C(r),_=(A.utcOffset()-this.utcOffset())*t,v=this-A,y=function(){return b.m(g,A)};switch(m){case h:p=y()/12;break;case u:p=y();break;case c:p=y()/3;break;case l:p=(v-_)/6048e5;break;case a:p=(v-_)/864e5;break;case o:p=v/n;break;case s:p=v/t;break;case i:p=v/e;break;default:p=v}return f?p:b.a(p)},A.daysInMonth=function(){return this.endOf(u).$D},A.$locale=function(){return y[this.$L]},A.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),r=E(e,t,!0);return r&&(n.$L=r),n},A.clone=function(){return b.w(this.$d,this)},A.toDate=function(){return new Date(this.valueOf())},A.toJSON=function(){return this.isValid()?this.toISOString():null},A.toISOString=function(){return this.$d.toISOString()},A.toString=function(){return this.$d.toUTCString()},m}(),I=w.prototype;return C.prototype=I,[["$ms",r],["$s",i],["$m",s],["$H",o],["$W",a],["$M",u],["$y",h],["$D",d]].forEach((function(e){I[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),C.extend=function(e,t){return e.$i||(e(t,w,C),e.$i=!0),C},C.locale=E,C.isDayjs=S,C.unix=function(e){return C(1e3*e)},C.en=y[v],C.Ls=y,C.p={},C}()}(hl);var dl=r(hl.exports);const fl="0.2.2",pl="aks_agent_token";class gl{setTrack(e){this.track=e}constructor(e){this.baseUrl="",this.eventSource=null,this.retryCount=0,this.retryMap=new Map,this.token="",this.track=()=>{},this.id=e.id,this.getSystemToken=e.getSystemToken,this.resetSSE=null==e?void 0:e.resetSSE,this.retryCount=e.retryCount||0,this.baseUrl=e.baseUrl||""}validateToken(t,n){return e(this,void 0,void 0,(function*(){return fetch(`${this.baseUrl}/iam/token/validate?accountId=${t}`,{method:"GET",headers:{authentication:n}}).then((e=>e.json()))}))}initToken(){return e(this,void 0,void 0,(function*(){try{const e=yield this.getSystemToken();if(!e)return{code:sl.FAILED,data:null,message:"get system token failed"};const t=yield this.validateToken(this.id,e);return t.code===sl.SUCCESS?(this.token=e,sessionStorage.setItem(pl,e),this.executePeriodically(this.refreshToken.bind(this),12e5),{code:sl.SUCCESS,data:null,message:t.message}):{code:sl.FAILED,data:null,message:t.message}}catch(e){return{code:sl.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"}}}))}refreshToken(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/iam/oauth2/refresh`}).then((e=>{var t;e.token?(this.token=e.token,sessionStorage.setItem(pl,e.token),this.eventSource&&(null===(t=this.resetSSE)||void 0===t||t.call(this))):this.track("token.refresh.fail")}))}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/status/list`})}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/voipPlatform/agent/getAgentByUserId`})}))}getAgentSetting(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getAgentSetting`,data:t})}))}updateAgentHangup(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent/${t}`,method:"PUT"})}))}updateAgentTicket(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/voipPlatform/agent/ticket`,data:t})}))}sendSSEACK(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat_ack?agentId=${t}`,method:"POST"})}))}registerSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:n,onMessage:r}=t;let i=e=>{};const s=new Promise((e=>{i=e})),o=this.token;return this.eventSource=new cl.EventSourcePolyfill(`${this.baseUrl}/crm/v1/agent_command/regist_agent_event?agentId=${n}`,{headers:{Authentication:o,"Cache-Control":"no-cache",Connection:"keep-alive"},heartbeatTimeout:12e6}),this.eventSource.onmessage=r,this.eventSource.onopen=()=>e(this,void 0,void 0,(function*(){this.track("sse.open"),i(!0)})),this.eventSource.onerror=()=>e(this,void 0,void 0,(function*(){this.track("sse.error.error"),i(!1)})),s}))}closeClientSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=null)}closeSSE(t){return e(this,void 0,void 0,(function*(){const{agentId:e,clearTicket:n}=t;if(this.eventSource)return this.request({url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_close?agentId=${e}&clearTicket=${n}`}).then((e=>(this.closeClientSSE(),e)))}))}sendHeartbeat(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/heartbeat?agentId=${t}&version=${fl}`})}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){return this.request({method:"PUT",url:`${this.baseUrl}/voipPlatform/agent/agentStatusSwitch`,data:t})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){const{phone:e,line:n}=t;return this.request({url:`${this.baseUrl}/crm/v1/agentOutBoundCall/dialer/startCall/${e}/${n}`,method:"POST"})}))}saveAgentResponseTime(t){return e(this,void 0,void 0,(function*(){return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/call_record/callRecordAgent`,data:t})}))}reportPDSTimeline(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/agent_command/reportPDSTimeline`,method:"POST",data:t})}))}reportSdkTrace(t,n){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/reportSdkTrace`;let r="";try{r=this.getTokenWithFallback()}catch(e){r=""}try{if((null==n?void 0:n.useBeacon)&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon){const n=new FormData;return n.append("timestamp",String(t.timestamp)),n.append("traceId",t.traceId),n.append("agentId",t.agentId),n.append("sdkVersion",t.sdkVersion),n.append("callId",t.callId),n.append("callRecordId",t.callRecordId),n.append("event",t.event),n.append("message",t.message),t.extra&&n.append("extra",JSON.stringify(t.extra)),r&&n.append("authentication",r),navigator.sendBeacon(e,n)}return(yield fetch(e,{method:"POST",keepalive:null==n?void 0:n.keepalive,headers:Object.assign({"Content-Type":"application/json"},r?{authentication:r}:{}),body:JSON.stringify(t)})).ok}catch(e){return!1}}))}getSdkTraceConfig(){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/crm/v1/agent_command/getSdkTraceConfig`;try{const t=yield fetch(e,{method:"GET"});if(!t.ok)return null;const n=yield t.json();return{collect:Boolean(null==n?void 0:n.collect)}}catch(e){return null}}))}getCallTaskInfo(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/call_tasks/getCallTaskName/${t.callTaskId}`})}))}getAfterCallProcessTime(t){return e(this,void 0,void 0,(function*(){return this.request({url:`${this.baseUrl}/crm/v1/predictCall/afterCallProcessTime/${t.callTaskId}`})}))}formatFormData(e){const t=new FormData;for(const n in e)e[n]&&t.append(n,e[n]);return t}agentAbnormalClose(e){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const t=this.formatFormData(e);return this.request({method:"POST",url:`${this.baseUrl}/crm/v1/agent_command/regist_agent_abnormal_close`,data:t},!0)}sendBeacon(e){if("function"==typeof navigator.sendBeacon&&e.url){e.createTime||(e.createTime=dl().format("yyyy-MM-DD HH:mm:ss")),e.sendTime=dl().format("yyyy-MM-DD HH:mm:ss"),e.Authentication=this.getTokenWithFallback();const{url:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["url"]),r=this.formatFormData(n),i=navigator.sendBeacon(t,r);if(!i){e.lastSendResult=i;const t=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");t.push(e),localStorage.setItem("aks_beacon_queue",JSON.stringify(t))}}}clearnSendBeaconQueue(){return e(this,void 0,void 0,(function*(){const e=JSON.parse(localStorage.getItem("aks_beacon_queue")||"[]");if(e.length){if(!(yield this.waitToken())){if((yield this.initToken()).code!==sl.SUCCESS)return}for(let t=0;t<e.length-1;t++)this.sendBeacon(e[t])}}))}getTokenWithFallback(){if(this.token)return this.token;return sessionStorage.getItem(pl)||""}waitToken(e=3e3,t=200){return new Promise((n=>{const r=setInterval((()=>{((e-=t)<=0||this.token)&&(clearInterval(r),n(Boolean(this.token)))}),200)}))}request(t){return e(this,arguments,void 0,(function*(t,n=!1){var r;if(!this.retryMap.has(t.url)&&this.retryCount&&this.retryMap.set(t.url,this.retryCount),!this.token){if(!(yield this.waitToken())){const e=yield this.initToken();if(e.code!==sl.SUCCESS)return{code:e.code,message:e.message,data:null}}}const i={method:t.method||"GET",headers:Object.assign({"Content-Type":"application/json",authentication:this.token},t.headers)};n?(i.method=t.method,i.headers={authentication:this.token},i.body=t.data):"GET"!==(null===(r=i.method)||void 0===r?void 0:r.toLocaleUpperCase())&&(i.body=JSON.stringify(t.data));const s=t.url.replace(this.baseUrl,"").split("?")[0].replace(/\/\d+/g,"/{id}");return fetch(t.url,i).then((n=>e(this,void 0,void 0,(function*(){if(401===n.status){const e=this.retryMap.get(t.url);if(e){this.retryMap.set(t.url,e-1),this.track("api.retry",{extra:{api:s,remaining:e-1}});const n=yield this.initToken();return n.code===sl.SUCCESS?this.request(t):n}return this.retryCount&&this.retryMap.delete(t.url),this.track("api.unauthorized.warn",{extra:{api:s}}),{code:sl.UNAUTHORIZED,message:"Unauthorized",data:null}}return n.ok||this.track("api.fail",{extra:{api:s,httpStatus:n.status}}),n.json()})))).catch((e=>{try{this.track("api.fail",{message:String(e),extra:{api:s}})}catch(e){}throw e}))}))}executePeriodically(e,t){let n=Date.now()+t;const r=()=>{const i=Date.now();i>=n&&(e(),n+=t);const s=Math.max(0,n-i);setTimeout(r,s)};r()}static getInstance(e){return!gl.instance&&e&&(gl.instance=new gl(e)),gl.instance}}gl.instance=null;const ml=e=>{if("string"!=typeof e)return"";let t=e;return t=t.replace(/https?:\/\/[^\s]+/g,(e=>e.split("?")[0].replace(/\/\d+(?=\/|$)/g,"/{id}"))),t=t.replace(/\d{7,}/g,(e=>`${e.slice(0,3)}****${e.slice(-2)}`)),t.length>1024&&(t=t.slice(0,1024)),t},Al="aks_trace_queue";class _l{constructor(e,t){this.storage=e,this.opts=t}read(){try{const e=this.storage.getItem(Al);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return[]}}enqueue(e){try{const t=this.read();t.push(e);const n=t.length-this.opts.cap;n>0&&t.splice(0,n),this.storage.setItem(Al,JSON.stringify(t))}catch(e){}}drain(){try{const e=this.opts.now()-this.opts.ttlMs,t=this.read().filter((t=>t.timestamp>=e));return this.storage.removeItem(Al),t}catch(e){return[]}}}class vl{constructor(e){var t,n;this.enabled=!1,this.traceId="",this.agentId="",this.lastSent=new Map,this.bucket=20,this.bucketTs=0,this.version=e.version,this.now=null!==(t=e.now)&&void 0!==t?t:()=>Date.now(),this.genId=null!==(n=e.genId)&&void 0!==n?n:()=>Date.now().toString(36)+Math.random().toString(36).slice(2,10),this.report=e.report,this.queue=new _l(e.storage,{cap:200,ttlMs:864e5,now:this.now})}applyConfig(e){this.enabled=Boolean(e)}setAgentId(e){this.agentId=String(null!=e?e:"")}resetTraceId(){try{this.traceId=this.genId()}catch(e){}}track(e,t){var n,r,i;try{if(!this.enabled)return;const s=this.now();if(this.isDeduped(e,s))return;if(!this.takeToken(s))return;this.lastSent.set(e,s),this.traceId||(this.traceId=this.genId());const o=Object.assign({timestamp:s,traceId:this.traceId,agentId:this.agentId,sdkVersion:this.version,callId:null!==(n=null==t?void 0:t.callId)&&void 0!==n?n:"",callRecordId:null!==(r=null==t?void 0:t.callRecordId)&&void 0!==r?r:"",event:e,message:ml(null!==(i=null==t?void 0:t.message)&&void 0!==i?i:"")},(null==t?void 0:t.extra)?{extra:t.extra}:{});this.report(o).then((e=>{e||this.queue.enqueue(o)})).catch((()=>{try{this.queue.enqueue(o)}catch(e){}}))}catch(e){}}flush(){try{if(!this.enabled)return;const e=this.queue.drain(),t="undefined"==typeof fetch;for(const n of e)try{this.report(n,{keepalive:!0,useBeacon:t}).catch((()=>{}))}catch(e){}}catch(e){}}isDeduped(e,t){const n=this.lastSent.get(e);return void 0!==n&&t-n<5e3}takeToken(e){return e-this.bucketTs>=1e3&&(this.bucket=20,this.bucketTs=e),!(this.bucket<=0)&&(this.bucket-=1,!0)}}const yl="aks_trace_config";var Tl,Sl,El;!function(e){e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.HANGUP=4]="HANGUP"}(Tl||(Tl={})),function(e){e[e.ANSWER=1]="ANSWER",e[e.HANGUP=2]="HANGUP"}(Sl||(Sl={})),function(e){e[e.INCOMMING=1]="INCOMMING",e[e.ACW=2]="ACW"}(El||(El={}));const Cl=1e4;return class{constructor(e){this.sip={},this.api={},this.isSipInit=!1,this.isInitSuccess=!1,this.agentInfo={},this.initEvent={},this.agentEvent={},this.agentWaitingTime=0,this.agentResponseTime=0,this.timer=null,this.callDetails={},this.baseUrl="",this.autoFinishACWTimer=null,this._acwAutoTriggered=!1,this.heartbeatTimer=null,this.heartbeatFailCount=0,this.isHeartbeatRunning=!1,this.baseUrl=(null==e?void 0:e.baseUrl)||"",this.api=gl.getInstance({id:e.id,getSystemToken:e.getSystemToken,retryCount:e.retryCount,baseUrl:this.baseUrl});try{const e=window.localStorage;this.tracker=new vl({report:(e,t)=>this.api.reportSdkTrace(e,t),storage:e,version:fl,genId:()=>t()}),this.tracker.applyConfig(!0===(e=>{try{const t=e.getItem(yl);return"true"===t||"false"!==t&&null}catch(e){return null}})(e)),this.api.setTrack(((e,t)=>this.tracker.track(e,t)))}catch(e){this.tracker={track:()=>{},flush:()=>{},applyConfig:()=>{},setAgentId:()=>{},resetTraceId:()=>{}}}this.sip=new ll({incomingCallCallback:this.incomingCall.bind(this),trackIncomingCallCallback:this.trackIncomingCall.bind(this),getMediaStream:null==e?void 0:e.getMediaStream,applyAnswer:this.answer.bind(this),track:(e,t)=>this.tracker.track(e,t)}),this.sip.attchSessionEvent("ended",this.sessionEnded.bind(this)),this.sip.attchSessionEvent("failed",this.sessionFailed.bind(this)),this.init().then((()=>{this.api.clearnSendBeaconQueue()})),"undefined"!=typeof window&&window.addEventListener("pagehide",(()=>this.tracker.flush()),{once:!0})}init(){return e(this,void 0,void 0,(function*(){this.tracker.resetTraceId();const e=yield this.api.getSdkTraceConfig();if(e){this.tracker.applyConfig(e.collect);try{((e,t)=>{try{e.setItem(yl,t?"true":"false")}catch(e){}})(window.localStorage,e.collect)}catch(e){}}const t=yield this.api.initToken();if(t.code!==sl.SUCCESS){this.tracker.track("init.fail",{message:t.message,extra:{stage:"initToken"}});const e=Object.assign(Object.assign({},t),{code:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const n=yield this.getAgentStatus();if(n.code!==ol.SUCCESS){n.code===ol.LOCKED?this.tracker.track("init.locked",{message:n.message}):this.tracker.track("init.fail",{message:n.message,extra:{stage:"getAgentStatus"}});const e=Object.assign(Object.assign({},n),{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED});return this.emitInitEvent("failed",e),this.isInitSuccess=!1,e}const r={code:ol.SUCCESS,data:null,message:"success"};return this.tracker.track("init.success"),this.emitInitEvent("success",r),this.isInitSuccess=!0,r}))}getAgentStatusList(){return e(this,void 0,void 0,(function*(){const e=yield this.api.getAgentStatusList();return e.code===sl.SUCCESS?{code:ol.SUCCESS,data:e.data||[],message:e.message}:{code:ol.FAILED,data:null,message:e.message}}))}getTicket(){let e=window.sessionStorage.getItem("wiz-agent-ticket");return e||(e=t(),window.sessionStorage.setItem("wiz-agent-ticket",e)),e}getHostName(e){try{return new URL(e).hostname}catch(e){return""}}createOpensips(){return e(this,void 0,void 0,(function*(){const e=yield this.waitSIPRegistered(7e3);return e.code!==ol.SUCCESS?(e.code!==ol.MIC_PERMISSION_DENIED&&this.sip.stop(!0),{code:e.code,message:e.message}):{code:ol.SUCCESS,message:"success"}}))}closeSip(){return e(this,void 0,void 0,(function*(){return this.sip.stop(!0),Promise.resolve({code:sl.SUCCESS,message:"failed"})}))}waitSIPRegistered(){return e(this,arguments,void 0,(function*(e=7e3){return new Promise((t=>{let n=!1;const r=e=>{n||(n=!0,t(e))};this.sip.on("registered",(()=>{n||(this.tracker.track("sip.registered"),r({code:ol.SUCCESS,message:"SIP registration successed"}))})),this.sip.on("registrationFailed",(()=>r({code:ol.FAILED,message:"SIP registration failed"}))),setTimeout((()=>{n||(this.tracker.track("sip.registerTimeout.fail"),r({code:ol.FAILED,message:"SIP registration failed"}))}),e),this.sip.start().then((e=>{e||(this.tracker.track("sip.startFail"),r({code:ol.MIC_PERMISSION_DENIED,message:"Microphone permission denied. Please allow microphone access in your browser settings and try again."}))}))}))}))}getAgentInfo(){return e(this,void 0,void 0,(function*(){var e;const t=yield this.api.getAgentInfo();if("code"in t&&t.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:t.message};if(!("data"in t)||!(null===(e=t.data)||void 0===e?void 0:e[0]))return{code:ol.FAILED,data:null,message:"Agent not found"};const n=t.data[0];this.agentInfo=n,this.tracker.setAgentId(n.id);const r=n.id;let i=n.ticket;const s=n.status,o=this.getTicket();if(i){if(s===Tl.OFFLINE){if((yield this.api.updateAgentTicket({agentId:r,ticket:"",type:Tl.OFFLINE})).code!==sl.SUCCESS)return{code:ol.FAILED,message:"Update Agent Ticket failed"};i="",n.ticket="",this.agentInfo.ticket=""}if(s===Tl.ONLINE&&i!==o)return{code:ol.LOCKED,data:n,message:"Agent ticket occupied, unable to perform agent online or offline."}}if(!this.isSipInit){const e=`sip:${n.number}@${this.getHostName(n.realm)}`;this.sip.init({wssuri:n.realm,password:n.password,uri:e}),this.isSipInit=!0}return{code:ol.SUCCESS,data:n,message:t.message}}))}getAgentStatus(){return e(this,void 0,void 0,(function*(){try{const e=yield Promise.allSettled([this.getAgentInfo(),this.api.getAgentSetting({key:"callCenter"})]),[n,r]=e.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value));if("agentWaitingTime"in r&&(this.agentWaitingTime=r.agentWaitingTime||0),"code"in n&&n.code!==ol.SUCCESS)return{code:n.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:n.message};if(!("data"in n)||!n.data)return{code:ol.FAILED,data:null,message:"Agent not found"};const i=n.data,s=i.status,o=i.id,a=i.groupId,l={code:ol.SUCCESS,data:{id:o,groupId:a,status:s,subStatus:i.statusName},message:"success"};if(this.agentInfo=i,s===Tl.OFFLINE)return l;if(s===Tl.ONLINE){if(n.code===ol.LOCKED)return{code:ol.LOCKED,data:null,message:n.message};this.tracker.track("agent.abnormalClose"),yield this.api.agentAbnormalClose({id:o,groupId:a,trace:t()});const e=yield this.api.switchAgentStatus({id:o,groupId:a,status:Tl.OFFLINE,subStatus:"offline"});return e.code!==sl.SUCCESS?{code:ol.FAILED,data:null,message:e.message}:(l.data.status=Tl.OFFLINE,l.data.subStatus="Offline",l)}return{code:ol.FAILED,data:null,message:"system error"}}catch(e){return{code:ol.FAILED,data:null,message:"system error"}}}))}onlineAgent(t){return e(this,void 0,void 0,(function*(){const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t});if(e.code!==sl.SUCCESS)return{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.ONLINE,subStatus:t},message:"Agent is already online"};return this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",i),this.startHeartbeat(),i}if(e===Tl.OFFLINE){const{code:e,message:i}=yield this.createOpensips();if(e!==ol.SUCCESS)return{code:e===ol.MIC_PERMISSION_DENIED?ol.MIC_PERMISSION_DENIED:ol.FAILED,data:null,message:i};const s=this.getTicket(),o=yield Promise.allSettled([this.api.updateAgentTicket({agentId:n,ticket:s,type:Tl.ONLINE}),this.api.switchAgentStatus({id:n,groupId:r,status:Tl.ONLINE,subStatus:t})]),[a,l]=o.map((e=>"fulfilled"!==e.status?{code:sl.FAILED,data:null,message:"system error"}:e.value)),u=a.code===sl.SUCCESS&&l.code===sl.SUCCESS,c=(null==a?void 0:a.code)!==sl.SUCCESS&&(null==l?void 0:l.code)!==sl.SUCCESS;if(!u&&!c){const e=[this.closeSip()];let t="";a.code!==sl.SUCCESS&&(t=a.message,e.push(this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:"Offline"}))),l.code!==sl.SUCCESS&&(t=l.message,e.push(this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE})));try{yield Promise.all(e)}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${t} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:t}}if(c){try{yield this.closeSip()}catch(e){return this.tracker.track("agent.online.fail",{message:String(e),extra:{stage:"rollback"}}),{code:ol.FAILED,data:null,message:`${a.message} & ${l.message} & Operation failed, and rollback was unsuccessful.`}}return{code:ol.FAILED,data:null,message:`${a.message} & ${l.message}`}}const h={code:e,data:{status:Tl.ONLINE,subStatus:t},message:i};return this.agentInfo.status=Tl.ONLINE,this.agentInfo.statusName=t,this.tracker.track("agent.online",{extra:{subStatus:t}}),this.emitAgentEvent("online",h),this.startHeartbeat(),h}return{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}offlineAgent(t){return e(this,void 0,void 0,(function*(){this.stopHeartbeat();const{status:e,id:n,groupId:r}=this.agentInfo;if(e===Tl.OFFLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.agentInfo.statusName=t,this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),i}if(e===Tl.ONLINE){const e=yield this.api.switchAgentStatus({id:n,groupId:r,status:Tl.OFFLINE,subStatus:t});if(e.code!==sl.SUCCESS)return this.tracker.track("agent.offline.fail",{message:e.message,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:e.message};this.api.updateAgentTicket({agentId:n,ticket:"",type:Tl.OFFLINE}),yield this.closeSip();const i={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:t},message:"Agent is already offline"};return this.tracker.track("agent.offline",{extra:{subStatus:t}}),this.emitAgentEvent("offline",i),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName=t,i}return this.tracker.track("agent.offline.fail",{message:"invalid status",extra:{reason:"invalid_status"}}),{code:ol.FAILED,data:null,message:"Agent Status is not valid"}}))}startHeartbeat(){this.isHeartbeatRunning&&this.stopHeartbeat(),this.isHeartbeatRunning=!0,this.heartbeatFailCount=0,this.executeHeartbeat()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isHeartbeatRunning=!1,this.heartbeatFailCount=0}executeHeartbeat(){return e(this,void 0,void 0,(function*(){if(this.isHeartbeatRunning)try{const{id:e}=this.agentInfo;if(yield this.api.sendHeartbeat(e)){const e=this.heartbeatFailCount;this.heartbeatFailCount=0,e>0&&this.tracker.track("heartbeat.recover"),this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}else if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat failed, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"fail"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}catch(e){if(this.heartbeatFailCount+=1,this.tracker.track("heartbeat.fail",{extra:{failCount:this.heartbeatFailCount}}),this.heartbeatFailCount>=4){this.stopHeartbeat();const e={code:ol.SUCCESS,data:{status:Tl.OFFLINE,subStatus:"offline"},message:"Heartbeat exception, agent offline"};this.tracker.track("agent.offline.heartbeat",{extra:{reason:"exception"}}),this.sip.stop(!0),this.agentInfo.status=Tl.OFFLINE,this.agentInfo.statusName="Offline",this.emitAgentEvent("offline",e)}else this.heartbeatTimer=setTimeout((()=>{this.executeHeartbeat()}),Cl)}}))}switchAgentStatus(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("status.switch.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Registration failed. Seat online and offline cannot be performed."};const e=yield this.getAgentInfo();if(e.code!==ol.SUCCESS)return{code:e.code===ol.LOCKED?ol.LOCKED:ol.FAILED,data:null,message:e.message};const{status:n,subStatus:r}=t;return this.tracker.track("status.switch",{extra:{from:this.agentInfo.status,to:n}}),n===Tl.ONLINE?this.onlineAgent(r):n===Tl.OFFLINE?this.offlineAgent(r):(this.tracker.track("status.switch.fail",{extra:{reason:"invalid"}}),{code:ol.FAILED,data:null,message:"system error"})}))}outboundCall(t){return e(this,void 0,void 0,(function*(){if(!this.isInitSuccess)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_init"}}),{code:ol.FAILED,data:null,message:"SIP Registration failed, Outbound calls cannot be made."};const e=this.agentInfo.outboundLineId;if(!e)return this.tracker.track("call.outbound.fail",{extra:{reason:"no_line"}}),Promise.resolve({code:ol.FAILED,data:null,message:"Agent has no outbound line"});this.sip.setCallType("outboundCall");const n=yield this.api.outboundCall({phone:t,line:e}).catch((e=>{throw this.sip.setCallType(""),e}));return n.code===sl.SUCCESS?(this.tracker.track("call.outbound",{extra:{line:e}}),{code:ol.SUCCESS,data:n.data,message:n.message||n.msg}):(this.sip.setCallType(""),this.tracker.track("call.outbound.fail",{message:n.message||n.msg,extra:{reason:"api_fail"}}),{code:ol.FAILED,data:null,message:n.message||n.msg})}))}autoFinishACW(){var e,t;let n=Number(this.callDetails.afterCallProcessTime);this.tracker.track("acw.start",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{seconds:n}});const r=()=>{if(n<=0)return this._acwAutoTriggered=!0,void this.finshACW();n-=1,this.autoFinishACWTimer=setTimeout(r,1e3)};this.autoFinishACWTimer=setTimeout(r,1e3)}finshACW(){return e(this,void 0,void 0,(function*(){var e,t;const n=!this._acwAutoTriggered;this._acwAutoTriggered=!1,this.tracker.track("acw.finish",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId,extra:{manual:n}}),this.autoFinishACWTimer&&(clearTimeout(this.autoFinishACWTimer),this.autoFinishACWTimer=null),this.api.reportPDSTimeline({callId:this.callDetails.callId,eventType:El.ACW});const{id:r,groupId:i}=this.agentInfo,s=yield this.api.switchAgentStatus({id:r,groupId:i,status:Tl.HANGUP});return{code:s.code===sl.SUCCESS?ol.SUCCESS:ol.FAILED,data:null,message:s.message}}))}sessionEnded(){return e(this,void 0,void 0,(function*(){this.autoFinishACW()}))}sessionFailed(){return e(this,void 0,void 0,(function*(){this.api.updateAgentHangup(this.agentInfo.id)}))}saveAgentResponseTime(e){this.api.saveAgentResponseTime({callId:this.callDetails.callId,agentId:this.agentInfo.id,agentResponseTime:this.agentResponseTime,agentGroupId:this.agentInfo.groupId,resultType:e}),this.timer&&(clearInterval(this.timer),this.agentResponseTime=0)}hangup(){var e,t;this.tracker.track("call.hangup",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.hangup()}timingResTime(){this.timer&&(clearInterval(this.timer),this.timer=null);let e=this.agentWaitingTime;this.agentResponseTime=0,this.timer=setInterval((()=>{if(e<=0)return clearInterval((null==this?void 0:this.timer)||0),this.timer=null,void this.ignore();e-=1,this.agentResponseTime+=1}),1e3)}trackIncomingCall(e){this.api.reportPDSTimeline({callId:e,eventType:El.INCOMMING,timestamp:(new Date).getTime()})}incomingCall(t){return e(this,void 0,void 0,(function*(){var e,n,r,i,s,o;try{const a=t.request,l=(null===(n=null===(e=a.headers["Call-Param"])||void 0===e?void 0:e[0])||void 0===n?void 0:n.raw)||"",u=l?atob(l):"",c=JSON.parse(u||"{}"),h=(null===(i=null===(r=a.headers["Call-ID"])||void 0===r?void 0:r[0])||void 0===i?void 0:i.raw)||null,d=(null===(o=null===(s=a.headers["Call-Record-Id"])||void 0===s?void 0:s[0])||void 0===o?void 0:o.raw)||null,f=Object.fromEntries(Object.entries(c).filter((([e])=>""!==e))),p=t.request.getHeader("Task-Name")||"",g=t.request.getHeader("After-Time")||"";let m=f.phone||f.Phone||f.PHONE||"";return m||(m=t.request.getHeader("Caller")||""),this.callDetails={callId:d||"",originCallId:h||"",callType:this.sip.getCallType()||"",taskName:p,afterCallProcessTime:g,phone:m,contactId:f.contactId||f.ContactId||f.CONTACT_ID||"",extraJson:f},"outboundCall"!==this.sip.getCallType()&&this.timingResTime(),Promise.resolve({code:ol.SUCCESS,data:this.callDetails,message:"success"})}catch(e){return this.tracker.track("call.incoming.fail",{message:String(e),extra:{errorName:null==e?void 0:e.name}}),Promise.resolve({code:ol.FAILED,data:null,message:(null==e?void 0:e.toString())||"system error"})}}))}answer(){var e,t;this.tracker.track("call.answer",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.answer(),this.saveAgentResponseTime(Sl.ANSWER)}ignore(){var e,t;this.tracker.track("call.ignore",{callId:null===(e=this.callDetails)||void 0===e?void 0:e.originCallId,callRecordId:null===(t=this.callDetails)||void 0===t?void 0:t.callId}),this.sip.ignore(),this.saveAgentResponseTime(Sl.HANGUP)}mute(){this.sip.mute()}unmute(){this.sip.unmute()}attachInitEvent(e,t){t&&"function"==typeof t&&(this.initEvent[e]||(this.initEvent[e]=[]),this.initEvent[e].push(t))}removeInitEvent(e,t){const n=this.initEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitInitEvent(e,t){(this.initEvent[e]||[]).forEach((e=>{e(t)}))}attachAgentEvent(e,t){t&&"function"==typeof t&&(this.agentEvent[e]||(this.agentEvent[e]=[]),this.agentEvent[e].push(t))}removeAgentEvent(e,t){const n=this.agentEvent[e];let r=null;if(n&&n.length)for(let e=0;e<n.length;e++)if(r=n[e],r===t){n.splice(e,1);break}}emitAgentEvent(e,t){(this.agentEvent[e]||[]).forEach((e=>{e(t)}))}attachAnswerEvent(e){this.sip.attachAnswerEvent(e)}removeAnswerEvent(e){this.sip.removeAnswerEvent(e)}attachAutoAnswerEvent(e){this.sip.attachAutoAnswerEvent(e)}removeAutoAnswerEvent(e){this.sip.removeAutoAnswerEvent(e)}attachNewMessageEvent(e){this.sip.attachNewMessageEvent(e)}removeNewMessageEvent(e){this.sip.removeNewMessageEvent(e)}attchSessionEvent(e,t){this.sip.attchSessionEvent(e,t)}removeSessionEvent(e,t){this.sip.removeSessionEvent(e,t)}}}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wizai/agent-sip-sdk",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Manages SIP clients and agent status, simplifying calls and events.",
5
5
  "main": "lib/agent-sip-sdk-cjs.js",
6
6
  "module": "lib/agent-sip-sdk-es.js",