@onedeskpro/chatbot-core 0.1.0 โ†’ 0.2.1

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 CHANGED
@@ -1,32 +1,36 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=3e4;function T(i){return typeof i=="object"&&i!==null&&typeof i.message=="string"}class v{constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,""),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??g}fail(t,e,n,s){const a={statusCode:e,message:t,code:n,timestamp:new Date().toISOString(),path:s};throw Object.assign(new Error(t),{apiError:a,status:e})}async request(t,e,n,s){const a=new URL(`${this.baseUrl}${e}`);if(s)for(const[p,M]of Object.entries(s))a.searchParams.set(p,M);const l={"Content-Type":"application/json","X-API-Key":this.apiKey},r=new AbortController,o=setTimeout(()=>r.abort(),this.timeoutMs);let c;try{c=await fetch(a.toString(),{method:t,headers:l,signal:r.signal,...n!==void 0?{body:JSON.stringify(n)}:{}})}catch(p){r.signal.aborted&&this.fail(`Request timed out after ${this.timeoutMs}ms.`,0,"TIMEOUT",e),this.fail(p instanceof Error?p.message:"Network request failed.",0,"NETWORK_ERROR",e)}finally{clearTimeout(o)}const d=await c.text();let h=null;if(d)try{h=JSON.parse(d)}catch{h=null}if(!c.ok){if(T(h))throw Object.assign(new Error(h.message),{apiError:h,status:c.status});this.fail(`Request failed with status ${c.status} ${c.statusText}`.trim(),c.status,"HTTP_ERROR",e)}return h===null&&this.fail("The server returned an empty or malformed response.",c.status,"BAD_RESPONSE",e),h.data}async sendMessage(t){return this.request("POST","/sdk/chat",t)}async fetchHistory(t){return this.request("GET","/sdk/chat-history",void 0,{sessionId:t})}async fetchConfig(){return this.request("GET","/sdk/config")}}const C="https://api.onedeskpro.com";class E{constructor(){this._listeners={}}on(t,e){return this._listeners[t]||(this._listeners[t]=[]),this._listeners[t].push(e),()=>this.off(t,e)}off(t,e){const n=this._listeners[t];n&&(this._listeners[t]=n.filter(s=>s!==e))}emit(t,...e){const n=this._listeners[t];if(n)for(const s of n)s(...e)}removeAllListeners(){for(const t of Object.keys(this._listeners))delete this._listeners[t]}}const f="onedeskpro_chatbot_session_id";function I(i){try{return typeof window<"u"?window.localStorage.getItem(i):null}catch{return null}}function L(i,t){try{typeof window<"u"&&window.localStorage.setItem(i,t)}catch{}}class k{constructor(){this.sessionId=null}init(t){if(t)return this.sessionId=t,this.persist(),this.sessionId;const e=I(f);return e?this.sessionId=e:(this.sessionId=this.generateId(),this.persist()),this.sessionId}get(){return this.sessionId}reset(){return this.sessionId=this.generateId(),this.persist(),this.sessionId}persist(){this.sessionId&&L(f,this.sessionId)}generateId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2)+Date.now().toString(36)}}function N(i,t){const e=`
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;function r(e){return typeof e==`object`&&!!e&&typeof e.message==`string`}function i(e){return e instanceof Error&&`apiError`in e&&`status`in e&&typeof e.status==`number`&&r(e.apiError)}var a=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,``),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??3e4}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,i,a){let o=new URL(`${this.baseUrl}${t}`);if(i)for(let[e,t]of Object.entries(i))o.searchParams.set(e,t);let s={"Content-Type":`application/json`,"X-API-Key":this.apiKey,...a},c=new AbortController,l=setTimeout(()=>c.abort(),this.timeoutMs),u;try{u=await fetch(o.toString(),{method:e,headers:s,signal:c.signal,...n===void 0?{}:{body:JSON.stringify(n)}})}catch(e){c.signal.aborted&&this.fail(`Request timed out after ${this.timeoutMs}ms.`,0,`TIMEOUT`,t),this.fail(e instanceof Error?e.message:`Network request failed.`,0,`NETWORK_ERROR`,t)}finally{clearTimeout(l)}let d=await u.text(),f=null;if(d)try{f=JSON.parse(d)}catch{f=null}if(!u.ok){if(r(f))throw Object.assign(Error(f.message),{apiError:f,status:u.status});this.fail(`Request failed with status ${u.status} ${u.statusText}`.trim(),u.status,`HTTP_ERROR`,t)}return f===null&&this.fail(`The server returned an empty or malformed response.`,u.status,`BAD_RESPONSE`,t),f.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 fetchConfig(){return this.request(`GET`,`/sdk/config`)}async requestHuman(e){return this.request(`POST`,`/sdk/human-request`,{visitorToken:e})}async fetchTicketStatus(e){return this.request(`GET`,`/sdk/ticket-status`,void 0,void 0,{"X-Visitor-Token":e})}},o=`https://api.onedeskpro.com`,s=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]}},c=Object.create(null);c.open=`0`,c.close=`1`,c.ping=`2`,c.pong=`3`,c.message=`4`,c.upgrade=`5`,c.noop=`6`;var l=Object.create(null);Object.keys(c).forEach(e=>{l[c[e]]=e});var u={type:`error`,data:`parser error`},d=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,f=typeof ArrayBuffer==`function`,p=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,m=({type:e,data:t},n,r)=>d&&t instanceof Blob?n?r(t):ee(t,r):f&&(t instanceof ArrayBuffer||p(t))?n?r(t):ee(new Blob([t]),r):r(c[e]+(t||``)),ee=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function te(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var h;function ne(e,t){if(d&&e.data instanceof Blob)return e.data.arrayBuffer().then(te).then(t);if(f&&(e.data instanceof ArrayBuffer||p(e.data)))return t(te(e.data));m(e,!1,e=>{h||=new TextEncoder,t(h.encode(e))})}var re=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,g=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)g[re.charCodeAt(e)]=e;var ie=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=g[e.charCodeAt(r)],o=g[e.charCodeAt(r+1)],s=g[e.charCodeAt(r+2)],c=g[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},ae=typeof ArrayBuffer==`function`,_=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:v(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:oe(e.substring(1),t)}:l[n]?e.length>1?{type:l[n],data:e.substring(1)}:{type:l[n]}:u},oe=(e,t)=>ae?v(ie(e),t):{base64:!0,data:e},v=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},y=``,se=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{m(e,!1,e=>{r[a]=e,++i===n&&t(r.join(y))})})},ce=(e,t)=>{let n=e.split(y),r=[];for(let e=0;e<n.length;e++){let i=_(n[e],t);if(r.push(i),i.type===`error`)break}return r};function le(){return new TransformStream({transform(e,t){ne(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 ue;function b(e){return e.reduce((e,t)=>e+t.length,0)}function x(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 de(e,t){ue||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(b(n)<1)break;let e=x(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(b(n)<2)break;let e=x(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(b(n)<8)break;let e=x(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(u);break}i=a*2**32+t.getUint32(4),r=3}else{if(b(n)<i)break;let e=x(n,i);s.enqueue(_(a?e:ue.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(u);break}}}})}function S(e){if(e)return fe(e)}function fe(e){for(var t in S.prototype)e[t]=S.prototype[t];return e}S.prototype.on=S.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},S.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},S.prototype.off=S.prototype.removeListener=S.prototype.removeAllListeners=S.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},S.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},S.prototype.emitReserved=S.prototype.emit,S.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},S.prototype.hasListeners=function(e){return!!this.listeners(e).length};var C=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),w=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),pe=`arraybuffer`;function me(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var he=w.setTimeout,ge=w.clearTimeout;function T(e,t){t.useNativeTimers?(e.setTimeoutFn=he.bind(w),e.clearTimeoutFn=ge.bind(w)):(e.setTimeoutFn=w.setTimeout.bind(w),e.clearTimeoutFn=w.clearTimeout.bind(w))}var _e=1.33;function ve(e){return typeof e==`string`?ye(e):Math.ceil((e.byteLength||e.size)*_e)}function ye(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 xe(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Se(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 Ce=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},E=class extends S{constructor(e){super(),this.writable=!1,T(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 Ce(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=_(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=xe(e);return t.length?`?`+t:``}},we=class extends E{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){ce(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,se(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)}},Te=!1;try{Te=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Ee=Te;function De(){}var Oe=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}},D=class e extends S{constructor(e,t,n){super(),this.createRequest=e,T(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=me(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=De,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(D.requestsCount=0,D.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,ke);else if(typeof addEventListener==`function`){let e=`onpagehide`in w?`pagehide`:`unload`;addEventListener(e,ke,!1)}}function ke(){for(let e in D.requests)D.requests.hasOwnProperty(e)&&D.requests[e].abort()}var Ae=(function(){let e=Me({xdomain:!1});return e&&e.responseType!==null})(),je=class extends Oe{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Ae&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new D(Me,this.uri(),e)}};function Me(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Ee))return new XMLHttpRequest}catch{}if(!t)try{return new w[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var Ne=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Pe=class extends E{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Ne?{}:me(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;m(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&C(()=>{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)}},O=w.WebSocket||w.MozWebSocket,Fe={websocket:class extends Pe{createSocket(e,t,n){return Ne?new O(e,t,n):t?new O(e,t):new O(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends E{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=de(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=le();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&&C(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:je},Ie=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Le=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function k(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=Ie.exec(e||``),a={},o=14;for(;o--;)a[Le[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=Re(a,a.path),a.queryKey=ze(a,a.query),a}function Re(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 ze(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var A=typeof addEventListener==`function`&&typeof removeEventListener==`function`,j=[];A&&addEventListener(`offline`,()=>{j.forEach(e=>e())},!1);var M=class e extends S{constructor(e,t){if(super(),this.binaryType=pe,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=k(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=k(t.host).host);T(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=Se(this.opts.query)),A&&(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`})},j.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+=ve(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,C(()=>{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(),A&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=j.indexOf(this._offlineEventListener);e!==-1&&j.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};M.protocol=4;var Be=class extends M{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;M.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;M.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}},N=class extends Be{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=>Fe[e]).filter(e=>!!e)),super(n?r:e,r)}};N.protocol;function Ve(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=k(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 He=typeof ArrayBuffer==`function`,Ue=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,P=Object.prototype.toString,We=typeof Blob==`function`||typeof Blob<`u`&&P.call(Blob)===`[object BlobConstructor]`,Ge=typeof File==`function`||typeof File<`u`&&P.call(File)===`[object FileConstructor]`;function F(e){return He&&(e instanceof ArrayBuffer||Ue(e))||We&&e instanceof Blob||Ge&&e instanceof File}function I(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(I(e[t]))return!0;return!1}if(F(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return I(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&I(e[t]))return!0;return!1}function Ke(e){let t=[],n=e.data,r=e;return r.data=L(n,t),r.attachments=t.length,{packet:r,buffers:t}}function L(e,t,n){if(!e)return e;if(F(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]=L(e[r],t);return n}if(typeof e==`object`&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON==`function`&&!n)return L(e.toJSON(),t,!0);let r={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=L(e[n],t));return r}return e}function qe(e,t){return e.data=R(e.data,t),delete e.attachments,e}function R(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]=R(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=R(e[n],t));return e}var Je=t({Decoder:()=>Xe,Encoder:()=>Ye,PacketType:()=>B,isPacketValid:()=>nt,protocol:()=>5}),z=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],B;(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`})(B||={});var Ye=class{constructor(e){this.replacer=e}encode(e){return(e.type===B.EVENT||e.type===B.ACK)&&I(e)?this.encodeAsBinary({type:e.type===B.EVENT?B.BINARY_EVENT:B.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===B.BINARY_EVENT||e.type===B.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=Ke(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Xe=class e extends S{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===B.BINARY_EVENT;n||t.type===B.BINARY_ACK?(t.type=n?B.EVENT:B.ACK,this.reconstructor=new Ze(t)):super.emitReserved(`decoded`,t)}else if(F(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(B[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===B.BINARY_EVENT||r.type===B.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(!$e(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 B.CONNECT:return V(t);case B.DISCONNECT:return t===void 0;case B.CONNECT_ERROR:return typeof t==`string`||V(t);case B.EVENT:case B.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&z.indexOf(t[0])===-1);case B.ACK:case B.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Ze=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=qe(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Qe(e){return typeof e==`string`}var $e=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function et(e){return e===void 0||$e(e)}function V(e){return Object.prototype.toString.call(e)===`[object Object]`}function tt(e,t){switch(e){case B.CONNECT:return t===void 0||V(t);case B.DISCONNECT:return t===void 0;case B.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&z.indexOf(t[0])===-1);case B.ACK:return Array.isArray(t);case B.CONNECT_ERROR:return typeof t==`string`||V(t);default:return!1}}function nt(e){return Qe(e.nsp)&&et(e.id)&&tt(e.type,e.data)}function H(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var rt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),it=class extends S{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=[H(e,`open`,this.onopen.bind(this)),H(e,`packet`,this.onpacket.bind(this)),H(e,`error`,this.onerror.bind(this)),H(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(rt.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:B.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:B.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 B.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 B.EVENT:case B.BINARY_EVENT:this.onevent(e);break;case B.ACK:case B.BINARY_ACK:this.onack(e);break;case B.DISCONNECT:this.ondisconnect();break;case B.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:B.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:B.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 U(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}U.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},U.prototype.reset=function(){this.attempts=0},U.prototype.setMin=function(e){this.ms=e},U.prototype.setMax=function(e){this.max=e},U.prototype.setJitter=function(e){this.jitter=e};var W=class extends S{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,T(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 U({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||Je;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 N(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=H(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=H(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(H(e,`ping`,this.onping.bind(this)),H(e,`data`,this.ondata.bind(this)),H(e,`error`,this.onerror.bind(this)),H(e,`close`,this.onclose.bind(this)),H(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){C(()=>{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 it(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)}},G={};function K(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=Ve(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=G[i]&&a in G[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new W(r,t):(G[i]||(G[i]=new W(r,t)),c=G[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(K,{Manager:W,Socket:it,io:K,connect:K});function at(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=at(e.baseUrl);this.socket=K(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)}},q=`onedeskpro_visitor_token`;function st(e){try{return typeof window<`u`?window.localStorage.getItem(e):null}catch{return null}}function ct(e,t){try{typeof window<`u`&&window.localStorage.setItem(e,t)}catch{}}function lt(e){try{typeof window<`u`&&window.localStorage.removeItem(e)}catch{}}var ut=class{constructor(){this.token=null,this.storageKey=q}setScope(e){this.storageKey=e?.trim()?`${q}:${e.trim()}`:q,this.token=st(this.storageKey)}get(){return this.token??st(this.storageKey)}set(e){this.token=e,ct(this.storageKey,e)}clear(){this.token=null,lt(this.storageKey)}},J=[{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:`๐Ÿ‡ณ๐Ÿ‡ต`}],dt=J.find(e=>e.iso===`BD`)??J[0];function ft(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}`}function pt(e,t){let n=`
2
2
  --ttcb-bg: #ffffff;
3
3
  --ttcb-bg-secondary: #f3f4f6;
4
4
  --ttcb-text: #111827;
5
5
  --ttcb-text-muted: #6b7280;
6
6
  --ttcb-border: #e5e7eb;
7
- --ttcb-user-bubble: ${i};
7
+ --ttcb-user-bubble: ${e};
8
8
  --ttcb-user-text: #ffffff;
9
9
  --ttcb-ai-bubble: #f3f4f6;
10
10
  --ttcb-ai-text: #111827;
11
11
  --ttcb-input-bg: #ffffff;
12
12
  --ttcb-shadow: 0 20px 60px rgba(0,0,0,0.15);
13
- `,n=`
13
+ --ttcb-online: #22c55e;
14
+ --ttcb-hint: #9ca3af;
15
+ `,r=`
14
16
  --ttcb-bg: #1f2937;
15
17
  --ttcb-bg-secondary: #111827;
16
18
  --ttcb-text: #f9fafb;
17
19
  --ttcb-text-muted: #9ca3af;
18
20
  --ttcb-border: #374151;
19
- --ttcb-user-bubble: ${i};
21
+ --ttcb-user-bubble: ${e};
20
22
  --ttcb-user-text: #ffffff;
21
23
  --ttcb-ai-bubble: #374151;
22
24
  --ttcb-ai-text: #f9fafb;
23
25
  --ttcb-input-bg: #111827;
24
26
  --ttcb-shadow: 0 20px 60px rgba(0,0,0,0.4);
25
- `;let s;return t==="dark"?s=`:host { ${n} }`:t==="light"?s=`:host { ${e} }`:s=`
26
- :host { ${e} }
27
- @media (prefers-color-scheme: dark) { :host { ${n} } }
27
+ --ttcb-online: #22c55e;
28
+ --ttcb-hint: #9ca3af;
29
+ `,i;return i=t===`dark`?`:host { ${r} }`:t===`light`?`:host { ${n} }`:`
30
+ :host { ${n} }
31
+ @media (prefers-color-scheme: dark) { :host { ${r} } }
28
32
  `,`
29
- ${s}
33
+ ${i}
30
34
 
31
35
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
32
36
 
@@ -34,7 +38,7 @@
34
38
  position: fixed;
35
39
  width: 56px; height: 56px;
36
40
  border-radius: 50%;
37
- background: ${i};
41
+ background: ${e};
38
42
  border: none; cursor: pointer;
39
43
  display: flex; align-items: center; justify-content: center;
40
44
  box-shadow: 0 4px 20px rgba(0,0,0,0.2);
@@ -48,7 +52,7 @@
48
52
 
49
53
  .ttcb-panel {
50
54
  position: fixed;
51
- width: 380px; height: 560px;
55
+ width: 380px;
52
56
  background: var(--ttcb-bg);
53
57
  border: 1px solid var(--ttcb-border);
54
58
  border-radius: 16px;
@@ -56,9 +60,17 @@
56
60
  box-shadow: var(--ttcb-shadow);
57
61
  overflow: hidden;
58
62
  z-index: 9998;
59
- transition: opacity 0.2s ease, transform 0.25s ease;
63
+ transition: opacity 0.2s ease, transform 0.25s ease, height 0.2s ease;
60
64
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
61
65
  }
66
+ .ttcb-panel.ttcb-mode-chat {
67
+ height: 560px;
68
+ }
69
+ .ttcb-panel.ttcb-mode-form,
70
+ .ttcb-panel.ttcb-mode-compact {
71
+ height: auto;
72
+ max-height: min(560px, calc(100vh - 100px));
73
+ }
62
74
  .ttcb-panel.bottom-right { bottom: 92px; right: 24px; }
63
75
  .ttcb-panel.bottom-left { bottom: 92px; left: 24px; }
64
76
  .ttcb-panel.hidden {
@@ -73,28 +85,98 @@
73
85
  background: var(--ttcb-bg);
74
86
  flex-shrink: 0;
75
87
  }
88
+ .ttcb-avatar-wrap {
89
+ flex-shrink: 0;
90
+ }
76
91
  .ttcb-avatar {
77
- width: 32px; height: 32px; border-radius: 50%;
78
- background: ${i}22;
92
+ width: 40px; height: 40px; border-radius: 10px;
93
+ background: ${e};
79
94
  display: flex; align-items: center; justify-content: center;
80
- flex-shrink: 0;
81
95
  }
82
- .ttcb-avatar svg { width: 16px; height: 16px; fill: ${i}; }
83
- .ttcb-header-title { font-weight: 600; font-size: 14px; color: var(--ttcb-text); flex: 1; }
84
- .ttcb-close-btn, .ttcb-new-session-btn {
96
+ .ttcb-avatar svg { width: 22px; height: 22px; fill: #fff; }
97
+ .ttcb-header-main {
98
+ flex: 1; min-width: 0;
99
+ display: flex; flex-direction: column; gap: 4px;
100
+ }
101
+ .ttcb-header-title-row {
102
+ display: flex; align-items: center; gap: 6px;
103
+ }
104
+ .ttcb-header-title {
105
+ font-weight: 700; font-size: 15px; color: var(--ttcb-text);
106
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
107
+ }
108
+ .ttcb-verified {
109
+ width: 16px; height: 16px; color: ${e};
110
+ flex-shrink: 0; display: flex;
111
+ }
112
+ .ttcb-verified svg { width: 16px; height: 16px; }
113
+ .ttcb-header-meta {
114
+ display: flex; align-items: center; gap: 8px;
115
+ font-size: 12px; color: var(--ttcb-text-muted);
116
+ }
117
+ .ttcb-meta-online {
118
+ display: inline-flex; align-items: center; gap: 5px;
119
+ color: var(--ttcb-online); font-weight: 500;
120
+ }
121
+ .ttcb-meta-online::before {
122
+ content: '';
123
+ width: 7px; height: 7px; border-radius: 50%;
124
+ background: var(--ttcb-online);
125
+ }
126
+ .ttcb-meta-sep {
127
+ width: 1px; height: 12px; background: var(--ttcb-border);
128
+ }
129
+ .ttcb-meta-replies {
130
+ display: inline-flex; align-items: center; gap: 4px;
131
+ color: var(--ttcb-text-muted);
132
+ }
133
+ .ttcb-meta-replies svg { width: 18px; height: 14px; }
134
+ .ttcb-header-actions {
135
+ display: flex; align-items: center; gap: 3px;
136
+ flex-shrink: 0; align-self: center;
137
+ }
138
+ .ttcb-close-btn, .ttcb-new-session-btn, .ttcb-request-human-btn {
85
139
  background: none; border: none; cursor: pointer;
86
- color: var(--ttcb-text-muted); padding: 4px; border-radius: 6px;
140
+ color: var(--ttcb-text-muted); padding: 6px; border-radius: 6px;
87
141
  display: flex; align-items: center; justify-content: center;
88
142
  }
89
- .ttcb-close-btn:hover, .ttcb-new-session-btn:hover { background: var(--ttcb-bg-secondary); }
90
- .ttcb-close-btn svg { width: 18px; height: 18px; fill: currentColor; }
91
- .ttcb-new-session-btn svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; }
143
+ .ttcb-close-btn:hover, .ttcb-new-session-btn:hover, .ttcb-request-human-btn:hover {
144
+ background: var(--ttcb-bg-secondary);
145
+ }
146
+ .ttcb-close-btn svg { width: 19px; height: 19px; fill: currentColor; }
147
+ .ttcb-new-session-btn svg,
148
+ .ttcb-request-human-btn svg {
149
+ width: 19px; height: 19px; fill: none; stroke: currentColor; stroke-width: 2;
150
+ }
151
+ .ttcb-new-session-btn.hidden, .ttcb-request-human-btn.hidden { display: none; }
152
+
153
+ .ttcb-mode-banner {
154
+ display: none;
155
+ padding: 10px 16px;
156
+ font-size: 12px;
157
+ line-height: 1.4;
158
+ color: var(--ttcb-text-muted);
159
+ background: var(--ttcb-bg-secondary);
160
+ border-top: 1px solid var(--ttcb-border);
161
+ flex-shrink: 0;
162
+ }
163
+ .ttcb-mode-banner.visible { display: block; }
164
+ .ttcb-mode-banner.waiting { color: var(--ttcb-text); }
165
+ .ttcb-mode-banner.closed {
166
+ color: var(--ttcb-text);
167
+ background: color-mix(in srgb, #ef4444 10%, var(--ttcb-bg-secondary));
168
+ }
169
+ .ttcb-mode-banner.human { color: var(--ttcb-text); }
92
170
 
93
171
  .ttcb-messages {
94
172
  flex: 1; overflow-y: auto; padding: 16px;
95
173
  display: flex; flex-direction: column; gap: 12px;
96
174
  scroll-behavior: smooth;
97
175
  font-size: 14px;
176
+ min-height: 120px;
177
+ }
178
+ .ttcb-panel.ttcb-mode-compact .ttcb-messages {
179
+ min-height: 160px;
98
180
  }
99
181
 
100
182
  .ttcb-empty {
@@ -127,32 +209,26 @@
127
209
  }
128
210
  @keyframes ttcb-spin { to { transform: rotate(360deg); } }
129
211
 
130
- .ttcb-blocked {
131
- display: flex; flex-direction: column; align-items: center;
132
- justify-content: center; text-align: center;
133
- padding: 32px 20px; flex: 1;
134
- }
135
- .ttcb-blocked-icon {
136
- width: 44px; height: 44px; border-radius: 50%;
137
- background: var(--ttcb-bg-secondary);
138
- display: flex; align-items: center; justify-content: center;
139
- margin-bottom: 14px;
140
- }
141
- .ttcb-blocked-icon svg { width: 20px; height: 20px; fill: var(--ttcb-text-muted); }
142
- .ttcb-blocked-title { font-size: 14px; font-weight: 600; color: var(--ttcb-text); margin-bottom: 8px; }
143
- .ttcb-blocked-desc { font-size: 12px; color: var(--ttcb-text-muted); line-height: 1.5; max-width: 220px; }
144
-
145
212
  .ttcb-msg { display: flex; gap: 8px; max-width: 100%; }
146
213
  .ttcb-msg.human { flex-direction: row-reverse; }
214
+ .ttcb-msg-body { display: flex; flex-direction: column; gap: 3px; max-width: 78%; }
215
+ .ttcb-msg.human .ttcb-msg-body { align-items: flex-end; }
216
+ .ttcb-msg-label {
217
+ font-size: 11px; font-weight: 600; color: var(--ttcb-text-muted);
218
+ padding-left: 2px;
219
+ }
147
220
  .ttcb-msg-avatar {
148
221
  width: 28px; height: 28px; border-radius: 50%;
149
222
  background: var(--ttcb-bg-secondary);
150
223
  display: flex; align-items: center; justify-content: center;
151
224
  flex-shrink: 0; margin-top: 2px;
152
225
  }
226
+ /* Offset past the "Agent" label so the avatar lines up with the bubble */
227
+ .ttcb-msg.agent .ttcb-msg-avatar { margin-top: 22px; }
153
228
  .ttcb-msg-avatar svg { width: 13px; height: 13px; fill: var(--ttcb-text-muted); }
229
+ .ttcb-msg.agent .ttcb-msg-avatar svg { fill: none; stroke: var(--ttcb-text-muted); stroke-width: 2; }
154
230
  .ttcb-bubble {
155
- max-width: 78%; padding: 9px 13px;
231
+ max-width: 100%; padding: 9px 13px;
156
232
  border-radius: 16px 16px 16px 4px;
157
233
  line-height: 1.5;
158
234
  color: var(--ttcb-ai-text);
@@ -165,8 +241,13 @@
165
241
  color: var(--ttcb-user-text);
166
242
  border-radius: 16px 16px 4px 16px;
167
243
  }
244
+ .ttcb-msg.agent .ttcb-bubble {
245
+ background: var(--ttcb-bg);
246
+ color: var(--ttcb-text);
247
+ border: 1px solid var(--ttcb-border);
248
+ border-radius: 16px 16px 16px 4px;
249
+ }
168
250
 
169
- /* Markdown styles inside AI bubble */
170
251
  .ttcb-bubble p { margin: 0 0 6px 0; }
171
252
  .ttcb-bubble p:last-child { margin-bottom: 0; }
172
253
  .ttcb-bubble strong { font-weight: 600; }
@@ -223,12 +304,12 @@
223
304
  transition: border-color 0.15s;
224
305
  font-family: inherit;
225
306
  }
226
- .ttcb-input:focus { border-color: ${i}; }
307
+ .ttcb-input:focus { border-color: ${e}; }
227
308
  .ttcb-input::placeholder { color: var(--ttcb-text-muted); }
228
309
  .ttcb-input:disabled { opacity: 0.6; cursor: not-allowed; }
229
310
  .ttcb-send-btn {
230
311
  padding: 0 14px; height: 38px;
231
- background: ${i}; color: #fff;
312
+ background: ${e}; color: #fff;
232
313
  border: none; border-radius: 8px; cursor: pointer;
233
314
  display: flex; align-items: center; justify-content: center;
234
315
  transition: opacity 0.15s; flex-shrink: 0;
@@ -237,29 +318,220 @@
237
318
  .ttcb-send-btn:disabled { opacity: 0.5; cursor: not-allowed; }
238
319
  .ttcb-send-btn svg { width: 16px; height: 16px; fill: #fff; }
239
320
 
321
+ .ttcb-identify {
322
+ display: none;
323
+ flex-direction: column;
324
+ gap: 14px;
325
+ padding: 16px 16px 14px;
326
+ overflow-y: auto;
327
+ }
328
+ .ttcb-panel.ttcb-mode-form .ttcb-identify.visible {
329
+ display: flex;
330
+ flex: 0 0 auto;
331
+ }
332
+ .ttcb-identify-form {
333
+ display: flex; flex-direction: column; gap: 14px;
334
+ }
335
+ .ttcb-field { display: flex; flex-direction: column; gap: 6px; }
336
+ .ttcb-field-label-row {
337
+ display: flex; align-items: baseline; justify-content: space-between; gap: 8px;
338
+ }
339
+ .ttcb-label {
340
+ font-size: 13px; font-weight: 600; color: var(--ttcb-text);
341
+ }
342
+ .ttcb-label .ttcb-req { color: #ef4444; font-weight: 600; }
343
+ .ttcb-field-hint {
344
+ font-size: 11px; color: var(--ttcb-hint); font-weight: 400;
345
+ white-space: nowrap;
346
+ }
347
+ .ttcb-input-wrap {
348
+ display: flex; align-items: center; gap: 8px;
349
+ border: 1px solid var(--ttcb-border);
350
+ border-radius: 10px;
351
+ padding: 0 12px;
352
+ background: var(--ttcb-input-bg);
353
+ transition: border-color 0.15s;
354
+ }
355
+ .ttcb-input-wrap:focus-within { border-color: ${e}; }
356
+ .ttcb-input-wrap.disabled { opacity: 0.6; }
357
+ .ttcb-input-icon {
358
+ width: 18px; height: 18px; color: var(--ttcb-text-muted);
359
+ flex-shrink: 0; display: flex;
360
+ }
361
+ .ttcb-input-icon svg { width: 18px; height: 18px; }
362
+ .ttcb-identify-input {
363
+ flex: 1; min-width: 0;
364
+ border: none; outline: none;
365
+ padding: 11px 0;
366
+ font-size: 14px;
367
+ background: transparent;
368
+ color: var(--ttcb-text);
369
+ font-family: inherit;
370
+ }
371
+ .ttcb-identify-input::placeholder { color: var(--ttcb-text-muted); }
372
+ .ttcb-identify-input:disabled { cursor: not-allowed; }
373
+
374
+ .ttcb-phone-row {
375
+ display: flex; align-items: stretch;
376
+ border: 1px solid var(--ttcb-border);
377
+ border-radius: 10px;
378
+ background: var(--ttcb-input-bg);
379
+ overflow: hidden;
380
+ transition: border-color 0.15s;
381
+ }
382
+ .ttcb-phone-row:focus-within { border-color: ${e}; }
383
+ .ttcb-phone-row.disabled { opacity: 0.6; }
384
+ .ttcb-dial-btn {
385
+ display: flex; align-items: center; gap: 4px;
386
+ padding: 0 10px;
387
+ border: none; border-right: 1px solid var(--ttcb-border);
388
+ background: var(--ttcb-bg-secondary);
389
+ cursor: pointer;
390
+ font-family: inherit;
391
+ font-size: 13px;
392
+ font-weight: 500;
393
+ color: var(--ttcb-text);
394
+ flex-shrink: 0;
395
+ }
396
+ .ttcb-dial-btn:disabled { cursor: not-allowed; }
397
+ .ttcb-dial-flag { font-size: 16px; line-height: 1; }
398
+ .ttcb-dial-code { letter-spacing: 0.01em; }
399
+ .ttcb-dial-btn svg {
400
+ width: 14px; height: 14px; color: var(--ttcb-text-muted);
401
+ }
402
+ .ttcb-phone-national {
403
+ flex: 1; min-width: 0;
404
+ border: none; outline: none;
405
+ padding: 11px 12px;
406
+ font-size: 14px;
407
+ background: transparent;
408
+ color: var(--ttcb-text);
409
+ font-family: inherit;
410
+ }
411
+ .ttcb-phone-national::placeholder { color: var(--ttcb-text-muted); }
412
+
413
+ .ttcb-country-popover {
414
+ display: none;
415
+ flex-direction: column;
416
+ border: 1px solid var(--ttcb-border);
417
+ border-radius: 10px;
418
+ background: var(--ttcb-bg);
419
+ box-shadow: 0 8px 24px rgba(0,0,0,0.12);
420
+ max-height: 220px;
421
+ overflow: hidden;
422
+ margin-top: -8px;
423
+ }
424
+ .ttcb-country-popover.open { display: flex; }
425
+ .ttcb-country-search {
426
+ border: none; border-bottom: 1px solid var(--ttcb-border);
427
+ padding: 10px 12px;
428
+ font-size: 13px; outline: none;
429
+ background: var(--ttcb-input-bg);
430
+ color: var(--ttcb-text);
431
+ font-family: inherit;
432
+ }
433
+ .ttcb-country-list {
434
+ overflow-y: auto;
435
+ max-height: 176px;
436
+ }
437
+ .ttcb-country-item {
438
+ display: flex; align-items: center; gap: 8px;
439
+ width: 100%;
440
+ padding: 8px 12px;
441
+ border: none; background: none;
442
+ cursor: pointer;
443
+ font-family: inherit;
444
+ font-size: 13px;
445
+ color: var(--ttcb-text);
446
+ text-align: left;
447
+ }
448
+ .ttcb-country-item:hover,
449
+ .ttcb-country-item[aria-selected="true"] {
450
+ background: var(--ttcb-bg-secondary);
451
+ }
452
+ .ttcb-country-item-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
453
+ .ttcb-country-item-dial { color: var(--ttcb-text-muted); flex-shrink: 0; }
454
+
455
+ .ttcb-identify-error {
456
+ font-size: 12px; color: #ef4444; min-height: 16px;
457
+ margin-top: -4px;
458
+ }
459
+ .ttcb-identify-submit {
460
+ width: 100%; height: 46px;
461
+ background: ${e}; color: #fff;
462
+ border: none; border-radius: 999px; cursor: pointer;
463
+ font-size: 15px; font-weight: 600; font-family: inherit;
464
+ display: flex; align-items: center; justify-content: center; gap: 8px;
465
+ }
466
+ .ttcb-identify-submit svg {
467
+ width: 18px; height: 18px; stroke: #fff; fill: none;
468
+ }
469
+ .ttcb-identify-submit:hover { opacity: 0.92; }
470
+ .ttcb-identify-submit:disabled { opacity: 0.55; cursor: not-allowed; }
471
+
472
+ .ttcb-trust {
473
+ display: flex; align-items: center; justify-content: center; gap: 6px;
474
+ font-size: 11px; color: var(--ttcb-text-muted);
475
+ padding-bottom: 2px;
476
+ }
477
+ .ttcb-trust svg {
478
+ width: 14px; height: 14px;
479
+ stroke: var(--ttcb-online);
480
+ fill: none;
481
+ flex-shrink: 0;
482
+ }
483
+
484
+ .ttcb-footer.hidden, .ttcb-messages.hidden { display: none; }
485
+
240
486
  @media (max-width: 440px) {
241
487
  .ttcb-panel { width: calc(100vw - 16px); right: 8px !important; left: 8px !important; bottom: 84px !important; }
242
488
  .ttcb-fab.bottom-right { right: 16px; }
243
489
  .ttcb-fab.bottom-left { left: 16px; }
244
490
  }
245
- `}function u(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function _(i){const t=[];let e=i.replace(/```[\w]*\n?([\s\S]*?)```/g,(r,o)=>{const c=t.length;return t.push(`<pre><code>${u(o.trim())}</code></pre>`),`${c}`});e=e.replace(/`([^`\n]+)`/g,(r,o)=>{const c=t.length;return t.push(`<code>${u(o)}</code>`),`${c}`}),e=u(e);const n=e.split(`
246
- `),s=[];let a="";const l=()=>{a&&(s.push(`</${a}>`),a="")};for(const r of n){let o;(o=r.match(/^### (.+)/))?(l(),s.push(`<h3>${o[1]}</h3>`)):(o=r.match(/^## (.+)/))?(l(),s.push(`<h2>${o[1]}</h2>`)):(o=r.match(/^# (.+)/))?(l(),s.push(`<h1>${o[1]}</h1>`)):(o=r.match(/^[*-] (.+)/))?(a!=="ul"&&(l(),s.push("<ul>"),a="ul"),s.push(`<li>${o[1]}</li>`)):(o=r.match(/^\d+\. (.+)/))?(a!=="ol"&&(l(),s.push("<ol>"),a="ol"),s.push(`<li>${o[1]}</li>`)):(l(),s.push(r))}return l(),e=s.join(`
247
- `),e=e.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>'),e=e.split(/\n{2,}/).map(r=>{const o=r.trim();return o?/^<(h[1-3]|ul|ol|pre|li)/.test(o)?o:o.split(/(\x04\d+\x05)/g).map(c=>{if(/^\x04\d+\x05$/.test(c))return c;const d=c.trim();return d?`<p>${d.replace(/\n/g,"<br>")}</p>`:""}).join(""):""}).filter(Boolean).join(""),e=e.replace(/\x04(\d+)\x05/g,(r,o)=>t[+o]??"").replace(/\x02(\d+)\x03/g,(r,o)=>t[+o]??""),e}function A(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
248
- <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"/>
249
- </svg>`}function x(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
250
- <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/>
251
- </svg>`}function B(){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">
491
+ `}function Y(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}function mt(e){let t=[],n=e.replace(/```[\w]*\n?([\s\S]*?)```/g,(e,n)=>{let r=t.length;return t.push(`<pre><code>${Y(n.trim())}</code></pre>`),`\x04${r}\x05`});n=n.replace(/`([^`\n]+)`/g,(e,n)=>{let r=t.length;return t.push(`<code>${Y(n)}</code>`),`\x02${r}\x03`}),n=Y(n);let r=n.split(`
492
+ `),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(`
493
+ `),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 ht(){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">
252
494
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
253
495
  <line x1="12" y1="8" x2="12" y2="14"/>
254
496
  <line x1="9" y1="11" x2="15" y2="11"/>
255
- </svg>`}function $(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
497
+ </svg>`}function gt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
256
498
  <path d="M20 2H4C2.9 2 2 2.9 2 4v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
257
- </svg>`}function O(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
499
+ </svg>`}function _t(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
258
500
  <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"/>
259
- </svg>`}function H(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
501
+ </svg>`}function vt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
260
502
  <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
261
- </svg>`}function m(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
503
+ </svg>`}function X(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
262
504
  <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"/>
263
- </svg>`}function z(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
505
+ </svg>`}function yt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
264
506
  <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"/>
265
- </svg>`}function w(i,t){const e=document.createElement("div");e.className=`ttcb-msg ${t}`;const n=document.createElement("div");n.className="ttcb-msg-avatar",n.innerHTML=t==="human"?z():m();const s=document.createElement("div");return s.className="ttcb-bubble",t==="human"?s.textContent=i:s.innerHTML=_(i),e.appendChild(n),e.appendChild(s),e}function R(){const i=document.createElement("div");i.className="ttcb-msg ai",i.id="ttcb-typing";const t=document.createElement("div");t.className="ttcb-msg-avatar",t.innerHTML=m();const e=document.createElement("div");return e.className="ttcb-typing",e.innerHTML="<span></span><span></span><span></span>",i.appendChild(t),i.appendChild(e),i}class U{constructor(t,e){this.isOpen=!1,this.destroyed=!1,this.position=t.position??"bottom-right",this.callbacks=e,this.mount(t)}mount(t){this.host=document.createElement("div"),this.host.id="onedeskpro-chatbot-host",this.shadow=this.host.attachShadow({mode:"closed"});const e=document.createElement("style");e.textContent=N(t.primaryColor??"#2563EB",t.theme??"auto"),this.shadow.appendChild(e);const n=document.createElement("button");n.className=`ttcb-fab ${this.position}`,n.setAttribute("aria-label","Open chat"),n.innerHTML=$(),n.addEventListener("click",()=>this.toggle()),this.shadow.appendChild(n),this.panel=document.createElement("div"),this.panel.className=`ttcb-panel ${this.position} hidden`,this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-modal","true"),this.panel.setAttribute("aria-label",t.chatbotName??"AI Assistant");const s=document.createElement("div");s.className="ttcb-header";const a=document.createElement("div");a.className="ttcb-avatar",a.innerHTML=m();const l=document.createElement("span");l.className="ttcb-header-title",l.textContent=t.chatbotName??"AI Assistant";const r=document.createElement("button");r.className="ttcb-new-session-btn",r.setAttribute("aria-label","New conversation"),r.title="New conversation",r.innerHTML=B(),r.addEventListener("click",()=>this.callbacks.onReset());const o=document.createElement("button");o.className="ttcb-close-btn",o.setAttribute("aria-label","Close chat"),o.innerHTML=O(),o.addEventListener("click",()=>this.close()),s.appendChild(a),s.appendChild(l),s.appendChild(r),s.appendChild(o),this.panel.appendChild(s),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);const c=document.createElement("div");c.className="ttcb-footer";const d=document.createElement("form");d.className="ttcb-form",d.addEventListener("submit",h=>{h.preventDefault(),this.handleSend()}),this.input=document.createElement("input"),this.input.type="text",this.input.className="ttcb-input",this.input.placeholder=t.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=H(),this.sendBtn.setAttribute("aria-label","Send message"),d.appendChild(this.input),d.appendChild(this.sendBtn),c.appendChild(d),this.panel.appendChild(c),this.shadow.appendChild(this.panel),this.attachToDocument(),this.showInitialLoading(),t.autoOpen&&this.open()}attachToDocument(){const t=()=>{this.destroyed||(document.body??document.documentElement).appendChild(this.host)};document.body?t():document.addEventListener("DOMContentLoaded",t,{once:!0})}showInitialLoading(){this.messagesContainer.innerHTML="",this.input.disabled=!0,this.sendBtn.disabled=!0;const t=document.createElement("div");t.className="ttcb-initial-loading",t.id="ttcb-initial-loading";const e=document.createElement("div");e.className="ttcb-spinner";const n=document.createElement("p");n.textContent="Loadingโ€ฆ",t.appendChild(e),t.appendChild(n),this.messagesContainer.appendChild(t)}showEmptyState(t){const e=document.createElement("div");e.className="ttcb-empty",e.id="ttcb-empty";const n=document.createElement("div");n.className="ttcb-empty-icon",n.innerHTML=m();const s=document.createElement("p"),a=document.createElement("strong");a.textContent=t,s.appendChild(document.createTextNode("Welcome to ")),s.appendChild(a);const l=document.createElement("p");l.textContent="Ask me anything โ€” I'm here to help!",l.style.marginTop="6px",l.style.fontSize="12px",e.appendChild(n),e.appendChild(s),e.appendChild(l),this.messagesContainer.appendChild(e)}removeEmptyState(){const t=this.shadow.getElementById("ttcb-empty");t&&t.remove()}handleSend(){const t=this.input.value.trim();t&&(this.input.value="",this.callbacks.onSend(t))}appendMessage(t){this.removeEmptyState();const e="message"in t?t.message:t,n=w(e.content,e.type);this.messagesContainer.appendChild(n),this.scrollToBottom()}setMessages(t){if(this.messagesContainer.innerHTML="",t.length!==0){for(const e of t){const n=w(e.message.content,e.message.type);this.messagesContainer.appendChild(n)}this.scrollToBottom()}}setLoading(t){if(this.sendBtn.disabled=t,this.input.disabled=t,t)this.shadow.getElementById("ttcb-typing")||(this.messagesContainer.appendChild(R()),this.scrollToBottom());else{const e=this.shadow.getElementById("ttcb-typing");e&&e.remove()}}open(){this.isOpen=!0,this.panel.classList.remove("hidden"),this.input.focus(),this.callbacks.onOpen()}close(){this.isOpen=!1,this.panel.classList.add("hidden"),this.callbacks.onClose()}toggle(){this.isOpen?this.close():this.open()}readyToChat(t){this.messagesContainer.innerHTML="",this.input.disabled=!1,this.sendBtn.disabled=!1;const e=this.shadow.querySelector(".ttcb-header-title");e&&t.chatbotName&&(e.textContent=t.chatbotName),t.welcomeMessage?this.appendMessage({type:"ai",content:t.welcomeMessage}):this.showEmptyState(t.chatbotName??"AI Assistant")}showBlocked(t){this.messagesContainer.innerHTML="";const e=document.createElement("div");e.className="ttcb-blocked";const n=document.createElement("div");n.className="ttcb-blocked-icon";const s=document.createElement("p");s.className="ttcb-blocked-title";const a=document.createElement("p");a.className="ttcb-blocked-desc",t==="no-prompt"?(n.innerHTML=x(),s.textContent="Business Context Required",a.textContent="Add a system prompt for this agent in the admin panel."):t==="no-directories"?(n.innerHTML=x(),s.textContent="Knowledge Base Required",a.textContent="Assign at least one knowledge-base directory to this agent in the admin panel."):(n.innerHTML=A(),s.textContent="Chatbot Settings Required",a.textContent="The chatbot has not been configured yet. Please set it up in the admin panel."),e.appendChild(n),e.appendChild(s),e.appendChild(a),this.messagesContainer.appendChild(e)}clearMessages(t){this.messagesContainer.innerHTML="",this.showEmptyState(t)}destroy(){this.destroyed=!0,this.host.remove()}scrollToBottom(){this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight}}const j={apiBaseUrl:C,chatbotName:"AI Assistant",primaryColor:"#2563EB",theme:"auto",position:"bottom-right",welcomeMessage:"",placeholder:"Type your messageโ€ฆ",autoOpen:!1,sessionId:"",requestTimeoutMs:g};function q(i){return Object.fromEntries(Object.entries(i).filter(([,t])=>t!==void 0))}let D=0;const y=()=>Date.now()*1e3+D++%1e3;class S{constructor(){this.emitter=new E,this.session=new k,this.widget=null,this.callerSetName=!1,this.initToken=0,this._state={isOpen:!1,isLoading:!1,isReady:!1,blockReason:null,messages:[],sessionId:null,error:null}}setState(t){this._state={...this._state,...t},this.emitter.emit("state-change",this._state)}async init(t){var l,r,o;if(!t.apiKey)throw new Error("[onedeskpro-chatbot] `apiKey` is required to initialise the chatbot.");const e=++this.initToken;(l=this.widget)==null||l.destroy(),this.widget=null,this.callerSetName=t.chatbotName!==void 0,this.options={...j,...q(t)},this.apiClient=new v({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,timeoutMs:this.options.requestTimeoutMs});const n=this.session.init(this.options.sessionId||void 0);this.setState({sessionId:n}),typeof window<"u"&&typeof document<"u"&&(this.widget=new U(this.options,{onSend:c=>void this.sendMessage(c),onOpen:()=>{this.setState({isOpen:!0}),this.emitter.emit("open")},onClose:()=>{this.setState({isOpen:!1}),this.emitter.emit("close")},onReset:()=>this.resetSession()}));const s=await this.fetchConfig();if(e!==this.initToken)return;s&&!this.callerSetName&&s.agentName.trim()&&(this.options.chatbotName=s.agentName);const a=(s==null?void 0:s.blockReason)??null;if(this.setState({blockReason:a,isReady:a===null}),a)(r=this.widget)==null||r.showBlocked(a);else if((o=this.widget)==null||o.readyToChat(this.options),await this.loadHistory(e),e!==this.initToken)return;this.emitter.emit("ready")}async fetchConfig(){try{return await this.apiClient.fetchConfig()}catch{return null}}async sendMessage(t){var a,l,r,o;const e=this.session.get();if(!this.apiClient||!e)throw new Error("[onedeskpro-chatbot] Call init() before sendMessage().");const n=t.trim();if(!n||this._state.isLoading)return;const s={id:y(),sessionId:e,message:{type:"human",content:n}};this.setState({messages:[...this._state.messages,s],isLoading:!0,error:null}),(a=this.widget)==null||a.appendMessage(s),(l=this.widget)==null||l.setLoading(!0),this.emitter.emit("message",s);try{const c=await this.apiClient.sendMessage({chatInput:n,sessionId:e}),d={id:y(),sessionId:e,message:{type:"ai",content:c.text}};this.setState({messages:[...this._state.messages,d],isLoading:!1}),(r=this.widget)==null||r.appendMessage(d),this.emitter.emit("message",d)}catch(c){const d=c instanceof Error?c:new Error(String(c));this.setState({error:d.message,isLoading:!1}),this.emitter.emit("error",d)}finally{(o=this.widget)==null||o.setLoading(!1)}}async loadHistory(t){var n;const e=this.session.get();if(e)try{const s=await this.apiClient.fetchHistory(e);if(t!==this.initToken)return;this.setState({messages:s}),s.length>0&&((n=this.widget)==null||n.setMessages(s))}catch{}}on(t,e){return this.emitter.on(t,e)}resetSession(){var e;if(!this._state.isReady)return;const t=this.session.reset();this.setState({sessionId:t,messages:[],error:null}),(e=this.widget)==null||e.clearMessages(this.options.chatbotName),this.emitter.emit("session-reset")}open(){var t;(t=this.widget)==null||t.open()}close(){var t;(t=this.widget)==null||t.close()}toggle(){var t;(t=this.widget)==null||t.toggle()}getState(){return{...this._state}}destroy(){var t;this.initToken++,(t=this.widget)==null||t.destroy(),this.widget=null,this.setState({isOpen:!1,isLoading:!1,isReady:!1})}}let b=null;const K={async init(i){return b=new S,await b.init(i),b},getInstance(){return b}};exports.ApiClient=v;exports.ChatbotCore=S;exports.DEFAULT_API_BASE_URL=C;exports.DEFAULT_REQUEST_TIMEOUT_MS=g;exports.EventEmitter=E;exports.OnedeskProChatbot=K;exports.SessionManager=k;
507
+ </svg>`}function bt(){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">
508
+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
509
+ <circle cx="12" cy="7" r="4"/>
510
+ </svg>`}function xt(){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">
511
+ <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"/>
512
+ <polyline points="22,6 12,13 2,6"/>
513
+ </svg>`}function St(){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">
514
+ <polyline points="6 9 12 15 18 9"/>
515
+ </svg>`}function Ct(){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">
516
+ <line x1="5" y1="12" x2="19" y2="12"/>
517
+ <polyline points="12 5 19 12 12 19"/>
518
+ </svg>`}function wt(){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">
519
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
520
+ <polyline points="9 12 11 14 15 10"/>
521
+ </svg>`}function Tt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
522
+ <circle cx="12" cy="12" r="10" fill="currentColor"/>
523
+ <path d="M9 12l2 2 4-4" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
524
+ </svg>`}function Et(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
525
+ <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"/>
526
+ <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"/>
527
+ <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"/>
528
+ </svg>`}function Dt(){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">
529
+ <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
530
+ <circle cx="9" cy="7" r="4"/>
531
+ <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
532
+ <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
533
+ </svg>`}function Ot(e,t){let n=document.createElement(`div`);n.className=`ttcb-msg ${t}`;let r=document.createElement(`div`);r.className=`ttcb-msg-avatar`,r.innerHTML=t===`human`?yt():t===`agent`?bt():X();let i=document.createElement(`div`);if(i.className=`ttcb-msg-body`,t===`agent`){let e=document.createElement(`span`);e.className=`ttcb-msg-label`,e.textContent=`Agent`,i.appendChild(e)}let a=document.createElement(`div`);return a.className=`ttcb-bubble`,t===`human`?a.textContent=e:a.innerHTML=mt(e),i.appendChild(a),n.appendChild(r),n.appendChild(i),n}function kt(){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 At=class{constructor(e,t){this.selectedCountry=dt,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=pt(e.primaryColor??`#2563EB`,e.theme??`auto`),this.shadow.appendChild(t);let n=document.createElement(`button`);n.className=`ttcb-fab ${this.position}`,n.setAttribute(`aria-label`,`Open chat`),n.innerHTML=gt(),n.addEventListener(`click`,()=>this.toggle()),this.shadow.appendChild(n),this.panel=document.createElement(`div`),this.panel.className=`ttcb-panel ${this.position} hidden ttcb-mode-compact`,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.modeBanner.setAttribute(`role`,`status`),this.panel.appendChild(this.modeBanner),this.footer=document.createElement(`div`),this.footer.className=`ttcb-footer`;let r=document.createElement(`form`);r.className=`ttcb-form`,r.addEventListener(`submit`,e=>{e.preventDefault(),this.handleSend()}),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=vt(),this.sendBtn.setAttribute(`aria-label`,`Send message`),r.appendChild(this.input),r.appendChild(this.sendBtn),this.footer.appendChild(r),this.panel.appendChild(this.footer),this.shadow.appendChild(this.panel),this.shadow.addEventListener(`click`,e=>{if(!this.countryOpen)return;let t=e.target;t&&(this.dialBtn.contains(t)||this.countryPopover.contains(t))||this.closeCountryPopover()}),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=Tt(),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=`${Et()}<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=Dt(),this.requestHumanBtn.addEventListener(`click`,()=>this.callbacks.onRequestHuman()),this.newSessionBtn=document.createElement(`button`),this.newSessionBtn.className=`ttcb-new-session-btn hidden`,this.newSessionBtn.setAttribute(`aria-label`,`New conversation`),this.newSessionBtn.title=`New conversation`,this.newSessionBtn.innerHTML=ht(),this.newSessionBtn.addEventListener(`click`,()=>this.callbacks.onReset());let f=document.createElement(`button`);return f.className=`ttcb-close-btn`,f.setAttribute(`aria-label`,`Close chat`),f.innerHTML=_t(),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}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.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:bt()}),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:xt()}),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>${Ct()}`,t.appendChild(this.identifySubmit),e.appendChild(t);let n=document.createElement(`div`);n.className=`ttcb-trust`,n.innerHTML=`${wt()}<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=St(),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=J.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=`
534
+ <span class="ttcb-dial-flag">${e.flag}</span>
535
+ <span class="ttcb-country-item-name">${e.name}</span>
536
+ <span class="ttcb-country-item-dial">+${e.dial}</span>
537
+ `,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();e&&!this.sendBtn.disabled&&(this.input.value=``,this.callbacks.onSend(e),this.input.focus())}handleIdentifySubmit(){let e=this.nameInput.value.trim(),t=ft(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=`message`in e?e.message:e,n=Ot(t.content,t.type);this.messagesContainer.appendChild(n),this.scrollToBottom()}setMessages(e){if(this.messagesContainer.innerHTML=``,e.length!==0){for(let t of e){let e=Ot(t.message.content,t.message.type);this.messagesContainer.appendChild(e)}this.scrollToBottom()}}setLoading(e){if(this.sendBtn.disabled=e||this.input.disabled,e)this.shadow.getElementById(`ttcb-typing`)||(this.messagesContainer.appendChild(kt()),this.scrollToBottom()),this.input.focus();else{let e=this.shadow.getElementById(`ttcb-typing`);e&&e.remove(),this.input.disabled||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>${Ct()}`,e&&this.closeCountryPopover()}showIdentifyError(e){this.identifyError.textContent=e}open(){this.isOpen=!0,this.panel.classList.remove(`hidden`),this.identifyContainer.classList.contains(`visible`)?this.nameInput.focus():this.input.focus(),this.callbacks.onOpen()}close(){this.isOpen=!1,this.closeCountryPopover(),this.panel.classList.add(`hidden`),this.callbacks.onClose()}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.showEmptyState(e)}setMode(e,t){let n=this.panel.classList.contains(`ttcb-mode-chat`),r=t?.agentName,i=t?.canRequestHuman===!0,a=n&&i,o=n&&e===`closed`,s=e===`closed`;this.requestHumanBtn.classList.toggle(`hidden`,!a),this.newSessionBtn.classList.toggle(`hidden`,!o),this.input.disabled=s,s?this.sendBtn.disabled=!0:this.shadow.getElementById(`ttcb-typing`)||(this.sendBtn.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.hideModeBanner()}showModeBanner(e,t){this.modeBanner.textContent=e,this.modeBanner.className=`ttcb-mode-banner visible ${t}`}hideModeBanner(){this.modeBanner.textContent=``,this.modeBanner.className=`ttcb-mode-banner`}destroy(){this.destroyed=!0,this.host.remove()}scrollToBottom(){this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight}},jt={apiBaseUrl:o,chatbotName:`AI Assistant`,primaryColor:`#2563EB`,theme:`auto`,position:`bottom-right`,welcomeMessage:``,placeholder:`Type your messageโ€ฆ`,autoOpen:!1,sessionId:``,requestTimeoutMs:n};function Mt(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var Nt=[5e3,15e3,3e4,6e4];function Pt(e){return i(e)?e.status===0||e.status>=500||e.apiError.code===`BAD_RESPONSE`:!1}function Ft(e){return i(e)?e.apiError.message:e instanceof Error?e.message:`Failed to load chatbot config.`}var It=0,Z=()=>Date.now()*1e3+It++%1e3;function Lt(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 Rt(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 Q=class{constructor(){this.emitter=new s,this.visitorTokens=new ut,this.widget=null,this.sdkSocket=null,this.callerSetName=!1,this.hasActiveTicket=!1,this.retryTimer=null,this.lastPushId=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})}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={...jt,...Mt(e)},this.apiClient=new a({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,timeoutMs:this.options.requestTimeoutMs}),this.hasActiveTicket=!1,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(Pt(n)){this.setState({isReady:!1,blockReason:`server-unavailable`,error:Ft(n)});let r=Nt[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 At(this.options,{onSend:e=>void this.sendMessage(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`)},onReset:()=>this.resetSession(),onRequestHuman:()=>void this.requestHuman()}))}clearRetry(){this.retryTimer!==null&&(clearTimeout(this.retryTimer),this.retryTimer=null)}handleConfigError(e){let t=(i(e)?e:null)?.apiError.code===`agent_not_assigned`?`no-agent`:null;this.setState({isReady:!1,blockReason:t,error:Ft(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)return;this.applyMode(n.mode,n)}catch{}}handleTicketStatus(e){e?.mode&&this.applyMode(e.mode,e)}handleMessageReceive(e){if(this._state.mode===`ai`)return;let t=Lt(e);if(!t)return;let n=Rt(e),r=this._state.messages[this._state.messages.length-1];if(r?.message.content===t&&(r.message.type===`ai`||r.message.type===`agent`&&(!n||n===this.lastPushId)))return;this.lastPushId=n;let i=this.visitorTokens.get()??this._state.visitorToken??``,a={id:Z(),sessionId:i,message:{type:`agent`,content:t}};this.setState({messages:[...this._state.messages,a]}),this.widget?.appendMessage(a),this.emitter.emit(`message`,a)}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 sendMessage(e){let t=this.visitorTokens.get()??this._state.visitorToken;if(!this.apiClient||!t)throw Error(`[onedeskpro-chatbot] Identify before 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,a=i===`ai`;this.setState({messages:[...this._state.messages,r],isLoading:!0,error:null}),this.widget?.appendMessage(r),a&&this.widget?.setLoading(!0),this.emitter.emit(`message`,r);try{let e=await this.apiClient.sendMessage({chatInput:n,visitorToken:t});this.hasActiveTicket=!0;let r=e.mode??i,a=[...this._state.messages],o=(e.text??``).trim();if(r!==i&&(this.setState({mode:r}),this.syncWidgetMode(r),this.emitter.emit(`ticket-status`,{mode:r})),o){let t=a[a.length-1];if(t?.message.type!==`agent`&&t?.message.type!==`ai`||t.message.content!==o){let t={id:Z(),sessionId:e.sessionId,message:{type:`ai`,content:o}};a.push(t),this.widget?.appendMessage(t),this.emitter.emit(`message`,t)}}this.setState({messages:a,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,zt={async init(e){return $=new Q,await $.init(e),$},getInstance(){return $}};exports.ApiClient=a,exports.ChatbotCore=Q,exports.DEFAULT_API_BASE_URL=o,exports.DEFAULT_REQUEST_TIMEOUT_MS=n,exports.EventEmitter=s,exports.OnedeskProChatbot=zt,exports.SdkSocket=ot,exports.SessionManager=ut,exports.isChatbotRequestError=i,exports.resolveSdkSocketUrl=at;