@flowengage/react-chatbot 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`react`);l=c(l);let u=require(`react/jsx-runtime`);var d=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},f={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},p=1e4,m=6e4,ee=480*60,h=3e4,g=typeof window<`u`,_=e=>e?`flowengage.visitorEmail.${e}`:null,te=()=>{if(!g)return`server-chat-id`;let e=window.localStorage.getItem(f.chatId);if(e)return e;let t=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return window.localStorage.setItem(f.chatId,t),t},v=()=>g?{isOpen:!1,activeScreen:window.sessionStorage.getItem(f.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(f.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(f.agentName),agentHeadshot:window.sessionStorage.getItem(f.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},ne=e=>{g&&Object.entries(e).forEach(([e,t])=>{let n=f[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},re=e=>{if(!g||!e)return``;let t=_(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(f.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(f.visitorEmail),n=e)}return n||``},ie=(e,t)=>{if(!g)return;let n=_(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(f.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(f.visitorEmail)},ae=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},oe=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},se=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await ae(await oe(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},ce=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},i=async(r,i={})=>ae(await oe(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}}));return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...a||{}})})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,t){return i(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:t})})},async trackVisitor(e){return i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(e,t,n,r){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let i=new Blob([JSON.stringify({session_id:n,messages:r})],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,i)}}},y=Object.create(null);y.open=`0`,y.close=`1`,y.ping=`2`,y.pong=`3`,y.message=`4`,y.upgrade=`5`,y.noop=`6`;var le=Object.create(null);Object.keys(y).forEach(e=>{le[y[e]]=e});var ue={type:`error`,data:`parser error`},de=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,fe=typeof ArrayBuffer==`function`,pe=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,me=({type:e,data:t},n,r)=>de&&t instanceof Blob?n?r(t):he(t,r):fe&&(t instanceof ArrayBuffer||pe(t))?n?r(t):he(new Blob([t]),r):r(y[e]+(t||``)),he=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function ge(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var _e;function ve(e,t){if(de&&e.data instanceof Blob)return e.data.arrayBuffer().then(ge).then(t);if(fe&&(e.data instanceof ArrayBuffer||pe(e.data)))return t(ge(e.data));me(e,!1,e=>{_e||=new TextEncoder,t(_e.encode(e))})}var ye=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,be=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)be[ye.charCodeAt(e)]=e;var xe=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=be[e.charCodeAt(r)],o=be[e.charCodeAt(r+1)],s=be[e.charCodeAt(r+2)],c=be[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Se=typeof ArrayBuffer==`function`,Ce=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Te(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:we(e.substring(1),t)}:le[n]?e.length>1?{type:le[n],data:e.substring(1)}:{type:le[n]}:ue},we=(e,t)=>Se?Te(xe(e),t):{base64:!0,data:e},Te=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ee=``,De=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{me(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ee))})})},Oe=(e,t)=>{let n=e.split(Ee),r=[];for(let e=0;e<n.length;e++){let i=Ce(n[e],t);if(r.push(i),i.type===`error`)break}return r};function ke(){return new TransformStream({transform(e,t){ve(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Ae;function je(e){return e.reduce((e,t)=>e+t.length,0)}function Me(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 Ne(e,t){Ae||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(je(n)<1)break;let e=Me(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(je(n)<2)break;let e=Me(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(je(n)<8)break;let e=Me(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(ue);break}i=a*2**32+t.getUint32(4),r=3}else{if(je(n)<i)break;let e=Me(n,i);s.enqueue(Ce(a?e:Ae.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(ue);break}}}})}function b(e){if(e)return Pe(e)}function Pe(e){for(var t in b.prototype)e[t]=b.prototype[t];return e}b.prototype.on=b.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},b.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},b.prototype.off=b.prototype.removeListener=b.prototype.removeAllListeners=b.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},b.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},b.prototype.emitReserved=b.prototype.emit,b.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},b.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Fe=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),x=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Ie=`arraybuffer`;function Le(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Re=x.setTimeout,ze=x.clearTimeout;function Be(e,t){t.useNativeTimers?(e.setTimeoutFn=Re.bind(x),e.clearTimeoutFn=ze.bind(x)):(e.setTimeoutFn=x.setTimeout.bind(x),e.clearTimeoutFn=x.clearTimeout.bind(x))}var Ve=1.33;function He(e){return typeof e==`string`?Ue(e):Math.ceil((e.byteLength||e.size)*Ve)}function Ue(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 We(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ge(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ke(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 S=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},C=class extends b{constructor(e){super(),this.writable=!1,Be(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 S(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=Ce(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=Ge(e);return t.length?`?`+t:``}},w=class extends C{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Oe(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,De(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=We()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},qe=!1;try{qe=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Je=qe;function Ye(){}var Xe=class extends w{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}},Ze=class e extends b{constructor(e,t,n){super(),this.createRequest=e,Be(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=Le(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=Ye,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(Ze.requestsCount=0,Ze.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Qe);else if(typeof addEventListener==`function`){let e=`onpagehide`in x?`pagehide`:`unload`;addEventListener(e,Qe,!1)}}function Qe(){for(let e in Ze.requests)Ze.requests.hasOwnProperty(e)&&Ze.requests[e].abort()}var $e=(function(){let e=tt({xdomain:!1});return e&&e.responseType!==null})(),et=class extends Xe{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=$e&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ze(tt,this.uri(),e)}};function tt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Je))return new XMLHttpRequest}catch{}if(!t)try{return new x[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var nt=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,rt=class extends C{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=nt?{}:Le(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;me(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Fe(()=>{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]=We()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},it=x.WebSocket||x.MozWebSocket,at={websocket:class extends rt{createSocket(e,t,n){return nt?new it(e,t,n):t?new it(e,t):new it(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends C{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=Ne(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ke();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Fe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:et},ot=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,st=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function ct(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=ot.exec(e||``),a={},o=14;for(;o--;)a[st[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=lt(a,a.path),a.queryKey=ut(a,a.query),a}function lt(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 ut(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var dt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,ft=[];dt&&addEventListener(`offline`,()=>{ft.forEach(e=>e())},!1);var pt=class e extends b{constructor(e,t){if(super(),this.binaryType=Ie,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=ct(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=ct(t.host).host);Be(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=Ke(this.opts.query)),dt&&(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`})},ft.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);break}}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+=He(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,Fe(()=>{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(),dt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=ft.indexOf(this._offlineEventListener);e!==-1&&ft.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};pt.protocol=4;var mt=class extends pt{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;pt.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;pt.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}},ht=class extends mt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>at[e]).filter(e=>!!e)),super(e,n)}};ht.protocol;function gt(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=ct(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 _t=typeof ArrayBuffer==`function`,vt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,yt=Object.prototype.toString,bt=typeof Blob==`function`||typeof Blob<`u`&&yt.call(Blob)===`[object BlobConstructor]`,xt=typeof File==`function`||typeof File<`u`&&yt.call(File)===`[object FileConstructor]`;function St(e){return _t&&(e instanceof ArrayBuffer||vt(e))||bt&&e instanceof Blob||xt&&e instanceof File}function Ct(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ct(e[t]))return!0;return!1}if(St(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ct(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ct(e[t]))return!0;return!1}function wt(e){let t=[],n=e.data,r=e;return r.data=Tt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Tt(e,t){if(!e)return e;if(St(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=Tt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Tt(e[r],t));return n}return e}function Et(e,t){return e.data=Dt(e.data,t),delete e.attachments,e}function Dt(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`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Dt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Dt(e[n],t));return e}var Ot=o({Decoder:()=>jt,Encoder:()=>At,PacketType:()=>T,isPacketValid:()=>Rt,protocol:()=>5}),kt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],T;(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`})(T||={});var At=class{constructor(e){this.replacer=e}encode(e){return(e.type===T.EVENT||e.type===T.ACK)&&Ct(e)?this.encodeAsBinary({type:e.type===T.EVENT?T.BINARY_EVENT:T.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===T.BINARY_EVENT||e.type===T.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=wt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},jt=class e extends b{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===T.BINARY_EVENT;n||t.type===T.BINARY_ACK?(t.type=n?T.EVENT:T.ACK,this.reconstructor=new Mt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(St(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(T[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===T.BINARY_EVENT||r.type===T.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(!Pt(a)||a<0)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 T.CONNECT:return It(t);case T.DISCONNECT:return t===void 0;case T.CONNECT_ERROR:return typeof t==`string`||It(t);case T.EVENT:case T.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&kt.indexOf(t[0])===-1);case T.ACK:case T.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Mt=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=Et(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Nt(e){return typeof e==`string`}var Pt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Ft(e){return e===void 0||Pt(e)}function It(e){return Object.prototype.toString.call(e)===`[object Object]`}function Lt(e,t){switch(e){case T.CONNECT:return t===void 0||It(t);case T.DISCONNECT:return t===void 0;case T.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&kt.indexOf(t[0])===-1);case T.ACK:return Array.isArray(t);case T.CONNECT_ERROR:return typeof t==`string`||It(t);default:return!1}}function Rt(e){return Nt(e.nsp)&&Ft(e.id)&&Lt(e.type,e.data)}function zt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Bt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Vt=class extends b{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=[zt(e,`open`,this.onopen.bind(this)),zt(e,`packet`,this.onpacket.bind(this)),zt(e,`error`,this.onerror.bind(this)),zt(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(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(Bt.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:T.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:T.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 T.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 T.EVENT:case T.BINARY_EVENT:this.onevent(e);break;case T.ACK:case T.BINARY_ACK:this.onack(e);break;case T.DISCONNECT:this.ondisconnect();break;case T.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}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:T.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:T.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 Ht(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}Ht.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},Ht.prototype.reset=function(){this.attempts=0},Ht.prototype.setMin=function(e){this.ms=e},Ht.prototype.setMax=function(e){this.max=e},Ht.prototype.setJitter=function(e){this.jitter=e};var Ut=class extends b{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,Be(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 Ht({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||Ot;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 ht(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=zt(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=zt(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(zt(e,`ping`,this.onping.bind(this)),zt(e,`data`,this.ondata.bind(this)),zt(e,`error`,this.onerror.bind(this)),zt(e,`close`,this.onclose.bind(this)),zt(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){Fe(()=>{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 Vt(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)}},Wt={};function Gt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=gt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=Wt[i]&&a in Wt[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Ut(r,t):(Wt[i]||(Wt[i]=new Ut(r,t)),c=Wt[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Gt,{Manager:Ut,Socket:Vt,io:Gt,connect:Gt});var Kt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Gt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),qt=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},a=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},o=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,timestamp:Date.now()})},c=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),o(n,r),n=e,r=Date.now(),a()},l=window.history.pushState.bind(window.history),u=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{l(...e),c()},window.history.replaceState=(...e)=>{u(...e),c()};let d=window.setInterval(s,p),f=()=>{o(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})};return window.addEventListener(`popstate`,c),window.addEventListener(`hashchange`,c),window.addEventListener(`beforeunload`,f),i(),s(),{notifyRouteChange:c,cleanup:()=>{window.clearInterval(d),window.history.pushState=l,window.history.replaceState=u,window.removeEventListener(`popstate`,c),window.removeEventListener(`hashchange`,c),window.removeEventListener(`beforeunload`,f)}}},Jt=(0,l.createContext)(null),Yt=()=>{let e=(0,l.useContext)(Jt);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function Xt(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}function Zt(...e){Xt()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Qt=`fe_pending_nav_section`,$t=15e3;function en(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem(Qt)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Qt)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>$t){Zt(`initNavigationHighlight: pending section expired, skipping:`,t);return}Zt(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=nn(null,t);if(e){rn(e),Zt(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):Zt(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var tn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`react`);l=c(l);let u=require(`react/jsx-runtime`);var d=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},f={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},p=1e4,m=6e4,ee=480*60,h=3e4,g=typeof window<`u`,_=e=>e?`flowengage.visitorEmail.${e}`:null,te=()=>{if(!g)return`server-chat-id`;let e=window.localStorage.getItem(f.chatId);if(e)return e;let t=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return window.localStorage.setItem(f.chatId,t),t},v=()=>g?{isOpen:!1,activeScreen:window.sessionStorage.getItem(f.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(f.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(f.agentName),agentHeadshot:window.sessionStorage.getItem(f.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},ne=e=>{g&&Object.entries(e).forEach(([e,t])=>{let n=f[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},re=e=>{if(!g||!e)return``;let t=_(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(f.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(f.visitorEmail),n=e)}return n||``},ie=(e,t)=>{if(!g)return;let n=_(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(f.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(f.visitorEmail)},ae=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},oe=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},se=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await ae(await oe(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},ce=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},i=async(r,i={})=>ae(await oe(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}}));return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...a||{}})})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return i(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a={session_id:r,messages:i,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}},o=new Blob([JSON.stringify(a)],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,o)}}},y=Object.create(null);y.open=`0`,y.close=`1`,y.ping=`2`,y.pong=`3`,y.message=`4`,y.upgrade=`5`,y.noop=`6`;var le=Object.create(null);Object.keys(y).forEach(e=>{le[y[e]]=e});var ue={type:`error`,data:`parser error`},de=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,fe=typeof ArrayBuffer==`function`,pe=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,me=({type:e,data:t},n,r)=>de&&t instanceof Blob?n?r(t):he(t,r):fe&&(t instanceof ArrayBuffer||pe(t))?n?r(t):he(new Blob([t]),r):r(y[e]+(t||``)),he=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function ge(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var _e;function ve(e,t){if(de&&e.data instanceof Blob)return e.data.arrayBuffer().then(ge).then(t);if(fe&&(e.data instanceof ArrayBuffer||pe(e.data)))return t(ge(e.data));me(e,!1,e=>{_e||=new TextEncoder,t(_e.encode(e))})}var ye=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,be=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)be[ye.charCodeAt(e)]=e;var xe=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=be[e.charCodeAt(r)],o=be[e.charCodeAt(r+1)],s=be[e.charCodeAt(r+2)],c=be[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Se=typeof ArrayBuffer==`function`,Ce=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Te(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:we(e.substring(1),t)}:le[n]?e.length>1?{type:le[n],data:e.substring(1)}:{type:le[n]}:ue},we=(e,t)=>Se?Te(xe(e),t):{base64:!0,data:e},Te=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ee=``,De=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{me(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ee))})})},Oe=(e,t)=>{let n=e.split(Ee),r=[];for(let e=0;e<n.length;e++){let i=Ce(n[e],t);if(r.push(i),i.type===`error`)break}return r};function ke(){return new TransformStream({transform(e,t){ve(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Ae;function je(e){return e.reduce((e,t)=>e+t.length,0)}function Me(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 Ne(e,t){Ae||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(je(n)<1)break;let e=Me(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(je(n)<2)break;let e=Me(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(je(n)<8)break;let e=Me(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(ue);break}i=a*2**32+t.getUint32(4),r=3}else{if(je(n)<i)break;let e=Me(n,i);s.enqueue(Ce(a?e:Ae.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(ue);break}}}})}function b(e){if(e)return Pe(e)}function Pe(e){for(var t in b.prototype)e[t]=b.prototype[t];return e}b.prototype.on=b.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},b.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},b.prototype.off=b.prototype.removeListener=b.prototype.removeAllListeners=b.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},b.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},b.prototype.emitReserved=b.prototype.emit,b.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},b.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Fe=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),x=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Ie=`arraybuffer`;function Le(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Re=x.setTimeout,ze=x.clearTimeout;function Be(e,t){t.useNativeTimers?(e.setTimeoutFn=Re.bind(x),e.clearTimeoutFn=ze.bind(x)):(e.setTimeoutFn=x.setTimeout.bind(x),e.clearTimeoutFn=x.clearTimeout.bind(x))}var Ve=1.33;function He(e){return typeof e==`string`?Ue(e):Math.ceil((e.byteLength||e.size)*Ve)}function Ue(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 We(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ge(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ke(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 S=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},C=class extends b{constructor(e){super(),this.writable=!1,Be(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 S(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=Ce(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=Ge(e);return t.length?`?`+t:``}},w=class extends C{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Oe(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,De(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=We()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},qe=!1;try{qe=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Je=qe;function Ye(){}var Xe=class extends w{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}},Ze=class e extends b{constructor(e,t,n){super(),this.createRequest=e,Be(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=Le(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=Ye,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(Ze.requestsCount=0,Ze.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Qe);else if(typeof addEventListener==`function`){let e=`onpagehide`in x?`pagehide`:`unload`;addEventListener(e,Qe,!1)}}function Qe(){for(let e in Ze.requests)Ze.requests.hasOwnProperty(e)&&Ze.requests[e].abort()}var $e=(function(){let e=tt({xdomain:!1});return e&&e.responseType!==null})(),et=class extends Xe{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=$e&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ze(tt,this.uri(),e)}};function tt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Je))return new XMLHttpRequest}catch{}if(!t)try{return new x[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var nt=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,rt=class extends C{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=nt?{}:Le(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;me(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Fe(()=>{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]=We()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},it=x.WebSocket||x.MozWebSocket,at={websocket:class extends rt{createSocket(e,t,n){return nt?new it(e,t,n):t?new it(e,t):new it(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends C{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=Ne(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ke();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Fe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:et},ot=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,st=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function ct(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=ot.exec(e||``),a={},o=14;for(;o--;)a[st[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=lt(a,a.path),a.queryKey=ut(a,a.query),a}function lt(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 ut(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var dt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,ft=[];dt&&addEventListener(`offline`,()=>{ft.forEach(e=>e())},!1);var pt=class e extends b{constructor(e,t){if(super(),this.binaryType=Ie,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=ct(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=ct(t.host).host);Be(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=Ke(this.opts.query)),dt&&(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`})},ft.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);break}}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+=He(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,Fe(()=>{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(),dt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=ft.indexOf(this._offlineEventListener);e!==-1&&ft.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};pt.protocol=4;var mt=class extends pt{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;pt.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;pt.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}},ht=class extends mt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>at[e]).filter(e=>!!e)),super(e,n)}};ht.protocol;function gt(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=ct(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 _t=typeof ArrayBuffer==`function`,vt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,yt=Object.prototype.toString,bt=typeof Blob==`function`||typeof Blob<`u`&&yt.call(Blob)===`[object BlobConstructor]`,xt=typeof File==`function`||typeof File<`u`&&yt.call(File)===`[object FileConstructor]`;function St(e){return _t&&(e instanceof ArrayBuffer||vt(e))||bt&&e instanceof Blob||xt&&e instanceof File}function Ct(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ct(e[t]))return!0;return!1}if(St(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ct(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ct(e[t]))return!0;return!1}function wt(e){let t=[],n=e.data,r=e;return r.data=Tt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Tt(e,t){if(!e)return e;if(St(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=Tt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Tt(e[r],t));return n}return e}function Et(e,t){return e.data=Dt(e.data,t),delete e.attachments,e}function Dt(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`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Dt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Dt(e[n],t));return e}var Ot=o({Decoder:()=>jt,Encoder:()=>At,PacketType:()=>T,isPacketValid:()=>Rt,protocol:()=>5}),kt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],T;(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`})(T||={});var At=class{constructor(e){this.replacer=e}encode(e){return(e.type===T.EVENT||e.type===T.ACK)&&Ct(e)?this.encodeAsBinary({type:e.type===T.EVENT?T.BINARY_EVENT:T.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===T.BINARY_EVENT||e.type===T.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=wt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},jt=class e extends b{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===T.BINARY_EVENT;n||t.type===T.BINARY_ACK?(t.type=n?T.EVENT:T.ACK,this.reconstructor=new Mt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(St(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(T[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===T.BINARY_EVENT||r.type===T.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(!Pt(a)||a<0)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 T.CONNECT:return It(t);case T.DISCONNECT:return t===void 0;case T.CONNECT_ERROR:return typeof t==`string`||It(t);case T.EVENT:case T.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&kt.indexOf(t[0])===-1);case T.ACK:case T.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Mt=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=Et(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Nt(e){return typeof e==`string`}var Pt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Ft(e){return e===void 0||Pt(e)}function It(e){return Object.prototype.toString.call(e)===`[object Object]`}function Lt(e,t){switch(e){case T.CONNECT:return t===void 0||It(t);case T.DISCONNECT:return t===void 0;case T.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&kt.indexOf(t[0])===-1);case T.ACK:return Array.isArray(t);case T.CONNECT_ERROR:return typeof t==`string`||It(t);default:return!1}}function Rt(e){return Nt(e.nsp)&&Ft(e.id)&&Lt(e.type,e.data)}function zt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Bt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Vt=class extends b{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=[zt(e,`open`,this.onopen.bind(this)),zt(e,`packet`,this.onpacket.bind(this)),zt(e,`error`,this.onerror.bind(this)),zt(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(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(Bt.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:T.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:T.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 T.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 T.EVENT:case T.BINARY_EVENT:this.onevent(e);break;case T.ACK:case T.BINARY_ACK:this.onack(e);break;case T.DISCONNECT:this.ondisconnect();break;case T.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}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:T.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:T.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 Ht(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}Ht.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},Ht.prototype.reset=function(){this.attempts=0},Ht.prototype.setMin=function(e){this.ms=e},Ht.prototype.setMax=function(e){this.max=e},Ht.prototype.setJitter=function(e){this.jitter=e};var Ut=class extends b{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,Be(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 Ht({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||Ot;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 ht(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=zt(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=zt(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(zt(e,`ping`,this.onping.bind(this)),zt(e,`data`,this.ondata.bind(this)),zt(e,`error`,this.onerror.bind(this)),zt(e,`close`,this.onclose.bind(this)),zt(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){Fe(()=>{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 Vt(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)}},Wt={};function Gt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=gt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=Wt[i]&&a in Wt[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Ut(r,t):(Wt[i]||(Wt[i]=new Ut(r,t)),c=Wt[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Gt,{Manager:Ut,Socket:Vt,io:Gt,connect:Gt});var Kt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Gt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),qt=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},a=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},o=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,timestamp:Date.now()})},c=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),o(n,r),n=e,r=Date.now(),a()},l=window.history.pushState.bind(window.history),u=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{l(...e),c()},window.history.replaceState=(...e)=>{u(...e),c()};let d=window.setInterval(s,p),f=()=>{o(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})};return window.addEventListener(`popstate`,c),window.addEventListener(`hashchange`,c),window.addEventListener(`beforeunload`,f),i(),s(),{notifyRouteChange:c,cleanup:()=>{window.clearInterval(d),window.history.pushState=l,window.history.replaceState=u,window.removeEventListener(`popstate`,c),window.removeEventListener(`hashchange`,c),window.removeEventListener(`beforeunload`,f)}}},Jt=(0,l.createContext)(null),Yt=()=>{let e=(0,l.useContext)(Jt);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function Xt(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}function Zt(...e){Xt()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Qt=`fe_pending_nav_section`,$t=15e3;function en(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem(Qt)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Qt)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>$t){Zt(`initNavigationHighlight: pending section expired, skipping:`,t);return}Zt(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=nn(null,t);if(e){rn(e),Zt(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):Zt(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var tn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
2
2
  .fe-highlight-section {
3
3
  outline: 3px solid #7c3aed !important;
4
4
  box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
5
5
  transition: all 0.3s ease !important;
6
6
  border-radius: 8px !important;
7
7
  }
8
- `,document.head.appendChild(e)};function nn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function rn(e){!e||typeof document>`u`||(tn(),an(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function an(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function on(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function sn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function cn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?sn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function ln(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Qt,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function un(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=on(e),r=new URL(t,window.location.origin);if(Zt(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return Zt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return Zt(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return Zt(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(Zt(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(ln(n),Zt(`branch: location.assign (full navigation, section stored):`,n)):Zt(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&ln(n);try{window.location.href=on(e)}catch{window.location.href=e}return!0}}var dn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),fn=(e=[])=>e.map(e=>({...e,message:dn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),pn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,mn=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},hn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},gn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function _n({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,l.useMemo)(()=>gn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,l.useState)(`booting`),[c,f]=(0,l.useState)(null),[p,g]=(0,l.useState)(null),[_,ae]=(0,l.useState)(``),[oe,y]=(0,l.useState)([]),[le,ue]=(0,l.useState)(v().isOpen),[de,fe]=(0,l.useState)(v().activeScreen),[pe,me]=(0,l.useState)(v().isHumanHandled),[he,ge]=(0,l.useState)(v().agentName),[_e,ve]=(0,l.useState)(v().agentHeadshot),[ye,be]=(0,l.useState)(()=>re(i?.siteId)),[xe,Se]=(0,l.useState)(!1),[Ce,we]=(0,l.useState)(!1),[Te,Ee]=(0,l.useState)(`idle`),[De,Oe]=(0,l.useState)(!1),[ke,Ae]=(0,l.useState)(!1),[je,Me]=(0,l.useState)(``),[Ne,b]=(0,l.useState)(!1),[Pe,Fe]=(0,l.useState)(!1),[x,Ie]=(0,l.useState)(null),[Le,Re]=(0,l.useState)(null),[ze,Be]=(0,l.useState)(`idle`),[Ve,He]=(0,l.useState)(null),[Ue,We]=(0,l.useState)(!1),[Ge,Ke]=(0,l.useState)(``),S=(0,l.useRef)(null),C=(0,l.useRef)(null),w=(0,l.useRef)(``),qe=(0,l.useRef)(null),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)([]),$e=(0,l.useRef)(null),et=(0,l.useRef)(null),tt=(0,l.useRef)(!1),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(``),it=(0,l.useRef)(he),at=(0,l.useRef)([]),ot=(0,l.useRef)(!1),st=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),ct=(0,l.useMemo)(()=>{let e=p?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:ee},[i,p]);(0,l.useEffect)(()=>{qe.current=x},[x]),(0,l.useEffect)(()=>{it.current=he},[he]);let lt=()=>{Ke(``)},ut=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return be(t),ie(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&be(re(e))},[i?.siteId]);let dt=()=>{Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),Ze.current=null,Qe.current=[],$e.current=null,et.current=null,tt.current=!1,We(!1),Ie(null),Re(null),Be(`idle`),He(null)},ft=(e=new Date().toISOString())=>{let t=S.current,n=$e.current||Ze.current?.callId;if(!t?.connected||!n||tt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:w.current,socketConnected:!!t?.connected,alreadyReported:tt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:w.current,connectedAt:e}),tt.current=!0,t.emit(`call:connected`,{callId:n,chatId:w.current,connectedAt:e})},pt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Ie(null),t||n){$e.current=e.callId,Re(e.callId),Be(e=>e===`connected`?e:`connecting`),ue(!0);return}Be(`idle`)}},mt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){dt();return}et.current=null,Ze.current=null,Qe.current=[],Ie(null),Be(`idle`)}},ht=async(e={})=>{let t=Je.current,n=S.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:w.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:w.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:w.current,queuedCount:Qe.current.length});for(let e of Qe.current)await t.addIceCandidate(new RTCIceCandidate(e));Qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:w.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:w.current})};(0,l.useEffect)(()=>{ne({isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e})},[le,de,pe,he,_e]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await se(t);if(!e)return;let o=te();w.current=o;let c=ce({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});C.current=c,g({...n,apiBaseUrl:t.apiBaseUrl}),ae(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Kt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});S.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),Ee(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),Ee(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:w.current}),we(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:w.current}),we(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:dn(t.message)};we(!1),Se(!1),y(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&y(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:dn(t.message)};we(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Se(!1),y(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(me(!0),fe(`agent`),ge(gn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ve(n.sender_headshot),ue(!0))}),l.on(`agent:joined`,e=>{let t=gn([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=gn([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,(e={})=>{let t=gn([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=gn([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{Fe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{y(fn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!1)}),l.on(`call:incoming`,(e={})=>{let t=gn([e.agentName,e.ownerName,e.agent?.name,he],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:w.current,agentName:t}),lt(),tt.current=!1,Ie({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ge(e=>gn([t,e],a)),Be(`incoming`),He(null),ue(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||w.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ze.current=e;try{await ht(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,hasPeerConnection:!!Je.current,hasCandidate:!!e.candidate});return}try{let t=mn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,candidate:hn(t),hasRemoteDescription:!!Je.current?.remoteDescription}),!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||w.current,queueSize:Qe.current.length+1}),Qe.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{lt(),dt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||w.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Ie(null),Be(`idle`));return}tt.current=!0,et.current=null,$e.current=e.callId,Re(e.callId),Ie(null),Be(`connected`),He(e.connectedAt||new Date().toISOString()),ue(!0)}),l.on(`call:unavailable`,(e={})=>{dt(),Ke(pn(e,`This visitor is not available for a call right now.`)),ue(!0)}),l.on(`call:error`,(e={})=>{dt(),Ke(pn(e,`We couldn't connect the call right now.`)),ue(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await cn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}un(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=nn(null,t);e&&rn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=nn(e||null,t||null);n&&rn(n)}),l.on(`visitor:clear_highlight`,()=>{an()}),st.current=qt({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(y(fn(u.chat_history||[])),me(!!u.is_human_handled),fe(u.is_human_handled?`agent`:de),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),f(t),s(`error`)}})(),()=>{e=!1,st.current?.cleanup?.(),dt(),S.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(Ne&&!ot.current&&at.current.length>0){let e=w.current,t=at.current,n=C.current,r=p?.apiBaseUrl||``,i=p?.userId||``;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(r,i,e,t)||n.syncVoice(e,t).catch(()=>{}),ot.current=!0)}},[Ne,p]),(0,l.useEffect)(()=>{if(!C.current||!_||o!==`ready`||pe)return;let e=window.setInterval(async()=>{try{let e=await C.current.checkHumanHandled(_);me(!!e.is_human_handled),e.is_human_handled&&(fe(`agent`),e.agent_info?.name&&ge(e.agent_info.name),e.agent_info?.headshot&&ve(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,o,pe]);let gt=async()=>{if(!(!x?.callId||!C.current||!S.current||!_)){lt(),et.current=x.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:x?.callId,chatId:_,socketConnected:!!S.current?.connected,hasPendingOffer:!!Ze.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:x.callId,chatId:_,trackCount:e.getTracks().length}),Ye.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Je.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:x.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}e===`connecting`&&Be(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:x.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}(e===`checking`||e===`new`)&&Be(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!S.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:x.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!S.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:x.callId,chatId:_,candidate:hn(e.candidate)}),S.current.emit(`call:ice-candidate`,{callId:x.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:x.callId,chatId:_,streamCount:e.streams?.length||0}),!Xe.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0]};let n=Ze.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||x.callId,chatId:_}),await ht({...n,callId:n.callId||x.callId})),await C.current.acceptCall(x.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:x.callId,chatId:_}),$e.current=x.callId,Re(x.callId),Be(`connecting`),Ie(null),ue(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),et.current=null,dt(),e?.status===404||e?.status===409||e?.status===422){Ke(pn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ke(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ke(`We couldn't connect the call right now. Please try again.`)}}},_t=async()=>{if(!x?.callId||!C.current||!_){dt();return}lt();try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ke(pn(e,`We couldn't decline the call cleanly.`))}finally{dt()}},vt=(0,l.useRef)(_t);vt.current=_t,(0,l.useEffect)(()=>{if(!x?.callId||Le)return;let e=x.callId,t=window.setTimeout(()=>{qe.current?.callId===e&&vt.current()},h);return()=>window.clearTimeout(t)},[x?.callId,Le]);let yt=async()=>{if(!Le||!C.current||!_){dt();return}lt();try{await C.current.endWebRTCCall(Le,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ke(pn(e,`The call ended locally, but the server could not be updated.`))}finally{dt()}},bt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ue;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),We(r)},xt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(ue(!0),!(!t||!C.current||!_||typeof window>`u`)){try{await C.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await C.current.updateChatStatus(_,`open`)}catch{}}},St=async e=>{let t=ut(e);if(!t||!C.current||!w.current)return t;try{await C.current.trackVisitor({chatId:w.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Ct=()=>{if(!_||!S.current?.connected||nt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!S.current?.connected,alreadyTyping:nt.current});return}nt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),S.current.emit(`typing:start`,{chatId:_,sender:`user`})},wt=()=>{if(!_||!S.current?.connected||!nt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!S.current?.connected,wasTyping:nt.current});return}nt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),S.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Tt=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!S.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!S.current?.connected,textLength:t.length});return}rt.current!==t&&(rt.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),S.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Et=async(e,t=``,n=null)=>{if(!e.trim()||!C.current||!_||o!==`ready`||Pe)return;wt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(y(e=>[...e,a]),pe&&S.current?.connected){S.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:ye||void 0,...n||{}});return}Oe(!0);try{let i=await C.current.sendAiMessage(_,e,r,t,{...n||{},...ye?{email:ye}:{}});y(fn(i.chat_history||[])),me(!!i.is_human_handled),fe(i.is_human_handled?`agent`:`ai`),we(!1),await C.current.updateChatStatus(_,`messageSent`)}catch(e){y(e=>e.filter(e=>e.id!==i)),we(!1),e.status===429?(Ae(!0),Me(e.message),window.setTimeout(()=>{Ae(!1),Me(``)},m)):f(e)}finally{Oe(!1)}},Dt=async e=>{if(!(!C.current||!_)){try{let t=e?`voice`:`text`;await C.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}b(e),e&&(ot.current=!1)}},Ot=async e=>{if(!ot.current){if(ot.current=!0,!C.current||!_||!e?.length){b(!1);return}try{let t=await C.current.syncVoice(_,e);if(t?.chat_history?.length)y(fn(t.chat_history));else if(t?.success)try{let e=await C.current.loadHistory(_,r);e?.chat_history?.length&&y(fn(e.chat_history))}catch{}}catch{}finally{b(!1)}}},kt=async()=>{if(!(!C.current||!_)){Ne&&!ot.current&&at.current.length>0&&await Ot(at.current);try{await C.current.endConversation(_)}catch{try{await C.current.updateChatStatus(_,`ended`)}catch{}}Fe(!0),y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,l.useEffect)(()=>{if(ze!==`connected`||!Le||!_||!Ve||!ct)return;let e=new Date(Ve).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,ct*1e3-t),r=window.setTimeout(()=>{Ke(`The call ended because it reached the time limit.`),yt()},n);return()=>window.clearTimeout(r)},[Le,Ve,ze,_,yt,ct]),(0,l.useEffect)(()=>{let e=()=>{let e=w.current,t=C.current;if(!t||!e)return;if($e.current){t.beaconEndWebRTCCall($e.current,e);return}let n=et.current||qe.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let T=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:p,resolvedConfig:i,chatId:_,chatHistory:oe,isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e,visitorEmail:ye,isAgentTyping:xe,isAiTyping:Ce,connectionStatus:Te,isLoading:De,isVoiceMode:Ne,isRateLimited:ke,rateLimitMessage:je,isConversationEnded:Pe,incomingCall:x,activeCallId:Le,callConnectionState:ze,callConnectedAt:Ve,isCallMuted:Ue,webRTCError:Ge,language:r,historyRef:at,hasSyncedRef:ot,dismissCallError:lt,captureVisitorEmail:St,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt,notifyRouteChange:()=>st.current?.notifyRouteChange?.(),openWidget:xt,closeWidget:()=>ue(!1),toggleWidget:()=>{if(le){ue(!1);return}xt({notifyChatInitiated:!0})},sendMessage:Et,setVoiceMode:Dt,onMessageSync:Ot,endConversation:kt,acceptCall:gt,rejectCall:_t,endWebRTCCall:yt,toggleCallMute:bt,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt}),[o,c,p,i,_,oe,le,de,pe,he,_e,ye,xe,Ce,Te,De,Ne,ke,je,Pe,x,Le,ze,Ve,Ue,Ge,r,St,Ct,wt,Tt,gt,_t,yt,bt,xt,Et,Dt,Ot,kt,lt]);return(0,u.jsx)(Jt.Provider,{value:T,children:n})}var vn=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),yn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),bn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),xn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Sn=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Cn=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),wn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Tn=({className:e=``})=>(0,u.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),En=({size:e=18,strokeWidth:t=2.5})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,u.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),Dn=({size:e=14})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 8V4H8`}),(0,u.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,u.jsx)(`path`,{d:`M2 14h2`}),(0,u.jsx)(`path`,{d:`M20 14h2`}),(0,u.jsx)(`path`,{d:`M15 13v2`}),(0,u.jsx)(`path`,{d:`M9 13v2`})]});function On({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,u.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,u.jsx)(`span`,{children:n}),a?(0,u.jsx)(vn,{color:`#fff`}):(0,u.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,u.jsx)(yn,{})})]})}function kn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function An({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,l.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,l.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,u.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,u.jsx)(`span`,{style:r,children:kn(t)})}function jn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Mn(e){let[t,n]=(0,l.useState)(`loading`),r=jn(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Nn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:d=`AI`,agentAvatarUrl:f=null,primaryColor:p=`#3B82F6`}){let{state:m,resolvedLogoUrl:ee}=Mn(e),h=i===`agent`,g=n||r||a?.fallbackAgentName||`Agent`;return(0,u.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[h?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:p,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,u.jsx)(An,{src:typeof f==`string`?f:``,name:g,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,u.jsxs)(u.Fragment,{children:[m!==`loading`&&(m===`error`||!ee&&!e?(0,u.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(e,{})}):m===`wide`?(0,u.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:ee.toLowerCase().includes(`.svg`)||ee.startsWith(`data:image/svg`)?0:`2px`}})})),m===`loading`&&(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,u.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,u.jsx)(Dn,{size:11}),(0,u.jsx)(`span`,{children:d})]})]}),(0,u.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,u.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(En,{})})})]})}var Pn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Fn=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function In(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Ln=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return In(t);let n=t.replace(/\r\n/g,`
8
+ `,document.head.appendChild(e)};function nn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function rn(e){!e||typeof document>`u`||(tn(),an(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function an(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function on(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function sn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function cn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?sn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function ln(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Qt,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function un(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=on(e),r=new URL(t,window.location.origin);if(Zt(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return Zt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return Zt(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return Zt(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(Zt(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(ln(n),Zt(`branch: location.assign (full navigation, section stored):`,n)):Zt(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&ln(n);try{window.location.href=on(e)}catch{window.location.href=e}return!0}}var dn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),fn=(e=[])=>e.map(e=>({...e,message:dn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),pn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,mn=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},hn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},gn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function _n({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,l.useMemo)(()=>gn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,l.useState)(`booting`),[c,f]=(0,l.useState)(null),[p,g]=(0,l.useState)(null),[_,ae]=(0,l.useState)(``),[oe,y]=(0,l.useState)([]),[le,ue]=(0,l.useState)(v().isOpen),[de,fe]=(0,l.useState)(v().activeScreen),[pe,me]=(0,l.useState)(v().isHumanHandled),[he,ge]=(0,l.useState)(v().agentName),[_e,ve]=(0,l.useState)(v().agentHeadshot),[ye,be]=(0,l.useState)(()=>re(i?.siteId)),[xe,Se]=(0,l.useState)(!1),[Ce,we]=(0,l.useState)(!1),[Te,Ee]=(0,l.useState)(`idle`),[De,Oe]=(0,l.useState)(!1),[ke,Ae]=(0,l.useState)(!1),[je,Me]=(0,l.useState)(``),[Ne,b]=(0,l.useState)(!1),[Pe,Fe]=(0,l.useState)(!1),[x,Ie]=(0,l.useState)(null),[Le,Re]=(0,l.useState)(null),[ze,Be]=(0,l.useState)(`idle`),[Ve,He]=(0,l.useState)(null),[Ue,We]=(0,l.useState)(!1),[Ge,Ke]=(0,l.useState)(``),S=(0,l.useRef)(null),C=(0,l.useRef)(null),w=(0,l.useRef)(``),qe=(0,l.useRef)(null),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)([]),$e=(0,l.useRef)(null),et=(0,l.useRef)(null),tt=(0,l.useRef)(!1),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(``),it=(0,l.useRef)(he),at=(0,l.useRef)([]),ot=(0,l.useRef)(!1),st=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),ct=(0,l.useMemo)(()=>{let e=p?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:ee},[i,p]);(0,l.useEffect)(()=>{qe.current=x},[x]),(0,l.useEffect)(()=>{it.current=he},[he]);let lt=()=>{Ke(``)},ut=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return be(t),ie(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&be(re(e))},[i?.siteId]);let dt=()=>{Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),Ze.current=null,Qe.current=[],$e.current=null,et.current=null,tt.current=!1,We(!1),Ie(null),Re(null),Be(`idle`),He(null)},ft=(e=new Date().toISOString())=>{let t=S.current,n=$e.current||Ze.current?.callId;if(!t?.connected||!n||tt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:w.current,socketConnected:!!t?.connected,alreadyReported:tt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:w.current,connectedAt:e}),tt.current=!0,t.emit(`call:connected`,{callId:n,chatId:w.current,connectedAt:e})},pt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Ie(null),t||n){$e.current=e.callId,Re(e.callId),Be(e=>e===`connected`?e:`connecting`),ue(!0);return}Be(`idle`)}},mt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){dt();return}et.current=null,Ze.current=null,Qe.current=[],Ie(null),Be(`idle`)}},ht=async(e={})=>{let t=Je.current,n=S.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:w.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:w.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:w.current,queuedCount:Qe.current.length});for(let e of Qe.current)await t.addIceCandidate(new RTCIceCandidate(e));Qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:w.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:w.current})};(0,l.useEffect)(()=>{ne({isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e})},[le,de,pe,he,_e]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await se(t);if(!e)return;let o=te();w.current=o;let c=ce({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});C.current=c,g({...n,apiBaseUrl:t.apiBaseUrl}),ae(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Kt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});S.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),Ee(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),Ee(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:w.current}),we(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:w.current}),we(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:dn(t.message)};we(!1),Se(!1),y(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&y(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:dn(t.message)};we(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Se(!1),y(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(me(!0),fe(`agent`),ge(gn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ve(n.sender_headshot),ue(!0))}),l.on(`agent:joined`,e=>{let t=gn([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=gn([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,(e={})=>{let t=gn([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=gn([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{Fe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{y(fn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!1)}),l.on(`call:incoming`,(e={})=>{let t=gn([e.agentName,e.ownerName,e.agent?.name,he],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:w.current,agentName:t}),lt(),tt.current=!1,Ie({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ge(e=>gn([t,e],a)),Be(`incoming`),He(null),ue(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||w.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ze.current=e;try{await ht(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,hasPeerConnection:!!Je.current,hasCandidate:!!e.candidate});return}try{let t=mn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,candidate:hn(t),hasRemoteDescription:!!Je.current?.remoteDescription}),!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||w.current,queueSize:Qe.current.length+1}),Qe.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{lt(),dt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||w.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Ie(null),Be(`idle`));return}tt.current=!0,et.current=null,$e.current=e.callId,Re(e.callId),Ie(null),Be(`connected`),He(e.connectedAt||new Date().toISOString()),ue(!0)}),l.on(`call:unavailable`,(e={})=>{dt(),Ke(pn(e,`This visitor is not available for a call right now.`)),ue(!0)}),l.on(`call:error`,(e={})=>{dt(),Ke(pn(e,`We couldn't connect the call right now.`)),ue(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await cn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}un(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=nn(null,t);e&&rn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=nn(e||null,t||null);n&&rn(n)}),l.on(`visitor:clear_highlight`,()=>{an()}),st.current=qt({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(y(fn(u.chat_history||[])),me(!!u.is_human_handled),fe(u.is_human_handled?`agent`:de),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),f(t),s(`error`)}})(),()=>{e=!1,st.current?.cleanup?.(),dt(),S.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(Ne&&!ot.current&&at.current.length>0){let e=w.current,t=at.current,n=C.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),ot.current=!0)}},[Ne,p]),(0,l.useEffect)(()=>{if(!C.current||!_||o!==`ready`||pe)return;let e=window.setInterval(async()=>{try{let e=await C.current.checkHumanHandled(_);me(!!e.is_human_handled),e.is_human_handled&&(fe(`agent`),e.agent_info?.name&&ge(e.agent_info.name),e.agent_info?.headshot&&ve(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,o,pe]);let gt=async()=>{if(!(!x?.callId||!C.current||!S.current||!_)){lt(),et.current=x.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:x?.callId,chatId:_,socketConnected:!!S.current?.connected,hasPendingOffer:!!Ze.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:x.callId,chatId:_,trackCount:e.getTracks().length}),Ye.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Je.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:x.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}e===`connecting`&&Be(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:x.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}(e===`checking`||e===`new`)&&Be(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!S.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:x.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!S.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:x.callId,chatId:_,candidate:hn(e.candidate)}),S.current.emit(`call:ice-candidate`,{callId:x.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:x.callId,chatId:_,streamCount:e.streams?.length||0}),!Xe.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0]};let n=Ze.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||x.callId,chatId:_}),await ht({...n,callId:n.callId||x.callId})),await C.current.acceptCall(x.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:x.callId,chatId:_}),$e.current=x.callId,Re(x.callId),Be(`connecting`),Ie(null),ue(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),et.current=null,dt(),e?.status===404||e?.status===409||e?.status===422){Ke(pn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ke(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ke(`We couldn't connect the call right now. Please try again.`)}}},_t=async()=>{if(!x?.callId||!C.current||!_){dt();return}lt();try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ke(pn(e,`We couldn't decline the call cleanly.`))}finally{dt()}},vt=(0,l.useRef)(_t);vt.current=_t,(0,l.useEffect)(()=>{if(!x?.callId||Le)return;let e=x.callId,t=window.setTimeout(()=>{qe.current?.callId===e&&vt.current()},h);return()=>window.clearTimeout(t)},[x?.callId,Le]);let yt=async()=>{if(!Le||!C.current||!_){dt();return}lt();try{await C.current.endWebRTCCall(Le,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ke(pn(e,`The call ended locally, but the server could not be updated.`))}finally{dt()}},bt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ue;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),We(r)},xt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(ue(!0),!(!t||!C.current||!_||typeof window>`u`)){try{await C.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await C.current.updateChatStatus(_,`open`)}catch{}}},St=async e=>{let t=ut(e);if(!t||!C.current||!w.current)return t;try{await C.current.trackVisitor({chatId:w.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Ct=()=>{if(!_||!S.current?.connected||nt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!S.current?.connected,alreadyTyping:nt.current});return}nt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),S.current.emit(`typing:start`,{chatId:_,sender:`user`})},wt=()=>{if(!_||!S.current?.connected||!nt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!S.current?.connected,wasTyping:nt.current});return}nt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),S.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Tt=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!S.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!S.current?.connected,textLength:t.length});return}rt.current!==t&&(rt.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),S.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Et=async(e,t=``,n=null)=>{if(!e.trim()||!C.current||!_||o!==`ready`||Pe)return;wt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(y(e=>[...e,a]),pe&&S.current?.connected){S.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:ye||void 0,...n||{}});return}Oe(!0);try{let i=await C.current.sendAiMessage(_,e,r,t,{...n||{},...ye?{email:ye}:{}});y(fn(i.chat_history||[])),me(!!i.is_human_handled),fe(i.is_human_handled?`agent`:`ai`),we(!1),await C.current.updateChatStatus(_,`messageSent`)}catch(e){y(e=>e.filter(e=>e.id!==i)),we(!1),e.status===429?(Ae(!0),Me(e.message),window.setTimeout(()=>{Ae(!1),Me(``)},m)):f(e)}finally{Oe(!1)}},Dt=async e=>{if(!(!C.current||!_)){try{let t=e?`voice`:`text`;await C.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}b(e),e&&(ot.current=!1)}},Ot=async e=>{if(!ot.current){if(ot.current=!0,!C.current||!_||!e?.length){b(!1);return}try{let t=await C.current.syncVoice(_,e);if(t?.chat_history?.length)y(fn(t.chat_history));else if(t?.success)try{let e=await C.current.loadHistory(_,r);e?.chat_history?.length&&y(fn(e.chat_history))}catch{}}catch{}finally{b(!1)}}},kt=async()=>{if(!(!C.current||!_)){Ne&&!ot.current&&at.current.length>0&&await Ot(at.current);try{await C.current.endConversation(_)}catch{try{await C.current.updateChatStatus(_,`ended`)}catch{}}Fe(!0),y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,l.useEffect)(()=>{if(ze!==`connected`||!Le||!_||!Ve||!ct)return;let e=new Date(Ve).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,ct*1e3-t),r=window.setTimeout(()=>{Ke(`The call ended because it reached the time limit.`),yt()},n);return()=>window.clearTimeout(r)},[Le,Ve,ze,_,yt,ct]),(0,l.useEffect)(()=>{let e=()=>{let e=w.current,t=C.current;if(!t||!e)return;if($e.current){t.beaconEndWebRTCCall($e.current,e);return}let n=et.current||qe.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let T=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:p,resolvedConfig:i,chatId:_,chatHistory:oe,isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e,visitorEmail:ye,isAgentTyping:xe,isAiTyping:Ce,connectionStatus:Te,isLoading:De,isVoiceMode:Ne,isRateLimited:ke,rateLimitMessage:je,isConversationEnded:Pe,incomingCall:x,activeCallId:Le,callConnectionState:ze,callConnectedAt:Ve,isCallMuted:Ue,webRTCError:Ge,language:r,historyRef:at,hasSyncedRef:ot,dismissCallError:lt,captureVisitorEmail:St,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt,notifyRouteChange:()=>st.current?.notifyRouteChange?.(),openWidget:xt,closeWidget:()=>ue(!1),toggleWidget:()=>{if(le){ue(!1);return}xt({notifyChatInitiated:!0})},sendMessage:Et,setVoiceMode:Dt,onMessageSync:Ot,endConversation:kt,acceptCall:gt,rejectCall:_t,endWebRTCCall:yt,toggleCallMute:bt,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt}),[o,c,p,i,_,oe,le,de,pe,he,_e,ye,xe,Ce,Te,De,Ne,ke,je,Pe,x,Le,ze,Ve,Ue,Ge,r,St,Ct,wt,Tt,gt,_t,yt,bt,xt,Et,Dt,Ot,kt,lt]);return(0,u.jsx)(Jt.Provider,{value:T,children:n})}var vn=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),yn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),bn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),xn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Sn=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Cn=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),wn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Tn=({className:e=``})=>(0,u.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),En=({size:e=18,strokeWidth:t=2.5})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,u.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),Dn=({size:e=14})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 8V4H8`}),(0,u.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,u.jsx)(`path`,{d:`M2 14h2`}),(0,u.jsx)(`path`,{d:`M20 14h2`}),(0,u.jsx)(`path`,{d:`M15 13v2`}),(0,u.jsx)(`path`,{d:`M9 13v2`})]});function On({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,u.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,u.jsx)(`span`,{children:n}),a?(0,u.jsx)(vn,{color:`#fff`}):(0,u.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,u.jsx)(yn,{})})]})}function kn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function An({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,l.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,l.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,u.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,u.jsx)(`span`,{style:r,children:kn(t)})}function jn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Mn(e){let[t,n]=(0,l.useState)(`loading`),r=jn(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Nn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:d=`AI`,agentAvatarUrl:f=null,primaryColor:p=`#3B82F6`}){let{state:m,resolvedLogoUrl:ee}=Mn(e),h=i===`agent`,g=n||r||a?.fallbackAgentName||`Agent`;return(0,u.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[h?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:p,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,u.jsx)(An,{src:typeof f==`string`?f:``,name:g,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,u.jsxs)(u.Fragment,{children:[m!==`loading`&&(m===`error`||!ee&&!e?(0,u.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(e,{})}):m===`wide`?(0,u.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:ee.toLowerCase().includes(`.svg`)||ee.startsWith(`data:image/svg`)?0:`2px`}})})),m===`loading`&&(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,u.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,u.jsx)(Dn,{size:11}),(0,u.jsx)(`span`,{children:d})]})]}),(0,u.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,u.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(En,{})})})]})}var Pn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Fn=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function In(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Ln=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return In(t);let n=t.replace(/\r\n/g,`
9
9
  `).replace(/\n{3,}/g,`
10
10
 
11
11
  `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>Fn(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return In(n.map(e=>{let t=e.split(`
@@ -462,15 +462,15 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
462
462
  <path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
463
463
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
464
464
  filter="url(#${Q}-csh)"/>
465
- </svg>`,Gh=null,Kh=!1;function qh(){return(!Gh||!Gh.isConnected)&&(Gh=document.createElement(`div`),Gh.id=`${Q}-cursor`,Gh.innerHTML=Wh,document.body.appendChild(Gh),Kh=!1),Gh}async function Jh(e){if(typeof document>`u`||!e)return;Ah();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=qh();Kh||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await $h(360)}function Yh(e=!1){Gh&&(e?(Gh.classList.remove(`${Q}-cursor-visible`),Kh=!1):(Gh.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{Kh=!1},250)))}async function Xh(e){Gh&&(Gh.classList.add(`${Q}-cursor-click`),await $h(280),Gh.classList.remove(`${Q}-cursor-click`))}function Zh(e){if(!e||typeof document>`u`)return;Ah();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}async function Qh(e,t,n){if(!e||!t)return;if(!(t.length<=72&&!/^https?:\/\//i.test(t)&&!/^\d+$/.test(t))){n(e,t);return}let r={bubbles:!0,cancelable:!0,composed:!0};n(e,``),e.dispatchEvent(new Event(`input`,r));for(let i=1;i<=t.length;i++){n(e,t.slice(0,i));try{e.dispatchEvent(new InputEvent(`input`,{...r,inputType:`insertText`,data:t[i-1]}))}catch{e.dispatchEvent(new Event(`input`,r))}await $h(28+Math.random()*27)}e.dispatchEvent(new Event(`change`,r))}function $h(e){return new Promise(t=>setTimeout(t,e))}function eg(e){return(...t)=>{try{let n=e(...t);return n instanceof Promise?n.catch(()=>{}):n}catch{return}}}var tg=eg(Ph),ng=eg(Fh),rg=eg(zh),ig=eg(Bh),ag=eg(Hh),og=eg(Uh),sg=eg(Vh),cg=eg(Jh),lg=eg(Yh),ug=eg(Xh),dg=eg(Zh);function $(...e){Xt()&&console.log(`[FlowEngage:voice-tools]`,...e)}var fg=`#flowengage-root, .flowengage-shell`;function pg(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(fg)}catch{return!1}}function mg(e){if(!e)return null;try{return e.closest(`form`)}catch{let t=e.parentElement;for(;t;){if(t.tagName===`FORM`)return t;t=t.parentElement}return null}}function hg(e){if(!e)return null;let t=e.querySelector(`h1, h2, h3, h4, h5, legend`);if(t)return t.textContent.replace(/\s+/g,` `).trim().slice(0,60);let n=e.getAttribute(`aria-label`);if(n)return n.trim().slice(0,60);let r=e.getAttribute(`title`);if(r)return r.trim().slice(0,60);let i=e.previousElementSibling;for(let e=0;e<3&&i;e++){if(/^H[1-5]$/.test(i.tagName))return i.textContent.replace(/\s+/g,` `).trim().slice(0,60);i=i.previousElementSibling}return null}function gg(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function _g(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!pg(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function vg(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function yg(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return vg(r.join(` `))}if(e.labels&&e.labels.length)return vg(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return vg(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return vg(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return vg(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=vg(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return vg(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return vg(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?vg(o):null}function bg(){let e=[];return _g(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(pg(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=gg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}try{if(e.offsetWidth===0&&e.offsetHeight===0)return!1}catch{}return!0}))}),e}function xg(){let e=bg(),t=new Map,n=0;return e.map((e,r)=>{let i=mg(e),a=i||`__orphan__`;t.has(a)||t.set(a,n++);let o=t.get(a);return{formIndex:o,formName:(i?hg(i):null)||`Form ${o}`,fieldIndex:r,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:yg(e),placeholder:e.placeholder||null}})}function Sg(){let e=[];return _g(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(pg(e)||e.disabled)return!1;try{let t=gg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Cg(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function wg(e){let t=Cg(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Tg(e,t){let n=wg(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=(e.type||``).toLowerCase();if(a===`email`&&/email|e-mail|mail/.test(n))return 100;if(a===`tel`&&/phone|mobile|tel|cell/.test(n))return 95;if(a===`url`&&/url|website|domain|link/.test(n))return 100;let o=[e.name,e.id,e.placeholder,yg(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Cg(e)),s=0;for(let e of o){if(!e)continue;if(e===n){s=100;break}if(e.includes(n)||n.includes(e)){s=Math.max(s,96);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);let i=r/t.length;i>0&&(s=Math.max(s,i*88))}return s}var Eg=22;function Dg(e,t){let n=null,r=0;for(let i of e){let e=Tg(i,t);e>r&&(r=e,n=i)}return!n||r<Eg?null:n}function Og(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,yg(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function kg(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Ag(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function jg(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function Mg(e){if(!jg(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,yg(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function Ng(e,t,n){let r=String(t??``),i=String(n??``),a=Ig(e,r)||Dg(e,r)||Og(e,r,i);if(!a)return[];let o=new Set([a]);if(kg(i)&&Ag(r))for(let t of e)t!==a&&Mg(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function Pg(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function Fg(e){if(!e||typeof e!=`string`)return null;let t=null;return _g(n=>{try{let r=n.getElementById(e);r&&!pg(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function Ig(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=Fg(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Fg(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function Lg(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r===n)return 100;if(r.includes(n))return 98;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function Rg(e,t){let n=[];_g(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(pg(e)||e.disabled)return!1;try{let t=gg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:Lg(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=Pg(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function zg(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Bg(e){let t=zg(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function Vg(e){if(!e||typeof e!=`string`)return e;let t=e.trim();return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?t:(t=t.replace(/\s+at\s+the\s+rate\s*(of)?\s+/gi,`@`),t=t.replace(/\s+at\s+/gi,`@`),t=t.replace(/\s+dot\s+/gi,`.`),t=t.replace(/\s+/g,``),t=t.replace(/\.{2,}/g,`.`).replace(/\.$/,``),t)}function Hg(e){if(!e||typeof e!=`string`)return e;let t={zero:`0`,one:`1`,two:`2`,three:`3`,four:`4`,five:`5`,six:`6`,seven:`7`,eight:`8`,nine:`9`,oh:`0`,o:`0`},n=e.toLowerCase().trim();for(let[e,r]of Object.entries(t))n=n.replace(RegExp(`\\b${e}\\b`,`g`),r);return n=n.replace(/[^\d+]/g,``),n}function Ug(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function Wg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=Vg(t),s=i.test(o),c=o.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(c)return a(`Email Address`,c[1]),n;if(!i.test(t)&&s){let e=o.match(i);if(e)return a(`Email Address`,e[1]),n}let l=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),l&&a(`Full Name`,l[1]),l=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),l){let e=l[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(l=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),l){let e=l[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function Gg(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function Kg(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function qg(e){let t=e.ownerDocument?.defaultView||window,n=e.tagName===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`);return(e,t)=>{try{e._valueTracker&&e._valueTracker.setValue(``)}catch{}r?.set?r.set.call(e,t):e.value=t}}async function Jg(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{await cg(e)}catch{}try{ag(e)}catch{}await new Promise(e=>setTimeout(e,180));try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase(),a={bubbles:!0,cancelable:!0,composed:!0};if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a)),og(e),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),og(e),!0;let o=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=qg(e);try{await Qh(e,o,t)}catch{t(e,o)}e.value!==o&&t(e,o)}else e.value=o;try{e.dispatchEvent(new InputEvent(`input`,{...a,inputType:`insertText`,data:o}))}catch{e.dispatchEvent(new Event(`input`,a))}e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a));try{e.focus({preventScroll:!0})}catch{}try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a))}catch{}})}catch{}return og(e),!0}function Yg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a=null,o={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let r=zg(n),i=Gg(r),a=r.section_text??r.sectionText??r.section;if($(`navigate_to_page · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}if(tg(`Navigating to ${i.replace(/^https?:\/\/[^/]+/,``)||`/`}…`),rg(),!await cn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){ig(),ng(200);let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,i),await un(i,{sectionText:a||void 0}),await new Promise(e=>setTimeout(e,600)),ig(),ng(300),a&&typeof a==`string`){let e=nn(null,a);e&&rn(e),$(`navigate_to_page · highlight`,{sectionText:a,found:!!e})}let e=``;try{let t=xg(),n=Sg();if(t.length>0){let r=t.map(e=>e.label||e.placeholder||e.name||e.id).filter(Boolean).join(`, `),i=n.map(e=>e.text).filter(Boolean).join(`, `);e=` This page has a form with fields: [${r}]`+(i?` and buttons: [${i}].`:`.`)+` Call list_page_forms then start filling.`}}catch{}let t=`OK_NAVIGATION ${i}${e}`;return $(`navigate_to_page ✓`,t),t}catch(e){ig(),ng(200);let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=zg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=nn(n||null,r||null);return i?(rn(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=Kg(zg(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),tg(`Searching site content…`,{spinner:!0}),!r)return ng(),$(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return ng(),$(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return ng(),$(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),ng(200),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){ng();let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},end_voice_session:async()=>($(`end_voice_session ▶`),tg(`Ending voice session…`,{icon:`👋`,spinner:!1,duration:2e3}),lg(!0),sg(),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),list_page_forms:async()=>{let e=xg(),t=Sg();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),a=null,JSON.stringify({fields:e,buttons:t,hint:`Fields are grouped by formIndex/formName. Work with ONE form at a time — only fill fields from the same formIndex. Do not jump to fields in a different form. field_key: use placeholder, label, name, or id from this list. click_page_button picks the button nearest the filled fields.`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=Bg(e);if(!t.length&&r){let e=r(),n=Ug(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=Wg(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;t.length>1&&tg(`Filling ${t.length} fields…`);let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let o=String(t).toLowerCase();/email|e-mail|mail/.test(o)?r=Vg(r):/phone|mobile|tel|cell/.test(o)&&(r=Hg(r)),tg(`Filling ${t}…`),$(`fill_form_fields · processing field:`,t,`=`,r);let s=bg(),c=s;if(a){let e=s.filter(e=>mg(e)===a);e.length>0&&(c=e,$(`fill_form_fields · scoped to active form, inputs:`,e.length))}$(`fill_form_fields · visible inputs count:`,s.length,`scoped:`,c.length);let l=!1;for(let e of[c,...c===s?[]:[s]]){let o=Ng(e,String(t),r);if(o.length){for(let e=0;e<o.length;e++)await Jg(o[e],r,{skipScroll:e>0}),await new Promise(e=>setTimeout(e,80));i=o,a=mg(o[0])||a,n.push(String(t)),l=!0;break}let s=Ig(e,String(t));if(s||=Dg(e,String(t)),s||=Og(e,String(t),r),s){await Jg(s,r),i=[s],a=mg(s)||a,n.push(String(t)),l=!0;break}}l||$(`fill_form_fields · no match for field:`,t)}ng(400);try{lg()}catch{}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let o=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,o),o}catch(e){ng(),sg(),lg(!0);let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=zg(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;tg(`Clicking "${n}"…`);let r=Rg(n,i);if(!r)return ng(200),$(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}try{await cg(r)}catch{}try{dg(r)}catch{}try{await ug(r)}catch{}let e=mg(r)||a,t=[];if(e){let n=Array.from(e.querySelectorAll(`input[required], textarea[required], select[required]`)).filter(e=>!pg(e));for(let e of n)if(!(e.value||``).trim()){let n=yg(e)||e.placeholder||e.name||e.type;t.push(n)}}if(t.length>0){ng(200);try{lg()}catch{}let e=`Cannot submit — these required fields are still empty: ${t.join(`, `)}. Fill them first with fill_form_fields, then click again.`;return $(`click_page_button ✖ empty required fields:`,t),e}r.focus?.(),r.click();let n=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`;ng(600);try{lg()}catch{}sg(),a=null,i=[];let o=`OK_CLICK ${n}`;return $(`click_page_button ✓`,o),o}catch(e){ng(200),lg(!0);let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...o,navigateToPage:o.navigate_to_page,highlightOnPage:o.highlight_on_page,searchSiteContent:o.search_site_content,endVoiceSession:o.end_voice_session,listPageForms:o.list_page_forms,fillFormFields:o.fill_form_fields,clickPageButton:o.click_page_button}}function Xg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Xt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var Zg={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},Qg={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function $g(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function e_({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[d,f]=(0,l.useState)(`idle`),[p,m]=(0,l.useState)(null),[ee,h]=(0,l.useState)(!1),g=(0,l.useRef)(null),_=(0,l.useRef)(null),te=(0,l.useRef)(``),v=(0,l.useRef)(async()=>{}),ne=(0,l.useRef)(!1),re=(0,l.useCallback)(async()=>{try{await g.current?.endSession?.()}catch{}g.current=null,h(!1),f(`idle`),ne.current=!1,typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]);v.current=re,(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;a.current=[],te.current=``,ne.current=!1;let o=Xg(Yg({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>te.current,requestEndSession:()=>{queueMicrotask(()=>{ne.current||(ne.current=!0,v.current?.())})}})),s=await kh.startSession({agentId:e,clientTools:o,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||f(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};n===`user`&&(te.current=r),a.current=[...a.current,i],$g(n,r)&&queueMicrotask(()=>{ne.current||(ne.current=!0,v.current?.())})},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),m(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),h(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,g.current=s,h(!0),f(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: when the user wants to go to any page (contact, pricing, about, services, etc.), call search_site_content then navigate_to_page immediately — never ask permission. After navigating to a page with a form, call list_page_forms and proactively start helping the user fill it. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit, Send Message) when the user wants to submit. Fill each field immediately after the user answers — never skip ahead. Voice: if the user wants to end the voice session, call end_voice_session or confirm and end.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),f(`error`),m(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):g.current&&g.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let ie=d===`listening`||d===`speaking`,ae=Qg[d]||Qg.idle,oe=Zg[d]||Zg.idle;return(0,u.jsxs)(`div`,{ref:_,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ie&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${ae}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ie&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${ae}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:oe,border:`3px solid ${ae}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${oe}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(bn,{size:44,color:ae})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:d===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[d===`idle`&&`Starting voice session…`,d===`listening`&&`Listening…`,d===`speaking`&&`AI is speaking…`,d===`error`&&(p||`Error`)]}),(0,u.jsxs)(`button`,{onClick:re,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(xn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
465
+ </svg>`,Gh=null,Kh=!1;function qh(){return(!Gh||!Gh.isConnected)&&(Gh=document.createElement(`div`),Gh.id=`${Q}-cursor`,Gh.innerHTML=Wh,document.body.appendChild(Gh),Kh=!1),Gh}async function Jh(e){if(typeof document>`u`||!e)return;Ah();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=qh();Kh||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await $h(360)}function Yh(e=!1){Gh&&(e?(Gh.classList.remove(`${Q}-cursor-visible`),Kh=!1):(Gh.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{Kh=!1},250)))}async function Xh(e){Gh&&(Gh.classList.add(`${Q}-cursor-click`),await $h(280),Gh.classList.remove(`${Q}-cursor-click`))}function Zh(e){if(!e||typeof document>`u`)return;Ah();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}async function Qh(e,t,n){if(!e||!t)return;if(!(t.length<=72&&!/^https?:\/\//i.test(t)&&!/^\d+$/.test(t))){n(e,t);return}let r={bubbles:!0,cancelable:!0,composed:!0};n(e,``),e.dispatchEvent(new Event(`input`,r));for(let i=1;i<=t.length;i++){n(e,t.slice(0,i));try{e.dispatchEvent(new InputEvent(`input`,{...r,inputType:`insertText`,data:t[i-1]}))}catch{e.dispatchEvent(new Event(`input`,r))}await $h(28+Math.random()*27)}e.dispatchEvent(new Event(`change`,r))}function $h(e){return new Promise(t=>setTimeout(t,e))}function eg(e){return(...t)=>{try{let n=e(...t);return n instanceof Promise?n.catch(()=>{}):n}catch{return}}}var tg=eg(Ph),ng=eg(Fh),rg=eg(zh),ig=eg(Bh),ag=eg(Hh),og=eg(Uh),sg=eg(Vh),cg=eg(Jh),lg=eg(Yh),ug=eg(Xh),dg=eg(Zh);function $(...e){Xt()&&console.log(`[FlowEngage:voice-tools]`,...e)}var fg=`#flowengage-root, .flowengage-shell`;function pg(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(fg)}catch{return!1}}function mg(e){if(!e)return null;try{return e.closest(`form`)}catch{let t=e.parentElement;for(;t;){if(t.tagName===`FORM`)return t;t=t.parentElement}return null}}function hg(e){if(!e)return null;let t=e.querySelector(`h1, h2, h3, h4, h5, legend`);if(t)return t.textContent.replace(/\s+/g,` `).trim().slice(0,60);let n=e.getAttribute(`aria-label`);if(n)return n.trim().slice(0,60);let r=e.getAttribute(`title`);if(r)return r.trim().slice(0,60);let i=e.previousElementSibling;for(let e=0;e<3&&i;e++){if(/^H[1-5]$/.test(i.tagName))return i.textContent.replace(/\s+/g,` `).trim().slice(0,60);i=i.previousElementSibling}return null}function gg(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function _g(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!pg(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function vg(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function yg(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return vg(r.join(` `))}if(e.labels&&e.labels.length)return vg(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return vg(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return vg(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return vg(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=vg(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return vg(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return vg(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?vg(o):null}function bg(){let e=[];return _g(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(pg(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=gg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}try{if(e.offsetWidth===0&&e.offsetHeight===0)return!1}catch{}return!0}))}),e}function xg(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`footer, [role="contentinfo"], #footer, .site-footer, [class*="footer"], [id*="footer"]`)}catch{return!1}}function Sg(){let e=bg();for(let t of e){if((t.type||``).toLowerCase()!==`email`||xg(t))continue;let e=mg(t);if(e)return e}return null}function Cg(){let e=bg(),t=new Map,n=0;return e.map((e,r)=>{let i=mg(e),a=i||`__orphan__`;t.has(a)||t.set(a,n++);let o=t.get(a);return{formIndex:o,formName:(i?hg(i):null)||`Form ${o}`,fieldIndex:r,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:yg(e),placeholder:e.placeholder||null}})}function wg(){let e=[];return _g(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(pg(e)||e.disabled)return!1;try{let t=gg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Tg(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Eg(e){let t=Tg(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Dg(e,t){let n=Eg(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|audit|conduct|site(\s|$)|page(\s|$)/.test(n)&&!/email|e-mail|mail|name|message|phone/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|audit|conduct/.test(n)&&!/email|e-mail|mail|name|message|phone/.test(n))return 100;let a=(e.type||``).toLowerCase();if(a===`email`&&/email|e-mail|mail/.test(n))return 100;if(a===`tel`&&/phone|mobile|tel|cell/.test(n))return 95;if(a===`url`&&/url|website|domain|link/.test(n))return 100;let o=[e.name,e.id,e.placeholder,yg(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Tg(e)),s=0;for(let e of o){if(!e)continue;if(e===n){s=100;break}if(e.includes(n)||n.includes(e)){s=Math.max(s,96);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);let i=r/t.length;i>0&&(s=Math.max(s,i*88))}return s}var Og=22;function kg(e,t){let n=null,r=0;for(let i of e){let e=Dg(i,t);e>r&&(r=e,n=i)}return!n||r<Og?null:n}function Ag(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i)||!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,yg(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function jg(e){let t=String(e??``).trim();return!t||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?!1:/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t)}function Mg(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function Ng(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function Pg(e){if(!Ng(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,yg(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function Fg(e,t,n){let r=String(t??``),i=String(n??``),a=Rg(e,r)||kg(e,r)||Ag(e,r,i);if(!a)return[];let o=new Set([a]);if(jg(i)&&Mg(r))for(let t of e)t!==a&&Pg(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function Ig(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function Lg(e){if(!e||typeof e!=`string`)return null;let t=null;return _g(n=>{try{let r=n.getElementById(e);r&&!pg(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function Rg(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=Lg(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Lg(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function zg(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r===n)return 100;if(r.includes(n))return 98;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function Bg(e,t){let n=[];_g(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(pg(e)||e.disabled)return!1;try{let t=gg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:zg(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=Ig(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function Vg(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Hg(e){let t=Vg(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function Ug(e){if(!e||typeof e!=`string`)return e;let t=e.trim();return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?t:(t=t.replace(/\s+at\s+the\s+rate\s*(of)?\s+/gi,`@`),t=t.replace(/\s+at\s+/gi,`@`),t=t.replace(/\s+dot\s+/gi,`.`),t=t.replace(/\s+/g,``),t=t.replace(/\.{2,}/g,`.`).replace(/\.$/,``),t)}function Wg(e){if(!e||typeof e!=`string`)return e;let t={zero:`0`,one:`1`,two:`2`,three:`3`,four:`4`,five:`5`,six:`6`,seven:`7`,eight:`8`,nine:`9`,oh:`0`,o:`0`},n=e.toLowerCase().trim();for(let[e,r]of Object.entries(t))n=n.replace(RegExp(`\\b${e}\\b`,`g`),r);return n=n.replace(/[^\d+]/g,``),n}function Gg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function Kg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=Ug(t),s=i.test(o),c=o.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(c)return a(`Email Address`,c[1]),n;if(!i.test(t)&&s){let e=o.match(i);if(e)return a(`Email Address`,e[1]),n}let l=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),l&&a(`Full Name`,l[1]),l=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),l){let e=l[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(l=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),l){let e=l[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function qg(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function Jg(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords??e.search_query??e.searchQuery??e.question??e.prompt??e.topic??e.intent;return t==null?null:String(t).trim()||null}function Yg(e){let t=e.ownerDocument?.defaultView||window,n=e.tagName===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`);return(e,t)=>{try{e._valueTracker&&e._valueTracker.setValue(``)}catch{}r?.set?r.set.call(e,t):e.value=t}}async function Xg(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{await cg(e)}catch{}try{ag(e)}catch{}await new Promise(e=>setTimeout(e,180));try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase(),a={bubbles:!0,cancelable:!0,composed:!0};if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a)),og(e),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),og(e),!0;let o=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=Yg(e);try{await Qh(e,o,t)}catch{t(e,o)}e.value!==o&&t(e,o)}else e.value=o;try{e.dispatchEvent(new InputEvent(`input`,{...a,inputType:`insertText`,data:o}))}catch{e.dispatchEvent(new Event(`input`,a))}e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a));try{e.focus({preventScroll:!0})}catch{}try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a))}catch{}})}catch{}return og(e),!0}function Zg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a=null,o={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let r=Vg(n),i=qg(r),a=r.section_text??r.sectionText??r.section;if($(`navigate_to_page · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}let o=typeof window<`u`?on(i):i;if(tg(`Navigating to ${String(o).replace(/^https?:\/\/[^/]+/,``)||`/`}…`),rg(),!await cn(o,{siteId:t,apiBaseUrl:e.apiBaseUrl})){ig(),ng(200);let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,o),await un(o,{sectionText:a||void 0}),await new Promise(e=>setTimeout(e,600)),ig(),ng(300),a&&typeof a==`string`){let e=nn(null,a);e&&rn(e),$(`navigate_to_page · highlight`,{sectionText:a,found:!!e})}let e=``;try{let t=Cg(),n=wg();if(t.length>0){let r=t.map(e=>e.label||e.placeholder||e.name||e.id).filter(Boolean).join(`, `),i=n.map(e=>e.text).filter(Boolean).join(`, `);e=` This page has a form with fields: [${r}]`+(i?` and buttons: [${i}].`:`.`)+` Call list_page_forms then start filling.`}}catch{}let t=`OK_NAVIGATION ${o}${e}`;return $(`navigate_to_page ✓`,t),t}catch(e){ig(),ng(200);let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=Vg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=nn(n||null,r||null);return i?(rn(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=Jg(Vg(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),tg(`Searching site content…`,{spinner:!0}),!r)return ng(),$(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return ng(),$(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return ng(),$(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),ng(200),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){ng();let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},end_voice_session:async()=>($(`end_voice_session ▶`),tg(`Ending voice session…`,{icon:`👋`,spinner:!1,duration:2e3}),lg(!0),sg(),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),list_page_forms:async()=>{let e=Cg(),t=wg();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),a=Sg(),$(`list_page_forms · activeFormAncestor`,a?`contact-preferring`:`none`),JSON.stringify({fields:e,buttons:t,hint:`Fields are grouped by formIndex/formName. Work with ONE form at a time — only fill fields from the same formIndex. Do not jump to fields in a different form. On pages with a contact form AND a footer 'Conduct Audit' / website URL field: only use the contact form unless the visitor explicitly asks to run an audit. Contact forms: fill in order Full Name → Email Address → Message. Message must be a short note the visitor wants to send (one or two sentences), never a recap of the whole chat or assistant replies. field_key: use placeholder, label, name, or id from this list. click_page_button picks the button nearest the filled fields (e.g. Send Message on the same form).`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=Hg(e);if(!t.length&&r){let e=r(),n=Gg(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=Kg(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;t.length>1&&tg(`Filling ${t.length} fields…`);let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let o=String(t).toLowerCase();if(/email|e-mail|mail/.test(o))r=Ug(r);else if(/phone|mobile|tel|cell/.test(o))r=Wg(r);else if(Mg(t)||o===`url`){let e=String(r??``).trim();if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)||/\bat\b/i.test(e)&&/\bdot\b/i.test(e)){let n=Ug(e);/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n.trim())&&($(`fill_form_fields · remapping url/website intent to Email Address (value is an email)`),t=`Email Address`,o=`email address`,r=n.trim())}}tg(`Filling ${t}…`),$(`fill_form_fields · processing field:`,t,`=`,r);let s=bg(),c=s;if(a){let e=s.filter(e=>mg(e)===a);e.length>0&&(c=e,$(`fill_form_fields · scoped to active form, inputs:`,e.length))}$(`fill_form_fields · visible inputs count:`,s.length,`scoped:`,c.length);let l=!1;for(let e of[c,...c===s?[]:[s]]){let o=Fg(e,String(t),r);if(o.length){for(let e=0;e<o.length;e++)await Xg(o[e],r,{skipScroll:e>0}),await new Promise(e=>setTimeout(e,80));i=o,a=mg(o[0])||a,n.push(String(t)),l=!0;break}let s=Rg(e,String(t));if(s||=kg(e,String(t)),s||=Ag(e,String(t),r),s){await Xg(s,r),i=[s],a=mg(s)||a,n.push(String(t)),l=!0;break}}l||$(`fill_form_fields · no match for field:`,t)}ng(400);try{lg()}catch{}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let o=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,o),o}catch(e){ng(),sg(),lg(!0);let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=Vg(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;tg(`Clicking "${n}"…`);let r=Bg(n,i);if(!r)return ng(200),$(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}try{await cg(r)}catch{}try{dg(r)}catch{}try{await ug(r)}catch{}let e=mg(r)||a,t=[];if(e){let n=Array.from(e.querySelectorAll(`input[required], textarea[required], select[required]`)).filter(e=>!pg(e));for(let e of n)if(!(e.value||``).trim()){let n=yg(e)||e.placeholder||e.name||e.type;t.push(n)}}if(t.length>0){ng(200);try{lg()}catch{}let e=`Cannot submit — these required fields are still empty: ${t.join(`, `)}. Fill them first with fill_form_fields, then click again.`;return $(`click_page_button ✖ empty required fields:`,t),e}r.focus?.(),r.click();let n=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`;ng(600);try{lg()}catch{}sg(),a=null,i=[];let o=`OK_CLICK ${n}`;return $(`click_page_button ✓`,o),o}catch(e){ng(200),lg(!0);let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...o,navigateToPage:o.navigate_to_page,highlightOnPage:o.highlight_on_page,searchSiteContent:o.search_site_content,endVoiceSession:o.end_voice_session,listPageForms:o.list_page_forms,fillFormFields:o.fill_form_fields,clickPageButton:o.click_page_button}}function Qg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Xt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var $g={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},e_={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function t_(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function n_({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[d,f]=(0,l.useState)(`idle`),[p,m]=(0,l.useState)(null),[ee,h]=(0,l.useState)(!1),g=(0,l.useRef)(null),_=(0,l.useRef)(null),te=(0,l.useRef)(``),v=(0,l.useRef)(async()=>{}),ne=(0,l.useRef)(!1),re=(0,l.useCallback)(async()=>{try{await g.current?.endSession?.()}catch{}g.current=null,h(!1),f(`idle`),ne.current=!1,typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]);v.current=re,(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;a.current=[],te.current=``,ne.current=!1;let o=Qg(Zg({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>te.current,requestEndSession:()=>{queueMicrotask(()=>{ne.current||(ne.current=!0,v.current?.())})}})),s=await kh.startSession({agentId:e,clientTools:o,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||f(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};n===`user`&&(te.current=r),a.current=[...a.current,i],t_(n,r)&&queueMicrotask(()=>{ne.current||(ne.current=!0,v.current?.())})},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),m(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),h(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,g.current=s,h(!0),f(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: when the user wants to go to any page (contact, pricing, about, services, etc.), call search_site_content then navigate_to_page immediately — never ask permission. After navigating to a page with a form, call list_page_forms and proactively start helping the user fill it. Contact / lead forms: use only the main contact form (Full Name, Email, Message). Ignore footer “Conduct Audit” or marketing URL fields unless the user explicitly asks to run a website audit. Fill in order: name → email → message. Message must be a short visitor note (what they want from the team), not a transcript of the conversation. Forms: use fill_form_fields then click_page_button (e.g. Send Message) when appropriate. Fill each field right after the user gives that value — do not click submit until required fields are filled. Voice: if the user wants to end the voice session, call end_voice_session or confirm and end.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),f(`error`),m(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):g.current&&g.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let ie=d===`listening`||d===`speaking`,ae=e_[d]||e_.idle,oe=$g[d]||$g.idle;return(0,u.jsxs)(`div`,{ref:_,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ie&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${ae}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ie&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${ae}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:oe,border:`3px solid ${ae}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${oe}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(bn,{size:44,color:ae})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:d===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[d===`idle`&&`Starting voice session…`,d===`listening`&&`Listening…`,d===`speaking`&&`AI is speaking…`,d===`error`&&(p||`Error`)]}),(0,u.jsxs)(`button`,{onClick:re,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(xn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
466
466
  @keyframes fe-orb-pulse {
467
467
  0% { transform: scale(1); opacity: 0.6; }
468
468
  50% { transform: scale(1.18); opacity: 0.15; }
469
469
  100% { transform: scale(1); opacity: 0.6; }
470
470
  }
471
- `})]})}var t_=[{key:`become_client`,label:`Become a Client`},{key:`sales_enquiry`,label:`Sales Enquiry`},{key:`learn_services`,label:`Learn about our Services`},{key:`get_support`,label:`Get Support`},{key:`looking_for_job`,label:`Looking for a Job`}],n_=()=>(0,u.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[[0,1,2].map(e=>(0,u.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e)),(0,u.jsx)(`style`,{children:`
471
+ `})]})}var r_=[{key:`become_client`,label:`Become a Client`},{key:`sales_enquiry`,label:`Sales Enquiry`},{key:`learn_services`,label:`Learn about our Services`},{key:`get_support`,label:`Get Support`},{key:`looking_for_job`,label:`Looking for a Job`}],i_=()=>(0,u.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[[0,1,2].map(e=>(0,u.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e)),(0,u.jsx)(`style`,{children:`
472
472
  @keyframes fe-dot-bounce {
473
473
  0%, 80%, 100% { transform: translateY(0); opacity: 0.5; }
474
474
  40% { transform: translateY(-5px); opacity: 1; }
475
475
  }
476
- `})]})});function r_(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,agentHeadshot:d,visitorEmail:f,isAgentTyping:p,isAiTyping:m,isLoading:ee,isVoiceMode:h,isRateLimited:g,rateLimitMessage:_,isConversationEnded:te,incomingCall:v,activeCallId:ne,callConnectionState:re,callConnectedAt:ie,isCallMuted:ae,webRTCError:oe,language:se,historyRef:ce,onMessageSync:y,endConversation:le,acceptCall:ue,rejectCall:de,endWebRTCCall:fe,toggleCallMute:pe,dismissCallError:me,captureVisitorEmail:he,openWidget:ge,closeWidget:_e,sendMessage:ve,setVoiceMode:ye,startTyping:be,stopTyping:xe,updateTypingDraft:Se}=Yt(),[Ce,we]=(0,l.useState)(``),[Te,Ee]=(0,l.useState)(null),[De,Oe]=(0,l.useState)(null),[ke,Ae]=(0,l.useState)(null),[je,Me]=(0,l.useState)(0),[Ne,b]=(0,l.useState)(f||``),[Pe,Fe]=(0,l.useState)(``);(0,l.useEffect)(()=>{try{en()}catch{}},[]);let x=t?.widgetSettings||{},Ie=n?.widgetSettings||{},Le={...Ie.branding||{},...x.branding||{}},Re={...Ie.theme||{},...x.theme||{}},ze=Re.primaryColor||`#3B82F6`,Be=Re.accentColor||`#1D4ED8`,Ve=(Re.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},He={"--flowengage-primary":ze,"--flowengage-accent":Be,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Ve},Ue=x.recommendations?.[se]||Ie.recommendations?.[se]||t_,We=x.greetings?.[se]||Ie.greetings?.[se],Ge=Le.chatButtonText||`Chat with us`,Ke=Le.headerName||t?.websiteName||`OpenSense Labs`,S=Le.logoUrl||null,C=Le.hideWatermark||!1,w=Ie.elevenLabsAgentId||t?.elevenLabsAgentId||null,qe=t?.siteId||n?.siteId||null,Je=t?.apiBaseUrl||``,Ye=Le.fallbackAgentName||`Agent`,Xe=Le.botLabel||`AI`,Ze=d&&String(d).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Qe=v?.agentName||c||Ye,$e=i.some(e=>e.sender===`user`),et=(0,l.useMemo)(()=>{let e=i.findIndex(e=>e.sender===`user`);return e===-1?!1:i.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[i]),tt=!f&&$e&&et;(0,l.useEffect)(()=>{b(f||``),f&&Fe(``)},[f]),(0,l.useEffect)(()=>{if(!ie||re!==`connected`){Me(0);return}let e=()=>{let e=new Date(ie).getTime();isNaN(e)||Me(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[ie,re]),(0,l.useEffect)(()=>{if(!s||h||te){Se(``),xe();return}if(!Ce.trim()){Se(``),xe();return}be();let e=window.setTimeout(()=>{Se(Ce)},120),t=window.setTimeout(()=>{xe()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Ce,s,h,te,be,xe,Se]);let nt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,rt=async e=>{if(e.preventDefault(),te)return;if(tt){let e=Ne.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Fe(`Please enter a valid email so we can continue helping you.`);return}await he(e),Fe(``);return}if(!Ce.trim())return;let t=Ce.trim(),n=nt(ke);we(``),Ae(null),await ve(t,``,n)},it=async()=>{if(tt){Fe(`Please share your email before starting a call.`);return}if(h){ye(!1);return}Oe(null);try{Ee(await navigator.mediaDevices.getUserMedia({audio:!0})),ye(!0)}catch(e){Oe(e.message||`Could not access microphone.`)}},at=()=>{Te&&(Te.getTracks().forEach(e=>e.stop()),Ee(null)),ye(!1)},ot=e=>{let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`};return e===`ready`?(0,u.jsxs)(`div`,{className:`flowengage-shell`,"data-open":a?`true`:`false`,style:He,children:[(0,u.jsx)(On,{isOpen:a,openWidget:ge,launcherText:Ge,primaryColor:ze,posInline:Ve}),a&&(0,u.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!h?`linear-gradient(to bottom, ${ze} 0%, ${ze} 70%, white 85%)`:`white`},children:[(0,u.jsx)(Nn,{logoUrl:S,brandName:Ke,agentName:c,fallbackAgentName:Ye,activeScreen:o,branding:Le,isConversationEnded:te,endConversation:le,closeWidget:_e,isInitial:i.length===0&&!h,botLabel:Xe,agentAvatarUrl:o===`agent`?Ze:null,primaryColor:ze}),(0,u.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:h?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(e_,{agentId:w,chatId:r,siteId:qe,apiBaseUrl:Je,historyRef:ce,onMessageSync:y,onEnd:at})},`voice`):i.length===0?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Vn,{greetings:We,recommendations:Ue,onSendMessage:ve})},`welcome`):(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Rn,{chatHistory:i,isAiTyping:m,isAgentTyping:p,setReplyContext:Ae,TypingDots:n_,primaryColor:ze,agentHeadshot:Ze,agentDisplayName:c||Ye})},`history`)}),(0,u.jsx)(Gn,{webRTCError:oe,micError:De,setMicError:Oe,dismissCallError:me,incomingCall:v,rejectCall:de,acceptCall:ue,activeCallId:ne,callConnectionState:re,formatCallDuration:ot,callDurationSeconds:je,endWebRTCCall:fe,isCallMuted:ae,toggleCallMute:pe,isAIVoiceActive:h,currentCallAgentName:Qe,isRateLimited:g,rateLimitMessage:_}),!h&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,u.jsx)(Hn,{input:Ce,setInput:we,onSubmit:rt,isConversationEnded:te,callUiActive:!!(v||ne),handleToggleVoice:it,activeScreen:o,inputDisabled:ee||g||te,replyContext:ke,clearReplyContext:()=>Ae(null),requiresEmail:tt,emailInput:Ne,setEmailInput:b,emailError:Pe})}),!C&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`12px`,paddingTop:`12px`,paddingBottom:`16px`,fontSize:`12px`,color:`#9ca3af`},children:(0,u.jsxs)(`div`,{children:[`Powered by `,(0,u.jsx)(`span`,{style:{color:`#3b82f6`},children:`Flow`}),(0,u.jsx)(`span`,{style:{color:`#ef4444`},children:`Engage`})]})})]})]}):null}exports.FlowEngageProvider=_n,exports.FlowEngageWidget=r_,exports.useFlowEngage=Yt;
476
+ `})]})});function a_(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,agentHeadshot:d,visitorEmail:f,isAgentTyping:p,isAiTyping:m,isLoading:ee,isVoiceMode:h,isRateLimited:g,rateLimitMessage:_,isConversationEnded:te,incomingCall:v,activeCallId:ne,callConnectionState:re,callConnectedAt:ie,isCallMuted:ae,webRTCError:oe,language:se,historyRef:ce,onMessageSync:y,endConversation:le,acceptCall:ue,rejectCall:de,endWebRTCCall:fe,toggleCallMute:pe,dismissCallError:me,captureVisitorEmail:he,openWidget:ge,closeWidget:_e,sendMessage:ve,setVoiceMode:ye,startTyping:be,stopTyping:xe,updateTypingDraft:Se}=Yt(),[Ce,we]=(0,l.useState)(``),[Te,Ee]=(0,l.useState)(null),[De,Oe]=(0,l.useState)(null),[ke,Ae]=(0,l.useState)(null),[je,Me]=(0,l.useState)(0),[Ne,b]=(0,l.useState)(f||``),[Pe,Fe]=(0,l.useState)(``);(0,l.useEffect)(()=>{try{en()}catch{}},[]);let x=t?.widgetSettings||{},Ie=n?.widgetSettings||{},Le={...Ie.branding||{},...x.branding||{}},Re={...Ie.theme||{},...x.theme||{}},ze=Re.primaryColor||`#3B82F6`,Be=Re.accentColor||`#1D4ED8`,Ve=(Re.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},He={"--flowengage-primary":ze,"--flowengage-accent":Be,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Ve},Ue=x.recommendations?.[se]||Ie.recommendations?.[se]||r_,We=x.greetings?.[se]||Ie.greetings?.[se],Ge=Le.chatButtonText||`Chat with us`,Ke=Le.headerName||t?.websiteName||`OpenSense Labs`,S=Le.logoUrl||null,C=Le.hideWatermark||!1,w=Ie.elevenLabsAgentId||t?.elevenLabsAgentId||null,qe=t?.siteId||n?.siteId||null,Je=t?.apiBaseUrl||``,Ye=Le.fallbackAgentName||`Agent`,Xe=Le.botLabel||`AI`,Ze=d&&String(d).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Qe=v?.agentName||c||Ye,$e=i.some(e=>e.sender===`user`),et=(0,l.useMemo)(()=>{let e=i.findIndex(e=>e.sender===`user`);return e===-1?!1:i.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[i]),tt=!f&&$e&&et;(0,l.useEffect)(()=>{b(f||``),f&&Fe(``)},[f]),(0,l.useEffect)(()=>{if(!ie||re!==`connected`){Me(0);return}let e=()=>{let e=new Date(ie).getTime();isNaN(e)||Me(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[ie,re]),(0,l.useEffect)(()=>{if(!s||h||te){Se(``),xe();return}if(!Ce.trim()){Se(``),xe();return}be();let e=window.setTimeout(()=>{Se(Ce)},120),t=window.setTimeout(()=>{xe()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Ce,s,h,te,be,xe,Se]);let nt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,rt=async e=>{if(e.preventDefault(),te)return;if(tt){let e=Ne.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Fe(`Please enter a valid email so we can continue helping you.`);return}await he(e),Fe(``);return}if(!Ce.trim())return;let t=Ce.trim(),n=nt(ke);we(``),Ae(null),await ve(t,``,n)},it=async()=>{if(tt){Fe(`Please share your email before starting a call.`);return}if(h){ye(!1);return}Oe(null);try{Ee(await navigator.mediaDevices.getUserMedia({audio:!0})),ye(!0)}catch(e){Oe(e.message||`Could not access microphone.`)}},at=()=>{Te&&(Te.getTracks().forEach(e=>e.stop()),Ee(null)),ye(!1)},ot=e=>{let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`};return e===`ready`?(0,u.jsxs)(`div`,{className:`flowengage-shell`,"data-open":a?`true`:`false`,style:He,children:[(0,u.jsx)(On,{isOpen:a,openWidget:ge,launcherText:Ge,primaryColor:ze,posInline:Ve}),a&&(0,u.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!h?`linear-gradient(to bottom, ${ze} 0%, ${ze} 70%, white 85%)`:`white`},children:[(0,u.jsx)(Nn,{logoUrl:S,brandName:Ke,agentName:c,fallbackAgentName:Ye,activeScreen:o,branding:Le,isConversationEnded:te,endConversation:le,closeWidget:_e,isInitial:i.length===0&&!h,botLabel:Xe,agentAvatarUrl:o===`agent`?Ze:null,primaryColor:ze}),(0,u.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:h?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(n_,{agentId:w,chatId:r,siteId:qe,apiBaseUrl:Je,historyRef:ce,onMessageSync:y,onEnd:at})},`voice`):i.length===0?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Vn,{greetings:We,recommendations:Ue,onSendMessage:ve})},`welcome`):(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Rn,{chatHistory:i,isAiTyping:m,isAgentTyping:p,setReplyContext:Ae,TypingDots:i_,primaryColor:ze,agentHeadshot:Ze,agentDisplayName:c||Ye})},`history`)}),(0,u.jsx)(Gn,{webRTCError:oe,micError:De,setMicError:Oe,dismissCallError:me,incomingCall:v,rejectCall:de,acceptCall:ue,activeCallId:ne,callConnectionState:re,formatCallDuration:ot,callDurationSeconds:je,endWebRTCCall:fe,isCallMuted:ae,toggleCallMute:pe,isAIVoiceActive:h,currentCallAgentName:Qe,isRateLimited:g,rateLimitMessage:_}),!h&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,u.jsx)(Hn,{input:Ce,setInput:we,onSubmit:rt,isConversationEnded:te,callUiActive:!!(v||ne),handleToggleVoice:it,activeScreen:o,inputDisabled:ee||g||te,replyContext:ke,clearReplyContext:()=>Ae(null),requiresEmail:tt,emailInput:Ne,setEmailInput:b,emailError:Pe})}),!C&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`12px`,paddingTop:`12px`,paddingBottom:`16px`,fontSize:`12px`,color:`#9ca3af`},children:(0,u.jsxs)(`div`,{children:[`Powered by `,(0,u.jsx)(`span`,{style:{color:`#3b82f6`},children:`Flow`}),(0,u.jsx)(`span`,{style:{color:`#ef4444`},children:`Engage`})]})})]})]}):null}exports.FlowEngageProvider=_n,exports.FlowEngageWidget=a_,exports.useFlowEngage=Yt;