@onedeskpro/chatbot-core 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +26 -26
- package/dist/index.iife.js +26 -26
- package/dist/index.js +353 -349
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n=3e4,r=12e4;function i(e){return typeof e==`object`&&!!e&&typeof e.message==`string`}function a(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.type==`string`&&typeof t.url==`string`&&typeof t.fileName==`string`&&typeof t.size==`number`}var o=[`ai`,`waiting`,`human`,`closed`];function s(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.mode==`string`&&o.includes(t.mode)&&(t.conversationId===void 0||typeof t.conversationId==`string`)&&(t.agentName===void 0||typeof t.agentName==`string`)}function c(e){return e instanceof Error&&`apiError`in e&&`status`in e&&typeof e.status==`number`&&i(e.apiError)}var l=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,``),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??3e4,this.uploadTimeoutMs=e.uploadTimeoutMs??r}fail(e,t,n,r){let i={statusCode:t,message:e,code:n,timestamp:new Date().toISOString(),path:r};throw Object.assign(Error(e),{apiError:i,status:t})}async request(e,t,n,r,a,o=this.timeoutMs){let s=new URL(`${this.baseUrl}${t}`);if(r)for(let[e,t]of Object.entries(r))s.searchParams.set(e,t);let c=typeof FormData<`u`&&n instanceof FormData,l={...c?{}:{"Content-Type":`application/json`},"X-API-Key":this.apiKey,...a},u=new AbortController,d=setTimeout(()=>u.abort(),o),f;try{f=await fetch(s.toString(),{method:e,headers:l,signal:u.signal,...n===void 0?{}:{body:c?n:JSON.stringify(n)}})}catch(e){u.signal.aborted&&this.fail(`Request timed out after ${o}ms.`,0,`TIMEOUT`,t),this.fail(e instanceof Error?e.message:`Network request failed.`,0,`NETWORK_ERROR`,t)}finally{clearTimeout(d)}let p=await f.text(),m=null;if(p)try{m=JSON.parse(p)}catch{m=null}if(!f.ok){if(i(m))throw Object.assign(Error(m.message),{apiError:m,status:f.status});this.fail(`Request failed with status ${f.status} ${f.statusText}`.trim(),f.status,`HTTP_ERROR`,t)}return m===null&&this.fail(`The server returned an empty or malformed response.`,f.status,`BAD_RESPONSE`,t),m.data}async identify(e){return this.request(`POST`,`/sdk/identify`,e)}async verifyVisitor(e){return this.request(`GET`,`/sdk/visitor`,void 0,void 0,{"X-Visitor-Token":e})}async sendMessage(e){return this.request(`POST`,`/sdk/chat`,e)}async uploadAttachment(e,t){let n=new FormData;n.append(`file`,e,e.name);let r=await this.request(`POST`,`/sdk/upload`,n,void 0,{"X-Visitor-Token":t},this.uploadTimeoutMs);return a(r)||this.fail(`The server returned an unexpected upload response.`,200,`BAD_RESPONSE`,`/sdk/upload`),r}async fetchConfig(){return this.request(`GET`,`/sdk/config`)}async requestHuman(e){return this.request(`POST`,`/sdk/human-request`,{visitorToken:e})}async cancelHumanRequest(e){return this.postTicketAction(`/sdk/human-request/cancel`,e)}async closeConversation(e){return this.postTicketAction(`/sdk/conversation/close`,e)}async postTicketAction(e,t){let n=await this.request(`POST`,e,{visitorToken:t});return s(n)||this.fail(`The server returned an unexpected ticket status.`,200,`BAD_RESPONSE`,e),n}async fetchTicketStatus(e){return this.request(`GET`,`/sdk/ticket-status`,void 0,void 0,{"X-Visitor-Token":e})}},u=`https://api.onedeskpro.com`,d=10485760,f=10;function p(e){if(e.length>10)return`You can send up to 10 files at a time.`;let t=e.find(e=>e.size>d);if(t){let e=Math.round(d/1048576);return`"${t.name||`This file`}" is larger than ${e} MB.`}return null}function m(e){return/^(https?:\/\/|blob:)/i.test(e)}function h(e){return typeof URL>`u`||typeof URL.createObjectURL!=`function`?``:URL.createObjectURL(e)}function g(e){e.startsWith(`blob:`)&&typeof URL<`u`&&typeof URL.revokeObjectURL==`function`&&URL.revokeObjectURL(e)}function ee(e){return{type:e.type||`application/octet-stream`,url:h(e),fileName:e.name||`attachment`,size:e.size}}function te(e){return!Number.isFinite(e)||e<0?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:`${(e/1048576).toFixed(1)} MB`}function ne(e){if(!e||typeof e!=`object`)return[];let t=e,n=t.attachments;if(!Array.isArray(n)&&t.message&&typeof t.message==`object`&&(n=t.message.attachments),!Array.isArray(n))return[];let r=[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=e;typeof t.url==`string`&&/^https?:\/\//i.test(t.url)&&r.push({type:typeof t.type==`string`&&t.type?t.type:`application/octet-stream`,url:t.url,fileName:typeof t.fileName==`string`&&t.fileName?t.fileName:`attachment`,size:typeof t.size==`number`&&t.size>=0?t.size:0,...typeof t.durationSeconds==`number`?{durationSeconds:t.durationSeconds}:{}})}return r}function re(e,t){let n=e.trim();return n?t.length===0?!1:t.some(e=>e.fileName===n)||/^\d+ files?$/.test(n)?!0:[`Image`,`Video`,`Audio`,`Attachment`].includes(n):!0}var _=16e3;function v(e){return(e??``).split(`;`)[0].trim().toLowerCase()||`audio/webm`}function ie(e){return e.includes(`mpeg`)||e.includes(`mp3`)?`mp3`:e.includes(`wav`)?`wav`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`ogg`)?`ogg`:`webm`}function y(e){if(!Number.isFinite(e)||e<0)return`0:00`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}function ae(){if(typeof window>`u`)return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function oe(){if(typeof window>`u`)return null;let e=window;return e.OfflineAudioContext??e.webkitOfflineAudioContext??null}async function se(e){let t=ae();if(!t)return null;let n=new t;try{let t=await e.arrayBuffer();return await n.decodeAudioData(t.slice(0))}catch{return null}finally{await n.close().catch(()=>void 0)}}async function ce(e){let t=oe();if(t)try{let n=new t(1,Math.max(1,Math.ceil(e.duration*_)),_),r=n.createBufferSource();return r.buffer=e,r.connect(n.destination),r.start(0),{samples:(await n.startRendering()).getChannelData(0),sampleRate:_}}catch{}return{samples:e.getChannelData(0),sampleRate:e.sampleRate}}function le(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r),a=(e,t)=>{for(let n=0;n<t.length;n++)i.setUint8(e+n,t.charCodeAt(n))};a(0,`RIFF`),i.setUint32(4,36+n,!0),a(8,`WAVE`),a(12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),a(36,`data`),i.setUint32(40,n,!0);let o=44;for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]??0));i.setInt16(o,Math.round(n<0?n*32768:n*32767),!0),o+=2}return new Blob([r],{type:`audio/wav`})}function ue(e,t=48){if(e.length===0)return[];let n=Math.max(1,Math.floor(e.length/t)),r=[],i=0;for(let a=0;a<t;a++){let t=a*n,o=Math.min(t+n,e.length),s=0;for(let n=t;n<o;n++){let t=e[n]??0;s+=t*t}let c=o>t?Math.sqrt(s/(o-t)):0;r.push(c),c>i&&(i=c)}return r.map(e=>i>0?Math.max(8,Math.min(100,Math.round(e/i*100))):8)}async function de(e){let t=Date.now(),n=Math.max(1,Math.round(e.durationSeconds||1)),r=v(e.mimeType??e.blob.type),i=await se(e.blob);if(!i)return{file:new File([e.blob],`voice-message-${t}.${ie(r)}`,{type:r}),durationSeconds:n};let{samples:a,sampleRate:o}=await ce(i);return{file:new File([le(a,o)],`voice-message-${t}.wav`,{type:`audio/wav`}),durationSeconds:Math.max(1,Math.round(i.duration||n)),waveform:ue(a)}}var fe=class{constructor(){this._listeners={}}on(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),()=>this.off(e,t)}off(e,t){let n=this._listeners[e];n&&(this._listeners[e]=n.filter(e=>e!==t))}emit(e,...t){let n=this._listeners[e];if(n)for(let e of n)e(...t)}removeAllListeners(){for(let e of Object.keys(this._listeners))delete this._listeners[e]}},b=Object.create(null);b.open=`0`,b.close=`1`,b.ping=`2`,b.pong=`3`,b.message=`4`,b.upgrade=`5`,b.noop=`6`;var x=Object.create(null);Object.keys(b).forEach(e=>{x[b[e]]=e});var pe={type:`error`,data:`parser error`},me=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,he=typeof ArrayBuffer==`function`,ge=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,S=({type:e,data:t},n,r)=>me&&t instanceof Blob?n?r(t):_e(t,r):he&&(t instanceof ArrayBuffer||ge(t))?n?r(t):_e(new Blob([t]),r):r(b[e]+(t||``)),_e=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function ve(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var ye;function be(e,t){if(me&&e.data instanceof Blob)return e.data.arrayBuffer().then(ve).then(t);if(he&&(e.data instanceof ArrayBuffer||ge(e.data)))return t(ve(e.data));S(e,!1,e=>{ye||=new TextEncoder,t(ye.encode(e))})}var xe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,C=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)C[xe.charCodeAt(e)]=e;var Se=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=C[e.charCodeAt(r)],o=C[e.charCodeAt(r+1)],s=C[e.charCodeAt(r+2)],c=C[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Ce=typeof ArrayBuffer==`function`,w=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Te(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:we(e.substring(1),t)}:x[n]?e.length>1?{type:x[n],data:e.substring(1)}:{type:x[n]}:pe},we=(e,t)=>Ce?Te(Se(e),t):{base64:!0,data:e},Te=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ee=``,De=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{S(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ee))})})},Oe=(e,t)=>{let n=e.split(Ee),r=[];for(let e=0;e<n.length;e++){let i=w(n[e],t);if(r.push(i),i.type===`error`)break}return r};function ke(){return new TransformStream({transform(e,t){be(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Ae;function T(e){return e.reduce((e,t)=>e+t.length,0)}function E(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function je(e,t){Ae||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(T(n)<1)break;let e=E(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(T(n)<2)break;let e=E(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(T(n)<8)break;let e=E(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(pe);break}i=a*2**32+t.getUint32(4),r=3}else{if(T(n)<i)break;let e=E(n,i);s.enqueue(w(a?e:Ae.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(pe);break}}}})}function D(e){if(e)return Me(e)}function Me(e){for(var t in D.prototype)e[t]=D.prototype[t];return e}D.prototype.on=D.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},D.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},D.prototype.off=D.prototype.removeListener=D.prototype.removeAllListeners=D.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},D.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},D.prototype.emitReserved=D.prototype.emit,D.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},D.prototype.hasListeners=function(e){return!!this.listeners(e).length};var O=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),k=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Ne=`arraybuffer`;function Pe(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Fe=k.setTimeout,Ie=k.clearTimeout;function A(e,t){t.useNativeTimers?(e.setTimeoutFn=Fe.bind(k),e.clearTimeoutFn=Ie.bind(k)):(e.setTimeoutFn=k.setTimeout.bind(k),e.clearTimeoutFn=k.clearTimeout.bind(k))}var Le=1.33;function Re(e){return typeof e==`string`?ze(e):Math.ceil((e.byteLength||e.size)*Le)}function ze(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function Be(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ve(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function He(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var Ue=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},j=class extends D{constructor(e){super(),this.writable=!1,A(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new Ue(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=w(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=Ve(e);return t.length?`?`+t:``}},We=class extends j{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Oe(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,De(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Be()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Ge=!1;try{Ge=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Ke=Ge;function qe(){}var Je=class extends We{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},M=class e extends D{constructor(e,t,n){super(),this.createRequest=e,A(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=Pe(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(this._xhr!==void 0&&this._xhr!==null){if(this._xhr.onreadystatechange=qe,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(M.requestsCount=0,M.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Ye);else if(typeof addEventListener==`function`){let e=`onpagehide`in k?`pagehide`:`unload`;addEventListener(e,Ye,!1)}}function Ye(){for(let e in M.requests)M.requests.hasOwnProperty(e)&&M.requests[e].abort()}var Xe=(function(){let e=Qe({xdomain:!1});return e&&e.responseType!==null})(),Ze=class extends Je{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Xe&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new M(Qe,this.uri(),e)}};function Qe(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Ke))return new XMLHttpRequest}catch{}if(!t)try{return new k.ActiveXObject(`Microsoft.XMLHTTP`)}catch{}}var $e=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,et=class extends j{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=$e?{}:Pe(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;S(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&O(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Be()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},N=k.WebSocket||k.MozWebSocket,tt={websocket:class extends et{createSocket(e,t,n){return $e?new N(e,t,n):t?new N(e,t):new N(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends j{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=je(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ke();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&O(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:Ze},nt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function P(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=nt.exec(e||``),a={},o=14;for(;o--;)a[rt[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=it(a,a.path),a.queryKey=at(a,a.query),a}function it(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function at(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var F=typeof addEventListener==`function`&&typeof removeEventListener==`function`,I=[];F&&addEventListener(`offline`,()=>{I.forEach(e=>e())},!1);var L=class e extends D{constructor(e,t){if(super(),this.binaryType=Ne,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=P(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=P(t.host).host);A(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=He(this.opts.query)),F&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},I.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data)}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=Re(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,O(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),F&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=I.indexOf(this._offlineEventListener);e!==-1&&I.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};L.protocol=4;var ot=class extends L{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;L.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n){if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;L.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},st=class extends ot{constructor(e,t={}){let n=typeof e==`object`,r=n?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]==`string`)&&(r.transports=(r.transports||[`polling`,`websocket`,`webtransport`]).map(e=>tt[e]).filter(e=>!!e)),super(n?r:e,r)}};st.protocol;function ct(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=P(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var lt=typeof ArrayBuffer==`function`,ut=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,dt=Object.prototype.toString,ft=typeof Blob==`function`||typeof Blob<`u`&&dt.call(Blob)===`[object BlobConstructor]`,pt=typeof File==`function`||typeof File<`u`&&dt.call(File)===`[object FileConstructor]`;function R(e){return lt&&(e instanceof ArrayBuffer||ut(e))||ft&&e instanceof Blob||pt&&e instanceof File}function z(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(z(e[t]))return!0;return!1}if(R(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return z(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&z(e[t]))return!0;return!1}function mt(e){let t=[],n=e.data,r=e;return r.data=B(n,t),r.attachments=t.length,{packet:r,buffers:t}}function B(e,t,n){if(!e)return e;if(R(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=B(e[r],t);return n}if(typeof e==`object`&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON==`function`&&!n)return B(e.toJSON(),t,!0);let r={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=B(e[n],t));return r}return e}function ht(e,t){return e.data=V(e.data,t),delete e.attachments,e}function V(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=V(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=V(e[n],t));return e}var gt=t({Decoder:()=>yt,Encoder:()=>vt,PacketType:()=>H,isPacketValid:()=>Tt,protocol:()=>5}),_t=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],H;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(H||={});var vt=class{constructor(e){this.replacer=e}encode(e){return(e.type===H.EVENT||e.type===H.ACK)&&z(e)?this.encodeAsBinary({type:e.type===H.EVENT?H.BINARY_EVENT:H.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===H.BINARY_EVENT||e.type===H.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=mt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},yt=class e extends D{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===H.BINARY_EVENT;n||t.type===H.BINARY_ACK?(t.type=n?H.EVENT:H.ACK,this.reconstructor=new bt(t)):super.emitReserved(`decoded`,t)}else if(R(e)||e.base64){if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`)}else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(H[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===H.BINARY_EVENT||r.type===H.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!St(a)||a<1)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&t.charAt(n)!==`,`&&n!==t.length;);r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case H.CONNECT:return U(t);case H.DISCONNECT:return t===void 0;case H.CONNECT_ERROR:return typeof t==`string`||U(t);case H.EVENT:case H.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&_t.indexOf(t[0])===-1);case H.ACK:case H.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},bt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=ht(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function xt(e){return typeof e==`string`}var St=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Ct(e){return e===void 0||St(e)}function U(e){return Object.prototype.toString.call(e)===`[object Object]`}function wt(e,t){switch(e){case H.CONNECT:return t===void 0||U(t);case H.DISCONNECT:return t===void 0;case H.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&_t.indexOf(t[0])===-1);case H.ACK:return Array.isArray(t);case H.CONNECT_ERROR:return typeof t==`string`||U(t);default:return!1}}function Tt(e){return xt(e.nsp)&&Ct(e.id)&&wt(e.type,e.data)}function W(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Et=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Dt=class extends D{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[W(e,`open`,this.onopen.bind(this)),W(e,`packet`,this.onpacket.bind(this)),W(e,`error`,this.onerror.bind(this)),W(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(Et.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:H.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:H.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case H.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case H.EVENT:case H.BINARY_EVENT:this.onevent(e);break;case H.ACK:case H.BINARY_ACK:this.onack(e);break;case H.DISCONNECT:this.ondisconnect();break;case H.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t)}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:H.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:H.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function G(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}G.prototype.duration=function(){var e=this.ms*this.factor**+this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},G.prototype.reset=function(){this.attempts=0},G.prototype.setMin=function(e){this.ms=e},G.prototype.setMax=function(e){this.max=e},G.prototype.setJitter=function(e){this.jitter=e};var K=class extends D{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,A(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new G({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||gt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new st(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=W(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=W(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(W(e,`ping`,this.onping.bind(this)),W(e,`data`,this.ondata.bind(this)),W(e,`error`,this.onerror.bind(this)),W(e,`close`,this.onclose.bind(this)),W(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){O(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Dt(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},q={};function J(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=ct(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=q[i]&&a in q[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new K(r,t):(q[i]||(q[i]=new K(r,t)),c=q[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(J,{Manager:K,Socket:Dt,io:J,connect:J});function Ot(e){let t=e.replace(/\/$/,``);try{return`${new URL(t).origin}/sdk`}catch{return`${t}/sdk`}}var kt=class{constructor(){this.socket=null}get connected(){return this.socket?.connected??!1}connect(e){this.disconnect();let t=Ot(e.baseUrl);this.socket=J(t,{auth:{apiKey:e.apiKey,visitorToken:e.visitorToken},transports:[`websocket`,`polling`],autoConnect:!0,reconnection:!0});let n=!1;this.socket.on(`connect`,()=>{n?e.onReconnect?.():n=!0}),this.socket.on(`ticket:status`,t=>{e.onTicketStatus?.(t)}),this.socket.on(`message:receive`,t=>{e.onMessageReceive?.(t)}),this.socket.on(`connect_error`,t=>{e.onConnectError?.(t)})}disconnect(){this.socket&&=(this.socket.removeAllListeners(),this.socket.disconnect(),null)}},Y=`onedeskpro_visitor_token`;function At(e){try{return typeof window<`u`?window.localStorage.getItem(e):null}catch{return null}}function jt(e,t){try{typeof window<`u`&&window.localStorage.setItem(e,t)}catch{}}function Mt(e){try{typeof window<`u`&&window.localStorage.removeItem(e)}catch{}}var Nt=class{constructor(){this.token=null,this.storageKey=Y}setScope(e){this.storageKey=e?.trim()?`${Y}:${e.trim()}`:Y,this.token=At(this.storageKey)}get(){return this.token??At(this.storageKey)}set(e){this.token=e,jt(this.storageKey,e)}clear(){this.token=null,Mt(this.storageKey)}},Pt=300,Ft=250,It=100,Lt=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/ogg;codecs=opus`];function Rt(){return typeof MediaRecorder>`u`||typeof MediaRecorder.isTypeSupported!=`function`?`audio/webm`:Lt.find(e=>MediaRecorder.isTypeSupported(e))??`audio/webm`}function zt(e){let t=e instanceof DOMException?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||t===`SecurityError`?`Microphone access was denied.`:t===`NotFoundError`||t===`DevicesNotFoundError`?`No microphone was found.`:`Could not start recording.`}var Bt=class e{constructor(e,t=300){this.onChange=e,this.maxDurationSeconds=t,this.recorder=null,this.stream=null,this.chunks=[],this.mimeType=`audio/webm`,this.startedAt=0,this.tickTimer=null,this.levelTimer=null,this.maxTimer=null,this.audioContext=null,this.analyser=null,this.snapshot={state:`idle`,elapsedSeconds:0,level:0,result:null}}static isSupported(){return typeof navigator<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`&&typeof MediaRecorder<`u`}getSnapshot(){return{...this.snapshot}}async start(){if(!e.isSupported())throw Error(`Voice messages are not supported in this browser.`);this.release(),this.chunks=[];let t;try{t=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){throw Error(zt(e))}try{this.mimeType=Rt();let e=new MediaRecorder(t,{mimeType:this.mimeType});e.ondataavailable=e=>{e.data.size>0&&this.chunks.push(e.data)},this.stream=t,this.recorder=e,this.startedAt=Date.now(),e.start(200)}catch(e){throw t.getTracks().forEach(e=>e.stop()),this.stream=null,this.recorder=null,Error(zt(e))}this.startLevelMeter(t),this.tickTimer=setInterval(()=>{this.update({elapsedSeconds:Math.floor(this.elapsedMs()/1e3)})},Ft),this.maxTimer=setTimeout(()=>void this.stop(),this.maxDurationSeconds*1e3),this.update({state:`recording`,elapsedSeconds:0,level:0,result:null})}async stop(){let e=this.recorder;if(!e||e.state===`inactive`)return this.release(),null;let t=Math.max(1,Math.round(this.elapsedMs()/1e3));this.clearTimers();let n=await new Promise(t=>{e.onstop=()=>{let e=this.chunks;this.chunks=[],t(new Blob(e,{type:v(this.mimeType)}))};try{e.stop()}catch{t(new Blob(this.chunks,{type:v(this.mimeType)}))}});this.releaseMedia();let r={blob:n,mimeType:v(this.mimeType),durationSeconds:t};return this.update({state:`preview`,elapsedSeconds:t,level:0,result:r}),r}cancel(){this.release(),this.update({state:`idle`,elapsedSeconds:0,level:0,result:null})}destroy(){this.release(),this.snapshot={state:`idle`,elapsedSeconds:0,level:0,result:null}}update(e){this.snapshot={...this.snapshot,...e},this.onChange({...this.snapshot})}elapsedMs(){return this.startedAt>0?Date.now()-this.startedAt:0}startLevelMeter(e){let t=typeof window>`u`?null:window,n=t?.AudioContext??t?.webkitAudioContext;if(n)try{let t=new n,r=t.createAnalyser();r.fftSize=256,t.createMediaStreamSource(e).connect(r),t.resume().catch(()=>void 0),this.audioContext=t,this.analyser=r;let i=new Uint8Array(r.frequencyBinCount);this.levelTimer=setInterval(()=>{r.getByteTimeDomainData(i);let e=0;for(let t=0;t<i.length;t++){let n=((i[t]??128)-128)/128;e+=n*n}this.update({level:Math.min(1,Math.sqrt(e/i.length)*3.2)})},It)}catch{}}clearTimers(){this.tickTimer&&clearInterval(this.tickTimer),this.levelTimer&&clearInterval(this.levelTimer),this.maxTimer&&clearTimeout(this.maxTimer),this.tickTimer=null,this.levelTimer=null,this.maxTimer=null}releaseMedia(){this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,this.recorder=null,this.analyser=null,this.audioContext&&=(this.audioContext.close().catch(()=>void 0),null),this.startedAt=0}release(){if(this.clearTimers(),this.recorder&&this.recorder.state!==`inactive`){this.recorder.onstop=null;try{this.recorder.stop()}catch{}}this.chunks=[],this.releaseMedia()}},X=[{iso:`BD`,name:`Bangladesh`,dial:`880`,flag:`🇧🇩`},{iso:`US`,name:`United States`,dial:`1`,flag:`🇺🇸`},{iso:`GB`,name:`United Kingdom`,dial:`44`,flag:`🇬🇧`},{iso:`IN`,name:`India`,dial:`91`,flag:`🇮🇳`},{iso:`PK`,name:`Pakistan`,dial:`92`,flag:`🇵🇰`},{iso:`AE`,name:`United Arab Emirates`,dial:`971`,flag:`🇦🇪`},{iso:`SA`,name:`Saudi Arabia`,dial:`966`,flag:`🇸🇦`},{iso:`CA`,name:`Canada`,dial:`1`,flag:`🇨🇦`},{iso:`AU`,name:`Australia`,dial:`61`,flag:`🇦🇺`},{iso:`DE`,name:`Germany`,dial:`49`,flag:`🇩🇪`},{iso:`FR`,name:`France`,dial:`33`,flag:`🇫🇷`},{iso:`IT`,name:`Italy`,dial:`39`,flag:`🇮🇹`},{iso:`ES`,name:`Spain`,dial:`34`,flag:`🇪🇸`},{iso:`NL`,name:`Netherlands`,dial:`31`,flag:`🇳🇱`},{iso:`SE`,name:`Sweden`,dial:`46`,flag:`🇸🇪`},{iso:`NO`,name:`Norway`,dial:`47`,flag:`🇳🇴`},{iso:`DK`,name:`Denmark`,dial:`45`,flag:`🇩🇰`},{iso:`FI`,name:`Finland`,dial:`358`,flag:`🇫🇮`},{iso:`IE`,name:`Ireland`,dial:`353`,flag:`🇮🇪`},{iso:`CH`,name:`Switzerland`,dial:`41`,flag:`🇨🇭`},{iso:`AT`,name:`Austria`,dial:`43`,flag:`🇦🇹`},{iso:`BE`,name:`Belgium`,dial:`32`,flag:`🇧🇪`},{iso:`PT`,name:`Portugal`,dial:`351`,flag:`🇵🇹`},{iso:`PL`,name:`Poland`,dial:`48`,flag:`🇵🇱`},{iso:`CZ`,name:`Czechia`,dial:`420`,flag:`🇨🇿`},{iso:`RO`,name:`Romania`,dial:`40`,flag:`🇷🇴`},{iso:`HU`,name:`Hungary`,dial:`36`,flag:`🇭🇺`},{iso:`GR`,name:`Greece`,dial:`30`,flag:`🇬🇷`},{iso:`TR`,name:`Turkey`,dial:`90`,flag:`🇹🇷`},{iso:`RU`,name:`Russia`,dial:`7`,flag:`🇷🇺`},{iso:`UA`,name:`Ukraine`,dial:`380`,flag:`🇺🇦`},{iso:`CN`,name:`China`,dial:`86`,flag:`🇨🇳`},{iso:`JP`,name:`Japan`,dial:`81`,flag:`🇯🇵`},{iso:`KR`,name:`South Korea`,dial:`82`,flag:`🇰🇷`},{iso:`SG`,name:`Singapore`,dial:`65`,flag:`🇸🇬`},{iso:`MY`,name:`Malaysia`,dial:`60`,flag:`🇲🇾`},{iso:`ID`,name:`Indonesia`,dial:`62`,flag:`🇮🇩`},{iso:`TH`,name:`Thailand`,dial:`66`,flag:`🇹🇭`},{iso:`VN`,name:`Vietnam`,dial:`84`,flag:`🇻🇳`},{iso:`PH`,name:`Philippines`,dial:`63`,flag:`🇵🇭`},{iso:`HK`,name:`Hong Kong`,dial:`852`,flag:`🇭🇰`},{iso:`TW`,name:`Taiwan`,dial:`886`,flag:`🇹🇼`},{iso:`NZ`,name:`New Zealand`,dial:`64`,flag:`🇳🇿`},{iso:`ZA`,name:`South Africa`,dial:`27`,flag:`🇿🇦`},{iso:`NG`,name:`Nigeria`,dial:`234`,flag:`🇳🇬`},{iso:`KE`,name:`Kenya`,dial:`254`,flag:`🇰🇪`},{iso:`EG`,name:`Egypt`,dial:`20`,flag:`🇪🇬`},{iso:`MA`,name:`Morocco`,dial:`212`,flag:`🇲🇦`},{iso:`BR`,name:`Brazil`,dial:`55`,flag:`🇧🇷`},{iso:`MX`,name:`Mexico`,dial:`52`,flag:`🇲🇽`},{iso:`AR`,name:`Argentina`,dial:`54`,flag:`🇦🇷`},{iso:`CL`,name:`Chile`,dial:`56`,flag:`🇨🇱`},{iso:`CO`,name:`Colombia`,dial:`57`,flag:`🇨🇴`},{iso:`PE`,name:`Peru`,dial:`51`,flag:`🇵🇪`},{iso:`IL`,name:`Israel`,dial:`972`,flag:`🇮🇱`},{iso:`QA`,name:`Qatar`,dial:`974`,flag:`🇶🇦`},{iso:`KW`,name:`Kuwait`,dial:`965`,flag:`🇰🇼`},{iso:`BH`,name:`Bahrain`,dial:`973`,flag:`🇧🇭`},{iso:`OM`,name:`Oman`,dial:`968`,flag:`🇴🇲`},{iso:`LK`,name:`Sri Lanka`,dial:`94`,flag:`🇱🇰`},{iso:`NP`,name:`Nepal`,dial:`977`,flag:`🇳🇵`}],Vt=X.find(e=>e.iso===`BD`)??X[0];function Ht(e,t){let n=t.trim();if(n.startsWith(`+`)){let e=n.replace(/\D/g,``);return e?`+${e}`:``}let r=n.replace(/\D/g,``);return!r||(r=r.replace(/^0+/,``),!r)?``:`+${e}${r}`}var Ut=`(max-width: 640px), (max-height: 500px) and (pointer: coarse)`;function Wt(e,t){let n=`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n=3e4,r=12e4;function i(e){return typeof e==`object`&&!!e&&typeof e.message==`string`}function a(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.type==`string`&&typeof t.url==`string`&&typeof t.fileName==`string`&&typeof t.size==`number`}var o=[`ai`,`waiting`,`human`,`closed`];function s(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.mode==`string`&&o.includes(t.mode)&&(t.conversationId===void 0||typeof t.conversationId==`string`)&&(t.agentName===void 0||typeof t.agentName==`string`)}function c(e){return e instanceof Error&&`apiError`in e&&`status`in e&&typeof e.status==`number`&&i(e.apiError)}var l=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,``),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??3e4,this.uploadTimeoutMs=e.uploadTimeoutMs??r}fail(e,t,n,r){let i={statusCode:t,message:e,code:n,timestamp:new Date().toISOString(),path:r};throw Object.assign(Error(e),{apiError:i,status:t})}async request(e,t,n,r,a,o=this.timeoutMs){let s=new URL(`${this.baseUrl}${t}`);if(r)for(let[e,t]of Object.entries(r))s.searchParams.set(e,t);let c=typeof FormData<`u`&&n instanceof FormData,l={...c?{}:{"Content-Type":`application/json`},"X-API-Key":this.apiKey,...a},u=new AbortController,d=setTimeout(()=>u.abort(),o),f;try{f=await fetch(s.toString(),{method:e,headers:l,signal:u.signal,...n===void 0?{}:{body:c?n:JSON.stringify(n)}})}catch(e){u.signal.aborted&&this.fail(`Request timed out after ${o}ms.`,0,`TIMEOUT`,t),this.fail(e instanceof Error?e.message:`Network request failed.`,0,`NETWORK_ERROR`,t)}finally{clearTimeout(d)}let p=await f.text(),m=null;if(p)try{m=JSON.parse(p)}catch{m=null}if(!f.ok){if(i(m))throw Object.assign(Error(m.message),{apiError:m,status:f.status});this.fail(`Request failed with status ${f.status} ${f.statusText}`.trim(),f.status,`HTTP_ERROR`,t)}return m===null&&this.fail(`The server returned an empty or malformed response.`,f.status,`BAD_RESPONSE`,t),m.data}async identify(e){return this.request(`POST`,`/sdk/identify`,e)}async verifyVisitor(e){return this.request(`GET`,`/sdk/visitor`,void 0,void 0,{"X-Visitor-Token":e})}async sendMessage(e){return this.request(`POST`,`/sdk/chat`,e)}async uploadAttachment(e,t){let n=new FormData;n.append(`file`,e,e.name);let r=await this.request(`POST`,`/sdk/upload`,n,void 0,{"X-Visitor-Token":t},this.uploadTimeoutMs);return a(r)||this.fail(`The server returned an unexpected upload response.`,200,`BAD_RESPONSE`,`/sdk/upload`),r}async fetchConfig(){return this.request(`GET`,`/sdk/config`)}async requestHuman(e){return this.request(`POST`,`/sdk/human-request`,{visitorToken:e})}async cancelHumanRequest(e){return this.postTicketAction(`/sdk/human-request/cancel`,e)}async closeConversation(e){return this.postTicketAction(`/sdk/conversation/close`,e)}async postTicketAction(e,t){let n=await this.request(`POST`,e,{visitorToken:t});return s(n)||this.fail(`The server returned an unexpected ticket status.`,200,`BAD_RESPONSE`,e),n}async fetchTicketStatus(e){return this.request(`GET`,`/sdk/ticket-status`,void 0,void 0,{"X-Visitor-Token":e})}},u=`https://api.onedeskpro.com`,d=10485760,f=10;function p(e){if(e.length>10)return`You can send up to 10 files at a time.`;let t=e.find(e=>e.size>d);if(t){let e=Math.round(d/1048576);return`"${t.name||`This file`}" is larger than ${e} MB.`}return null}function m(e){return/^(https?:\/\/|blob:)/i.test(e)}function h(e){return typeof URL>`u`||typeof URL.createObjectURL!=`function`?``:URL.createObjectURL(e)}function g(e){e.startsWith(`blob:`)&&typeof URL<`u`&&typeof URL.revokeObjectURL==`function`&&URL.revokeObjectURL(e)}function ee(e){return{type:e.type||`application/octet-stream`,url:h(e),fileName:e.name||`attachment`,size:e.size}}function te(e){return!Number.isFinite(e)||e<0?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:`${(e/1048576).toFixed(1)} MB`}function ne(e){if(!e||typeof e!=`object`)return[];let t=e,n=t.attachments;if(!Array.isArray(n)&&t.message&&typeof t.message==`object`&&(n=t.message.attachments),!Array.isArray(n))return[];let r=[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=e;typeof t.url==`string`&&/^https?:\/\//i.test(t.url)&&r.push({type:typeof t.type==`string`&&t.type?t.type:`application/octet-stream`,url:t.url,fileName:typeof t.fileName==`string`&&t.fileName?t.fileName:`attachment`,size:typeof t.size==`number`&&t.size>=0?t.size:0,...typeof t.durationSeconds==`number`?{durationSeconds:t.durationSeconds}:{}})}return r}function re(e,t){let n=e.trim();return n?t.length===0?!1:t.some(e=>e.fileName===n)||/^\d+ files?$/.test(n)?!0:[`Image`,`Video`,`Audio`,`Attachment`].includes(n):!0}var _=16e3;function v(e){return(e??``).split(`;`)[0].trim().toLowerCase()||`audio/webm`}function ie(e){return e.includes(`mpeg`)||e.includes(`mp3`)?`mp3`:e.includes(`wav`)?`wav`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`ogg`)?`ogg`:`webm`}function y(e){if(!Number.isFinite(e)||e<0)return`0:00`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}function ae(){if(typeof window>`u`)return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function oe(){if(typeof window>`u`)return null;let e=window;return e.OfflineAudioContext??e.webkitOfflineAudioContext??null}async function se(e){let t=ae();if(!t)return null;let n=new t;try{let t=await e.arrayBuffer();return await n.decodeAudioData(t.slice(0))}catch{return null}finally{await n.close().catch(()=>void 0)}}async function ce(e){let t=oe();if(t)try{let n=new t(1,Math.max(1,Math.ceil(e.duration*_)),_),r=n.createBufferSource();return r.buffer=e,r.connect(n.destination),r.start(0),{samples:(await n.startRendering()).getChannelData(0),sampleRate:_}}catch{}return{samples:e.getChannelData(0),sampleRate:e.sampleRate}}function le(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r),a=(e,t)=>{for(let n=0;n<t.length;n++)i.setUint8(e+n,t.charCodeAt(n))};a(0,`RIFF`),i.setUint32(4,36+n,!0),a(8,`WAVE`),a(12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),a(36,`data`),i.setUint32(40,n,!0);let o=44;for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]??0));i.setInt16(o,Math.round(n<0?n*32768:n*32767),!0),o+=2}return new Blob([r],{type:`audio/wav`})}function ue(e,t=48){if(e.length===0)return[];let n=Math.max(1,Math.floor(e.length/t)),r=[],i=0;for(let a=0;a<t;a++){let t=a*n,o=Math.min(t+n,e.length),s=0;for(let n=t;n<o;n++){let t=e[n]??0;s+=t*t}let c=o>t?Math.sqrt(s/(o-t)):0;r.push(c),c>i&&(i=c)}return r.map(e=>i>0?Math.max(8,Math.min(100,Math.round(e/i*100))):8)}async function de(e){let t=Date.now(),n=Math.max(1,Math.round(e.durationSeconds||1)),r=v(e.mimeType??e.blob.type),i=await se(e.blob);if(!i)return{file:new File([e.blob],`voice-message-${t}.${ie(r)}`,{type:r}),durationSeconds:n};let{samples:a,sampleRate:o}=await ce(i);return{file:new File([le(a,o)],`voice-message-${t}.wav`,{type:`audio/wav`}),durationSeconds:Math.max(1,Math.round(i.duration||n)),waveform:ue(a)}}var fe=class{constructor(){this._listeners={}}on(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),()=>this.off(e,t)}off(e,t){let n=this._listeners[e];n&&(this._listeners[e]=n.filter(e=>e!==t))}emit(e,...t){let n=this._listeners[e];if(n)for(let e of n)e(...t)}removeAllListeners(){for(let e of Object.keys(this._listeners))delete this._listeners[e]}},b=Object.create(null);b.open=`0`,b.close=`1`,b.ping=`2`,b.pong=`3`,b.message=`4`,b.upgrade=`5`,b.noop=`6`;var x=Object.create(null);Object.keys(b).forEach(e=>{x[b[e]]=e});var S={type:`error`,data:`parser error`},pe=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,me=typeof ArrayBuffer==`function`,he=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,C=({type:e,data:t},n,r)=>pe&&t instanceof Blob?n?r(t):ge(t,r):me&&(t instanceof ArrayBuffer||he(t))?n?r(t):ge(new Blob([t]),r):r(b[e]+(t||``)),ge=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function _e(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var ve;function ye(e,t){if(pe&&e.data instanceof Blob)return e.data.arrayBuffer().then(_e).then(t);if(me&&(e.data instanceof ArrayBuffer||he(e.data)))return t(_e(e.data));C(e,!1,e=>{ve||=new TextEncoder,t(ve.encode(e))})}var be=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,w=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)w[be.charCodeAt(e)]=e;var xe=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=w[e.charCodeAt(r)],o=w[e.charCodeAt(r+1)],s=w[e.charCodeAt(r+2)],c=w[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Se=typeof ArrayBuffer==`function`,T=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:we(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:Ce(e.substring(1),t)}:x[n]?e.length>1?{type:x[n],data:e.substring(1)}:{type:x[n]}:S},Ce=(e,t)=>Se?we(xe(e),t):{base64:!0,data:e},we=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Te=``,Ee=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{C(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Te))})})},De=(e,t)=>{let n=e.split(Te),r=[];for(let e=0;e<n.length;e++){let i=T(n[e],t);if(r.push(i),i.type===`error`)break}return r};function Oe(){return new TransformStream({transform(e,t){ye(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var ke;function E(e){return e.reduce((e,t)=>e+t.length,0)}function D(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function Ae(e,t){ke||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(E(n)<1)break;let e=D(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(E(n)<2)break;let e=D(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(E(n)<8)break;let e=D(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(S);break}i=a*2**32+t.getUint32(4),r=3}else{if(E(n)<i)break;let e=D(n,i);s.enqueue(T(a?e:ke.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(S);break}}}})}function O(e){if(e)return je(e)}function je(e){for(var t in O.prototype)e[t]=O.prototype[t];return e}O.prototype.on=O.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},O.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},O.prototype.off=O.prototype.removeListener=O.prototype.removeAllListeners=O.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},O.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},O.prototype.emitReserved=O.prototype.emit,O.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},O.prototype.hasListeners=function(e){return!!this.listeners(e).length};var k=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),A=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Me=`arraybuffer`;function Ne(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Pe=A.setTimeout,Fe=A.clearTimeout;function j(e,t){t.useNativeTimers?(e.setTimeoutFn=Pe.bind(A),e.clearTimeoutFn=Fe.bind(A)):(e.setTimeoutFn=A.setTimeout.bind(A),e.clearTimeoutFn=A.clearTimeout.bind(A))}var Ie=1.33;function Le(e){return typeof e==`string`?Re(e):Math.ceil((e.byteLength||e.size)*Ie)}function Re(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function ze(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Be(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ve(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var He=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},M=class extends O{constructor(e){super(),this.writable=!1,j(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new He(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=T(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=Be(e);return t.length?`?`+t:``}},Ue=class extends M{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){De(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,Ee(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ze()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},We=!1;try{We=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Ge=We;function Ke(){}var qe=class extends Ue{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},N=class e extends O{constructor(e,t,n){super(),this.createRequest=e,j(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=Ne(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(this._xhr!==void 0&&this._xhr!==null){if(this._xhr.onreadystatechange=Ke,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(N.requestsCount=0,N.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Je);else if(typeof addEventListener==`function`){let e=`onpagehide`in A?`pagehide`:`unload`;addEventListener(e,Je,!1)}}function Je(){for(let e in N.requests)N.requests.hasOwnProperty(e)&&N.requests[e].abort()}var Ye=(function(){let e=Ze({xdomain:!1});return e&&e.responseType!==null})(),Xe=class extends qe{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Ye&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new N(Ze,this.uri(),e)}};function Ze(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Ge))return new XMLHttpRequest}catch{}if(!t)try{return new A.ActiveXObject(`Microsoft.XMLHTTP`)}catch{}}var Qe=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,$e=class extends M{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Qe?{}:Ne(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;C(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&k(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ze()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},P=A.WebSocket||A.MozWebSocket,et={websocket:class extends $e{createSocket(e,t,n){return Qe?new P(e,t,n):t?new P(e,t):new P(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends M{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Ae(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Oe();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&k(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:Xe},tt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function F(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=tt.exec(e||``),a={},o=14;for(;o--;)a[nt[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=rt(a,a.path),a.queryKey=it(a,a.query),a}function rt(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function it(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var I=typeof addEventListener==`function`&&typeof removeEventListener==`function`,L=[];I&&addEventListener(`offline`,()=>{L.forEach(e=>e())},!1);var R=class e extends O{constructor(e,t){if(super(),this.binaryType=Me,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=F(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=F(t.host).host);j(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=Ve(this.opts.query)),I&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},L.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data)}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=Le(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,k(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),I&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=L.indexOf(this._offlineEventListener);e!==-1&&L.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};R.protocol=4;var at=class extends R{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;R.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n){if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;R.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},ot=class extends at{constructor(e,t={}){let n=typeof e==`object`,r=n?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]==`string`)&&(r.transports=(r.transports||[`polling`,`websocket`,`webtransport`]).map(e=>et[e]).filter(e=>!!e)),super(n?r:e,r)}};ot.protocol;function st(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=F(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var ct=typeof ArrayBuffer==`function`,lt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,ut=Object.prototype.toString,dt=typeof Blob==`function`||typeof Blob<`u`&&ut.call(Blob)===`[object BlobConstructor]`,ft=typeof File==`function`||typeof File<`u`&&ut.call(File)===`[object FileConstructor]`;function z(e){return ct&&(e instanceof ArrayBuffer||lt(e))||dt&&e instanceof Blob||ft&&e instanceof File}function B(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(B(e[t]))return!0;return!1}if(z(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return B(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&B(e[t]))return!0;return!1}function pt(e){let t=[],n=e.data,r=e;return r.data=V(n,t),r.attachments=t.length,{packet:r,buffers:t}}function V(e,t,n){if(!e)return e;if(z(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=V(e[r],t);return n}if(typeof e==`object`&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON==`function`&&!n)return V(e.toJSON(),t,!0);let r={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=V(e[n],t));return r}return e}function mt(e,t){return e.data=H(e.data,t),delete e.attachments,e}function H(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=H(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=H(e[n],t));return e}var ht=t({Decoder:()=>vt,Encoder:()=>_t,PacketType:()=>U,isPacketValid:()=>wt,protocol:()=>5}),gt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],U;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(U||={});var _t=class{constructor(e){this.replacer=e}encode(e){return(e.type===U.EVENT||e.type===U.ACK)&&B(e)?this.encodeAsBinary({type:e.type===U.EVENT?U.BINARY_EVENT:U.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===U.BINARY_EVENT||e.type===U.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=pt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},vt=class e extends O{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===U.BINARY_EVENT;n||t.type===U.BINARY_ACK?(t.type=n?U.EVENT:U.ACK,this.reconstructor=new yt(t)):super.emitReserved(`decoded`,t)}else if(z(e)||e.base64){if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`)}else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(U[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===U.BINARY_EVENT||r.type===U.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!xt(a)||a<1)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&t.charAt(n)!==`,`&&n!==t.length;);r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case U.CONNECT:return W(t);case U.DISCONNECT:return t===void 0;case U.CONNECT_ERROR:return typeof t==`string`||W(t);case U.EVENT:case U.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&>.indexOf(t[0])===-1);case U.ACK:case U.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},yt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=mt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function bt(e){return typeof e==`string`}var xt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function St(e){return e===void 0||xt(e)}function W(e){return Object.prototype.toString.call(e)===`[object Object]`}function Ct(e,t){switch(e){case U.CONNECT:return t===void 0||W(t);case U.DISCONNECT:return t===void 0;case U.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&>.indexOf(t[0])===-1);case U.ACK:return Array.isArray(t);case U.CONNECT_ERROR:return typeof t==`string`||W(t);default:return!1}}function wt(e){return bt(e.nsp)&&St(e.id)&&Ct(e.type,e.data)}function G(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Tt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Et=class extends O{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[G(e,`open`,this.onopen.bind(this)),G(e,`packet`,this.onpacket.bind(this)),G(e,`error`,this.onerror.bind(this)),G(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(Tt.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:U.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:U.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case U.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case U.EVENT:case U.BINARY_EVENT:this.onevent(e);break;case U.ACK:case U.BINARY_ACK:this.onack(e);break;case U.DISCONNECT:this.ondisconnect();break;case U.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t)}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:U.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:U.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function K(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}K.prototype.duration=function(){var e=this.ms*this.factor**+this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},K.prototype.reset=function(){this.attempts=0},K.prototype.setMin=function(e){this.ms=e},K.prototype.setMax=function(e){this.max=e},K.prototype.setJitter=function(e){this.jitter=e};var q=class extends O{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,j(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new K({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||ht;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new ot(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=G(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=G(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(G(e,`ping`,this.onping.bind(this)),G(e,`data`,this.ondata.bind(this)),G(e,`error`,this.onerror.bind(this)),G(e,`close`,this.onclose.bind(this)),G(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){k(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Et(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},J={};function Y(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=st(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=J[i]&&a in J[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new q(r,t):(J[i]||(J[i]=new q(r,t)),c=J[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Y,{Manager:q,Socket:Et,io:Y,connect:Y});function Dt(e){let t=e.replace(/\/$/,``);try{return`${new URL(t).origin}/sdk`}catch{return`${t}/sdk`}}var Ot=class{constructor(){this.socket=null}get connected(){return this.socket?.connected??!1}connect(e){this.disconnect();let t=Dt(e.baseUrl);this.socket=Y(t,{auth:{apiKey:e.apiKey,visitorToken:e.visitorToken},transports:[`websocket`,`polling`],autoConnect:!0,reconnection:!0});let n=!1;this.socket.on(`connect`,()=>{n?e.onReconnect?.():n=!0}),this.socket.on(`ticket:status`,t=>{e.onTicketStatus?.(t)}),this.socket.on(`message:receive`,t=>{e.onMessageReceive?.(t)}),this.socket.on(`connect_error`,t=>{e.onConnectError?.(t)})}disconnect(){this.socket&&=(this.socket.removeAllListeners(),this.socket.disconnect(),null)}},kt=`onedeskpro_visitor_token`;function At(e){try{return typeof window<`u`?window.localStorage.getItem(e):null}catch{return null}}function jt(e,t){try{typeof window<`u`&&window.localStorage.setItem(e,t)}catch{}}function Mt(e){try{typeof window<`u`&&window.localStorage.removeItem(e)}catch{}}var Nt=class{constructor(){this.token=null,this.storageKey=kt}setScope(e){this.storageKey=e?.trim()?`${kt}:${e.trim()}`:kt,this.token=At(this.storageKey)}get(){return this.token??At(this.storageKey)}set(e){this.token=e,jt(this.storageKey,e)}clear(){this.token=null,Mt(this.storageKey)}},Pt=300,Ft=250,It=100,Lt=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/ogg;codecs=opus`];function Rt(){return typeof MediaRecorder>`u`||typeof MediaRecorder.isTypeSupported!=`function`?`audio/webm`:Lt.find(e=>MediaRecorder.isTypeSupported(e))??`audio/webm`}function zt(e){let t=e instanceof DOMException?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||t===`SecurityError`?`Microphone access was denied.`:t===`NotFoundError`||t===`DevicesNotFoundError`?`No microphone was found.`:`Could not start recording.`}var Bt=class e{constructor(e,t=300){this.onChange=e,this.maxDurationSeconds=t,this.recorder=null,this.stream=null,this.chunks=[],this.mimeType=`audio/webm`,this.startedAt=0,this.tickTimer=null,this.levelTimer=null,this.maxTimer=null,this.audioContext=null,this.analyser=null,this.snapshot={state:`idle`,elapsedSeconds:0,level:0,result:null}}static isSupported(){return typeof navigator<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`&&typeof MediaRecorder<`u`}getSnapshot(){return{...this.snapshot}}async start(){if(!e.isSupported())throw Error(`Voice messages are not supported in this browser.`);this.release(),this.chunks=[];let t;try{t=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){throw Error(zt(e))}try{this.mimeType=Rt();let e=new MediaRecorder(t,{mimeType:this.mimeType});e.ondataavailable=e=>{e.data.size>0&&this.chunks.push(e.data)},this.stream=t,this.recorder=e,this.startedAt=Date.now(),e.start(200)}catch(e){throw t.getTracks().forEach(e=>e.stop()),this.stream=null,this.recorder=null,Error(zt(e))}this.startLevelMeter(t),this.tickTimer=setInterval(()=>{this.update({elapsedSeconds:Math.floor(this.elapsedMs()/1e3)})},Ft),this.maxTimer=setTimeout(()=>void this.stop(),this.maxDurationSeconds*1e3),this.update({state:`recording`,elapsedSeconds:0,level:0,result:null})}async stop(){let e=this.recorder;if(!e||e.state===`inactive`)return this.release(),null;let t=Math.max(1,Math.round(this.elapsedMs()/1e3));this.clearTimers();let n=await new Promise(t=>{e.onstop=()=>{let e=this.chunks;this.chunks=[],t(new Blob(e,{type:v(this.mimeType)}))};try{e.stop()}catch{t(new Blob(this.chunks,{type:v(this.mimeType)}))}});this.releaseMedia();let r={blob:n,mimeType:v(this.mimeType),durationSeconds:t};return this.update({state:`preview`,elapsedSeconds:t,level:0,result:r}),r}cancel(){this.release(),this.update({state:`idle`,elapsedSeconds:0,level:0,result:null})}destroy(){this.release(),this.snapshot={state:`idle`,elapsedSeconds:0,level:0,result:null}}update(e){this.snapshot={...this.snapshot,...e},this.onChange({...this.snapshot})}elapsedMs(){return this.startedAt>0?Date.now()-this.startedAt:0}startLevelMeter(e){let t=typeof window>`u`?null:window,n=t?.AudioContext??t?.webkitAudioContext;if(n)try{let t=new n,r=t.createAnalyser();r.fftSize=256,t.createMediaStreamSource(e).connect(r),t.resume().catch(()=>void 0),this.audioContext=t,this.analyser=r;let i=new Uint8Array(r.frequencyBinCount);this.levelTimer=setInterval(()=>{r.getByteTimeDomainData(i);let e=0;for(let t=0;t<i.length;t++){let n=((i[t]??128)-128)/128;e+=n*n}this.update({level:Math.min(1,Math.sqrt(e/i.length)*3.2)})},It)}catch{}}clearTimers(){this.tickTimer&&clearInterval(this.tickTimer),this.levelTimer&&clearInterval(this.levelTimer),this.maxTimer&&clearTimeout(this.maxTimer),this.tickTimer=null,this.levelTimer=null,this.maxTimer=null}releaseMedia(){this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,this.recorder=null,this.analyser=null,this.audioContext&&=(this.audioContext.close().catch(()=>void 0),null),this.startedAt=0}release(){if(this.clearTimers(),this.recorder&&this.recorder.state!==`inactive`){this.recorder.onstop=null;try{this.recorder.stop()}catch{}}this.chunks=[],this.releaseMedia()}},Vt=[{iso:`BD`,name:`Bangladesh`,dial:`880`,flag:`🇧🇩`},{iso:`US`,name:`United States`,dial:`1`,flag:`🇺🇸`},{iso:`GB`,name:`United Kingdom`,dial:`44`,flag:`🇬🇧`},{iso:`IN`,name:`India`,dial:`91`,flag:`🇮🇳`},{iso:`PK`,name:`Pakistan`,dial:`92`,flag:`🇵🇰`},{iso:`AE`,name:`United Arab Emirates`,dial:`971`,flag:`🇦🇪`},{iso:`SA`,name:`Saudi Arabia`,dial:`966`,flag:`🇸🇦`},{iso:`CA`,name:`Canada`,dial:`1`,flag:`🇨🇦`},{iso:`AU`,name:`Australia`,dial:`61`,flag:`🇦🇺`},{iso:`DE`,name:`Germany`,dial:`49`,flag:`🇩🇪`},{iso:`FR`,name:`France`,dial:`33`,flag:`🇫🇷`},{iso:`IT`,name:`Italy`,dial:`39`,flag:`🇮🇹`},{iso:`ES`,name:`Spain`,dial:`34`,flag:`🇪🇸`},{iso:`NL`,name:`Netherlands`,dial:`31`,flag:`🇳🇱`},{iso:`SE`,name:`Sweden`,dial:`46`,flag:`🇸🇪`},{iso:`NO`,name:`Norway`,dial:`47`,flag:`🇳🇴`},{iso:`DK`,name:`Denmark`,dial:`45`,flag:`🇩🇰`},{iso:`FI`,name:`Finland`,dial:`358`,flag:`🇫🇮`},{iso:`IE`,name:`Ireland`,dial:`353`,flag:`🇮🇪`},{iso:`CH`,name:`Switzerland`,dial:`41`,flag:`🇨🇭`},{iso:`AT`,name:`Austria`,dial:`43`,flag:`🇦🇹`},{iso:`BE`,name:`Belgium`,dial:`32`,flag:`🇧🇪`},{iso:`PT`,name:`Portugal`,dial:`351`,flag:`🇵🇹`},{iso:`PL`,name:`Poland`,dial:`48`,flag:`🇵🇱`},{iso:`CZ`,name:`Czechia`,dial:`420`,flag:`🇨🇿`},{iso:`RO`,name:`Romania`,dial:`40`,flag:`🇷🇴`},{iso:`HU`,name:`Hungary`,dial:`36`,flag:`🇭🇺`},{iso:`GR`,name:`Greece`,dial:`30`,flag:`🇬🇷`},{iso:`TR`,name:`Turkey`,dial:`90`,flag:`🇹🇷`},{iso:`RU`,name:`Russia`,dial:`7`,flag:`🇷🇺`},{iso:`UA`,name:`Ukraine`,dial:`380`,flag:`🇺🇦`},{iso:`CN`,name:`China`,dial:`86`,flag:`🇨🇳`},{iso:`JP`,name:`Japan`,dial:`81`,flag:`🇯🇵`},{iso:`KR`,name:`South Korea`,dial:`82`,flag:`🇰🇷`},{iso:`SG`,name:`Singapore`,dial:`65`,flag:`🇸🇬`},{iso:`MY`,name:`Malaysia`,dial:`60`,flag:`🇲🇾`},{iso:`ID`,name:`Indonesia`,dial:`62`,flag:`🇮🇩`},{iso:`TH`,name:`Thailand`,dial:`66`,flag:`🇹🇭`},{iso:`VN`,name:`Vietnam`,dial:`84`,flag:`🇻🇳`},{iso:`PH`,name:`Philippines`,dial:`63`,flag:`🇵🇭`},{iso:`HK`,name:`Hong Kong`,dial:`852`,flag:`🇭🇰`},{iso:`TW`,name:`Taiwan`,dial:`886`,flag:`🇹🇼`},{iso:`NZ`,name:`New Zealand`,dial:`64`,flag:`🇳🇿`},{iso:`ZA`,name:`South Africa`,dial:`27`,flag:`🇿🇦`},{iso:`NG`,name:`Nigeria`,dial:`234`,flag:`🇳🇬`},{iso:`KE`,name:`Kenya`,dial:`254`,flag:`🇰🇪`},{iso:`EG`,name:`Egypt`,dial:`20`,flag:`🇪🇬`},{iso:`MA`,name:`Morocco`,dial:`212`,flag:`🇲🇦`},{iso:`BR`,name:`Brazil`,dial:`55`,flag:`🇧🇷`},{iso:`MX`,name:`Mexico`,dial:`52`,flag:`🇲🇽`},{iso:`AR`,name:`Argentina`,dial:`54`,flag:`🇦🇷`},{iso:`CL`,name:`Chile`,dial:`56`,flag:`🇨🇱`},{iso:`CO`,name:`Colombia`,dial:`57`,flag:`🇨🇴`},{iso:`PE`,name:`Peru`,dial:`51`,flag:`🇵🇪`},{iso:`IL`,name:`Israel`,dial:`972`,flag:`🇮🇱`},{iso:`QA`,name:`Qatar`,dial:`974`,flag:`🇶🇦`},{iso:`KW`,name:`Kuwait`,dial:`965`,flag:`🇰🇼`},{iso:`BH`,name:`Bahrain`,dial:`973`,flag:`🇧🇭`},{iso:`OM`,name:`Oman`,dial:`968`,flag:`🇴🇲`},{iso:`LK`,name:`Sri Lanka`,dial:`94`,flag:`🇱🇰`},{iso:`NP`,name:`Nepal`,dial:`977`,flag:`🇳🇵`}],Ht=Vt.find(e=>e.iso===`BD`)??Vt[0];function Ut(e,t){let n=t.trim();if(n.startsWith(`+`)){let e=n.replace(/\D/g,``);return e?`+${e}`:``}let r=n.replace(/\D/g,``);return!r||(r=r.replace(/^0+/,``),!r)?``:`+${e}${r}`}var Wt=`(max-width: 640px), (max-height: 500px) and (pointer: coarse)`;function Gt(e,t){let n=`
|
|
2
2
|
--ttcb-bg: #ffffff;
|
|
3
3
|
--ttcb-bg-secondary: #f3f4f6;
|
|
4
4
|
--ttcb-text: #111827;
|
|
@@ -662,7 +662,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
662
662
|
|
|
663
663
|
.ttcb-footer.hidden, .ttcb-messages.hidden { display: none; }
|
|
664
664
|
|
|
665
|
-
@media ${
|
|
665
|
+
@media ${Wt} {
|
|
666
666
|
.ttcb-fab.bottom-right { right: 16px; bottom: calc(16px + env(safe-area-inset-bottom, 0px)); }
|
|
667
667
|
.ttcb-fab.bottom-left { left: 16px; bottom: calc(16px + env(safe-area-inset-bottom, 0px)); }
|
|
668
668
|
/* The open panel covers the launcher; its own close button takes over. */
|
|
@@ -726,75 +726,75 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
726
726
|
.ttcb-phone-national,
|
|
727
727
|
.ttcb-country-search { font-size: 16px; }
|
|
728
728
|
}
|
|
729
|
-
`}function
|
|
729
|
+
`}function Kt(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}function qt(e){let t=[],n=e.replace(/```[\w]*\n?([\s\S]*?)```/g,(e,n)=>{let r=t.length;return t.push(`<pre><code>${Kt(n.trim())}</code></pre>`),`\x04${r}\x05`});n=n.replace(/`([^`\n]+)`/g,(e,n)=>{let r=t.length;return t.push(`<code>${Kt(n)}</code>`),`\x02${r}\x03`}),n=Kt(n);let r=n.split(`
|
|
730
730
|
`),i=[],a=``,o=()=>{a&&=(i.push(`</${a}>`),``)};for(let e of r){let t;(t=e.match(/^### (.+)/))?(o(),i.push(`<h3>${t[1]}</h3>`)):(t=e.match(/^## (.+)/))?(o(),i.push(`<h2>${t[1]}</h2>`)):(t=e.match(/^# (.+)/))?(o(),i.push(`<h1>${t[1]}</h1>`)):(t=e.match(/^[*-] (.+)/))?(a!==`ul`&&(o(),i.push(`<ul>`),a=`ul`),i.push(`<li>${t[1]}</li>`)):(t=e.match(/^\d+\. (.+)/))?(a!==`ol`&&(o(),i.push(`<ol>`),a=`ol`),i.push(`<li>${t[1]}</li>`)):(o(),i.push(e))}return o(),n=i.join(`
|
|
731
|
-
`),n=n.replace(/\*\*(.+?)\*\*/gs,`<strong>$1</strong>`).replace(/__(.+?)__/gs,`<strong>$1</strong>`).replace(/\*(.+?)\*/gs,`<em>$1</em>`).replace(/_(.+?)_/gs,`<em>$1</em>`).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`),n=n.split(/\n{2,}/).map(e=>{let t=e.trim();return t?/^<(h[1-3]|ul|ol|pre|li)/.test(t)?t:t.split(/(\x04\d+\x05)/g).map(e=>{if(/^\x04\d+\x05$/.test(e))return e;let t=e.trim();return t?`<p>${t.replace(/\n/g,`<br>`)}</p>`:``}).join(``):``}).filter(Boolean).join(``),n=n.replace(/\x04(\d+)\x05/g,(e,n)=>t[+n]??``).replace(/\x02(\d+)\x03/g,(e,n)=>t[+n]??``),n}function
|
|
731
|
+
`),n=n.replace(/\*\*(.+?)\*\*/gs,`<strong>$1</strong>`).replace(/__(.+?)__/gs,`<strong>$1</strong>`).replace(/\*(.+?)\*/gs,`<em>$1</em>`).replace(/_(.+?)_/gs,`<em>$1</em>`).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`),n=n.split(/\n{2,}/).map(e=>{let t=e.trim();return t?/^<(h[1-3]|ul|ol|pre|li)/.test(t)?t:t.split(/(\x04\d+\x05)/g).map(e=>{if(/^\x04\d+\x05$/.test(e))return e;let t=e.trim();return t?`<p>${t.replace(/\n/g,`<br>`)}</p>`:``}).join(``):``}).filter(Boolean).join(``),n=n.replace(/\x04(\d+)\x05/g,(e,n)=>t[+n]??``).replace(/\x02(\d+)\x03/g,(e,n)=>t[+n]??``),n}function Jt(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
732
732
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
|
733
733
|
<line x1="12" y1="8" x2="12" y2="14"/>
|
|
734
734
|
<line x1="9" y1="11" x2="15" y2="11"/>
|
|
735
|
-
</svg>`}function Jt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
736
|
-
<path d="M20 2H4C2.9 2 2 2.9 2 4v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
|
|
737
735
|
</svg>`}function Yt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
738
|
-
<path d="
|
|
736
|
+
<path d="M20 2H4C2.9 2 2 2.9 2 4v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
|
|
739
737
|
</svg>`}function Xt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
738
|
+
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
|
|
739
|
+
</svg>`}function Zt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
740
740
|
<path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
|
|
741
|
-
</svg>`}function
|
|
741
|
+
</svg>`}function X(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
742
742
|
<path d="M20 9V7c0-1.1-.9-2-2-2h-3c0-1.66-1.34-3-3-3S9 3.34 9 5H6c-1.1 0-2 .9-2 2v2c-1.66 0-3 1.34-3 3s1.34 3 3 3v4c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-4c1.66 0 3-1.34 3-3s-1.34-3-3-3zm-2 10H6V7h12v12zm-9-6c-.83 0-1.5-.67-1.5-1.5S8.17 10 9 10s1.5.67 1.5 1.5S9.83 13 9 13zm6 0c-.83 0-1.5-.67-1.5-1.5S14.17 10 15 10s1.5.67 1.5 1.5S15.83 13 15 13z"/>
|
|
743
|
-
</svg>`}function
|
|
743
|
+
</svg>`}function Qt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
744
744
|
<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
|
|
745
|
-
</svg>`}function
|
|
745
|
+
</svg>`}function $t(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
746
746
|
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
|
|
747
747
|
<circle cx="12" cy="7" r="4"/>
|
|
748
|
-
</svg>`}function
|
|
748
|
+
</svg>`}function en(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
749
749
|
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
|
|
750
750
|
<polyline points="22,6 12,13 2,6"/>
|
|
751
|
-
</svg>`}function
|
|
751
|
+
</svg>`}function tn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
752
752
|
<polyline points="6 9 12 15 18 9"/>
|
|
753
|
-
</svg>`}function
|
|
753
|
+
</svg>`}function nn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
754
754
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
755
755
|
<polyline points="12 5 19 12 12 19"/>
|
|
756
|
-
</svg>`}function
|
|
756
|
+
</svg>`}function rn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
757
757
|
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
|
758
758
|
<polyline points="9 12 11 14 15 10"/>
|
|
759
|
-
</svg>`}function
|
|
759
|
+
</svg>`}function an(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
760
760
|
<circle cx="12" cy="12" r="10" fill="currentColor"/>
|
|
761
761
|
<path d="M9 12l2 2 4-4" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
|
|
762
|
-
</svg>`}function
|
|
762
|
+
</svg>`}function on(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
763
763
|
<path fill="#F59E0B" d="M8 2.5l1.1 2.2 2.4.3-1.7 1.7.4 2.4L8 8l-2.2 1.1.4-2.4L4.5 5l2.4-.3L8 2.5z"/>
|
|
764
764
|
<path fill="#F59E0B" d="M16 3.5l.8 1.6 1.8.2-1.3 1.3.3 1.8L16 7.5l-1.6.9.3-1.8-1.3-1.3 1.8-.2L16 3.5z"/>
|
|
765
765
|
<path fill="#FBBF24" d="M12 11.5l1 2 2.2.3-1.6 1.6.4 2.2-2-1.1-2 1.1.4-2.2-1.6-1.6 2.2-.3 1-2z"/>
|
|
766
|
-
</svg>`}function
|
|
766
|
+
</svg>`}function sn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
767
767
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
|
768
768
|
<circle cx="9" cy="7" r="4"/>
|
|
769
769
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
|
770
770
|
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
|
771
|
-
</svg>`}function
|
|
771
|
+
</svg>`}function cn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
772
772
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
773
773
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
774
|
-
</svg>`}function cn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
775
|
-
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
|
|
776
774
|
</svg>`}function ln(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
775
|
+
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
|
|
776
|
+
</svg>`}function un(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
777
777
|
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
|
|
778
778
|
<circle cx="8.5" cy="8.5" r="1.5"/>
|
|
779
779
|
<polyline points="21 15 16 10 5 21"/>
|
|
780
|
-
</svg>`}function
|
|
780
|
+
</svg>`}function dn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
781
781
|
<path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>
|
|
782
782
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
|
|
783
783
|
<line x1="12" y1="19" x2="12" y2="23"/>
|
|
784
784
|
<line x1="8" y1="23" x2="16" y2="23"/>
|
|
785
|
-
</svg>`}function
|
|
785
|
+
</svg>`}function fn(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
786
786
|
<rect x="6" y="6" width="12" height="12" rx="2" fill="currentColor"/>
|
|
787
|
-
</svg>`}function
|
|
787
|
+
</svg>`}function pn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
788
788
|
<polyline points="3 6 5 6 21 6"/>
|
|
789
789
|
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
|
|
790
790
|
<path d="M10 11v6"/>
|
|
791
791
|
<path d="M14 11v6"/>
|
|
792
792
|
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>
|
|
793
|
-
</svg>`}function
|
|
793
|
+
</svg>`}function mn(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
794
794
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
795
795
|
<polyline points="14 2 14 8 20 8"/>
|
|
796
|
-
</svg>`}function mn(e){let t=m(e.url)?e.url:``,n=e.type.toLowerCase();if(t&&n.startsWith(`image/`)){let n=document.createElement(`a`);n.className=`ttcb-attachment ttcb-attachment-image`,n.href=t,n.target=`_blank`,n.rel=`noopener noreferrer`,n.setAttribute(`aria-label`,`Open ${e.fileName}`);let r=document.createElement(`img`);return r.src=t,r.alt=e.fileName,r.loading=`lazy`,n.appendChild(r),n}if(t&&n.startsWith(`video/`)){let n=document.createElement(`video`);return n.className=`ttcb-attachment ttcb-attachment-video`,n.controls=!0,n.preload=`metadata`,n.src=t,n.setAttribute(`aria-label`,e.fileName),n}if(t&&n.startsWith(`audio/`)){let n=document.createElement(`div`);n.className=`ttcb-attachment ttcb-attachment-voice`;let r=document.createElement(`audio`);if(r.className=`ttcb-attachment-audio`,r.controls=!0,r.preload=`metadata`,r.src=t,r.setAttribute(`aria-label`,e.fileName),n.appendChild(r),typeof e.durationSeconds==`number`&&e.durationSeconds>0){let t=document.createElement(`span`);t.className=`ttcb-attachment-duration`,t.textContent=y(e.durationSeconds),n.appendChild(t)}return n}let r=document.createElement(t?`a`:`div`);r.className=`ttcb-attachment ttcb-attachment-file`,r instanceof HTMLAnchorElement&&(r.href=t,r.target=`_blank`,r.rel=`noopener noreferrer`);let i=document.createElement(`span`);i.className=`ttcb-attachment-icon`,i.setAttribute(`aria-hidden`,`true`),i.innerHTML=pn();let a=document.createElement(`span`);a.className=`ttcb-attachment-meta`;let o=document.createElement(`span`);o.className=`ttcb-attachment-name`,o.textContent=e.fileName,a.appendChild(o);let s=te(e.size);if(s){let e=document.createElement(`span`);e.className=`ttcb-attachment-size`,e.textContent=s,a.appendChild(e)}return r.appendChild(i),r.appendChild(a),r}function hn(e){let{type:t,content:n}=e,r=e.attachments??[],i=document.createElement(`div`);i.className=`ttcb-msg ${t}`,e.pending&&i.classList.add(`ttcb-pending`);let a=document.createElement(`div`);a.className=`ttcb-msg-avatar`,a.innerHTML=t===`human`?Zt():t===`agent`?Qt():Z();let o=document.createElement(`div`);if(o.className=`ttcb-msg-body`,t===`agent`){let e=document.createElement(`span`);e.className=`ttcb-msg-label`,e.textContent=`Agent`,o.appendChild(e)}if(r.length>0){let e=document.createElement(`div`);e.className=`ttcb-attachments`;for(let t of r)e.appendChild(mn(t));o.appendChild(e)}if(r.length===0||!re(n,r)){let e=document.createElement(`div`);e.className=`ttcb-bubble`,t===`human`?e.textContent=n:e.innerHTML=Kt(n),o.appendChild(e)}if(e.pending){let e=document.createElement(`span`);e.className=`ttcb-msg-status`,e.textContent=`Uploading…`,o.appendChild(e)}return i.appendChild(a),i.appendChild(o),i}function gn(){let e=document.createElement(`div`);e.className=`ttcb-msg ai`,e.id=`ttcb-typing`;let t=document.createElement(`div`);t.className=`ttcb-msg-avatar`,t.innerHTML=Z();let n=document.createElement(`div`);return n.className=`ttcb-typing`,n.innerHTML=`<span></span><span></span><span></span>`,e.appendChild(t),e.appendChild(n),e}var _n=`image/jpeg,image/png,image/gif,video/mp4,video/webm,audio/ogg,audio/mpeg,audio/wav,audio/x-m4a,audio/aac,audio/opus,application/pdf,text/csv`,vn=`image/jpeg,image/png,image/gif`,yn=class{constructor(e,t){this.stopViewportSync=null,this.confirmingNew=!1,this.actionPending=!1,this.ticketMode=`ai`,this.pendingFiles=[],this.attachMenuOpen=!1,this.recorder=null,this.voicePreviewUrl=``,this.selectedCountry=Vt,this.countryOpen=!1,this.isOpen=!1,this.destroyed=!1,this.position=e.position??`bottom-right`,this.callbacks=t,this.autoOpen=e.autoOpen===!0,this.mount(e)}mount(e){this.host=document.createElement(`div`),this.host.id=`onedeskpro-chatbot-host`,this.host.style.display=`none`,this.shadow=this.host.attachShadow({mode:`closed`});let t=document.createElement(`style`);t.textContent=Wt(e.primaryColor??`#2563EB`,e.theme??`auto`),this.shadow.appendChild(t),this.fab=document.createElement(`button`),this.fab.className=`ttcb-fab ${this.position}`,this.fab.setAttribute(`aria-label`,`Open chat`),this.fab.innerHTML=Jt(),this.fab.addEventListener(`click`,()=>this.toggle()),this.shadow.appendChild(this.fab),this.panel=document.createElement(`div`),this.panel.className=`ttcb-panel ${this.position} hidden ttcb-mode-compact`,this.panel.tabIndex=-1,this.panel.setAttribute(`role`,`dialog`),this.panel.setAttribute(`aria-modal`,`true`),this.panel.setAttribute(`aria-label`,e.chatbotName??`AI Assistant`),this.panel.appendChild(this.buildHeader(e)),this.identifyContainer=document.createElement(`div`),this.identifyContainer.className=`ttcb-identify`,this.buildIdentifyForm(this.identifyContainer),this.panel.appendChild(this.identifyContainer),this.messagesContainer=document.createElement(`div`),this.messagesContainer.className=`ttcb-messages`,this.messagesContainer.setAttribute(`aria-live`,`polite`),this.messagesContainer.setAttribute(`aria-label`,`Chat messages`),this.panel.appendChild(this.messagesContainer),this.modeBanner=document.createElement(`div`),this.modeBanner.className=`ttcb-mode-banner`,this.modeBannerText=document.createElement(`span`),this.modeBannerText.className=`ttcb-mode-banner-text`,this.modeBannerText.setAttribute(`role`,`status`),this.cancelHumanBtn=this.buildBannerButton(`Cancel request`,()=>{this.actionPending||this.callbacks.onCancelHumanRequest()}),this.cancelHumanBtn.classList.add(`hidden`),this.modeBanner.appendChild(this.modeBannerText),this.modeBanner.appendChild(this.cancelHumanBtn),this.panel.appendChild(this.modeBanner),this.panel.appendChild(this.buildConfirmNewBar()),this.footer=document.createElement(`div`),this.footer.className=`ttcb-footer`,this.pendingTray=document.createElement(`div`),this.pendingTray.className=`ttcb-pending-tray`,this.pendingTray.setAttribute(`role`,`list`),this.pendingTray.setAttribute(`aria-label`,`Files to send`),this.footer.appendChild(this.pendingTray),this.composeError=document.createElement(`p`),this.composeError.className=`ttcb-compose-error`,this.composeError.setAttribute(`role`,`alert`),this.footer.appendChild(this.composeError),this.footer.appendChild(this.buildVoiceBar()),this.footer.appendChild(this.buildVoicePreview());let n=document.createElement(`form`);n.className=`ttcb-form`,n.addEventListener(`submit`,e=>{e.preventDefault(),this.handleSend()}),this.composeForm=n,n.appendChild(this.buildAttachControls()),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`ttcb-input`,this.input.placeholder=e.placeholder??`Type your message…`,this.input.setAttribute(`aria-label`,`Message input`),this.input.setAttribute(`autocomplete`,`off`),this.sendBtn=document.createElement(`button`),this.sendBtn.type=`submit`,this.sendBtn.className=`ttcb-send-btn`,this.sendBtn.innerHTML=Xt(),this.sendBtn.setAttribute(`aria-label`,`Send message`),this.micBtn=document.createElement(`button`),this.micBtn.type=`button`,this.micBtn.className=`ttcb-mic-btn`,this.micBtn.setAttribute(`aria-label`,`Record voice message`),this.micBtn.title=`Record voice message`,this.micBtn.innerHTML=un(),this.micBtn.addEventListener(`click`,()=>void this.startVoice()),n.appendChild(this.input),n.appendChild(this.micBtn),n.appendChild(this.sendBtn),this.footer.appendChild(n),this.panel.appendChild(this.footer),this.shadow.appendChild(this.panel),this.shadow.addEventListener(`click`,e=>{let t=e.target;this.attachMenuOpen&&!(t&&(this.attachBtn.contains(t)||this.attachMenu.contains(t)))&&this.closeAttachMenu(),this.countryOpen&&(t&&(this.dialBtn.contains(t)||this.countryPopover.contains(t))||this.closeCountryPopover())}),this.panel.addEventListener(`keydown`,e=>{e.key===`Escape`&&this.attachMenuOpen?(e.stopPropagation(),this.closeAttachMenu(),this.attachBtn.focus()):e.key===`Escape`&&this.confirmingNew&&(e.stopPropagation(),this.hideConfirmNew(),this.newSessionBtn.focus())}),this.attachToDocument(),this.showInitialLoading()}reveal(){this.host.style.removeProperty(`display`),this.autoOpen&&!this.isOpen&&this.open()}buildHeader(e){let t=document.createElement(`div`);t.className=`ttcb-header`;let n=document.createElement(`div`);n.className=`ttcb-avatar-wrap`;let r=document.createElement(`div`);r.className=`ttcb-avatar`,r.innerHTML=Z(),n.appendChild(r);let i=document.createElement(`div`);i.className=`ttcb-header-main`;let a=document.createElement(`div`);a.className=`ttcb-header-title-row`,this.headerTitle=document.createElement(`span`),this.headerTitle.className=`ttcb-header-title`,this.headerTitle.textContent=e.chatbotName??`AI Assistant`;let o=document.createElement(`span`);o.className=`ttcb-verified`,o.setAttribute(`aria-label`,`Verified`),o.innerHTML=rn(),a.appendChild(this.headerTitle),a.appendChild(o);let s=document.createElement(`div`);s.className=`ttcb-header-meta`;let c=document.createElement(`span`);c.className=`ttcb-meta-online`,c.textContent=`Online`;let l=document.createElement(`span`);l.className=`ttcb-meta-sep`,l.setAttribute(`aria-hidden`,`true`);let u=document.createElement(`span`);u.className=`ttcb-meta-replies`,u.innerHTML=`${an()}<span>Replies instantly</span>`,s.appendChild(c),s.appendChild(l),s.appendChild(u),i.appendChild(a),i.appendChild(s);let d=document.createElement(`div`);d.className=`ttcb-header-actions`,this.requestHumanBtn=document.createElement(`button`),this.requestHumanBtn.type=`button`,this.requestHumanBtn.className=`ttcb-request-human-btn hidden`,this.requestHumanBtn.id=`ttcb-request-human-btn`,this.requestHumanBtn.setAttribute(`aria-label`,`Request human agent`),this.requestHumanBtn.title=`Request human agent`,this.requestHumanBtn.innerHTML=on(),this.requestHumanBtn.addEventListener(`click`,()=>this.callbacks.onRequestHuman()),this.newSessionBtn=document.createElement(`button`),this.newSessionBtn.type=`button`,this.newSessionBtn.className=`ttcb-new-session-btn hidden`,this.newSessionBtn.setAttribute(`aria-label`,`New conversation`),this.newSessionBtn.title=`New conversation`,this.newSessionBtn.innerHTML=qt(),this.newSessionBtn.addEventListener(`click`,()=>{this.actionPending||(this.ticketMode===`closed`?this.callbacks.onNewConversation():this.showConfirmNew())});let f=document.createElement(`button`);return f.className=`ttcb-close-btn`,f.setAttribute(`aria-label`,`Close chat`),f.innerHTML=Yt(),f.addEventListener(`click`,()=>this.close()),d.appendChild(this.requestHumanBtn),d.appendChild(this.newSessionBtn),d.appendChild(f),t.appendChild(n),t.appendChild(i),t.appendChild(d),t}buildBannerButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`ttcb-banner-btn`,n.textContent=e,n.addEventListener(`click`,t),n}buildConfirmNewBar(){this.confirmNewBar=document.createElement(`div`),this.confirmNewBar.className=`ttcb-confirm-bar`,this.confirmNewBar.setAttribute(`role`,`group`),this.confirmNewBar.setAttribute(`aria-label`,`Start a new conversation`);let e=document.createElement(`span`);e.className=`ttcb-confirm-text`,e.textContent=`End this conversation and start a new one?`,this.confirmNewBtn=this.buildBannerButton(`Start new`,()=>{this.actionPending||(this.hideConfirmNew(),this.input.focus(),this.callbacks.onNewConversation())}),this.confirmNewBtn.classList.add(`primary`),this.keepChattingBtn=this.buildBannerButton(`Keep chatting`,()=>{this.hideConfirmNew(),this.newSessionBtn.focus()});let t=document.createElement(`div`);return t.className=`ttcb-confirm-actions`,t.appendChild(this.confirmNewBtn),t.appendChild(this.keepChattingBtn),this.confirmNewBar.appendChild(e),this.confirmNewBar.appendChild(t),this.confirmNewBar}showConfirmNew(){this.confirmingNew=!0,this.confirmNewBar.classList.add(`visible`),queueMicrotask(()=>this.keepChattingBtn.focus())}hideConfirmNew(){this.confirmingNew=!1,this.confirmNewBar.classList.remove(`visible`)}setActionPending(e){this.actionPending=e;for(let t of[this.newSessionBtn,this.cancelHumanBtn,this.confirmNewBtn])t.setAttribute(`aria-disabled`,String(e))}buildAttachControls(){let e=document.createElement(`div`);e.className=`ttcb-attach`,this.attachBtn=document.createElement(`button`),this.attachBtn.type=`button`,this.attachBtn.className=`ttcb-attach-btn`,this.attachBtn.setAttribute(`aria-label`,`Add attachment`),this.attachBtn.setAttribute(`aria-haspopup`,`menu`),this.attachBtn.setAttribute(`aria-expanded`,`false`),this.attachBtn.title=`Add attachment`,this.attachBtn.innerHTML=sn(),this.attachBtn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleAttachMenu()}),this.attachMenu=document.createElement(`div`),this.attachMenu.className=`ttcb-attach-menu`,this.attachMenu.setAttribute(`role`,`menu`),this.attachFileInput=this.createFileInput(_n,`Choose files`),this.attachPhotoInput=this.createFileInput(vn,`Choose photos`);let t=[{label:`Attachment`,icon:cn(),input:this.attachFileInput},{label:`Photo`,icon:ln(),input:this.attachPhotoInput}];for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`ttcb-attach-item`,t.setAttribute(`role`,`menuitem`),t.innerHTML=`${e.icon}<span>${e.label}</span>`,t.addEventListener(`click`,()=>{this.closeAttachMenu(),e.input.click()}),this.attachMenu.appendChild(t)}return e.appendChild(this.attachBtn),e.appendChild(this.attachMenu),e.appendChild(this.attachFileInput),e.appendChild(this.attachPhotoInput),e}createFileInput(e,t){let n=document.createElement(`input`);return n.type=`file`,n.multiple=!0,n.accept=e,n.className=`ttcb-file-input`,n.tabIndex=-1,n.setAttribute(`aria-label`,t),n.addEventListener(`change`,()=>{this.addPendingFiles(Array.from(n.files??[])),n.value=``}),n}toggleAttachMenu(){this.attachMenuOpen?this.closeAttachMenu():this.openAttachMenu()}openAttachMenu(){if(this.attachBtn.disabled)return;this.attachMenuOpen=!0,this.attachMenu.classList.add(`open`),this.attachBtn.setAttribute(`aria-expanded`,`true`);let e=this.attachMenu.querySelector(`.ttcb-attach-item`);queueMicrotask(()=>e?.focus())}closeAttachMenu(){this.attachMenuOpen&&(this.attachMenuOpen=!1,this.attachMenu.classList.remove(`open`),this.attachBtn.setAttribute(`aria-expanded`,`false`))}addPendingFiles(e){if(e.length===0)return;let t=p([...this.pendingFiles.map(e=>e.file),...e]);if(t)this.showComposeError(t);else{this.showComposeError(``);for(let t of e){let e=t.type.startsWith(`image/`)?h(t):``;this.pendingFiles.push({file:t,previewUrl:e})}this.renderPendingTray(),this.input.focus()}}removePendingFile(e){let[t]=this.pendingFiles.splice(e,1);t&&g(t.previewUrl),this.renderPendingTray(),this.input.focus()}clearPendingFiles(){for(let e of this.pendingFiles)g(e.previewUrl);this.pendingFiles=[],this.renderPendingTray()}renderPendingTray(){this.pendingTray.innerHTML=``,this.pendingTray.classList.toggle(`visible`,this.pendingFiles.length>0),this.pendingFiles.forEach((e,t)=>{let n=document.createElement(`div`);if(n.className=`ttcb-pending-item`,n.setAttribute(`role`,`listitem`),e.previewUrl){let t=document.createElement(`img`);t.className=`ttcb-pending-thumb`,t.src=e.previewUrl,t.alt=``,n.appendChild(t)}else{let e=document.createElement(`span`);e.className=`ttcb-pending-icon`,e.setAttribute(`aria-hidden`,`true`),e.innerHTML=pn(),n.appendChild(e)}let r=document.createElement(`span`);r.className=`ttcb-pending-name`,r.textContent=e.file.name||`attachment`,r.title=e.file.name,n.appendChild(r);let i=document.createElement(`button`);i.type=`button`,i.className=`ttcb-pending-remove`,i.setAttribute(`aria-label`,`Remove ${e.file.name||`attachment`}`),i.innerHTML=Yt(),i.addEventListener(`click`,()=>this.removePendingFile(t)),n.appendChild(i),this.pendingTray.appendChild(n)})}buildVoiceBar(){this.voiceBar=document.createElement(`div`),this.voiceBar.className=`ttcb-voice-bar`,this.voiceBar.setAttribute(`role`,`group`),this.voiceBar.setAttribute(`aria-label`,`Recording voice message`);let e=document.createElement(`span`);e.className=`ttcb-voice-dot`,e.setAttribute(`aria-hidden`,`true`),this.voiceTime=document.createElement(`span`),this.voiceTime.className=`ttcb-voice-time`,this.voiceTime.setAttribute(`role`,`timer`),this.voiceTime.textContent=`0:00`;let t=document.createElement(`div`);return t.className=`ttcb-voice-meter`,t.setAttribute(`aria-hidden`,`true`),this.voiceLevel=document.createElement(`span`),this.voiceLevel.className=`ttcb-voice-level`,t.appendChild(this.voiceLevel),this.voiceCancelBtn=this.createVoiceButton(`Cancel recording`,fn(),()=>this.cancelVoice()),this.voiceStopBtn=this.createVoiceButton(`Stop recording`,dn(),()=>void this.stopVoice()),this.voiceStopBtn.classList.add(`primary`),this.voiceBar.appendChild(e),this.voiceBar.appendChild(this.voiceTime),this.voiceBar.appendChild(t),this.voiceBar.appendChild(this.voiceCancelBtn),this.voiceBar.appendChild(this.voiceStopBtn),this.voiceBar}buildVoicePreview(){return this.voicePreview=document.createElement(`div`),this.voicePreview.className=`ttcb-voice-preview`,this.voicePreview.setAttribute(`role`,`group`),this.voicePreview.setAttribute(`aria-label`,`Voice message preview`),this.voiceAudio=document.createElement(`audio`),this.voiceAudio.className=`ttcb-voice-audio`,this.voiceAudio.controls=!0,this.voiceAudio.preload=`metadata`,this.voiceAudio.setAttribute(`aria-label`,`Recorded voice message`),this.voicePreviewTime=document.createElement(`span`),this.voicePreviewTime.className=`ttcb-voice-time`,this.voiceDiscardBtn=this.createVoiceButton(`Discard voice message`,fn(),()=>this.cancelVoice()),this.voiceSendBtn=this.createVoiceButton(`Send voice message`,Xt(),()=>this.sendVoice()),this.voiceSendBtn.classList.add(`primary`),this.voicePreview.appendChild(this.voiceAudio),this.voicePreview.appendChild(this.voicePreviewTime),this.voicePreview.appendChild(this.voiceDiscardBtn),this.voicePreview.appendChild(this.voiceSendBtn),this.voicePreview}createVoiceButton(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ttcb-voice-btn`,r.setAttribute(`aria-label`,e),r.title=e,r.innerHTML=t,r.addEventListener(`click`,n),r}async startVoice(){if(!this.micBtn.disabled){if(this.closeAttachMenu(),this.showComposeError(``),!Bt.isSupported())this.showComposeError(`Voice messages are not supported in this browser.`);else{this.recorder?.destroy(),this.recorder=new Bt(e=>this.renderVoice(e));try{await this.recorder.start()}catch(e){this.showComposeError(e instanceof Error?e.message:`Could not start recording.`),this.recorder.destroy(),this.recorder=null,this.renderVoice({state:`idle`,elapsedSeconds:0,level:0,result:null})}}}}async stopVoice(){await this.recorder?.stop()}cancelVoice(){this.recorder?.cancel(),this.recorder?.destroy(),this.recorder=null,this.renderVoice({state:`idle`,elapsedSeconds:0,level:0,result:null}),this.input.focus()}sendVoice(){let e=this.recorder?.getSnapshot().result;e&&(this.cancelVoice(),this.callbacks.onSendVoice(e))}renderVoice(e){if(this.destroyed)return;let{state:t}=e;this.composeForm.classList.toggle(`hidden`,t!==`idle`),this.voiceBar.classList.toggle(`visible`,t===`recording`),this.voicePreview.classList.toggle(`visible`,t===`preview`),t===`recording`?(this.voiceTime.textContent=y(e.elapsedSeconds),this.voiceLevel.style.width=`${Math.max(4,Math.round(e.level*100))}%`):(g(this.voicePreviewUrl),this.voicePreviewUrl=``,this.voiceAudio.removeAttribute(`src`),t===`preview`&&e.result&&(this.voicePreviewUrl=h(new File([e.result.blob],`voice-preview`,{type:e.result.blob.type})),this.voicePreviewUrl&&(this.voiceAudio.src=this.voicePreviewUrl),this.voicePreviewTime.textContent=y(e.result.durationSeconds),queueMicrotask(()=>this.voiceSendBtn.focus())))}showComposeError(e){this.composeError.textContent=e,this.composeError.classList.toggle(`visible`,!!e)}setPanelMode(e){this.panel.classList.remove(`ttcb-mode-form`,`ttcb-mode-chat`,`ttcb-mode-compact`),this.panel.classList.add(`ttcb-mode-${e}`),e!==`chat`&&(this.requestHumanBtn.classList.add(`hidden`),this.newSessionBtn.classList.add(`hidden`),this.hideConfirmNew(),this.hideModeBanner())}buildIdentifyForm(e){let t=document.createElement(`form`);t.className=`ttcb-identify-form`,t.addEventListener(`submit`,e=>{e.preventDefault(),this.handleIdentifySubmit()}),this.nameInput=this.createIconField(t,{id:`name`,label:`Name`,required:!0,hint:`Required`,placeholder:`Your name`,type:`text`,autocomplete:`name`,icon:Qt()}),this.createPhoneField(t),this.emailInput=this.createIconField(t,{id:`email`,label:`Email (optional)`,required:!1,hint:`For chat transcript`,placeholder:`Email (optional)`,type:`email`,autocomplete:`email`,icon:$t()}),this.identifyError=document.createElement(`p`),this.identifyError.className=`ttcb-identify-error`,t.appendChild(this.identifyError),this.identifySubmit=document.createElement(`button`),this.identifySubmit.type=`submit`,this.identifySubmit.className=`ttcb-identify-submit`,this.identifySubmit.innerHTML=`<span>Start Chatting</span>${tn()}`,t.appendChild(this.identifySubmit),e.appendChild(t);let n=document.createElement(`div`);n.className=`ttcb-trust`,n.innerHTML=`${nn()}<span>Encrypted connection • No spam, ever</span>`,e.appendChild(n)}createIconField(e,t){let n=document.createElement(`div`);n.className=`ttcb-field`;let r=document.createElement(`div`);r.className=`ttcb-field-label-row`;let i=document.createElement(`label`);i.className=`ttcb-label`,i.htmlFor=`ttcb-${t.id}`,t.required?i.innerHTML=`${t.label.replace(` (optional)`,``)} <span class="ttcb-req">*</span>`:i.textContent=t.label;let a=document.createElement(`span`);a.className=`ttcb-field-hint`,a.textContent=t.hint,r.appendChild(i),r.appendChild(a);let o=document.createElement(`div`);o.className=`ttcb-input-wrap`;let s=document.createElement(`span`);s.className=`ttcb-input-icon`,s.setAttribute(`aria-hidden`,`true`),s.innerHTML=t.icon;let c=document.createElement(`input`);return c.id=`ttcb-${t.id}`,c.name=t.id,c.type=t.type,c.className=`ttcb-identify-input`,c.placeholder=t.placeholder,c.required=t.required,c.autocomplete=t.autocomplete,o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(o),e.appendChild(n),c}createPhoneField(e){let t=document.createElement(`div`);t.className=`ttcb-field`;let n=document.createElement(`div`);n.className=`ttcb-field-label-row`;let r=document.createElement(`label`);r.className=`ttcb-label`,r.htmlFor=`ttcb-tel`,r.innerHTML=`Phone <span class="ttcb-req">*</span>`;let i=document.createElement(`span`);i.className=`ttcb-field-hint`,i.textContent=`SMS / WhatsApp sync`,n.appendChild(r),n.appendChild(i);let a=document.createElement(`div`);a.className=`ttcb-phone-row`,a.id=`ttcb-phone-row`,this.dialBtn=document.createElement(`button`),this.dialBtn.type=`button`,this.dialBtn.className=`ttcb-dial-btn`,this.dialBtn.setAttribute(`aria-label`,`Select country code`),this.dialBtn.setAttribute(`aria-haspopup`,`listbox`),this.dialBtn.setAttribute(`aria-expanded`,`false`),this.dialFlag=document.createElement(`span`),this.dialFlag.className=`ttcb-dial-flag`,this.dialCode=document.createElement(`span`),this.dialCode.className=`ttcb-dial-code`,this.syncDialButton(),this.dialBtn.appendChild(this.dialFlag),this.dialBtn.appendChild(this.dialCode);let o=document.createElement(`span`);o.setAttribute(`aria-hidden`,`true`),o.innerHTML=en(),this.dialBtn.appendChild(o),this.dialBtn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleCountryPopover()}),this.phoneInput=document.createElement(`input`),this.phoneInput.id=`ttcb-tel`,this.phoneInput.name=`tel`,this.phoneInput.type=`tel`,this.phoneInput.className=`ttcb-phone-national`,this.phoneInput.placeholder=`1712-345678`,this.phoneInput.required=!0,this.phoneInput.autocomplete=`tel-national`,this.phoneInput.setAttribute(`inputmode`,`tel`),a.appendChild(this.dialBtn),a.appendChild(this.phoneInput),this.countryPopover=document.createElement(`div`),this.countryPopover.className=`ttcb-country-popover`,this.countryPopover.setAttribute(`role`,`listbox`),this.countrySearch=document.createElement(`input`),this.countrySearch.type=`search`,this.countrySearch.className=`ttcb-country-search`,this.countrySearch.placeholder=`Search country…`,this.countrySearch.setAttribute(`aria-label`,`Search countries`),this.countrySearch.addEventListener(`input`,()=>this.renderCountryList()),this.countryList=document.createElement(`div`),this.countryList.className=`ttcb-country-list`,this.countryPopover.appendChild(this.countrySearch),this.countryPopover.appendChild(this.countryList),this.renderCountryList(),t.appendChild(n),t.appendChild(a),t.appendChild(this.countryPopover),e.appendChild(t)}syncDialButton(){this.dialFlag.textContent=this.selectedCountry.flag,this.dialCode.textContent=`+${this.selectedCountry.dial}`}toggleCountryPopover(){this.countryOpen?this.closeCountryPopover():this.openCountryPopover()}openCountryPopover(){this.countryOpen=!0,this.countryPopover.classList.add(`open`),this.dialBtn.setAttribute(`aria-expanded`,`true`),this.countrySearch.value=``,this.renderCountryList(),queueMicrotask(()=>this.countrySearch.focus())}closeCountryPopover(){this.countryOpen=!1,this.countryPopover.classList.remove(`open`),this.dialBtn.setAttribute(`aria-expanded`,`false`)}renderCountryList(){let e=this.countrySearch.value.trim().toLowerCase(),t=X.filter(t=>!e||t.name.toLowerCase().includes(e)||t.dial.includes(e)||t.iso.toLowerCase().includes(e)||`+${t.dial}`.includes(e));this.countryList.innerHTML=``;for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`ttcb-country-item`,t.setAttribute(`role`,`option`),t.setAttribute(`aria-selected`,e.iso===this.selectedCountry.iso?`true`:`false`),t.innerHTML=`
|
|
796
|
+
</svg>`}function hn(e){let t=m(e.url)?e.url:``,n=e.type.toLowerCase();if(t&&n.startsWith(`image/`)){let n=document.createElement(`a`);n.className=`ttcb-attachment ttcb-attachment-image`,n.href=t,n.target=`_blank`,n.rel=`noopener noreferrer`,n.setAttribute(`aria-label`,`Open ${e.fileName}`);let r=document.createElement(`img`);return r.src=t,r.alt=e.fileName,r.loading=`lazy`,n.appendChild(r),n}if(t&&n.startsWith(`video/`)){let n=document.createElement(`video`);return n.className=`ttcb-attachment ttcb-attachment-video`,n.controls=!0,n.preload=`metadata`,n.src=t,n.setAttribute(`aria-label`,e.fileName),n}if(t&&n.startsWith(`audio/`)){let n=document.createElement(`div`);n.className=`ttcb-attachment ttcb-attachment-voice`;let r=document.createElement(`audio`);if(r.className=`ttcb-attachment-audio`,r.controls=!0,r.preload=`metadata`,r.src=t,r.setAttribute(`aria-label`,e.fileName),n.appendChild(r),typeof e.durationSeconds==`number`&&e.durationSeconds>0){let t=document.createElement(`span`);t.className=`ttcb-attachment-duration`,t.textContent=y(e.durationSeconds),n.appendChild(t)}return n}let r=document.createElement(t?`a`:`div`);r.className=`ttcb-attachment ttcb-attachment-file`,r instanceof HTMLAnchorElement&&(r.href=t,r.target=`_blank`,r.rel=`noopener noreferrer`);let i=document.createElement(`span`);i.className=`ttcb-attachment-icon`,i.setAttribute(`aria-hidden`,`true`),i.innerHTML=mn();let a=document.createElement(`span`);a.className=`ttcb-attachment-meta`;let o=document.createElement(`span`);o.className=`ttcb-attachment-name`,o.textContent=e.fileName,a.appendChild(o);let s=te(e.size);if(s){let e=document.createElement(`span`);e.className=`ttcb-attachment-size`,e.textContent=s,a.appendChild(e)}return r.appendChild(i),r.appendChild(a),r}function gn(e){let{type:t,content:n}=e,r=e.attachments??[],i=document.createElement(`div`);i.className=`ttcb-msg ${t}`,e.pending&&i.classList.add(`ttcb-pending`);let a=document.createElement(`div`);a.className=`ttcb-msg-avatar`,a.innerHTML=t===`human`?Qt():t===`agent`?$t():X();let o=document.createElement(`div`);if(o.className=`ttcb-msg-body`,t===`agent`){let e=document.createElement(`span`);e.className=`ttcb-msg-label`,e.textContent=`Agent`,o.appendChild(e)}if(r.length>0){let e=document.createElement(`div`);e.className=`ttcb-attachments`;for(let t of r)e.appendChild(hn(t));o.appendChild(e)}if(r.length===0||!re(n,r)){let e=document.createElement(`div`);e.className=`ttcb-bubble`,t===`human`?e.textContent=n:e.innerHTML=qt(n),o.appendChild(e)}if(e.pending){let e=document.createElement(`span`);e.className=`ttcb-msg-status`,e.textContent=`Uploading…`,o.appendChild(e)}return i.appendChild(a),i.appendChild(o),i}function _n(){let e=document.createElement(`div`);e.className=`ttcb-msg ai`,e.id=`ttcb-typing`;let t=document.createElement(`div`);t.className=`ttcb-msg-avatar`,t.innerHTML=X();let n=document.createElement(`div`);return n.className=`ttcb-typing`,n.innerHTML=`<span></span><span></span><span></span>`,e.appendChild(t),e.appendChild(n),e}var vn=`image/jpeg,image/png,image/gif,video/mp4,video/webm,audio/ogg,audio/mpeg,audio/wav,audio/x-m4a,audio/aac,audio/opus,application/pdf,text/csv`,yn=`image/jpeg,image/png,image/gif`,bn=class{constructor(e,t){this.stopViewportSync=null,this.confirmingNew=!1,this.actionPending=!1,this.ticketMode=`ai`,this.pendingFiles=[],this.attachMenuOpen=!1,this.recorder=null,this.voicePreviewUrl=``,this.selectedCountry=Ht,this.countryOpen=!1,this.isOpen=!1,this.destroyed=!1,this.position=e.position??`bottom-right`,this.callbacks=t,this.autoOpen=e.autoOpen===!0,this.mount(e)}mount(e){this.host=document.createElement(`div`),this.host.id=`onedeskpro-chatbot-host`,this.host.style.display=`none`,this.shadow=this.host.attachShadow({mode:`closed`});let t=document.createElement(`style`);t.textContent=Gt(e.primaryColor??`#2563EB`,e.theme??`auto`),this.shadow.appendChild(t),this.fab=document.createElement(`button`),this.fab.className=`ttcb-fab ${this.position}`,this.fab.setAttribute(`aria-label`,`Open chat`),this.fab.innerHTML=Yt(),this.fab.addEventListener(`click`,()=>this.toggle()),this.shadow.appendChild(this.fab),this.panel=document.createElement(`div`),this.panel.className=`ttcb-panel ${this.position} hidden ttcb-mode-compact`,this.panel.tabIndex=-1,this.panel.setAttribute(`role`,`dialog`),this.panel.setAttribute(`aria-modal`,`true`),this.panel.setAttribute(`aria-label`,e.chatbotName??`AI Assistant`),this.panel.appendChild(this.buildHeader(e)),this.identifyContainer=document.createElement(`div`),this.identifyContainer.className=`ttcb-identify`,this.buildIdentifyForm(this.identifyContainer),this.panel.appendChild(this.identifyContainer),this.messagesContainer=document.createElement(`div`),this.messagesContainer.className=`ttcb-messages`,this.messagesContainer.setAttribute(`aria-live`,`polite`),this.messagesContainer.setAttribute(`aria-label`,`Chat messages`),this.panel.appendChild(this.messagesContainer),this.modeBanner=document.createElement(`div`),this.modeBanner.className=`ttcb-mode-banner`,this.modeBannerText=document.createElement(`span`),this.modeBannerText.className=`ttcb-mode-banner-text`,this.modeBannerText.setAttribute(`role`,`status`),this.cancelHumanBtn=this.buildBannerButton(`Cancel request`,()=>{this.actionPending||this.callbacks.onCancelHumanRequest()}),this.cancelHumanBtn.classList.add(`hidden`),this.modeBanner.appendChild(this.modeBannerText),this.modeBanner.appendChild(this.cancelHumanBtn),this.panel.appendChild(this.modeBanner),this.panel.appendChild(this.buildConfirmNewBar()),this.footer=document.createElement(`div`),this.footer.className=`ttcb-footer`,this.pendingTray=document.createElement(`div`),this.pendingTray.className=`ttcb-pending-tray`,this.pendingTray.setAttribute(`role`,`list`),this.pendingTray.setAttribute(`aria-label`,`Files to send`),this.footer.appendChild(this.pendingTray),this.composeError=document.createElement(`p`),this.composeError.className=`ttcb-compose-error`,this.composeError.setAttribute(`role`,`alert`),this.footer.appendChild(this.composeError),this.footer.appendChild(this.buildVoiceBar()),this.footer.appendChild(this.buildVoicePreview());let n=document.createElement(`form`);n.className=`ttcb-form`,n.addEventListener(`submit`,e=>{e.preventDefault(),this.handleSend()}),this.composeForm=n,n.appendChild(this.buildAttachControls()),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`ttcb-input`,this.input.placeholder=e.placeholder??`Type your message…`,this.input.setAttribute(`aria-label`,`Message input`),this.input.setAttribute(`autocomplete`,`off`),this.sendBtn=document.createElement(`button`),this.sendBtn.type=`submit`,this.sendBtn.className=`ttcb-send-btn`,this.sendBtn.innerHTML=Zt(),this.sendBtn.setAttribute(`aria-label`,`Send message`),this.micBtn=document.createElement(`button`),this.micBtn.type=`button`,this.micBtn.className=`ttcb-mic-btn`,this.micBtn.setAttribute(`aria-label`,`Record voice message`),this.micBtn.title=`Record voice message`,this.micBtn.innerHTML=dn(),this.micBtn.addEventListener(`click`,()=>void this.startVoice()),n.appendChild(this.input),n.appendChild(this.micBtn),n.appendChild(this.sendBtn),this.footer.appendChild(n),this.panel.appendChild(this.footer),this.shadow.appendChild(this.panel),this.shadow.addEventListener(`click`,e=>{let t=e.target;this.attachMenuOpen&&!(t&&(this.attachBtn.contains(t)||this.attachMenu.contains(t)))&&this.closeAttachMenu(),this.countryOpen&&(t&&(this.dialBtn.contains(t)||this.countryPopover.contains(t))||this.closeCountryPopover())}),this.panel.addEventListener(`keydown`,e=>{e.key===`Escape`&&this.attachMenuOpen?(e.stopPropagation(),this.closeAttachMenu(),this.attachBtn.focus()):e.key===`Escape`&&this.confirmingNew&&(e.stopPropagation(),this.hideConfirmNew(),this.newSessionBtn.focus())}),this.attachToDocument(),this.showInitialLoading()}reveal(){this.host.style.removeProperty(`display`),this.autoOpen&&!this.isOpen&&this.open()}buildHeader(e){let t=document.createElement(`div`);t.className=`ttcb-header`;let n=document.createElement(`div`);n.className=`ttcb-avatar-wrap`;let r=document.createElement(`div`);r.className=`ttcb-avatar`,r.innerHTML=X(),n.appendChild(r);let i=document.createElement(`div`);i.className=`ttcb-header-main`;let a=document.createElement(`div`);a.className=`ttcb-header-title-row`,this.headerTitle=document.createElement(`span`),this.headerTitle.className=`ttcb-header-title`,this.headerTitle.textContent=e.chatbotName??`AI Assistant`;let o=document.createElement(`span`);o.className=`ttcb-verified`,o.setAttribute(`aria-label`,`Verified`),o.innerHTML=an(),a.appendChild(this.headerTitle),a.appendChild(o);let s=document.createElement(`div`);s.className=`ttcb-header-meta`;let c=document.createElement(`span`);c.className=`ttcb-meta-online`,c.textContent=`Online`;let l=document.createElement(`span`);l.className=`ttcb-meta-sep`,l.setAttribute(`aria-hidden`,`true`);let u=document.createElement(`span`);u.className=`ttcb-meta-replies`,u.innerHTML=`${on()}<span>Replies instantly</span>`,s.appendChild(c),s.appendChild(l),s.appendChild(u),i.appendChild(a),i.appendChild(s);let d=document.createElement(`div`);d.className=`ttcb-header-actions`,this.requestHumanBtn=document.createElement(`button`),this.requestHumanBtn.type=`button`,this.requestHumanBtn.className=`ttcb-request-human-btn hidden`,this.requestHumanBtn.id=`ttcb-request-human-btn`,this.requestHumanBtn.setAttribute(`aria-label`,`Request human agent`),this.requestHumanBtn.title=`Request human agent`,this.requestHumanBtn.innerHTML=sn(),this.requestHumanBtn.addEventListener(`click`,()=>this.callbacks.onRequestHuman()),this.newSessionBtn=document.createElement(`button`),this.newSessionBtn.type=`button`,this.newSessionBtn.className=`ttcb-new-session-btn hidden`,this.newSessionBtn.setAttribute(`aria-label`,`New conversation`),this.newSessionBtn.title=`New conversation`,this.newSessionBtn.innerHTML=Jt(),this.newSessionBtn.addEventListener(`click`,()=>{this.actionPending||(this.ticketMode===`closed`?this.callbacks.onNewConversation():this.showConfirmNew())});let f=document.createElement(`button`);return f.className=`ttcb-close-btn`,f.setAttribute(`aria-label`,`Close chat`),f.innerHTML=Xt(),f.addEventListener(`click`,()=>this.close()),d.appendChild(this.requestHumanBtn),d.appendChild(this.newSessionBtn),d.appendChild(f),t.appendChild(n),t.appendChild(i),t.appendChild(d),t}buildBannerButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`ttcb-banner-btn`,n.textContent=e,n.addEventListener(`click`,t),n}buildConfirmNewBar(){this.confirmNewBar=document.createElement(`div`),this.confirmNewBar.className=`ttcb-confirm-bar`,this.confirmNewBar.setAttribute(`role`,`group`),this.confirmNewBar.setAttribute(`aria-label`,`Start a new conversation`);let e=document.createElement(`span`);e.className=`ttcb-confirm-text`,e.textContent=`End this conversation and start a new one?`,this.confirmNewBtn=this.buildBannerButton(`Start new`,()=>{this.actionPending||(this.hideConfirmNew(),this.input.focus(),this.callbacks.onNewConversation())}),this.confirmNewBtn.classList.add(`primary`),this.keepChattingBtn=this.buildBannerButton(`Keep chatting`,()=>{this.hideConfirmNew(),this.newSessionBtn.focus()});let t=document.createElement(`div`);return t.className=`ttcb-confirm-actions`,t.appendChild(this.confirmNewBtn),t.appendChild(this.keepChattingBtn),this.confirmNewBar.appendChild(e),this.confirmNewBar.appendChild(t),this.confirmNewBar}showConfirmNew(){this.confirmingNew=!0,this.confirmNewBar.classList.add(`visible`),queueMicrotask(()=>this.keepChattingBtn.focus())}hideConfirmNew(){this.confirmingNew=!1,this.confirmNewBar.classList.remove(`visible`)}setActionPending(e){this.actionPending=e;for(let t of[this.newSessionBtn,this.cancelHumanBtn,this.confirmNewBtn])t.setAttribute(`aria-disabled`,String(e))}buildAttachControls(){let e=document.createElement(`div`);e.className=`ttcb-attach`,this.attachBtn=document.createElement(`button`),this.attachBtn.type=`button`,this.attachBtn.className=`ttcb-attach-btn`,this.attachBtn.setAttribute(`aria-label`,`Add attachment`),this.attachBtn.setAttribute(`aria-haspopup`,`menu`),this.attachBtn.setAttribute(`aria-expanded`,`false`),this.attachBtn.title=`Add attachment`,this.attachBtn.innerHTML=cn(),this.attachBtn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleAttachMenu()}),this.attachMenu=document.createElement(`div`),this.attachMenu.className=`ttcb-attach-menu`,this.attachMenu.setAttribute(`role`,`menu`),this.attachFileInput=this.createFileInput(vn,`Choose files`),this.attachPhotoInput=this.createFileInput(yn,`Choose photos`);let t=[{label:`Attachment`,icon:ln(),input:this.attachFileInput},{label:`Photo`,icon:un(),input:this.attachPhotoInput}];for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`ttcb-attach-item`,t.setAttribute(`role`,`menuitem`),t.innerHTML=`${e.icon}<span>${e.label}</span>`,t.addEventListener(`click`,()=>{this.closeAttachMenu(),e.input.click()}),this.attachMenu.appendChild(t)}return e.appendChild(this.attachBtn),e.appendChild(this.attachMenu),e.appendChild(this.attachFileInput),e.appendChild(this.attachPhotoInput),e}createFileInput(e,t){let n=document.createElement(`input`);return n.type=`file`,n.multiple=!0,n.accept=e,n.className=`ttcb-file-input`,n.tabIndex=-1,n.setAttribute(`aria-label`,t),n.addEventListener(`change`,()=>{this.addPendingFiles(Array.from(n.files??[])),n.value=``}),n}toggleAttachMenu(){this.attachMenuOpen?this.closeAttachMenu():this.openAttachMenu()}openAttachMenu(){if(this.attachBtn.disabled)return;this.attachMenuOpen=!0,this.attachMenu.classList.add(`open`),this.attachBtn.setAttribute(`aria-expanded`,`true`);let e=this.attachMenu.querySelector(`.ttcb-attach-item`);queueMicrotask(()=>e?.focus())}closeAttachMenu(){this.attachMenuOpen&&(this.attachMenuOpen=!1,this.attachMenu.classList.remove(`open`),this.attachBtn.setAttribute(`aria-expanded`,`false`))}addPendingFiles(e){if(e.length===0)return;let t=p([...this.pendingFiles.map(e=>e.file),...e]);if(t)this.showComposeError(t);else{this.showComposeError(``);for(let t of e){let e=t.type.startsWith(`image/`)?h(t):``;this.pendingFiles.push({file:t,previewUrl:e})}this.renderPendingTray(),this.input.focus()}}removePendingFile(e){let[t]=this.pendingFiles.splice(e,1);t&&g(t.previewUrl),this.renderPendingTray(),this.input.focus()}clearPendingFiles(){for(let e of this.pendingFiles)g(e.previewUrl);this.pendingFiles=[],this.renderPendingTray()}renderPendingTray(){this.pendingTray.innerHTML=``,this.pendingTray.classList.toggle(`visible`,this.pendingFiles.length>0),this.pendingFiles.forEach((e,t)=>{let n=document.createElement(`div`);if(n.className=`ttcb-pending-item`,n.setAttribute(`role`,`listitem`),e.previewUrl){let t=document.createElement(`img`);t.className=`ttcb-pending-thumb`,t.src=e.previewUrl,t.alt=``,n.appendChild(t)}else{let e=document.createElement(`span`);e.className=`ttcb-pending-icon`,e.setAttribute(`aria-hidden`,`true`),e.innerHTML=mn(),n.appendChild(e)}let r=document.createElement(`span`);r.className=`ttcb-pending-name`,r.textContent=e.file.name||`attachment`,r.title=e.file.name,n.appendChild(r);let i=document.createElement(`button`);i.type=`button`,i.className=`ttcb-pending-remove`,i.setAttribute(`aria-label`,`Remove ${e.file.name||`attachment`}`),i.innerHTML=Xt(),i.addEventListener(`click`,()=>this.removePendingFile(t)),n.appendChild(i),this.pendingTray.appendChild(n)})}buildVoiceBar(){this.voiceBar=document.createElement(`div`),this.voiceBar.className=`ttcb-voice-bar`,this.voiceBar.setAttribute(`role`,`group`),this.voiceBar.setAttribute(`aria-label`,`Recording voice message`);let e=document.createElement(`span`);e.className=`ttcb-voice-dot`,e.setAttribute(`aria-hidden`,`true`),this.voiceTime=document.createElement(`span`),this.voiceTime.className=`ttcb-voice-time`,this.voiceTime.setAttribute(`role`,`timer`),this.voiceTime.textContent=`0:00`;let t=document.createElement(`div`);return t.className=`ttcb-voice-meter`,t.setAttribute(`aria-hidden`,`true`),this.voiceLevel=document.createElement(`span`),this.voiceLevel.className=`ttcb-voice-level`,t.appendChild(this.voiceLevel),this.voiceCancelBtn=this.createVoiceButton(`Cancel recording`,pn(),()=>this.cancelVoice()),this.voiceStopBtn=this.createVoiceButton(`Stop recording`,fn(),()=>void this.stopVoice()),this.voiceStopBtn.classList.add(`primary`),this.voiceBar.appendChild(e),this.voiceBar.appendChild(this.voiceTime),this.voiceBar.appendChild(t),this.voiceBar.appendChild(this.voiceCancelBtn),this.voiceBar.appendChild(this.voiceStopBtn),this.voiceBar}buildVoicePreview(){return this.voicePreview=document.createElement(`div`),this.voicePreview.className=`ttcb-voice-preview`,this.voicePreview.setAttribute(`role`,`group`),this.voicePreview.setAttribute(`aria-label`,`Voice message preview`),this.voiceAudio=document.createElement(`audio`),this.voiceAudio.className=`ttcb-voice-audio`,this.voiceAudio.controls=!0,this.voiceAudio.preload=`metadata`,this.voiceAudio.setAttribute(`aria-label`,`Recorded voice message`),this.voicePreviewTime=document.createElement(`span`),this.voicePreviewTime.className=`ttcb-voice-time`,this.voiceDiscardBtn=this.createVoiceButton(`Discard voice message`,pn(),()=>this.cancelVoice()),this.voiceSendBtn=this.createVoiceButton(`Send voice message`,Zt(),()=>this.sendVoice()),this.voiceSendBtn.classList.add(`primary`),this.voicePreview.appendChild(this.voiceAudio),this.voicePreview.appendChild(this.voicePreviewTime),this.voicePreview.appendChild(this.voiceDiscardBtn),this.voicePreview.appendChild(this.voiceSendBtn),this.voicePreview}createVoiceButton(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ttcb-voice-btn`,r.setAttribute(`aria-label`,e),r.title=e,r.innerHTML=t,r.addEventListener(`click`,n),r}async startVoice(){if(!this.micBtn.disabled){if(this.closeAttachMenu(),this.showComposeError(``),!Bt.isSupported())this.showComposeError(`Voice messages are not supported in this browser.`);else{this.recorder?.destroy(),this.recorder=new Bt(e=>this.renderVoice(e));try{await this.recorder.start()}catch(e){this.showComposeError(e instanceof Error?e.message:`Could not start recording.`),this.recorder.destroy(),this.recorder=null,this.renderVoice({state:`idle`,elapsedSeconds:0,level:0,result:null})}}}}async stopVoice(){await this.recorder?.stop()}cancelVoice(){this.recorder?.cancel(),this.recorder?.destroy(),this.recorder=null,this.renderVoice({state:`idle`,elapsedSeconds:0,level:0,result:null}),this.input.focus()}sendVoice(){let e=this.recorder?.getSnapshot().result;e&&(this.cancelVoice(),this.callbacks.onSendVoice(e))}renderVoice(e){if(this.destroyed)return;let{state:t}=e;this.composeForm.classList.toggle(`hidden`,t!==`idle`),this.voiceBar.classList.toggle(`visible`,t===`recording`),this.voicePreview.classList.toggle(`visible`,t===`preview`),t===`recording`?(this.voiceTime.textContent=y(e.elapsedSeconds),this.voiceLevel.style.width=`${Math.max(4,Math.round(e.level*100))}%`):(g(this.voicePreviewUrl),this.voicePreviewUrl=``,this.voiceAudio.removeAttribute(`src`),t===`preview`&&e.result&&(this.voicePreviewUrl=h(new File([e.result.blob],`voice-preview`,{type:e.result.blob.type})),this.voicePreviewUrl&&(this.voiceAudio.src=this.voicePreviewUrl),this.voicePreviewTime.textContent=y(e.result.durationSeconds),queueMicrotask(()=>this.voiceSendBtn.focus())))}showComposeError(e){this.composeError.textContent=e,this.composeError.classList.toggle(`visible`,!!e)}setPanelMode(e){this.panel.classList.remove(`ttcb-mode-form`,`ttcb-mode-chat`,`ttcb-mode-compact`),this.panel.classList.add(`ttcb-mode-${e}`),e!==`chat`&&(this.requestHumanBtn.classList.add(`hidden`),this.newSessionBtn.classList.add(`hidden`),this.hideConfirmNew(),this.hideModeBanner())}buildIdentifyForm(e){let t=document.createElement(`form`);t.className=`ttcb-identify-form`,t.addEventListener(`submit`,e=>{e.preventDefault(),this.handleIdentifySubmit()}),this.nameInput=this.createIconField(t,{id:`name`,label:`Name`,required:!0,hint:`Required`,placeholder:`Your name`,type:`text`,autocomplete:`name`,icon:$t()}),this.createPhoneField(t),this.emailInput=this.createIconField(t,{id:`email`,label:`Email (optional)`,required:!1,hint:`For chat transcript`,placeholder:`Email (optional)`,type:`email`,autocomplete:`email`,icon:en()}),this.identifyError=document.createElement(`p`),this.identifyError.className=`ttcb-identify-error`,t.appendChild(this.identifyError),this.identifySubmit=document.createElement(`button`),this.identifySubmit.type=`submit`,this.identifySubmit.className=`ttcb-identify-submit`,this.identifySubmit.innerHTML=`<span>Start Chatting</span>${nn()}`,t.appendChild(this.identifySubmit),e.appendChild(t);let n=document.createElement(`div`);n.className=`ttcb-trust`,n.innerHTML=`${rn()}<span>Encrypted connection • No spam, ever</span>`,e.appendChild(n)}createIconField(e,t){let n=document.createElement(`div`);n.className=`ttcb-field`;let r=document.createElement(`div`);r.className=`ttcb-field-label-row`;let i=document.createElement(`label`);i.className=`ttcb-label`,i.htmlFor=`ttcb-${t.id}`,t.required?i.innerHTML=`${t.label.replace(` (optional)`,``)} <span class="ttcb-req">*</span>`:i.textContent=t.label;let a=document.createElement(`span`);a.className=`ttcb-field-hint`,a.textContent=t.hint,r.appendChild(i),r.appendChild(a);let o=document.createElement(`div`);o.className=`ttcb-input-wrap`;let s=document.createElement(`span`);s.className=`ttcb-input-icon`,s.setAttribute(`aria-hidden`,`true`),s.innerHTML=t.icon;let c=document.createElement(`input`);return c.id=`ttcb-${t.id}`,c.name=t.id,c.type=t.type,c.className=`ttcb-identify-input`,c.placeholder=t.placeholder,c.required=t.required,c.autocomplete=t.autocomplete,o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(o),e.appendChild(n),c}createPhoneField(e){let t=document.createElement(`div`);t.className=`ttcb-field`;let n=document.createElement(`div`);n.className=`ttcb-field-label-row`;let r=document.createElement(`label`);r.className=`ttcb-label`,r.htmlFor=`ttcb-tel`,r.innerHTML=`Phone <span class="ttcb-req">*</span>`;let i=document.createElement(`span`);i.className=`ttcb-field-hint`,i.textContent=`SMS / WhatsApp sync`,n.appendChild(r),n.appendChild(i);let a=document.createElement(`div`);a.className=`ttcb-phone-row`,a.id=`ttcb-phone-row`,this.dialBtn=document.createElement(`button`),this.dialBtn.type=`button`,this.dialBtn.className=`ttcb-dial-btn`,this.dialBtn.setAttribute(`aria-label`,`Select country code`),this.dialBtn.setAttribute(`aria-haspopup`,`listbox`),this.dialBtn.setAttribute(`aria-expanded`,`false`),this.dialFlag=document.createElement(`span`),this.dialFlag.className=`ttcb-dial-flag`,this.dialCode=document.createElement(`span`),this.dialCode.className=`ttcb-dial-code`,this.syncDialButton(),this.dialBtn.appendChild(this.dialFlag),this.dialBtn.appendChild(this.dialCode);let o=document.createElement(`span`);o.setAttribute(`aria-hidden`,`true`),o.innerHTML=tn(),this.dialBtn.appendChild(o),this.dialBtn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleCountryPopover()}),this.phoneInput=document.createElement(`input`),this.phoneInput.id=`ttcb-tel`,this.phoneInput.name=`tel`,this.phoneInput.type=`tel`,this.phoneInput.className=`ttcb-phone-national`,this.phoneInput.placeholder=`1712-345678`,this.phoneInput.required=!0,this.phoneInput.autocomplete=`tel-national`,this.phoneInput.setAttribute(`inputmode`,`tel`),a.appendChild(this.dialBtn),a.appendChild(this.phoneInput),this.countryPopover=document.createElement(`div`),this.countryPopover.className=`ttcb-country-popover`,this.countryPopover.setAttribute(`role`,`listbox`),this.countrySearch=document.createElement(`input`),this.countrySearch.type=`search`,this.countrySearch.className=`ttcb-country-search`,this.countrySearch.placeholder=`Search country…`,this.countrySearch.setAttribute(`aria-label`,`Search countries`),this.countrySearch.addEventListener(`input`,()=>this.renderCountryList()),this.countryList=document.createElement(`div`),this.countryList.className=`ttcb-country-list`,this.countryPopover.appendChild(this.countrySearch),this.countryPopover.appendChild(this.countryList),this.renderCountryList(),t.appendChild(n),t.appendChild(a),t.appendChild(this.countryPopover),e.appendChild(t)}syncDialButton(){this.dialFlag.textContent=this.selectedCountry.flag,this.dialCode.textContent=`+${this.selectedCountry.dial}`}toggleCountryPopover(){this.countryOpen?this.closeCountryPopover():this.openCountryPopover()}openCountryPopover(){this.countryOpen=!0,this.countryPopover.classList.add(`open`),this.dialBtn.setAttribute(`aria-expanded`,`true`),this.countrySearch.value=``,this.renderCountryList(),queueMicrotask(()=>this.countrySearch.focus())}closeCountryPopover(){this.countryOpen=!1,this.countryPopover.classList.remove(`open`),this.dialBtn.setAttribute(`aria-expanded`,`false`)}renderCountryList(){let e=this.countrySearch.value.trim().toLowerCase(),t=Vt.filter(t=>!e||t.name.toLowerCase().includes(e)||t.dial.includes(e)||t.iso.toLowerCase().includes(e)||`+${t.dial}`.includes(e));this.countryList.innerHTML=``;for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`ttcb-country-item`,t.setAttribute(`role`,`option`),t.setAttribute(`aria-selected`,e.iso===this.selectedCountry.iso?`true`:`false`),t.innerHTML=`
|
|
797
797
|
<span class="ttcb-dial-flag">${e.flag}</span>
|
|
798
798
|
<span class="ttcb-country-item-name">${e.name}</span>
|
|
799
799
|
<span class="ttcb-country-item-dial">+${e.dial}</span>
|
|
800
|
-
`,t.addEventListener(`click`,()=>{this.selectedCountry=e,this.syncDialButton(),this.closeCountryPopover(),this.phoneInput.focus()}),this.countryList.appendChild(t)}}attachToDocument(){let e=()=>{this.destroyed||(document.body??document.documentElement).appendChild(this.host)};document.body?e():document.addEventListener(`DOMContentLoaded`,e,{once:!0})}showInitialLoading(){this.setPanelMode(`compact`),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.add(`hidden`),this.messagesContainer.innerHTML=``,this.input.disabled=!0,this.sendBtn.disabled=!0;let e=document.createElement(`div`);e.className=`ttcb-initial-loading`,e.id=`ttcb-initial-loading`;let t=document.createElement(`div`);t.className=`ttcb-spinner`;let n=document.createElement(`p`);n.textContent=`Loading…`,e.appendChild(t),e.appendChild(n),this.messagesContainer.appendChild(e)}showEmptyState(e){let t=document.createElement(`div`);t.className=`ttcb-empty`,t.id=`ttcb-empty`;let n=document.createElement(`div`);n.className=`ttcb-empty-icon`,n.innerHTML=Z();let r=document.createElement(`p`),i=document.createElement(`strong`);i.textContent=e,r.appendChild(document.createTextNode(`Welcome to `)),r.appendChild(i);let a=document.createElement(`p`);a.textContent=`Ask me anything — I'm here to help!`,a.style.marginTop=`6px`,a.style.fontSize=`12px`,t.appendChild(n),t.appendChild(r),t.appendChild(a),this.messagesContainer.appendChild(t)}removeEmptyState(){let e=this.shadow.getElementById(`ttcb-empty`);e&&e.remove()}handleSend(){let e=this.input.value.trim();if(!this.sendBtn.disabled){if(this.pendingFiles.length>0){let t=this.pendingFiles.map(e=>e.file);this.clearPendingFiles(),this.showComposeError(``),this.input.value=``,this.callbacks.onSendAttachments(t,e),this.input.focus()}else e&&(this.input.value=``,this.callbacks.onSend(e),this.input.focus())}}handleIdentifySubmit(){let e=this.nameInput.value.trim(),t=Ht(this.selectedCountry.dial,this.phoneInput.value),n=this.emailInput.value.trim();!e||!t?this.showIdentifyError(`Name and phone are required.`):(this.showIdentifyError(``),this.callbacks.onIdentify({name:e,phone:t,...n?{email:n}:{}}))}appendMessage(e){this.removeEmptyState();let t=this.buildMessage(e);this.messagesContainer.appendChild(t),this.scrollToBottom()}replaceMessage(e,t){let n=this.findMessageEl(e);n?(n.replaceWith(this.buildMessage(t)),this.scrollToBottom()):this.appendMessage(t)}removeMessage(e){this.findMessageEl(e)?.remove()}buildMessage(e){if(`message`in e){let t=hn({...e.message,pending:e.pending});return t.dataset.msgId=String(e.id),t}return hn(e)}findMessageEl(e){for(let t of this.messagesContainer.querySelectorAll(`.ttcb-msg`))if(t.dataset.msgId===String(e))return t;return null}setMessages(e){if(this.messagesContainer.innerHTML=``,e.length!==0){for(let t of e)this.messagesContainer.appendChild(this.buildMessage(t));this.scrollToBottom()}}setLoading(e){if(this.sendBtn.disabled=e||this.input.disabled,this.attachBtn.disabled=e||this.input.disabled,this.micBtn.disabled=e||this.input.disabled,e)this.closeAttachMenu(),this.shadow.getElementById(`ttcb-typing`)||(this.messagesContainer.appendChild(gn()),this.scrollToBottom()),this.isFullScreen()||this.input.focus();else{let e=this.shadow.getElementById(`ttcb-typing`);e&&e.remove(),!this.input.disabled&&!this.isFullScreen()&&this.input.focus()}}setIdentifyLoading(e){this.identifySubmit.disabled=e,this.nameInput.disabled=e,this.phoneInput.disabled=e,this.emailInput.disabled=e,this.dialBtn.disabled=e,this.shadow.getElementById(`ttcb-phone-row`)?.classList.toggle(`disabled`,e);for(let t of this.identifyContainer.querySelectorAll(`.ttcb-input-wrap`))t.classList.toggle(`disabled`,e);this.identifySubmit.innerHTML=e?`<span>Starting…</span>`:`<span>Start Chatting</span>${tn()}`,e&&this.closeCountryPopover()}showIdentifyError(e){this.identifyError.textContent=e}open(){this.isOpen=!0,this.startViewportSync(),this.panel.classList.remove(`hidden`),this.fab.classList.add(`ttcb-open`),this.isFullScreen()?this.panel.focus({preventScroll:!0}):this.identifyContainer.classList.contains(`visible`)?this.nameInput.focus():this.input.focus(),this.callbacks.onOpen()}close(){this.isOpen=!1,this.closeCountryPopover(),this.closeAttachMenu(),this.panel.classList.add(`hidden`),this.fab.classList.remove(`ttcb-open`),this.stopViewportSync?.(),this.stopViewportSync=null,this.fab.focus({preventScroll:!0}),this.callbacks.onClose()}isFullScreen(){return typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 640px), (max-height: 500px) and (pointer: coarse)`).matches}startViewportSync(){let e=window.visualViewport;if(!e||this.stopViewportSync)return;let t=()=>{let t=this.messagesContainer,n=t.scrollHeight-t.scrollTop-t.clientHeight<40;this.panel.style.setProperty(`--ttcb-vv-top`,`${e.offsetTop}px`),this.panel.style.setProperty(`--ttcb-vv-left`,`${e.offsetLeft}px`),this.panel.style.setProperty(`--ttcb-vv-width`,`${e.width}px`),this.panel.style.setProperty(`--ttcb-vv-height`,`${e.height}px`),n&&this.scrollToBottom()};e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),this.stopViewportSync=()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}}toggle(){this.isOpen?this.close():this.open()}showIdentifyForm(e){this.setPanelMode(`form`),e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),this.messagesContainer.classList.add(`hidden`),this.footer.classList.add(`hidden`),this.identifyContainer.classList.add(`visible`),this.showIdentifyError(``),this.setIdentifyLoading(!1)}readyToChat(e){this.setPanelMode(`chat`),this.closeCountryPopover(),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.remove(`hidden`),this.messagesContainer.innerHTML=``,e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),e.welcomeMessage?this.appendMessage({type:`ai`,content:e.welcomeMessage}):this.showEmptyState(e.chatbotName??`AI Assistant`),this.setMode(`ai`)}clearMessages(e){this.messagesContainer.innerHTML=``,this.clearPendingFiles(),this.showComposeError(``),this.hideConfirmNew(),this.showEmptyState(e)}setMode(e,t){let n=this.panel.classList.contains(`ttcb-mode-chat`),r=t?.agentName,i=t?.canRequestHuman===!0,a=t?.canStartNew??e===`closed`,o=n&&i,s=n&&a,c=e===`closed`;this.ticketMode=e,this.requestHumanBtn.classList.toggle(`hidden`,!o),this.newSessionBtn.classList.toggle(`hidden`,!s),(!s||c)&&this.hideConfirmNew(),this.input.disabled=c,c?(this.sendBtn.disabled=!0,this.attachBtn.disabled=!0,this.micBtn.disabled=!0,this.closeAttachMenu(),this.clearPendingFiles(),this.recorder&&this.cancelVoice(),this.showComposeError(``)):this.shadow.getElementById(`ttcb-typing`)||(this.sendBtn.disabled=!1,this.attachBtn.disabled=!1,this.micBtn.disabled=!1),n?(e===`waiting`?this.showModeBanner(`Waiting for a human agent…`,`waiting`):e===`closed`?this.showModeBanner(`This conversation is closed`,`closed`):e===`human`&&r?.trim()?this.showModeBanner(`Connected with ${r.trim()}`,`human`):this.hideModeBanner(),this.rescueFocus()):(this.hideModeBanner(),this.rescueFocus())}showModeBanner(e,t){this.modeBannerText.textContent=e,this.modeBanner.className=`ttcb-mode-banner visible ${t}`,this.cancelHumanBtn.classList.toggle(`hidden`,t!==`waiting`)}hideModeBanner(){this.modeBannerText.textContent=``,this.modeBanner.className=`ttcb-mode-banner`,this.cancelHumanBtn.classList.add(`hidden`)}rescueFocus(){let e=this.shadow.activeElement;e instanceof HTMLElement&&(e.closest(`.hidden`)||e.closest(`.ttcb-mode-banner:not(.visible)`))&&(this.input.disabled?this.panel.focus({preventScroll:!0}):this.input.focus())}destroy(){this.destroyed=!0,this.stopViewportSync?.(),this.stopViewportSync=null,this.clearPendingFiles(),this.recorder?.destroy(),this.recorder=null,g(this.voicePreviewUrl),this.voicePreviewUrl=``,this.host.remove()}scrollToBottom(){this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight}},bn={apiBaseUrl:u,chatbotName:`AI Assistant`,primaryColor:`#2563EB`,theme:`auto`,position:`bottom-right`,welcomeMessage:``,placeholder:`Type your message…`,autoOpen:!1,sessionId:``,requestTimeoutMs:n};function xn(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var Sn=[5e3,15e3,3e4,6e4];function Cn(e){return c(e)?e.status===0||e.status>=500||e.apiError.code===`BAD_RESPONSE`:!1}function wn(e){return c(e)?e.apiError.message:e instanceof Error?e.message:`Failed to load chatbot config.`}var Tn=0,Q=()=>Date.now()*1e3+Tn++%1e3;function En(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.textMessage==`string`&&t.textMessage.trim())return t.textMessage.trim();if(typeof t.content==`string`&&t.content.trim())return t.content.trim();if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.content==`string`&&e.content.trim())return e.content.trim();if(typeof e.textMessage==`string`&&e.textMessage.trim())return e.textMessage.trim()}return null}function Dn(e){let t=(e.attachments??[]).map(e=>e.url).join(``);return`${e.content}\u0000${t}`}function On(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id==`string`&&t.id)return t.id;if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.id==`string`&&e.id)return e.id}return null}var kn=class{constructor(){this.emitter=new fe,this.visitorTokens=new Nt,this.widget=null,this.sdkSocket=null,this.callerSetName=!1,this.hasActiveTicket=!1,this.retryTimer=null,this.lastPushId=null,this.endedConversationId=null,this.initToken=0,this._state={isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0,blockReason:null,messages:[],visitorToken:null,visitorName:null,error:null,mode:`ai`}}setState(e){this._state={...this._state,...e},this.emitter.emit(`state-change`,this._state)}applyMode(e,t){t?this.syncHasActiveTicket(t):e!==`ai`&&(this.hasActiveTicket=!0),this.setState({mode:e}),this.syncWidgetMode(e,t?.agentName),t&&this.emitter.emit(`ticket-status`,t)}syncHasActiveTicket(e){this.hasActiveTicket=!!(e.conversationId||e.mode!==`ai`)}syncWidgetMode(e,t){this.widget?.setMode(e,{agentName:t,canRequestHuman:e===`ai`&&this.hasActiveTicket,canStartNew:e===`closed`||this.hasActiveTicket})}isEndedConversation(e){return e.mode===`closed`&&!!e.conversationId&&e.conversationId===this.endedConversationId}async init(e){if(!e.apiKey)throw Error("[onedeskpro-chatbot] `apiKey` is required to initialise the chatbot.");let t=++this.initToken;this.clearRetry(),this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.callerSetName=e.chatbotName!==void 0,this.options={...bn,...xn(e)},this.apiClient=new l({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,timeoutMs:this.options.requestTimeoutMs}),this.hasActiveTicket=!1,this.endedConversationId=null,this.setState({isReady:!1,blockReason:null,visitorToken:null,visitorName:null,needsIdentify:!0,messages:[],error:null,mode:`ai`}),await this.checkReadiness(t,0)}async checkReadiness(e,t){let n;try{n=await this.apiClient.fetchConfig()}catch(n){if(e!==this.initToken)return;if(Cn(n)){this.setState({isReady:!1,blockReason:`server-unavailable`,error:wn(n)});let r=Sn[t];if(r!==void 0){this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.checkReadiness(e,t+1)},r);return}}else this.handleConfigError(n);this.emitter.emit(`ready`);return}if(e!==this.initToken)return;!this.callerSetName&&n.agentName.trim()&&(this.options.chatbotName=n.agentName);let r=n.blockReason??null,i=n.ready&&r===null;this.setState({blockReason:r,isReady:i,error:null}),i?(this.mountWidget(),this.visitorTokens.setScope(n.agentId),await this.resolveVisitorGate(e),e===this.initToken&&(this.widget?.reveal(),this.emitter.emit(`ready`))):this.emitter.emit(`ready`)}mountWidget(){typeof window<`u`&&typeof document<`u`&&(this.widget=new yn(this.options,{onSend:e=>void this.sendMessage(e),onSendAttachments:(e,t)=>void this.sendAttachments(e,t),onSendVoice:e=>void this.sendVoice(e),onIdentify:e=>void this.submitIdentify(e),onOpen:()=>{this.setState({isOpen:!0}),this.emitter.emit(`open`)},onClose:()=>{this.setState({isOpen:!1}),this.emitter.emit(`close`)},onNewConversation:()=>void this.startNewConversation(),onRequestHuman:()=>void this.requestHuman(),onCancelHumanRequest:()=>void this.cancelHumanRequest()}))}clearRetry(){this.retryTimer!==null&&(clearTimeout(this.retryTimer),this.retryTimer=null)}handleConfigError(e){let t=(c(e)?e:null)?.apiError.code===`agent_not_assigned`?`no-agent`:null;this.setState({isReady:!1,blockReason:t,error:wn(e)})}async resolveVisitorGate(e){let t=this.visitorTokens.get();if(t){try{let n=await this.apiClient.verifyVisitor(t);if(e!==this.initToken)return;if(n.valid){await this.enterChat(t,n.name,e);return}}catch{}this.visitorTokens.clear()}this.setState({needsIdentify:!0,visitorToken:null,visitorName:null}),this.widget?.showIdentifyForm(this.options)}async enterChat(e,t,n=this.initToken){this.visitorTokens.set(e),this.setState({visitorToken:e,visitorName:t,needsIdentify:!1,messages:[],error:null}),this.widget?.readyToChat(this.options),this.connectSdkSocket(e),await this.restoreTicketStatus(e,n)}connectSdkSocket(e){this.sdkSocket||=new kt,this.sdkSocket.connect({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,visitorToken:e,onTicketStatus:e=>this.handleTicketStatus(e),onMessageReceive:e=>this.handleMessageReceive(e),onReconnect:()=>{let e=this.visitorTokens.get()??this._state.visitorToken;e&&this.restoreTicketStatus(e,this.initToken)},onConnectError:e=>{this.emitter.emit(`error`,e)}})}disconnectSdkSocket(){this.sdkSocket?.disconnect(),this.sdkSocket=null}async restoreTicketStatus(e,t){try{let n=await this.apiClient.fetchTicketStatus(e);if(t!==this.initToken||this.isEndedConversation(n))return;this.applyMode(n.mode,n)}catch{}}handleTicketStatus(e){e?.mode&&!this.isEndedConversation(e)&&this.applyMode(e.mode,e)}handleMessageReceive(e){if(this._state.mode===`ai`)return;let t=En(e)??``,n=ne(e);if(!t&&n.length===0)return;let r=On(e),i=this._state.messages[this._state.messages.length-1];if(i&&Dn(i.message)===Dn({content:t,attachments:n})&&(i.message.type===`ai`||i.message.type===`agent`&&(!r||r===this.lastPushId)))return;this.lastPushId=r;let a=this.visitorTokens.get()??this._state.visitorToken??``,o={id:Q(),sessionId:a,message:{type:`agent`,content:t,...n.length>0?{attachments:n}:{}}};this.setState({messages:[...this._state.messages,o]}),this.widget?.appendMessage(o),this.emitter.emit(`message`,o)}async submitIdentify(e){if(!this.apiClient||this._state.isLoading||!this._state.isReady)return;let t=e.name.trim(),n=e.phone.trim();if(t&&n){this.setState({isLoading:!0,error:null}),this.widget?.setIdentifyLoading(!0);try{let r=await this.apiClient.identify({name:t,phone:n,...e.email?.trim()?{email:e.email.trim()}:{}});await this.enterChat(r.visitorToken,t)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.widget?.showIdentifyError(t.message),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1}),this.widget?.setIdentifyLoading(!1)}}}async requestHuman(){if(!this.apiClient||this._state.mode!==`ai`||!this.hasActiveTicket||this._state.isLoading)return;let e=this.visitorTokens.get()??this._state.visitorToken;if(!e)throw Error(`[onedeskpro-chatbot] Identify before requestHuman().`);this.setState({isLoading:!0,error:null});try{let t=await this.apiClient.requestHuman(e);this.applyMode(t.mode,t),this.emitter.emit(`human-requested`)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1})}}async cancelHumanRequest(){if(!this.apiClient||this._state.mode!==`waiting`||this._state.isLoading)return;let e=this.requireVisitorToken(`cancelHumanRequest`),t=this.initToken;this.setState({isLoading:!0,error:null}),this.widget?.setActionPending(!0),this.widget?.showComposeError(``);try{let n=await this.apiClient.cancelHumanRequest(e);if(t!==this.initToken)return;this.applyMode(n.mode,n),n.mode===`ai`&&this.emitter.emit(`human-request-cancelled`)}catch(e){if(t!==this.initToken)return;this.rejectAction(e,`Could not cancel the request. Please try again.`)}finally{t===this.initToken&&(this.setState({isLoading:!1}),this.widget?.setActionPending(!1))}}async startNewConversation(){if(!this.apiClient||!this._state.isReady||this._state.needsIdentify||this._state.isLoading)return;let e=this.requireVisitorToken(`startNewConversation`),t=this.initToken;this.setState({isLoading:!0,error:null}),this.widget?.setActionPending(!0),this.widget?.showComposeError(``);try{let n=await this.apiClient.closeConversation(e);if(t!==this.initToken)return;this.endedConversationId=n.mode===`closed`?n.conversationId??null:null,this.hasActiveTicket=!1,this.setState({messages:[],error:null,mode:`ai`}),this.widget?.clearMessages(this.options.chatbotName),this.syncWidgetMode(`ai`),this.emitter.emit(`session-reset`)}catch(e){if(t!==this.initToken)return;this.rejectAction(e,`Could not start a new conversation. Please try again.`)}finally{t===this.initToken&&(this.setState({isLoading:!1}),this.widget?.setActionPending(!1))}}rejectAction(e,t){let n=e instanceof Error?e:Error(String(e));this.setState({error:n.message}),this.widget?.showComposeError(t),this.emitter.emit(`error`,n)}requireVisitorToken(e){let t=this.visitorTokens.get()??this._state.visitorToken;if(!this.apiClient||!t)throw Error(`[onedeskpro-chatbot] Identify before ${e}().`);return t}pushLocalMessage(e){this.setState({messages:[...this._state.messages,e],isLoading:!0,error:null}),this.widget?.appendMessage(e),this.emitter.emit(`message`,e)}replaceMessage(e,t){this.setState({messages:this._state.messages.map(n=>n.id===e?t:n)}),this.widget?.replaceMessage(e,t)}removeMessage(e){this.setState({messages:this._state.messages.filter(t=>t.id!==e)}),this.widget?.removeMessage(e)}async sendMessage(e){let t=this.requireVisitorToken(`sendMessage`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}let n=e.trim();if(!n||this._state.isLoading||this._state.needsIdentify)return;let r={id:Q(),sessionId:t,message:{type:`human`,content:n}},i=this._state.mode;this.pushLocalMessage(r),i===`ai`&&this.widget?.setLoading(!0),await this.deliver({chatInput:n,visitorToken:t},i)}rejectSend(e){this.setState({error:e}),this.widget?.showComposeError(e),this.emitter.emit(`error`,Error(e))}async sendAttachments(e,t=``){let n=this.requireVisitorToken(`sendAttachments`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}if(e.length===0||this._state.isLoading||this._state.needsIdentify)return;let r=p(e);r?this.rejectSend(r):await this.uploadThenDeliver({visitorToken:n,files:e,previews:e.map(ee),caption:t.trim()})}async sendVoice(e){let t=this.requireVisitorToken(`sendVoice`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}if(!e?.blob||e.blob.size===0||this._state.isLoading||this._state.needsIdentify)return;let n;try{n=await de(e)}catch{this.rejectSend(`Could not process the recording.`);return}if(n.file.size>10485760){this.rejectSend(`This voice message is too long to send.`);return}let r={durationSeconds:n.durationSeconds,...n.waveform?{waveform:n.waveform}:{}},i={type:n.file.type,url:h(n.file),fileName:n.file.name,size:n.file.size,...r};await this.uploadThenDeliver({visitorToken:t,files:[n.file],previews:[i],caption:``,messageType:`voice`,decorate:e=>({...e,...r})})}async uploadThenDeliver(e){let{visitorToken:t,files:n,previews:r,caption:i}=e,a={id:Q(),sessionId:t,message:{type:`human`,content:i,attachments:r},pending:!0},o=this._state.mode;this.pushLocalMessage(a);let s=[];try{for(let r of n){let n=await this.apiClient.uploadAttachment(r,t);s.push(e.decorate?e.decorate(n):n)}}catch(e){this.removeMessage(a.id);for(let e of r)g(e.url);let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message,isLoading:!1}),this.widget?.showComposeError(t.message),this.emitter.emit(`error`,t);return}let c={...a,pending:!1,message:{...a.message,attachments:s}};this.replaceMessage(a.id,c);for(let e of r)g(e.url);o===`ai`&&this.widget?.setLoading(!0),await this.deliver({chatInput:i,visitorToken:t,attachments:s,...e.messageType?{messageType:e.messageType}:{}},o)}async deliver(e,t){try{let n=await this.apiClient.sendMessage(e);this.hasActiveTicket=!0,this.endedConversationId=null;let r=n.mode??t,i=[...this._state.messages],a=(n.text??``).trim();if(r!==t&&(this.setState({mode:r}),this.syncWidgetMode(r),this.emitter.emit(`ticket-status`,{mode:r})),a){let e=i[i.length-1];if(e?.message.type!==`agent`&&e?.message.type!==`ai`||e.message.content!==a){let e={id:Q(),sessionId:n.sessionId,message:{type:`ai`,content:a}};i.push(e),this.widget?.appendMessage(e),this.emitter.emit(`message`,e)}}this.setState({messages:i,isLoading:!1,mode:r}),this.syncWidgetMode(r)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message,isLoading:!1}),this.emitter.emit(`error`,t)}finally{this.widget?.setLoading(!1)}}on(e,t){return this.emitter.on(e,t)}resetSession(){this._state.isReady&&!this._state.needsIdentify&&this._state.mode===`closed`&&(this.hasActiveTicket=!1,this.setState({messages:[],error:null,mode:`ai`}),this.widget?.clearMessages(this.options.chatbotName),this.syncWidgetMode(`ai`),this.emitter.emit(`session-reset`))}open(){this.widget?.open()}close(){this.widget?.close()}toggle(){this.widget?.toggle()}getState(){return{...this._state}}destroy(){this.initToken++,this.clearRetry(),this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.setState({isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0})}},$=null,An={async init(e){return $=new kn,await $.init(e),$},getInstance(){return $}};exports.ApiClient=l,exports.ChatbotCore=kn,exports.DEFAULT_API_BASE_URL=u,exports.DEFAULT_REQUEST_TIMEOUT_MS=n,exports.EventEmitter=fe,exports.OnedeskProChatbot=An,exports.SDK_CHAT_MAX_ATTACHMENTS=f,exports.SDK_UPLOAD_MAX_BYTES=d,exports.SdkSocket=kt,exports.SessionManager=Nt,exports.VOICE_MAX_DURATION_SECONDS=Pt,exports.VoiceRecorder=Bt,exports.isChatbotRequestError=c,exports.resolveSdkSocketUrl=Ot;
|
|
800
|
+
`,t.addEventListener(`click`,()=>{this.selectedCountry=e,this.syncDialButton(),this.closeCountryPopover(),this.phoneInput.focus()}),this.countryList.appendChild(t)}}attachToDocument(){let e=()=>{this.destroyed||(document.body??document.documentElement).appendChild(this.host)};document.body?e():document.addEventListener(`DOMContentLoaded`,e,{once:!0})}showInitialLoading(){this.setPanelMode(`compact`),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.add(`hidden`),this.messagesContainer.innerHTML=``,this.input.disabled=!0,this.sendBtn.disabled=!0;let e=document.createElement(`div`);e.className=`ttcb-initial-loading`,e.id=`ttcb-initial-loading`;let t=document.createElement(`div`);t.className=`ttcb-spinner`;let n=document.createElement(`p`);n.textContent=`Loading…`,e.appendChild(t),e.appendChild(n),this.messagesContainer.appendChild(e)}showEmptyState(e){let t=document.createElement(`div`);t.className=`ttcb-empty`,t.id=`ttcb-empty`;let n=document.createElement(`div`);n.className=`ttcb-empty-icon`,n.innerHTML=X();let r=document.createElement(`p`),i=document.createElement(`strong`);i.textContent=e,r.appendChild(document.createTextNode(`Welcome to `)),r.appendChild(i);let a=document.createElement(`p`);a.textContent=`Ask me anything — I'm here to help!`,a.style.marginTop=`6px`,a.style.fontSize=`12px`,t.appendChild(n),t.appendChild(r),t.appendChild(a),this.messagesContainer.appendChild(t)}removeEmptyState(){let e=this.shadow.getElementById(`ttcb-empty`);e&&e.remove()}handleSend(){let e=this.input.value.trim();if(!this.sendBtn.disabled){if(this.pendingFiles.length>0){let t=this.pendingFiles.map(e=>e.file);this.clearPendingFiles(),this.showComposeError(``),this.input.value=``,this.callbacks.onSendAttachments(t,e),this.input.focus()}else e&&(this.input.value=``,this.callbacks.onSend(e),this.input.focus())}}handleIdentifySubmit(){let e=this.nameInput.value.trim(),t=Ut(this.selectedCountry.dial,this.phoneInput.value),n=this.emailInput.value.trim();!e||!t?this.showIdentifyError(`Name and phone are required.`):(this.showIdentifyError(``),this.callbacks.onIdentify({name:e,phone:t,...n?{email:n}:{}}))}appendMessage(e){this.removeEmptyState();let t=this.buildMessage(e);this.messagesContainer.appendChild(t),this.scrollToBottom()}replaceMessage(e,t){let n=this.findMessageEl(e);n?(n.replaceWith(this.buildMessage(t)),this.scrollToBottom()):this.appendMessage(t)}removeMessage(e){this.findMessageEl(e)?.remove()}buildMessage(e){if(`message`in e){let t=gn({...e.message,pending:e.pending});return t.dataset.msgId=String(e.id),t}return gn(e)}findMessageEl(e){for(let t of this.messagesContainer.querySelectorAll(`.ttcb-msg`))if(t.dataset.msgId===String(e))return t;return null}setMessages(e){if(this.messagesContainer.innerHTML=``,e.length!==0){for(let t of e)this.messagesContainer.appendChild(this.buildMessage(t));this.scrollToBottom()}}setLoading(e){if(this.sendBtn.disabled=e||this.input.disabled,this.attachBtn.disabled=e||this.input.disabled,this.micBtn.disabled=e||this.input.disabled,e)this.closeAttachMenu(),this.shadow.getElementById(`ttcb-typing`)||(this.messagesContainer.appendChild(_n()),this.scrollToBottom()),this.isFullScreen()||this.input.focus();else{let e=this.shadow.getElementById(`ttcb-typing`);e&&e.remove(),!this.input.disabled&&!this.isFullScreen()&&this.input.focus()}}setIdentifyLoading(e){this.identifySubmit.disabled=e,this.nameInput.disabled=e,this.phoneInput.disabled=e,this.emailInput.disabled=e,this.dialBtn.disabled=e,this.shadow.getElementById(`ttcb-phone-row`)?.classList.toggle(`disabled`,e);for(let t of this.identifyContainer.querySelectorAll(`.ttcb-input-wrap`))t.classList.toggle(`disabled`,e);this.identifySubmit.innerHTML=e?`<span>Starting…</span>`:`<span>Start Chatting</span>${nn()}`,e&&this.closeCountryPopover()}showIdentifyError(e){this.identifyError.textContent=e}open(){this.isOpen=!0,this.startViewportSync(),this.panel.classList.remove(`hidden`),this.fab.classList.add(`ttcb-open`),this.isFullScreen()?this.panel.focus({preventScroll:!0}):this.identifyContainer.classList.contains(`visible`)?this.nameInput.focus():this.input.focus(),this.callbacks.onOpen()}close(){this.isOpen=!1,this.closeCountryPopover(),this.closeAttachMenu(),this.panel.classList.add(`hidden`),this.fab.classList.remove(`ttcb-open`),this.stopViewportSync?.(),this.stopViewportSync=null,this.fab.focus({preventScroll:!0}),this.callbacks.onClose()}isFullScreen(){return typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 640px), (max-height: 500px) and (pointer: coarse)`).matches}startViewportSync(){let e=window.visualViewport;if(!e||this.stopViewportSync)return;let t=()=>{let t=this.messagesContainer,n=t.scrollHeight-t.scrollTop-t.clientHeight<40;this.panel.style.setProperty(`--ttcb-vv-top`,`${e.offsetTop}px`),this.panel.style.setProperty(`--ttcb-vv-left`,`${e.offsetLeft}px`),this.panel.style.setProperty(`--ttcb-vv-width`,`${e.width}px`),this.panel.style.setProperty(`--ttcb-vv-height`,`${e.height}px`),n&&this.scrollToBottom()};e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),this.stopViewportSync=()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}}toggle(){this.isOpen?this.close():this.open()}showIdentifyForm(e){this.setPanelMode(`form`),e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),this.messagesContainer.classList.add(`hidden`),this.footer.classList.add(`hidden`),this.identifyContainer.classList.add(`visible`),this.showIdentifyError(``),this.setIdentifyLoading(!1)}readyToChat(e){this.setPanelMode(`chat`),this.closeCountryPopover(),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.remove(`hidden`),this.messagesContainer.innerHTML=``,e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),e.welcomeMessage?this.appendMessage({type:`ai`,content:e.welcomeMessage}):this.showEmptyState(e.chatbotName??`AI Assistant`),this.setMode(`ai`)}clearMessages(e){this.messagesContainer.innerHTML=``,this.clearPendingFiles(),this.showComposeError(``),this.hideConfirmNew(),this.showEmptyState(e)}setMode(e,t){let n=this.panel.classList.contains(`ttcb-mode-chat`),r=t?.agentName,i=t?.canRequestHuman===!0,a=t?.canStartNew??e===`closed`,o=n&&i,s=n&&a,c=e===`closed`;this.ticketMode=e,this.requestHumanBtn.classList.toggle(`hidden`,!o),this.newSessionBtn.classList.toggle(`hidden`,!s),(!s||c)&&this.hideConfirmNew(),this.input.disabled=c,c?(this.sendBtn.disabled=!0,this.attachBtn.disabled=!0,this.micBtn.disabled=!0,this.closeAttachMenu(),this.clearPendingFiles(),this.recorder&&this.cancelVoice(),this.showComposeError(``)):this.shadow.getElementById(`ttcb-typing`)||(this.sendBtn.disabled=!1,this.attachBtn.disabled=!1,this.micBtn.disabled=!1),n?(e===`waiting`?this.showModeBanner(`Waiting for a human agent…`,`waiting`):e===`closed`?this.showModeBanner(`This conversation is closed`,`closed`):e===`human`&&r?.trim()?this.showModeBanner(`Connected with ${r.trim()}`,`human`):this.hideModeBanner(),this.rescueFocus()):(this.hideModeBanner(),this.rescueFocus())}showModeBanner(e,t){this.modeBannerText.textContent=e,this.modeBanner.className=`ttcb-mode-banner visible ${t}`,this.cancelHumanBtn.classList.toggle(`hidden`,t!==`waiting`)}hideModeBanner(){this.modeBannerText.textContent=``,this.modeBanner.className=`ttcb-mode-banner`,this.cancelHumanBtn.classList.add(`hidden`)}rescueFocus(){let e=this.shadow.activeElement;e instanceof HTMLElement&&(e.closest(`.hidden`)||e.closest(`.ttcb-mode-banner:not(.visible)`))&&(this.input.disabled?this.panel.focus({preventScroll:!0}):this.input.focus())}destroy(){this.destroyed=!0,this.stopViewportSync?.(),this.stopViewportSync=null,this.clearPendingFiles(),this.recorder?.destroy(),this.recorder=null,g(this.voicePreviewUrl),this.voicePreviewUrl=``,this.host.remove()}scrollToBottom(){this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight}},xn={apiBaseUrl:u,chatbotName:`AI Assistant`,primaryColor:`#2563EB`,theme:`auto`,position:`bottom-right`,welcomeMessage:``,placeholder:`Type your message…`,autoOpen:!1,sessionId:``,requestTimeoutMs:n};function Sn(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var Cn=[5e3,15e3,3e4,6e4];function wn(e){return c(e)?e.status===0||e.status>=500||e.apiError.code===`BAD_RESPONSE`:!1}function Tn(e){return c(e)?e.apiError.message:e instanceof Error?e.message:`Failed to load chatbot config.`}var En=0,Z=()=>Date.now()*1e3+En++%1e3;function Dn(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.textMessage==`string`&&t.textMessage.trim())return t.textMessage.trim();if(typeof t.content==`string`&&t.content.trim())return t.content.trim();if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.content==`string`&&e.content.trim())return e.content.trim();if(typeof e.textMessage==`string`&&e.textMessage.trim())return e.textMessage.trim()}return null}function Q(e){let t=(e.attachments??[]).map(e=>e.url).join(``);return`${e.content}\u0000${t}`}function On(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id==`string`&&t.id)return t.id;if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.id==`string`&&e.id)return e.id}return null}var kn=class{constructor(){this.emitter=new fe,this.visitorTokens=new Nt,this.widget=null,this.sdkSocket=null,this.callerSetName=!1,this.hasActiveTicket=!1,this.retryTimer=null,this.lastPushId=null,this.endedConversationId=null,this.initToken=0,this._state={isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0,blockReason:null,messages:[],visitorToken:null,visitorName:null,error:null,mode:`ai`}}setState(e){this._state={...this._state,...e},this.emitter.emit(`state-change`,this._state)}applyMode(e,t){t?this.syncHasActiveTicket(t):e!==`ai`&&(this.hasActiveTicket=!0),this.setState({mode:e}),this.syncWidgetMode(e,t?.agentName),t&&this.emitter.emit(`ticket-status`,t)}syncHasActiveTicket(e){this.hasActiveTicket=!!(e.conversationId||e.mode!==`ai`)}syncWidgetMode(e,t){this.widget?.setMode(e,{agentName:t,canRequestHuman:e===`ai`&&this.hasActiveTicket,canStartNew:e===`closed`||this.hasActiveTicket})}isEndedConversation(e){return e.mode===`closed`&&!!e.conversationId&&e.conversationId===this.endedConversationId}async init(e){if(!e.apiKey)throw Error("[onedeskpro-chatbot] `apiKey` is required to initialise the chatbot.");let t=++this.initToken;this.clearRetry(),this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.callerSetName=e.chatbotName!==void 0,this.options={...xn,...Sn(e)},this.apiClient=new l({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,timeoutMs:this.options.requestTimeoutMs}),this.hasActiveTicket=!1,this.endedConversationId=null,this.setState({isReady:!1,blockReason:null,visitorToken:null,visitorName:null,needsIdentify:!0,messages:[],error:null,mode:`ai`}),await this.checkReadiness(t,0)}async checkReadiness(e,t){let n;try{n=await this.apiClient.fetchConfig()}catch(n){if(e!==this.initToken)return;if(wn(n)){this.setState({isReady:!1,blockReason:`server-unavailable`,error:Tn(n)});let r=Cn[t];if(r!==void 0){this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.checkReadiness(e,t+1)},r);return}}else this.handleConfigError(n);this.emitter.emit(`ready`);return}if(e!==this.initToken)return;!this.callerSetName&&n.agentName.trim()&&(this.options.chatbotName=n.agentName);let r=n.blockReason??null,i=n.ready&&r===null;this.setState({blockReason:r,isReady:i,error:null}),i?(this.mountWidget(),this.visitorTokens.setScope(n.agentId),await this.resolveVisitorGate(e),e===this.initToken&&(this.widget?.reveal(),this.emitter.emit(`ready`))):this.emitter.emit(`ready`)}mountWidget(){typeof window<`u`&&typeof document<`u`&&(this.widget=new bn(this.options,{onSend:e=>void this.sendMessage(e),onSendAttachments:(e,t)=>void this.sendAttachments(e,t),onSendVoice:e=>void this.sendVoice(e),onIdentify:e=>void this.submitIdentify(e),onOpen:()=>{this.setState({isOpen:!0}),this.emitter.emit(`open`)},onClose:()=>{this.setState({isOpen:!1}),this.emitter.emit(`close`)},onNewConversation:()=>void this.startNewConversation(),onRequestHuman:()=>void this.requestHuman(),onCancelHumanRequest:()=>void this.cancelHumanRequest()}))}clearRetry(){this.retryTimer!==null&&(clearTimeout(this.retryTimer),this.retryTimer=null)}handleConfigError(e){let t=(c(e)?e:null)?.apiError.code===`agent_not_assigned`?`no-agent`:null;this.setState({isReady:!1,blockReason:t,error:Tn(e)})}async resolveVisitorGate(e){let t=this.visitorTokens.get();if(t){try{let n=await this.apiClient.verifyVisitor(t);if(e!==this.initToken)return;if(n.valid){await this.enterChat(t,n.name,e);return}}catch{}this.visitorTokens.clear()}this.setState({needsIdentify:!0,visitorToken:null,visitorName:null}),this.widget?.showIdentifyForm(this.options)}async enterChat(e,t,n=this.initToken){this.visitorTokens.set(e),this.setState({visitorToken:e,visitorName:t,needsIdentify:!1,messages:[],error:null}),this.widget?.readyToChat(this.options),this.connectSdkSocket(e),await this.restoreTicketStatus(e,n)}connectSdkSocket(e){this.sdkSocket||=new Ot,this.sdkSocket.connect({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,visitorToken:e,onTicketStatus:e=>this.handleTicketStatus(e),onMessageReceive:e=>this.handleMessageReceive(e),onReconnect:()=>{let e=this.visitorTokens.get()??this._state.visitorToken;e&&this.restoreTicketStatus(e,this.initToken)},onConnectError:e=>{this.emitter.emit(`error`,e)}})}disconnectSdkSocket(){this.sdkSocket?.disconnect(),this.sdkSocket=null}async restoreTicketStatus(e,t){try{let n=await this.apiClient.fetchTicketStatus(e);if(t!==this.initToken||this.isEndedConversation(n))return;this.applyMode(n.mode,n)}catch{}}handleTicketStatus(e){e?.mode&&!this.isEndedConversation(e)&&this.applyMode(e.mode,e)}handleMessageReceive(e){if(this._state.mode===`ai`)return;let t=Dn(e)??``,n=ne(e);if(!t&&n.length===0)return;let r=On(e),i=this._state.messages[this._state.messages.length-1];if(i&&Q(i.message)===Q({content:t,attachments:n})&&(i.message.type===`ai`||i.message.type===`agent`&&(!r||r===this.lastPushId)))return;this.lastPushId=r;let a=this.visitorTokens.get()??this._state.visitorToken??``,o={id:Z(),sessionId:a,message:{type:`agent`,content:t,...n.length>0?{attachments:n}:{}}};this.setState({messages:[...this._state.messages,o]}),this.widget?.appendMessage(o),this.emitter.emit(`message`,o)}async submitIdentify(e){if(!this.apiClient||this._state.isLoading||!this._state.isReady)return;let t=e.name.trim(),n=e.phone.trim();if(t&&n){this.setState({isLoading:!0,error:null}),this.widget?.setIdentifyLoading(!0);try{let r=await this.apiClient.identify({name:t,phone:n,...e.email?.trim()?{email:e.email.trim()}:{}});await this.enterChat(r.visitorToken,t)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.widget?.showIdentifyError(t.message),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1}),this.widget?.setIdentifyLoading(!1)}}}async requestHuman(){if(!this.apiClient||this._state.mode!==`ai`||!this.hasActiveTicket||this._state.isLoading)return;let e=this.visitorTokens.get()??this._state.visitorToken;if(!e)throw Error(`[onedeskpro-chatbot] Identify before requestHuman().`);this.setState({isLoading:!0,error:null});try{let t=await this.apiClient.requestHuman(e);this.applyMode(t.mode,t),this.emitter.emit(`human-requested`)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1})}}async cancelHumanRequest(){if(!this.apiClient||this._state.mode!==`waiting`||this._state.isLoading)return;let e=this.requireVisitorToken(`cancelHumanRequest`),t=this.initToken;this.setState({isLoading:!0,error:null}),this.widget?.setActionPending(!0),this.widget?.showComposeError(``);try{let n=await this.apiClient.cancelHumanRequest(e);if(t!==this.initToken)return;this.applyMode(n.mode,n),n.mode===`ai`&&this.emitter.emit(`human-request-cancelled`)}catch(e){if(t!==this.initToken)return;this.rejectAction(e,`Could not cancel the request. Please try again.`)}finally{t===this.initToken&&(this.setState({isLoading:!1}),this.widget?.setActionPending(!1))}}async startNewConversation(){if(!this.apiClient||!this._state.isReady||this._state.needsIdentify||this._state.isLoading)return;let e=this.requireVisitorToken(`startNewConversation`),t=this.initToken;this.setState({isLoading:!0,error:null}),this.widget?.setActionPending(!0),this.widget?.showComposeError(``);try{let n=await this.apiClient.closeConversation(e);if(t!==this.initToken)return;this.endedConversationId=n.mode===`closed`?n.conversationId??null:null,this.hasActiveTicket=!1,this.setState({messages:[],error:null,mode:`ai`}),this.widget?.clearMessages(this.options.chatbotName),this.syncWidgetMode(`ai`),this.emitter.emit(`session-reset`)}catch(e){if(t!==this.initToken)return;this.rejectAction(e,`Could not start a new conversation. Please try again.`)}finally{t===this.initToken&&(this.setState({isLoading:!1}),this.widget?.setActionPending(!1))}}rejectAction(e,t){let n=e instanceof Error?e:Error(String(e));this.setState({error:n.message}),this.widget?.showComposeError(t),this.emitter.emit(`error`,n)}requireVisitorToken(e){let t=this.visitorTokens.get()??this._state.visitorToken;if(!this.apiClient||!t)throw Error(`[onedeskpro-chatbot] Identify before ${e}().`);return t}pushLocalMessage(e){this.setState({messages:[...this._state.messages,e],isLoading:!0,error:null}),this.widget?.appendMessage(e),this.emitter.emit(`message`,e)}replaceMessage(e,t){this.setState({messages:this._state.messages.map(n=>n.id===e?t:n)}),this.widget?.replaceMessage(e,t)}removeMessage(e){this.setState({messages:this._state.messages.filter(t=>t.id!==e)}),this.widget?.removeMessage(e)}async sendMessage(e){let t=this.requireVisitorToken(`sendMessage`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}let n=e.trim();if(!n||this._state.isLoading||this._state.needsIdentify)return;let r={id:Z(),sessionId:t,message:{type:`human`,content:n}},i=this._state.mode;this.pushLocalMessage(r),i===`ai`&&this.widget?.setLoading(!0),await this.deliver({chatInput:n,visitorToken:t},i)}rejectSend(e){this.setState({error:e}),this.widget?.showComposeError(e),this.emitter.emit(`error`,Error(e))}async sendAttachments(e,t=``){let n=this.requireVisitorToken(`sendAttachments`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}if(e.length===0||this._state.isLoading||this._state.needsIdentify)return;let r=p(e);r?this.rejectSend(r):await this.uploadThenDeliver({visitorToken:n,files:e,previews:e.map(ee),caption:t.trim()})}async sendVoice(e){let t=this.requireVisitorToken(`sendVoice`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}if(!e?.blob||e.blob.size===0||this._state.isLoading||this._state.needsIdentify)return;let n;try{n=await de(e)}catch{this.rejectSend(`Could not process the recording.`);return}if(n.file.size>10485760){this.rejectSend(`This voice message is too long to send.`);return}let r={durationSeconds:n.durationSeconds,...n.waveform?{waveform:n.waveform}:{}},i={type:n.file.type,url:h(n.file),fileName:n.file.name,size:n.file.size,...r};await this.uploadThenDeliver({visitorToken:t,files:[n.file],previews:[i],caption:``,messageType:`voice`,decorate:e=>({...e,...r})})}async uploadThenDeliver(e){let{visitorToken:t,files:n,previews:r,caption:i}=e,a={id:Z(),sessionId:t,message:{type:`human`,content:i,attachments:r},pending:!0},o=this._state.mode;this.pushLocalMessage(a);let s=[];try{for(let r of n){let n=await this.apiClient.uploadAttachment(r,t);s.push(e.decorate?e.decorate(n):n)}}catch(e){this.removeMessage(a.id);for(let e of r)g(e.url);let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message,isLoading:!1}),this.widget?.showComposeError(t.message),this.emitter.emit(`error`,t);return}let c={...a,pending:!1,message:{...a.message,attachments:s}};this.replaceMessage(a.id,c);for(let e of r)g(e.url);o===`ai`&&this.widget?.setLoading(!0),await this.deliver({chatInput:i,visitorToken:t,attachments:s,...e.messageType?{messageType:e.messageType}:{}},o)}async deliver(e,t){try{let n=await this.apiClient.sendMessage(e);this.hasActiveTicket=!0,this.endedConversationId=null;let r=n.mode??t,i=[...this._state.messages],a=(n.text??``).trim(),o=ne(n);if(r!==t&&(this.setState({mode:r}),this.syncWidgetMode(r),this.emitter.emit(`ticket-status`,{mode:r})),a||o.length>0){let e=i[i.length-1];if(e?.message.type!==`agent`&&e?.message.type!==`ai`||Q(e.message)!==Q({content:a,attachments:o})){let e={id:Z(),sessionId:n.sessionId,message:{type:`ai`,content:a,...o.length>0?{attachments:o}:{}}};i.push(e),this.widget?.appendMessage(e),this.emitter.emit(`message`,e)}}this.setState({messages:i,isLoading:!1,mode:r}),this.syncWidgetMode(r)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message,isLoading:!1}),this.emitter.emit(`error`,t)}finally{this.widget?.setLoading(!1)}}on(e,t){return this.emitter.on(e,t)}resetSession(){this._state.isReady&&!this._state.needsIdentify&&this._state.mode===`closed`&&(this.hasActiveTicket=!1,this.setState({messages:[],error:null,mode:`ai`}),this.widget?.clearMessages(this.options.chatbotName),this.syncWidgetMode(`ai`),this.emitter.emit(`session-reset`))}open(){this.widget?.open()}close(){this.widget?.close()}toggle(){this.widget?.toggle()}getState(){return{...this._state}}destroy(){this.initToken++,this.clearRetry(),this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.setState({isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0})}},$=null,An={async init(e){return $=new kn,await $.init(e),$},getInstance(){return $}};exports.ApiClient=l,exports.ChatbotCore=kn,exports.DEFAULT_API_BASE_URL=u,exports.DEFAULT_REQUEST_TIMEOUT_MS=n,exports.EventEmitter=fe,exports.OnedeskProChatbot=An,exports.SDK_CHAT_MAX_ATTACHMENTS=f,exports.SDK_UPLOAD_MAX_BYTES=d,exports.SdkSocket=Ot,exports.SessionManager=Nt,exports.VOICE_MAX_DURATION_SECONDS=Pt,exports.VoiceRecorder=Bt,exports.isChatbotRequestError=c,exports.resolveSdkSocketUrl=Dt;
|