Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@freeday-ai/webchat-sdk

Package Overview
Dependencies
Maintainers
0
Versions
40
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@freeday-ai/webchat-sdk - npm Package Compare versions

Comparing version 0.0.1-alpha.12 to 0.0.1-alpha.13

4

dist/freeday-webchat-sdk.iife.js

@@ -1,2 +0,2 @@

var Ge=Object.defineProperty;var xe=(R,S,A)=>S in R?Ge(R,S,{enumerable:!0,configurable:!0,writable:!0,value:A}):R[S]=A;var u=(R,S,A)=>xe(R,typeof S!="symbol"?S+"":S,A);(function(){"use strict";var R={exports:{}};(function(t){var e=function(s){var i=Object.prototype,r=i.hasOwnProperty,o=Object.defineProperty||function(a,n,h){a[n]=h.value},c,l=typeof Symbol=="function"?Symbol:{},g=l.iterator||"@@iterator",v=l.asyncIterator||"@@asyncIterator",T=l.toStringTag||"@@toStringTag";function m(a,n,h){return Object.defineProperty(a,n,{value:h,enumerable:!0,configurable:!0,writable:!0}),a[n]}try{m({},"")}catch{m=function(n,h,f){return n[h]=f}}function W(a,n,h,f){var d=n&&n.prototype instanceof Y?n:Y,p=Object.create(d.prototype),y=new te(f||[]);return o(p,"_invoke",{value:Be(a,h,y)}),p}s.wrap=W;function B(a,n,h){try{return{type:"normal",arg:a.call(n,h)}}catch(f){return{type:"throw",arg:f}}}var he="suspendedStart",Pe="suspendedYield",ce="executing",F="completed",k={};function Y(){}function z(){}function L(){}var Q={};m(Q,g,function(){return this});var Z=Object.getPrototypeOf,J=Z&&Z(Z(se([])));J&&J!==i&&r.call(J,g)&&(Q=J);var $=L.prototype=Y.prototype=Object.create(Q);z.prototype=L,o($,"constructor",{value:L,configurable:!0}),o(L,"constructor",{value:z,configurable:!0}),z.displayName=m(L,T,"GeneratorFunction");function le(a){["next","throw","return"].forEach(function(n){m(a,n,function(h){return this._invoke(n,h)})})}s.isGeneratorFunction=function(a){var n=typeof a=="function"&&a.constructor;return n?n===z||(n.displayName||n.name)==="GeneratorFunction":!1},s.mark=function(a){return Object.setPrototypeOf?Object.setPrototypeOf(a,L):(a.__proto__=L,m(a,T,"GeneratorFunction")),a.prototype=Object.create($),a},s.awrap=function(a){return{__await:a}};function V(a,n){function h(p,y,w,C){var b=B(a[p],a,y);if(b.type==="throw")C(b.arg);else{var ie=b.arg,H=ie.value;return H&&typeof H=="object"&&r.call(H,"__await")?n.resolve(H.__await).then(function(M){h("next",M,w,C)},function(M){h("throw",M,w,C)}):n.resolve(H).then(function(M){ie.value=M,w(ie)},function(M){return h("throw",M,w,C)})}}var f;function d(p,y){function w(){return new n(function(C,b){h(p,y,C,b)})}return f=f?f.then(w,w):w()}o(this,"_invoke",{value:d})}le(V.prototype),m(V.prototype,v,function(){return this}),s.AsyncIterator=V,s.async=function(a,n,h,f,d){d===void 0&&(d=Promise);var p=new V(W(a,n,h,f),d);return s.isGeneratorFunction(n)?p:p.next().then(function(y){return y.done?y.value:p.next()})};function Be(a,n,h){var f=he;return function(p,y){if(f===ce)throw new Error("Generator is already running");if(f===F){if(p==="throw")throw y;return De()}for(h.method=p,h.arg=y;;){var w=h.delegate;if(w){var C=ue(w,h);if(C){if(C===k)continue;return C}}if(h.method==="next")h.sent=h._sent=h.arg;else if(h.method==="throw"){if(f===he)throw f=F,h.arg;h.dispatchException(h.arg)}else h.method==="return"&&h.abrupt("return",h.arg);f=ce;var b=B(a,n,h);if(b.type==="normal"){if(f=h.done?F:Pe,b.arg===k)continue;return{value:b.arg,done:h.done}}else b.type==="throw"&&(f=F,h.method="throw",h.arg=b.arg)}}}function ue(a,n){var h=n.method,f=a.iterator[h];if(f===c)return n.delegate=null,h==="throw"&&a.iterator.return&&(n.method="return",n.arg=c,ue(a,n),n.method==="throw")||h!=="return"&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+h+"' method")),k;var d=B(f,a.iterator,n.arg);if(d.type==="throw")return n.method="throw",n.arg=d.arg,n.delegate=null,k;var p=d.arg;if(!p)return n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,k;if(p.done)n[a.resultName]=p.value,n.next=a.nextLoc,n.method!=="return"&&(n.method="next",n.arg=c);else return p;return n.delegate=null,k}le($),m($,T,"Generator"),m($,g,function(){return this}),m($,"toString",function(){return"[object Generator]"});function He(a){var n={tryLoc:a[0]};1 in a&&(n.catchLoc=a[1]),2 in a&&(n.finallyLoc=a[2],n.afterLoc=a[3]),this.tryEntries.push(n)}function ee(a){var n=a.completion||{};n.type="normal",delete n.arg,a.completion=n}function te(a){this.tryEntries=[{tryLoc:"root"}],a.forEach(He,this),this.reset(!0)}s.keys=function(a){var n=Object(a),h=[];for(var f in n)h.push(f);return h.reverse(),function d(){for(;h.length;){var p=h.pop();if(p in n)return d.value=p,d.done=!1,d}return d.done=!0,d}};function se(a){if(a!=null){var n=a[g];if(n)return n.call(a);if(typeof a.next=="function")return a;if(!isNaN(a.length)){var h=-1,f=function d(){for(;++h<a.length;)if(r.call(a,h))return d.value=a[h],d.done=!1,d;return d.value=c,d.done=!0,d};return f.next=f}}throw new TypeError(typeof a+" is not iterable")}s.values=se;function De(){return{value:c,done:!0}}return te.prototype={constructor:te,reset:function(a){if(this.prev=0,this.next=0,this.sent=this._sent=c,this.done=!1,this.delegate=null,this.method="next",this.arg=c,this.tryEntries.forEach(ee),!a)for(var n in this)n.charAt(0)==="t"&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=c)},stop:function(){this.done=!0;var a=this.tryEntries[0],n=a.completion;if(n.type==="throw")throw n.arg;return this.rval},dispatchException:function(a){if(this.done)throw a;var n=this;function h(C,b){return p.type="throw",p.arg=a,n.next=C,b&&(n.method="next",n.arg=c),!!b}for(var f=this.tryEntries.length-1;f>=0;--f){var d=this.tryEntries[f],p=d.completion;if(d.tryLoc==="root")return h("end");if(d.tryLoc<=this.prev){var y=r.call(d,"catchLoc"),w=r.call(d,"finallyLoc");if(y&&w){if(this.prev<d.catchLoc)return h(d.catchLoc,!0);if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else if(y){if(this.prev<d.catchLoc)return h(d.catchLoc,!0)}else if(w){if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(a,n){for(var h=this.tryEntries.length-1;h>=0;--h){var f=this.tryEntries[h];if(f.tryLoc<=this.prev&&r.call(f,"finallyLoc")&&this.prev<f.finallyLoc){var d=f;break}}d&&(a==="break"||a==="continue")&&d.tryLoc<=n&&n<=d.finallyLoc&&(d=null);var p=d?d.completion:{};return p.type=a,p.arg=n,d?(this.method="next",this.next=d.finallyLoc,k):this.complete(p)},complete:function(a,n){if(a.type==="throw")throw a.arg;return a.type==="break"||a.type==="continue"?this.next=a.arg:a.type==="return"?(this.rval=this.arg=a.arg,this.method="return",this.next="end"):a.type==="normal"&&n&&(this.next=n),k},finish:function(a){for(var n=this.tryEntries.length-1;n>=0;--n){var h=this.tryEntries[n];if(h.finallyLoc===a)return this.complete(h.completion,h.afterLoc),ee(h),k}},catch:function(a){for(var n=this.tryEntries.length-1;n>=0;--n){var h=this.tryEntries[n];if(h.tryLoc===a){var f=h.completion;if(f.type==="throw"){var d=f.arg;ee(h)}return d}}throw new Error("illegal catch attempt")},delegateYield:function(a,n,h){return this.delegate={iterator:se(a),resultName:n,nextLoc:h},this.method==="next"&&(this.arg=c),k}},s}(t.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(R);const S="https://webchat.freeday.chat",A=t=>!!(t.location.hostname==="localhost"||t.location.hostname==="[::1]"||t.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)),de=(t=S)=>{const[e,s]=t.split("://");return`${e==="https"?"wss":"ws"}://${s}/socket`},fe=t=>!t||!t.length?!1:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),ge=t=>t.replace(/_([a-z])/g,(e,s)=>s.toUpperCase()),q=t=>Array.isArray(t)?t.map(e=>q(e)):t!==null&&typeof t=="object"?Object.keys(t).reduce((e,s)=>{const i=ge(s);return e[i]=q(t[s]),e},{}):t;class pe{constructor(e=S){u(this,"baseUrl");this.baseUrl=e}getDefaultOptions(e,s){return{method:e,headers:{"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0}}get(e,s={}){const i=new URLSearchParams(s).toString(),r=`${this.baseUrl}${e}?${i}`;return fetch(r,this.getDefaultOptions("GET")).then(o=>{if(!o.ok)throw new Error(`GET request failed: ${o.statusText}`);return o.json()}).catch(o=>{throw new Error(`Error occurred during GET request: ${o.message}`)})}post(e,s){const i=`${this.baseUrl}${e}`;return fetch(i,this.getDefaultOptions("POST",s)).then(r=>{if(!r.ok)throw new Error(`POST request failed: ${r.statusText}`);return r.json()}).catch(r=>{throw new Error(`Error occurred during POST request: ${r.message}`)})}async put(e,s){const i=`${this.baseUrl}${e}`;return fetch(i,this.getDefaultOptions("PUT",s)).then(r=>{if(!r.ok)throw new Error(`PUT request failed: ${r.statusText}`);return r.json()}).catch(r=>{throw new Error(`Error occurred during PUT request: ${r.message}`)})}}class me{constructor(e,s){u(this,"http");u(this,"token");this.token=e,this.http=new pe(s)}async healthCheck(){return this.http.get("/api/health-check").then(e=>e.status)}async fetchWidgetSettings(){return this.http.get(`/api/widget/settings/${this.token}`).then(e=>q(e.data))}async updateWidgetSettingsMetadata(e){return this.http.put(`/api/widget/settings/${this.token}/metadata`,e)}async createNewUser(e={}){return this.http.post("/api/users",{user:{...e,first_seen:new Date().toISOString(),last_seen:new Date().toISOString()}})}async isValidUser(e){return this.http.get(`/api/users/${e}/exists`).then(s=>s.exists)}async updateUserMetadata(e,s){return this.http.put(`/api/users/${e}/metadata`,{metadata:s}).then(i=>i.data)}async findUserByExternalId(e){const s=this.token;return this.http.get("/api/users/identify",{external_id:e,token:s})}async fetchConversationById(e){return this.http.get(`/api/conversations/${e}`).then(s=>s.data)}async createNewConversation(e){return this.http.post("/api/conversations",{conversation:{user_id:e}}).then(s=>s.data)}}var N=t=>typeof t=="function"?t:function(){return t},ve=typeof self<"u"?self:null,O=typeof window<"u"?window:null,j=ve||O||j,ye="2.0.0",U={connecting:0,open:1,closing:2,closed:3},we=1e4,be=1e3,E={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},_={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},K={longpoll:"longpoll",websocket:"websocket"},Ee={complete:4},D=class{constructor(t,e,s,i){this.channel=t,this.event=e,this.payload=s||function(){return{}},this.receivedResp=null,this.timeout=i,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:t,response:e,_ref:s}){this.recHooks.filter(i=>i.status===t).forEach(i=>i.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},re=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Ce=class{constructor(t,e,s){this.state=E.closed,this.topic=t,this.params=N(e||{}),this.socket=s,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new D(this,_.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new re(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=E.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=E.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=E.closed,this.socket.remove(this)}),this.onError(i=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,i),this.isJoining()&&this.joinPush.reset(),this.state=E.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new D(this,_.leave,N({}),this.timeout).send(),this.state=E.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(_.reply,(i,r)=>{this.trigger(this.replyEventName(r),i)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(t){this.on(_.close,t)}onError(t){return this.on(_.error,e=>t(e))}on(t,e){let s=this.bindingRef++;return this.bindings.push({event:t,ref:s,callback:e}),s}off(t,e){this.bindings=this.bindings.filter(s=>!(s.event===t&&(typeof e>"u"||e===s.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,s=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let i=new D(this,t,function(){return e},s);return this.canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=E.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(_.close,"leave")},s=new D(this,_.leave,N({}),t);return s.receive("ok",()=>e()).receive("timeout",()=>e()),s.send(),this.canPush()||s.trigger("ok",{}),s}onMessage(t,e,s){return e}isMember(t,e,s,i){return this.topic!==t?!1:i&&i!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:s,joinRef:i}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=E.joining,this.joinPush.resend(t))}trigger(t,e,s,i){let r=this.onMessage(t,e,s,i);if(e&&!r)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let o=this.bindings.filter(c=>c.event===t);for(let c=0;c<o.length;c++)o[c].callback(r,s,i||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===E.closed}isErrored(){return this.state===E.errored}isJoined(){return this.state===E.joined}isJoining(){return this.state===E.joining}isLeaving(){return this.state===E.leaving}},G=class{static request(t,e,s,i,r,o,c){if(j.XDomainRequest){let l=new j.XDomainRequest;return this.xdomainRequest(l,t,e,i,r,o,c)}else{let l=new j.XMLHttpRequest;return this.xhrRequest(l,t,e,s,i,r,o,c)}}static xdomainRequest(t,e,s,i,r,o,c){return t.timeout=r,t.open(e,s),t.onload=()=>{let l=this.parseJSON(t.responseText);c&&c(l)},o&&(t.ontimeout=o),t.onprogress=()=>{},t.send(i),t}static xhrRequest(t,e,s,i,r,o,c,l){return t.open(e,s,!0),t.timeout=o,t.setRequestHeader("Content-Type",i),t.onerror=()=>l&&l(null),t.onreadystatechange=()=>{if(t.readyState===Ee.complete&&l){let g=this.parseJSON(t.responseText);l(g)}},c&&(t.ontimeout=c),t.send(r),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let s=[];for(var i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let r=e?`${e}[${i}]`:i,o=t[i];typeof o=="object"?s.push(this.serialize(o,r)):s.push(encodeURIComponent(r)+"="+encodeURIComponent(o))}return s.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let s=t.match(/\?/)?"&":"?";return`${t}${s}${this.serialize(e)}`}},Te=t=>{let e="",s=new Uint8Array(t),i=s.byteLength;for(let r=0;r<i;r++)e+=String.fromCharCode(s[r]);return btoa(e)},P=class{constructor(t){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=U.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+K.websocket),"$1/"+K.longpoll)}endpointURL(){return G.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,s){this.close(t,e,s),this.readyState=U.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===U.open||this.readyState===U.connecting}poll(){this.ajax("GET","application/json",null,()=>this.ontimeout(),t=>{if(t){var{status:e,token:s,messages:i}=t;this.token=s}else e=0;switch(e){case 200:i.forEach(r=>{setTimeout(()=>this.onmessage({data:r}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=U.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${e}`)}})}send(t){typeof t!="string"&&(t=Te(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",t.join(`
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,s){for(let r of this.reqs)r.abort();this.readyState=U.closed;let i=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:s});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",i)):this.onclose(i)}ajax(t,e,s,i,r){let o,c=()=>{this.reqs.delete(o),i()};o=G.request(t,this.endpointURL(),e,s,this.timeout,c,l=>{this.reqs.delete(o),this.isActive()&&r(l)}),this.reqs.add(o)}},x={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let s=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(s))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[s,i,r,o,c]=JSON.parse(t);return e({join_ref:s,ref:i,topic:r,event:o,payload:c})}},binaryEncode(t){let{join_ref:e,ref:s,event:i,topic:r,payload:o}=t,c=this.META_LENGTH+e.length+s.length+r.length+i.length,l=new ArrayBuffer(this.HEADER_LENGTH+c),g=new DataView(l),v=0;g.setUint8(v++,this.KINDS.push),g.setUint8(v++,e.length),g.setUint8(v++,s.length),g.setUint8(v++,r.length),g.setUint8(v++,i.length),Array.from(e,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(s,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(r,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(i,m=>g.setUint8(v++,m.charCodeAt(0)));var T=new Uint8Array(l.byteLength+o.byteLength);return T.set(new Uint8Array(l),0),T.set(new Uint8Array(o),l.byteLength),T.buffer},binaryDecode(t){let e=new DataView(t),s=e.getUint8(0),i=new TextDecoder;switch(s){case this.KINDS.push:return this.decodePush(t,e,i);case this.KINDS.reply:return this.decodeReply(t,e,i);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,i)}},decodePush(t,e,s){let i=e.getUint8(1),r=e.getUint8(2),o=e.getUint8(3),c=this.HEADER_LENGTH+this.META_LENGTH-1,l=s.decode(t.slice(c,c+i));c=c+i;let g=s.decode(t.slice(c,c+r));c=c+r;let v=s.decode(t.slice(c,c+o));c=c+o;let T=t.slice(c,t.byteLength);return{join_ref:l,ref:null,topic:g,event:v,payload:T}},decodeReply(t,e,s){let i=e.getUint8(1),r=e.getUint8(2),o=e.getUint8(3),c=e.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,g=s.decode(t.slice(l,l+i));l=l+i;let v=s.decode(t.slice(l,l+r));l=l+r;let T=s.decode(t.slice(l,l+o));l=l+o;let m=s.decode(t.slice(l,l+c));l=l+c;let W=t.slice(l,t.byteLength),B={status:m,response:W};return{join_ref:g,ref:v,topic:T,event:_.reply,payload:B}},decodeBroadcast(t,e,s){let i=e.getUint8(1),r=e.getUint8(2),o=this.HEADER_LENGTH+2,c=s.decode(t.slice(o,o+i));o=o+i;let l=s.decode(t.slice(o,o+r));o=o+r;let g=t.slice(o,t.byteLength);return{join_ref:null,ref:null,topic:c,event:l,payload:g}}},ke=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||we,this.transport=e.transport||j.WebSocket||P,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||j&&j.sessionStorage,this.establishedConnections=0,this.defaultEncoder=x.encode.bind(x),this.defaultDecoder=x.decode.bind(x),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==P?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;O&&O.addEventListener&&(O.addEventListener("pagehide",i=>{this.conn&&(this.disconnect(),s=this.connectClock)}),O.addEventListener("pageshow",i=>{s===this.connectClock&&(s=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=i=>e.rejoinAfterMs?e.rejoinAfterMs(i):[1e3,2e3,5e3][i-1]||1e4,this.reconnectAfterMs=i=>e.reconnectAfterMs?e.reconnectAfterMs(i):[10,50,100,150,200,250,500,1e3,2e3][i-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(i,r,o)=>{console.log(`${i}: ${r}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=N(e.params||{}),this.endPoint=`${t}/${K.websocket}`,this.vsn=e.vsn||ye,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new re(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return P}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=G.appendParams(G.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,s){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(t,e,s)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=N(t)),!this.conn&&(this.longPollFallbackMs&&this.transport!==P?this.connectWithFallback(P,this.longPollFallbackMs):this.transportConnect())}log(t,e,s){this.logger&&this.logger(t,e,s)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),s=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let i=this.onMessage(r=>{r.ref===e&&(this.off([i]),t(Date.now()-s))});return!0}transportConnect(){this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let s=!1,i=!0,r,o,c=l=>{this.log("transport",`falling back to ${t.name}...`,l),this.off([r,o]),i=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${t.name}`))return c("memorized");this.fallbackTimer=setTimeout(c,e),o=this.onError(l=>{this.log("transport","error",l),i&&!s&&(clearTimeout(this.fallbackTimer),c(l))}),this.onOpen(()=>{if(s=!0,!i)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t.name}`,"true"),this.log("transport",`established ${t.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(c,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,t])=>t())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),be,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,s){if(!this.conn)return t&&t();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,s||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(t,e+1)},150*e)}waitForSocketClosed(t,e=1){if(e===5||!this.conn||this.conn.readyState===U.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(t,e+1)},150*e)}onConnClose(t){let e=t&&t.code;this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,s])=>s(t))}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,s=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,i])=>{i(t,e,s)}),(e===this.transport||s>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(_.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case U.connecting:return"connecting";case U.open:return"open";case U.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([s])=>t.indexOf(s)===-1)}channel(t,e={}){let s=new Ce(t,e,this);return this.channels.push(s),s}push(t){if(this.hasLogger()){let{topic:e,event:s,payload:i,ref:r,join_ref:o}=t;this.log("push",`${e} ${s} (${o}, ${r})`,i)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:s,event:i,payload:r,ref:o,join_ref:c}=e;o&&o===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${r.status||""} ${s} ${i} ${o&&"("+o+")"||""}`,r);for(let l=0;l<this.channels.length;l++){const g=this.channels[l];g.isMember(s,i,r,c)&&g.trigger(i,r,o,c)}for(let l=0;l<this.stateChangeCallbacks.message.length;l++){let[,g]=this.stateChangeCallbacks.message[l];g(e)}})}leaveOpenTopic(t){let e=this.channels.find(s=>s.topic===t&&(s.isJoined()||s.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Se{constructor(e){u(this,"debugModeEnabled");this.debugModeEnabled=!!e}debug(...e){this.debugModeEnabled&&console.debug("[@freeday/webchat-sdk]",...e)}log(...e){this.debugModeEnabled&&console.log("[@freeday/webchat-sdk]",...e)}info(...e){console.info("[@freeday/webchat-sdk]",...e)}warn(...e){console.warn("[@freeday/webchat-sdk]",...e)}error(...e){console.error("[@freeday/webchat-sdk]",...e)}}const ne="__FREEDAY__",Ue=t=>{try{return t&&(t.localStorage||t.sessionStorage)}catch{return{_db:{},getItem(s){return this._db[s]||null},setItem(s,i){this._db[s]=i},removeItem(s){delete this._db[s]}}}};function _e(t){const e=Ue(t),s=o=>{const c=e.getItem(`${ne}${o}`);if(!c)return null;try{return JSON.parse(c)}catch{return c}},i=(o,c)=>{e.setItem(`${ne}${o}`,JSON.stringify(c))},r=o=>{e.removeItem(o)};return{getUserId:()=>s("__USER_ID__"),setUserId:o=>i("__USER_ID__",o),removeUserId:()=>r("__USER_ID__")}}const I=class I{constructor(e){u(this,"socket");u(this,"channel");u(this,"api");u(this,"logger");u(this,"storage");u(this,"config");u(this,"userId");u(this,"conversationId");u(this,"messages");u(this,"settings");u(this,"start",async()=>{this.connect();const e=await this.fetchWidgetSettings();await this.isValidUserId(this.userId);const s=this.userId,i=this.config.user||{},r=await this.checkForExistingUser(i,s);return this.conversationId?this.setWidgetSettings(e).setUserId(r).fetchConversation(this.conversationId):this.setWidgetSettings(e).setUserId(r).fetchLatestConversation()});u(this,"connect",()=>{this.socket.connect()});u(this,"disconnect",()=>{var e;this.socket.disconnect(),(e=this.channel)==null||e.leave()});u(this,"setWidgetSettings",e=>(this.settings=e,this));u(this,"setUserId",e=>(this.logger.debug("Setting user ID:",e),this.userId=e,this.cacheUserId(e),window.dispatchEvent(new CustomEvent("freeday:user:set",{detail:e})),this));u(this,"fetchConversation",async e=>{try{const s=this.userId;this.logger.debug("Fetching conversation for user:",s,"conversationId:",e);const i=await this.fetchUserConversationById(e);return i?(this.setConversationId(e).setMessages([]),i):(this.logger.debug("Conversation not exist"),null)}catch(s){return this.logger.debug("Error fetching conversation!",s),null}});u(this,"fetchLatestConversation",async()=>null);u(this,"fetchUserConversationById",async e=>this.api.fetchConversationById(e).then(s=>(s?this.logger.debug("Found conversation:",s):this.logger.debug("No conversation found with id:",e),s||null)));u(this,"setConversationId",e=>(this.conversationId=e,this.joinConversationChannel(e),this));u(this,"joinConversationChannel",e=>{this.channel&&this.channel.leave&&this.channel.leave(),this.logger.debug("Joining channel:",e),this.channel=this.socket.channel(`conversations:${e}`,{user_id:this.userId}),this.channel.on("stream_event",i=>{this.logger.debug("New conversation data received",i),this.handleMessageCreated(i)}),this.channel.on("loading",i=>{var o,c,l,g;const{status:r}=i;this.logger.debug("loading",r),r?(c=(o=this.config).onStreamStart)==null||c.call(o):(g=(l=this.config).onStreamEnd)==null||g.call(l)});const s=this.channel.onMessage.bind(this.channel);return this.channel.onMessage=(i,r,o)=>(this.logger.debug("Channel onMessage:",i,r,o),s(i,r,o)),this.channel.join().receive("ok",i=>{this.logger.debug("Joined conversation successfully!",i)}).receive("error",i=>{this.logger.debug("Unable to join conversation!",i)}),this});u(this,"handleMessageCreated",e=>{const{messages:s=[]}=this,i=s.find(o=>o.id===e.id&&o.sender_id===e.sender_id),r=i?s.map(o=>o.sent_at===i.sent_at?e:o):[...s,e];this.setMessages(r)});u(this,"setMessages",e=>(this.messages=e,this.config.onMessagesUpdated&&this.config.onMessagesUpdated(e),this));u(this,"validateMessageContent",e=>!(!e||e.trim().length===0));u(this,"constructMessagePayload",(e,s)=>({blocks:[{id:"1",type:"text",text:e}],id:"temp-id",request_user_feedback:!1,user_feedback_value:null,channel_id:"fake",sender_id:this.userId,sender_name:null,sender_type:"user",sent_at:s,type:"message"}));u(this,"pushMessageToChannel",(e,s,i)=>{var r;(r=this.channel)==null||r.push("new_text",e)});u(this,"sendNewMessage",async e=>{const{userId:s,conversationId:i}=this;if(console.log("sendNewMessage",e,i,s),!this.validateMessageContent(e)){console.warn("Invalid message content, skipping send");return}const r=new Date().toISOString(),o=this.constructMessagePayload(e,r);this.setMessages([...this.messages,o]),console.log("sendNewMessage",s,i),(!s||!i)&&await this.initializeNewConversation(s),this.pushMessageToChannel(e,this.userId,r)});u(this,"createNewConversation",async e=>this.api.createNewConversation(e));u(this,"initializeNewConversation",async e=>{const{user:s={}}=this.config,i=s,r=await this.createOrUpdateUser(e,i);console.log("initializeNewConversation",r,e);const{id:o}=await this.createNewConversation(r);return this.setUserId(r).setConversationId(o)});u(this,"createNewUser",e=>(this.logger.debug("Creating new user:",e),this.api.createNewUser(e)));u(this,"identify",async(e,s={})=>{try{const i=this.userId||this.getCachedUserId(),r=await this.isValidUserId(i),o={...s,external_id:e};if(r){this.logger.debug("Valid user found for ID:",i);const{id:g}=await this.api.updateUserMetadata(i,s);return this.setUserId(g)}const c=await this.checkForExistingUser(o),{id:l}=c?await this.api.updateUserMetadata(c,s):await this.createNewUser(o);return this.setUserId(l)}catch(i){this.logger.error("Failed to update or create user:",i),this.logger.error("Retrying...");const{id:r}=await this.createNewUser(s);return this.setUserId(r)}});u(this,"createOrUpdateUser",async(e,s={})=>{try{const i=e?await this.api.updateUserMetadata(e,s):await this.createNewUser(s),{id:r}=i;return r}catch(i){this.logger.error("Failed to update or create user:",i),this.logger.error("Retrying...");const{id:r}=await this.createNewUser(s);return r}});u(this,"fetchWidgetSettings",async()=>{const e={};return this.api.fetchWidgetSettings().then(s=>s||e).catch(()=>e)});u(this,"updateWidgetSettingsMetadata",async e=>this.api.updateWidgetSettingsMetadata(e).catch(s=>{this.logger.error("Failed to update widget metadata:",s)}));u(this,"findUserByExternalId",async e=>{const s=await this.api.findUserByExternalId(e);return(s==null?void 0:s.id)||null});u(this,"findUserByMetadata",async e=>{if(!e||!(e!=null&&e.external_id))return null;const{external_id:s}=e;return await this.findUserByExternalId(s)});u(this,"checkForExistingUser",async(e,s=null)=>s);u(this,"updateExistingUser",async(e,s)=>{if(s)try{await this.api.updateUserMetadata(e,s)}catch(i){this.logger.debug("Error updating user metadata!",i)}});u(this,"getCachedUserId",()=>this.storage.getUserId());u(this,"cacheUserId",e=>{this.logger.debug("Caching user ID:",e),e?this.storage.setUserId(e):this.storage.removeUserId()});u(this,"isValidUserId",async e=>{if(!e||!e.length||!fe(e))return!1;try{return await this.api.isValidUser(e)}catch{return this.logger.warn("Failed to validate user ID."),this.logger.warn("You might be on an older version of Freeday."),!0}});u(this,"checkHealth",async()=>this.api.healthCheck().then(()=>!0).catch(()=>!1));u(this,"notify",(e,s,i={})=>{this.logger.debug({type:e,message:s,options:i})});const s=window,{baseUrl:i,token:r,conversationId:o,userId:c,debug:l=!1}=e,g=A(s)||l;this.config=e,this.api=new me(r,i),this.logger=new Se(g),this.storage=_e(s),this.userId=c||this.getCachedUserId()||null,this.conversationId=o||null,this.messages=[],this.settings={};const v=de(i);this.socket=new ke(v,{params:{token:r}}),this.settings={}}};u(I,"init",e=>new I(e)),u(I,"open",()=>window.dispatchEvent(new Event("freeday:open"))),u(I,"close",()=>window.dispatchEvent(new Event("freeday:close"))),u(I,"toggle",()=>window.dispatchEvent(new Event("freeday:toggle"))),u(I,"restart",()=>window.dispatchEvent(new Event("freeday:restart")));let X=I;const oe=window,Ie=oe.Freeday&&oe.Freeday.config||{},{token:ae,userId:Re,baseUrl:je,greeting:Le,debug:Me,onSetUserId:Ae,onSetConversationId:$e,onSetWidgetSettings:Ne,onPresenceSync:Oe}=Ie;if(!ae)throw new Error("An account token is required to start Freeday!");X.init({token:ae,userId:Re,baseUrl:je,greeting:Le,debug:Me,onSetUserId:Ae,onSetConversationId:$e,onSetWidgetSettings:Ne,onPresenceSync:Oe})})();
var Ge=Object.defineProperty;var Fe=(I,T,A)=>T in I?Ge(I,T,{enumerable:!0,configurable:!0,writable:!0,value:A}):I[T]=A;var u=(I,T,A)=>Fe(I,typeof T!="symbol"?T+"":T,A);(function(){"use strict";var I={exports:{}};(function(t){var e=function(s){var n=Object.prototype,i=n.hasOwnProperty,o=Object.defineProperty||function(a,r,h){a[r]=h.value},c,l=typeof Symbol=="function"?Symbol:{},f=l.iterator||"@@iterator",v=l.asyncIterator||"@@asyncIterator",E=l.toStringTag||"@@toStringTag";function m(a,r,h){return Object.defineProperty(a,r,{value:h,enumerable:!0,configurable:!0,writable:!0}),a[r]}try{m({},"")}catch{m=function(r,h,p){return r[h]=p}}function F(a,r,h,p){var d=r&&r.prototype instanceof Y?r:Y,g=Object.create(d.prototype),_=new te(p||[]);return o(g,"_invoke",{value:xe(a,h,_)}),g}s.wrap=F;function H(a,r,h){try{return{type:"normal",arg:a.call(r,h)}}catch(p){return{type:"throw",arg:p}}}var he="suspendedStart",He="suspendedYield",ce="executing",V="completed",C={};function Y(){}function W(){}function O(){}var Z={};m(Z,f,function(){return this});var Q=Object.getPrototypeOf,z=Q&&Q(Q(se([])));z&&z!==n&&i.call(z,f)&&(Z=z);var N=O.prototype=Y.prototype=Object.create(Z);W.prototype=O,o(N,"constructor",{value:O,configurable:!0}),o(O,"constructor",{value:W,configurable:!0}),W.displayName=m(O,E,"GeneratorFunction");function le(a){["next","throw","return"].forEach(function(r){m(a,r,function(h){return this._invoke(r,h)})})}s.isGeneratorFunction=function(a){var r=typeof a=="function"&&a.constructor;return r?r===W||(r.displayName||r.name)==="GeneratorFunction":!1},s.mark=function(a){return Object.setPrototypeOf?Object.setPrototypeOf(a,O):(a.__proto__=O,m(a,E,"GeneratorFunction")),a.prototype=Object.create(N),a},s.awrap=function(a){return{__await:a}};function q(a,r){function h(g,_,b,k){var y=H(a[g],a,_);if(y.type==="throw")k(y.arg);else{var ne=y.arg,x=ne.value;return x&&typeof x=="object"&&i.call(x,"__await")?r.resolve(x.__await).then(function(j){h("next",j,b,k)},function(j){h("throw",j,b,k)}):r.resolve(x).then(function(j){ne.value=j,b(ne)},function(j){return h("throw",j,b,k)})}}var p;function d(g,_){function b(){return new r(function(k,y){h(g,_,k,y)})}return p=p?p.then(b,b):b()}o(this,"_invoke",{value:d})}le(q.prototype),m(q.prototype,v,function(){return this}),s.AsyncIterator=q,s.async=function(a,r,h,p,d){d===void 0&&(d=Promise);var g=new q(F(a,r,h,p),d);return s.isGeneratorFunction(r)?g:g.next().then(function(_){return _.done?_.value:g.next()})};function xe(a,r,h){var p=he;return function(g,_){if(p===ce)throw new Error("Generator is already running");if(p===V){if(g==="throw")throw _;return Be()}for(h.method=g,h.arg=_;;){var b=h.delegate;if(b){var k=ue(b,h);if(k){if(k===C)continue;return k}}if(h.method==="next")h.sent=h._sent=h.arg;else if(h.method==="throw"){if(p===he)throw p=V,h.arg;h.dispatchException(h.arg)}else h.method==="return"&&h.abrupt("return",h.arg);p=ce;var y=H(a,r,h);if(y.type==="normal"){if(p=h.done?V:He,y.arg===C)continue;return{value:y.arg,done:h.done}}else y.type==="throw"&&(p=V,h.method="throw",h.arg=y.arg)}}}function ue(a,r){var h=r.method,p=a.iterator[h];if(p===c)return r.delegate=null,h==="throw"&&a.iterator.return&&(r.method="return",r.arg=c,ue(a,r),r.method==="throw")||h!=="return"&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+h+"' method")),C;var d=H(p,a.iterator,r.arg);if(d.type==="throw")return r.method="throw",r.arg=d.arg,r.delegate=null,C;var g=d.arg;if(!g)return r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,C;if(g.done)r[a.resultName]=g.value,r.next=a.nextLoc,r.method!=="return"&&(r.method="next",r.arg=c);else return g;return r.delegate=null,C}le(N),m(N,E,"Generator"),m(N,f,function(){return this}),m(N,"toString",function(){return"[object Generator]"});function $e(a){var r={tryLoc:a[0]};1 in a&&(r.catchLoc=a[1]),2 in a&&(r.finallyLoc=a[2],r.afterLoc=a[3]),this.tryEntries.push(r)}function ee(a){var r=a.completion||{};r.type="normal",delete r.arg,a.completion=r}function te(a){this.tryEntries=[{tryLoc:"root"}],a.forEach($e,this),this.reset(!0)}s.keys=function(a){var r=Object(a),h=[];for(var p in r)h.push(p);return h.reverse(),function d(){for(;h.length;){var g=h.pop();if(g in r)return d.value=g,d.done=!1,d}return d.done=!0,d}};function se(a){if(a!=null){var r=a[f];if(r)return r.call(a);if(typeof a.next=="function")return a;if(!isNaN(a.length)){var h=-1,p=function d(){for(;++h<a.length;)if(i.call(a,h))return d.value=a[h],d.done=!1,d;return d.value=c,d.done=!0,d};return p.next=p}}throw new TypeError(typeof a+" is not iterable")}s.values=se;function Be(){return{value:c,done:!0}}return te.prototype={constructor:te,reset:function(a){if(this.prev=0,this.next=0,this.sent=this._sent=c,this.done=!1,this.delegate=null,this.method="next",this.arg=c,this.tryEntries.forEach(ee),!a)for(var r in this)r.charAt(0)==="t"&&i.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=c)},stop:function(){this.done=!0;var a=this.tryEntries[0],r=a.completion;if(r.type==="throw")throw r.arg;return this.rval},dispatchException:function(a){if(this.done)throw a;var r=this;function h(k,y){return g.type="throw",g.arg=a,r.next=k,y&&(r.method="next",r.arg=c),!!y}for(var p=this.tryEntries.length-1;p>=0;--p){var d=this.tryEntries[p],g=d.completion;if(d.tryLoc==="root")return h("end");if(d.tryLoc<=this.prev){var _=i.call(d,"catchLoc"),b=i.call(d,"finallyLoc");if(_&&b){if(this.prev<d.catchLoc)return h(d.catchLoc,!0);if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else if(_){if(this.prev<d.catchLoc)return h(d.catchLoc,!0)}else if(b){if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(a,r){for(var h=this.tryEntries.length-1;h>=0;--h){var p=this.tryEntries[h];if(p.tryLoc<=this.prev&&i.call(p,"finallyLoc")&&this.prev<p.finallyLoc){var d=p;break}}d&&(a==="break"||a==="continue")&&d.tryLoc<=r&&r<=d.finallyLoc&&(d=null);var g=d?d.completion:{};return g.type=a,g.arg=r,d?(this.method="next",this.next=d.finallyLoc,C):this.complete(g)},complete:function(a,r){if(a.type==="throw")throw a.arg;return a.type==="break"||a.type==="continue"?this.next=a.arg:a.type==="return"?(this.rval=this.arg=a.arg,this.method="return",this.next="end"):a.type==="normal"&&r&&(this.next=r),C},finish:function(a){for(var r=this.tryEntries.length-1;r>=0;--r){var h=this.tryEntries[r];if(h.finallyLoc===a)return this.complete(h.completion,h.afterLoc),ee(h),C}},catch:function(a){for(var r=this.tryEntries.length-1;r>=0;--r){var h=this.tryEntries[r];if(h.tryLoc===a){var p=h.completion;if(p.type==="throw"){var d=p.arg;ee(h)}return d}}throw new Error("illegal catch attempt")},delegateYield:function(a,r,h){return this.delegate={iterator:se(a),resultName:r,nextLoc:h},this.method==="next"&&(this.arg=c),C}},s}(t.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(I);var T={NVM_INC:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/include/node",COREPACK_ROOT:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/lib/node_modules/corepack",HERD_PHP_80_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/80/",TERM_PROGRAM:"vscode",NODE:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin/node",INIT_CWD:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",NVM_CD_FLAGS:"-q",npm_package_dependencies_axios:"^1.7.7",npm_package_dependencies_vite_plugin_dts:"^4.2.1",npm_package_devDependencies_typescript:"^5.6.2",TERM:"xterm-256color",SHELL:"/bin/zsh",npm_package_unpkg:"dist/freeday-webchat-sdk.iife.js",npm_package_devDependencies_vite:"^5.4.6",HOMEBREW_REPOSITORY:"/opt/homebrew",TMPDIR:"/var/folders/lt/0l1rfzpn6sq61y39zg58rb340000gn/T/",npm_package_scripts_lint:"eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",TERM_PROGRAM_VERSION:"1.93.1",npm_package_devDependencies__vitejs_plugin_react:"^4.3.1",npm_package_scripts_dev:"vite",ZDOTDIR:"/Users/beaudinngreve",ORIGINAL_XDG_CURRENT_DESKTOP:"undefined",MallocNanoZone:"0",npm_config_registry:"https://registry.npmjs.org/",HERD_PHP_83_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/83/",ZSH:"/Users/beaudinngreve/.oh-my-zsh",npm_package_dependencies_react_dom:"^18.3.1",npm_package_devDependencies_eslint_plugin_react_refresh:"^0.4.12",npm_package_dependencies_regenerator_runtime:"^0.14.1",NVM_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm",USER:"beaudinngreve",npm_package_description:"Freeday webchat sdk",LS_COLORS:"di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43",npm_package_license:"MIT",npm_package_devDependencies__types_react:"^18.3.7",COMMAND_MODE:"unix2003",PNPM_SCRIPT_SRC_DIR:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",npm_package_exports___import:"./dist/freeday-webchat-sdk-lib.js",SSH_AUTH_SOCK:"/private/tmp/com.apple.launchd.ZL0H8zIN6v/Listeners",__CF_USER_TEXT_ENCODING:"0x1F5:0x0:0x5",npm_package_devDependencies_eslint:"^9.10.0",HERD_PHP_82_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/82/",npm_package_devDependencies__typescript_eslint_eslint_plugin:"^8.6.0",npm_execpath:"/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/bin/pnpm.cjs",PAGER:"less",npm_package_module:"./dist/freeday-webchat-widget-lib.js",LSCOLORS:"Gxfxcxdxbxegedabagacad",npm_package_devDependencies__types_react_dom:"^18.3.0",npm_config_frozen_lockfile:"",npm_package_devDependencies__typescript_eslint_parser:"^8.6.0",PATH:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.bin:/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node-gyp-bin:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.bin:/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node-gyp-bin:/opt/homebrew/share/google-cloud-sdk/bin:/opt/homebrew/opt/postgresql@16/bin:/Users/beaudinngreve/Library/Application Support/Herd/bin/:/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/opt/homebrew/share/google-cloud-sdk/bin:/opt/homebrew/opt/postgresql@16/bin:/Users/beaudinngreve/Library/Application Support/Herd/bin/:/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/opt/homebrew/sbin",COREPACK_ENABLE_DOWNLOAD_PROMPT:"1",USER_ZDOTDIR:"/Users/beaudinngreve",__CFBundleIdentifier:"com.microsoft.VSCode",npm_package_author:"freeday",PWD:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",npm_command:"run-script",npm_package_scripts_preview:"vite preview",npm_package_devDependencies_eslint_plugin_react_hooks:"^4.6.2",npm_lifecycle_event:"build-widget",LANG:"en_US.UTF-8",npm_package_name:"@freeday-ai/webchat-sdk",npm_package_types:"./dist/freeday-webchat-sdk-lib.d.ts",npm_package_packageManager:"pnpm@9.4.0",npm_package_scripts_build_widget:"vite build --config vite.widget.config.js",NODE_PATH:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.6/node_modules/vite/bin/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.6/node_modules/vite/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.6/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/node_modules",npm_package_scripts_build:"pnpm build-module-bundle && pnpm build-widget",npm_package_dependencies_phoenix:"^1.7.14",VSCODE_GIT_ASKPASS_EXTRA_ARGS:"",XPC_FLAGS:"0x0",npm_package_devDependencies_vitest:"^2.1.1",npm_package_main:"./dist/freeday-webchat-sdk-lib.umd.cjs",npm_config_node_gyp:"/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node_modules/node-gyp/bin/node-gyp.js",XPC_SERVICE_NAME:"0",npm_package_version:"0.0.1-alpha.12",VSCODE_INJECTION:"1",SHLVL:"3",HOME:"/Users/beaudinngreve",npm_package_type:"module",VSCODE_GIT_ASKPASS_MAIN:"/Applications/Visual Studio Code.app/Contents/Resources/app/extensions/git/dist/askpass-main.js",npm_package_scripts_test:"vitest",HOMEBREW_PREFIX:"/opt/homebrew",LESS:"-R",LOGNAME:"beaudinngreve",npm_package_exports___require:"./dist/freeday-webchat-sdk-lib.umd.cjs",npm_lifecycle_script:"vite build --config vite.widget.config.js",VSCODE_GIT_IPC_HANDLE:"/var/folders/lt/0l1rfzpn6sq61y39zg58rb340000gn/T/vscode-git-fa5ed45fba.sock",npm_package_dependencies_react:"^18.3.1",NVM_BIN:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin",npm_config_user_agent:"pnpm/9.4.0 npm/? node/v20.13.1 darwin arm64",VSCODE_GIT_ASKPASS_NODE:"/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin)",GIT_ASKPASS:"/Applications/Visual Studio Code.app/Contents/Resources/app/extensions/git/dist/askpass.sh",HERD_PHP_74_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/74/",INFOPATH:"/opt/homebrew/share/info:/opt/homebrew/share/info:",HOMEBREW_CELLAR:"/opt/homebrew/Cellar",npm_package_devDependencies__types_phoenix:"^1.6.5",npm_package_files_0:"dist",npm_package_scripts_build_module_bundle:"vite build --config vite.config.js ",COLORTERM:"truecolor",npm_node_execpath:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin/node",NODE_ENV:"production"};const A=T.NEXT_PUBLIC_BASE_URL||"https://webchat.freeday.chat",de=t=>!!(t.location.hostname==="localhost"||t.location.hostname==="[::1]"||t.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)),pe=(t=A)=>{const[e,s]=t.split("://");return`${e==="https"?"wss":"ws"}://${s}/socket`},fe=t=>!t||!t.length?!1:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),ge=t=>t.replace(/_([a-z])/g,(e,s)=>s.toUpperCase()),J=t=>Array.isArray(t)?t.map(e=>J(e)):t!==null&&typeof t=="object"?Object.keys(t).reduce((e,s)=>{const n=ge(s);return e[n]=J(t[s]),e},{}):t;class me{constructor(e=A){u(this,"baseUrl");this.baseUrl=e}getDefaultOptions(e,s){return{method:e,headers:{"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0}}get(e,s={}){const n=new URLSearchParams(s).toString(),i=`${this.baseUrl}${e}?${n}`;return fetch(i,this.getDefaultOptions("GET")).then(o=>{if(!o.ok)throw new Error(`GET request failed: ${o.statusText}`);return o.json()}).catch(o=>{throw new Error(`Error occurred during GET request: ${o.message}`)})}post(e,s){const n=`${this.baseUrl}${e}`;return fetch(n,this.getDefaultOptions("POST",s)).then(i=>{if(!i.ok)throw new Error(`POST request failed: ${i.statusText}`);return i.json()}).catch(i=>{throw new Error(`Error occurred during POST request: ${i.message}`)})}async put(e,s){const n=`${this.baseUrl}${e}`;return fetch(n,this.getDefaultOptions("PUT",s)).then(i=>{if(!i.ok)throw new Error(`PUT request failed: ${i.statusText}`);return i.json()}).catch(i=>{throw new Error(`Error occurred during PUT request: ${i.message}`)})}}class ve{constructor(e,s){u(this,"http");u(this,"token");this.token=e,this.http=new me(s)}async healthCheck(){return this.http.get("/api/health-check").then(e=>e.status)}async fetchWidgetSettings(){return this.http.get(`/api/widget/settings/${this.token}`).then(e=>J(e.data))}async updateWidgetSettingsMetadata(e){return this.http.put(`/api/widget/settings/${this.token}/metadata`,e)}async createNewUser(e={}){return this.http.post("/api/users",{user:{...e,first_seen:new Date().toISOString(),last_seen:new Date().toISOString()}}).then(s=>s.data)}async isValidUser(e){return this.http.get(`/api/users/${e}/exists`).then(s=>s.exists)}async updateUserMetadata(e,s){return this.http.put(`/api/users/${e}/metadata`,{metadata:s}).then(n=>n.data)}async findUserByExternalId(e){const s=this.token;return this.http.get("/api/users/identify",{external_id:e,token:s})}async fetchConversationById(e){return this.http.get(`/api/conversations/${e}`).then(s=>s.data)}async createNewConversation(e){return this.http.post("/api/conversations",{conversation:{user_id:e}}).then(s=>s.data)}}var M=t=>typeof t=="function"?t:function(){return t},_e=typeof self<"u"?self:null,P=typeof window<"u"?window:null,L=_e||P||L,be="2.0.0",S={connecting:0,open:1,closing:2,closed:3},ye=1e4,we=1e3,w={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},U={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},K={longpoll:"longpoll",websocket:"websocket"},ke={complete:4},$=class{constructor(t,e,s,n){this.channel=t,this.event=e,this.payload=s||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:t,response:e,_ref:s}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},ie=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Ee=class{constructor(t,e,s){this.state=w.closed,this.topic=t,this.params=M(e||{}),this.socket=s,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new $(this,U.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ie(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=w.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=w.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=w.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=w.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new $(this,U.leave,M({}),this.timeout).send(),this.state=w.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(U.reply,(n,i)=>{this.trigger(this.replyEventName(i),n)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(t){this.on(U.close,t)}onError(t){return this.on(U.error,e=>t(e))}on(t,e){let s=this.bindingRef++;return this.bindings.push({event:t,ref:s,callback:e}),s}off(t,e){this.bindings=this.bindings.filter(s=>!(s.event===t&&(typeof e>"u"||e===s.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,s=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new $(this,t,function(){return e},s);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=w.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(U.close,"leave")},s=new $(this,U.leave,M({}),t);return s.receive("ok",()=>e()).receive("timeout",()=>e()),s.send(),this.canPush()||s.trigger("ok",{}),s}onMessage(t,e,s){return e}isMember(t,e,s,n){return this.topic!==t?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:s,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=w.joining,this.joinPush.resend(t))}trigger(t,e,s,n){let i=this.onMessage(t,e,s,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let o=this.bindings.filter(c=>c.event===t);for(let c=0;c<o.length;c++)o[c].callback(i,s,n||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===w.closed}isErrored(){return this.state===w.errored}isJoined(){return this.state===w.joined}isJoining(){return this.state===w.joining}isLeaving(){return this.state===w.leaving}},B=class{static request(t,e,s,n,i,o,c){if(L.XDomainRequest){let l=new L.XDomainRequest;return this.xdomainRequest(l,t,e,n,i,o,c)}else{let l=new L.XMLHttpRequest;return this.xhrRequest(l,t,e,s,n,i,o,c)}}static xdomainRequest(t,e,s,n,i,o,c){return t.timeout=i,t.open(e,s),t.onload=()=>{let l=this.parseJSON(t.responseText);c&&c(l)},o&&(t.ontimeout=o),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,s,n,i,o,c,l){return t.open(e,s,!0),t.timeout=o,t.setRequestHeader("Content-Type",n),t.onerror=()=>l&&l(null),t.onreadystatechange=()=>{if(t.readyState===ke.complete&&l){let f=this.parseJSON(t.responseText);l(f)}},c&&(t.ontimeout=c),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let s=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,o=t[n];typeof o=="object"?s.push(this.serialize(o,i)):s.push(encodeURIComponent(i)+"="+encodeURIComponent(o))}return s.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let s=t.match(/\?/)?"&":"?";return`${t}${s}${this.serialize(e)}`}},Ce=t=>{let e="",s=new Uint8Array(t),n=s.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(s[i]);return btoa(e)},D=class{constructor(t){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=S.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+K.websocket),"$1/"+K.longpoll)}endpointURL(){return B.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,s){this.close(t,e,s),this.readyState=S.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===S.open||this.readyState===S.connecting}poll(){this.ajax("GET","application/json",null,()=>this.ontimeout(),t=>{if(t){var{status:e,token:s,messages:n}=t;this.token=s}else e=0;switch(e){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=S.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${e}`)}})}send(t){typeof t!="string"&&(t=Ce(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",t.join(`
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,s){for(let i of this.reqs)i.abort();this.readyState=S.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:s});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(t,e,s,n,i){let o,c=()=>{this.reqs.delete(o),n()};o=B.request(t,this.endpointURL(),e,s,this.timeout,c,l=>{this.reqs.delete(o),this.isActive()&&i(l)}),this.reqs.add(o)}},G={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let s=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(s))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[s,n,i,o,c]=JSON.parse(t);return e({join_ref:s,ref:n,topic:i,event:o,payload:c})}},binaryEncode(t){let{join_ref:e,ref:s,event:n,topic:i,payload:o}=t,c=this.META_LENGTH+e.length+s.length+i.length+n.length,l=new ArrayBuffer(this.HEADER_LENGTH+c),f=new DataView(l),v=0;f.setUint8(v++,this.KINDS.push),f.setUint8(v++,e.length),f.setUint8(v++,s.length),f.setUint8(v++,i.length),f.setUint8(v++,n.length),Array.from(e,m=>f.setUint8(v++,m.charCodeAt(0))),Array.from(s,m=>f.setUint8(v++,m.charCodeAt(0))),Array.from(i,m=>f.setUint8(v++,m.charCodeAt(0))),Array.from(n,m=>f.setUint8(v++,m.charCodeAt(0)));var E=new Uint8Array(l.byteLength+o.byteLength);return E.set(new Uint8Array(l),0),E.set(new Uint8Array(o),l.byteLength),E.buffer},binaryDecode(t){let e=new DataView(t),s=e.getUint8(0),n=new TextDecoder;switch(s){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,s){let n=e.getUint8(1),i=e.getUint8(2),o=e.getUint8(3),c=this.HEADER_LENGTH+this.META_LENGTH-1,l=s.decode(t.slice(c,c+n));c=c+n;let f=s.decode(t.slice(c,c+i));c=c+i;let v=s.decode(t.slice(c,c+o));c=c+o;let E=t.slice(c,t.byteLength);return{join_ref:l,ref:null,topic:f,event:v,payload:E}},decodeReply(t,e,s){let n=e.getUint8(1),i=e.getUint8(2),o=e.getUint8(3),c=e.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,f=s.decode(t.slice(l,l+n));l=l+n;let v=s.decode(t.slice(l,l+i));l=l+i;let E=s.decode(t.slice(l,l+o));l=l+o;let m=s.decode(t.slice(l,l+c));l=l+c;let F=t.slice(l,t.byteLength),H={status:m,response:F};return{join_ref:f,ref:v,topic:E,event:U.reply,payload:H}},decodeBroadcast(t,e,s){let n=e.getUint8(1),i=e.getUint8(2),o=this.HEADER_LENGTH+2,c=s.decode(t.slice(o,o+n));o=o+n;let l=s.decode(t.slice(o,o+i));o=o+i;let f=t.slice(o,t.byteLength);return{join_ref:null,ref:null,topic:c,event:l,payload:f}}},Se=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||ye,this.transport=e.transport||L.WebSocket||D,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||L&&L.sessionStorage,this.establishedConnections=0,this.defaultEncoder=G.encode.bind(G),this.defaultDecoder=G.decode.bind(G),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==D?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;P&&P.addEventListener&&(P.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),P.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,o)=>{console.log(`${n}: ${i}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=M(e.params||{}),this.endPoint=`${t}/${K.websocket}`,this.vsn=e.vsn||be,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ie(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return D}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=B.appendParams(B.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,s){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(t,e,s)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=M(t)),!this.conn&&(this.longPollFallbackMs&&this.transport!==D?this.connectWithFallback(D,this.longPollFallbackMs):this.transportConnect())}log(t,e,s){this.logger&&this.logger(t,e,s)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),s=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-s))});return!0}transportConnect(){this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let s=!1,n=!0,i,o,c=l=>{this.log("transport",`falling back to ${t.name}...`,l),this.off([i,o]),n=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${t.name}`))return c("memorized");this.fallbackTimer=setTimeout(c,e),o=this.onError(l=>{this.log("transport","error",l),n&&!s&&(clearTimeout(this.fallbackTimer),c(l))}),this.onOpen(()=>{if(s=!0,!n)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t.name}`,"true"),this.log("transport",`established ${t.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(c,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,t])=>t())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),we,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,s){if(!this.conn)return t&&t();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,s||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(t,e+1)},150*e)}waitForSocketClosed(t,e=1){if(e===5||!this.conn||this.conn.readyState===S.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(t,e+1)},150*e)}onConnClose(t){let e=t&&t.code;this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,s])=>s(t))}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,s=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,n])=>{n(t,e,s)}),(e===this.transport||s>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(U.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case S.connecting:return"connecting";case S.open:return"open";case S.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([s])=>t.indexOf(s)===-1)}channel(t,e={}){let s=new Ee(t,e,this);return this.channels.push(s),s}push(t){if(this.hasLogger()){let{topic:e,event:s,payload:n,ref:i,join_ref:o}=t;this.log("push",`${e} ${s} (${o}, ${i})`,n)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:s,event:n,payload:i,ref:o,join_ref:c}=e;o&&o===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${i.status||""} ${s} ${n} ${o&&"("+o+")"||""}`,i);for(let l=0;l<this.channels.length;l++){const f=this.channels[l];f.isMember(s,n,i,c)&&f.trigger(n,i,o,c)}for(let l=0;l<this.stateChangeCallbacks.message.length;l++){let[,f]=this.stateChangeCallbacks.message[l];f(e)}})}leaveOpenTopic(t){let e=this.channels.find(s=>s.topic===t&&(s.isJoined()||s.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Te{constructor(e){u(this,"debugModeEnabled");this.debugModeEnabled=!!e}debug(...e){this.debugModeEnabled&&console.debug("[@freeday/webchat-sdk]",...e)}log(...e){this.debugModeEnabled&&console.log("[@freeday/webchat-sdk]",...e)}info(...e){console.info("[@freeday/webchat-sdk]",...e)}warn(...e){console.warn("[@freeday/webchat-sdk]",...e)}error(...e){console.error("[@freeday/webchat-sdk]",...e)}}const re="__FREEDAY__",Ue=t=>{try{return t&&(t.localStorage||t.sessionStorage)}catch{return{_db:{},getItem(s){return this._db[s]||null},setItem(s,n){this._db[s]=n},removeItem(s){delete this._db[s]}}}};function Re(t){const e=Ue(t),s=o=>{const c=e.getItem(`${re}${o}`);if(!c)return null;try{return JSON.parse(c)}catch{return c}},n=(o,c)=>{e.setItem(`${re}${o}`,JSON.stringify(c))},i=o=>{e.removeItem(o)};return{getUserId:()=>s("__USER_ID__"),setUserId:o=>n("__USER_ID__",o),removeUserId:()=>i("__USER_ID__")}}const R=class R{constructor(e){u(this,"socket");u(this,"channel");u(this,"api");u(this,"logger");u(this,"storage");u(this,"config");u(this,"userId");u(this,"conversationId");u(this,"messages");u(this,"settings");u(this,"start",async()=>{this.connect();const e=await this.fetchWidgetSettings();await this.isValidUserId(this.userId);const s=this.userId,n=this.config.user||{},i=await this.checkForExistingUser(n,s);return this.conversationId?this.setWidgetSettings(e).setUserId(i).fetchConversation(this.conversationId):this.setWidgetSettings(e).setUserId(i).fetchLatestConversation()});u(this,"connect",()=>{this.socket.connect()});u(this,"disconnect",()=>{var e;this.socket.disconnect(),(e=this.channel)==null||e.leave()});u(this,"setWidgetSettings",e=>(this.settings=e,this));u(this,"setUserId",e=>{var s,n;return this.logger.debug("Setting user ID:",e),this.userId=e,this.cacheUserId(e),window.dispatchEvent(new CustomEvent("freeday:user:set",{detail:e})),(n=(s=this.config).onSetUserId)==null||n.call(s,e),this});u(this,"fetchConversation",async e=>{try{const s=this.userId;this.logger.debug("Fetching conversation for user:",s,"conversationId:",e);const n=await this.fetchUserConversationById(e);return n?(this.setConversationId(e).setMessages([]),n):(this.logger.debug("Conversation not exist"),null)}catch(s){return this.logger.debug("Error fetching conversation!",s),null}});u(this,"fetchLatestConversation",async()=>null);u(this,"fetchUserConversationById",async e=>this.api.fetchConversationById(e).then(s=>(s?this.logger.debug("Found conversation:",s):this.logger.debug("No conversation found with id:",e),s||null)));u(this,"setConversationId",e=>(this.conversationId=e,this.joinConversationChannel(e),this));u(this,"joinConversationChannel",e=>{this.channel&&this.channel.leave&&this.channel.leave(),this.logger.debug("Joining channel:",e),this.channel=this.socket.channel(`conversations:${e}`,{user_id:this.userId}),this.channel.on("stream_event",n=>{this.logger.debug("New conversation data received",n),this.handleMessageCreated(n)}),this.channel.on("loading",n=>{var o,c,l,f;const{status:i}=n;this.logger.debug("loading",i),i?(c=(o=this.config).onStreamStart)==null||c.call(o):(f=(l=this.config).onStreamEnd)==null||f.call(l)});const s=this.channel.onMessage.bind(this.channel);return this.channel.onMessage=(n,i,o)=>(this.logger.debug("Channel onMessage:",n,i,o),s(n,i,o)),this.channel.join().receive("ok",n=>{this.logger.debug("Joined conversation successfully!",n)}).receive("error",n=>{this.logger.debug("Unable to join conversation!",n)}),this});u(this,"handleMessageCreated",e=>{const{messages:s=[]}=this,n=s.find(o=>o.id===e.id&&o.sender_id===e.sender_id),i=n?s.map(o=>o.sent_at===n.sent_at?e:o):[...s,e];this.setMessages(i)});u(this,"setMessages",e=>(this.messages=e,this.config.onMessagesUpdated&&this.config.onMessagesUpdated(e),this));u(this,"validateMessageContent",e=>!(!e||e.trim().length===0));u(this,"constructMessagePayload",(e,s)=>({blocks:[{id:"1",type:"text",text:e}],id:"temp-id",request_user_feedback:!1,user_feedback_value:null,channel_id:"fake",sender_id:this.userId,sender_name:null,sender_type:"user",sent_at:s,type:"message"}));u(this,"pushMessageToChannel",(e,s,n)=>{var i;(i=this.channel)==null||i.push("new_text",e)});u(this,"sendNewMessage",async e=>{const{userId:s,conversationId:n}=this;if(!this.validateMessageContent(e)){console.warn("Invalid message content, skipping send");return}const i=new Date().toISOString(),o=this.constructMessagePayload(e,i);this.setMessages([...this.messages,o]),(!s||!n)&&await this.initializeNewConversation(s),this.pushMessageToChannel(e,this.userId,i)});u(this,"createNewConversation",async e=>this.api.createNewConversation(e));u(this,"initializeNewConversation",async e=>{const{user:s={}}=this.config,n=s,i=await this.createOrUpdateUser(e,n),{id:o}=await this.createNewConversation(i);return this.setUserId(i).setConversationId(o)});u(this,"createNewUser",e=>(this.logger.debug("Creating new user:",e),this.api.createNewUser(e)));u(this,"identify",async(e,s={})=>{try{const n=this.userId||this.getCachedUserId(),i=await this.isValidUserId(n),o={...s,external_id:e};if(i){this.logger.debug("Valid user found for ID:",n);const{id:f}=await this.api.updateUserMetadata(n,s);return this.setUserId(f)}const c=await this.checkForExistingUser(o),{id:l}=c?await this.api.updateUserMetadata(c,s):await this.createNewUser(o);return this.setUserId(l)}catch(n){this.logger.error("Failed to update or create user:",n),this.logger.error("Retrying...");const{id:i}=await this.createNewUser(s);return this.setUserId(i)}});u(this,"createOrUpdateUser",async(e,s={})=>{try{const n=e?await this.api.updateUserMetadata(e,s):await this.createNewUser(s),{id:i}=n;return i}catch(n){this.logger.error("Failed to update or create user:",n),this.logger.error("Retrying...");const{id:i}=await this.createNewUser(s);return i}});u(this,"fetchWidgetSettings",async()=>{const e={};return this.api.fetchWidgetSettings().then(s=>s||e).catch(()=>e)});u(this,"updateWidgetSettingsMetadata",async e=>this.api.updateWidgetSettingsMetadata(e).catch(s=>{this.logger.error("Failed to update widget metadata:",s)}));u(this,"findUserByExternalId",async e=>{const s=await this.api.findUserByExternalId(e);return(s==null?void 0:s.id)||null});u(this,"findUserByMetadata",async e=>{if(!e||!(e!=null&&e.external_id))return null;const{external_id:s}=e;return await this.findUserByExternalId(s)});u(this,"checkForExistingUser",async(e,s=null)=>s);u(this,"updateExistingUser",async(e,s)=>{if(s)try{await this.api.updateUserMetadata(e,s)}catch(n){this.logger.debug("Error updating user metadata!",n)}});u(this,"getCachedUserId",()=>this.storage.getUserId());u(this,"cacheUserId",e=>{this.logger.debug("Caching user ID:",e),e?this.storage.setUserId(e):this.storage.removeUserId()});u(this,"isValidUserId",async e=>{if(!e||!e.length||!fe(e))return!1;try{return await this.api.isValidUser(e)}catch{return this.logger.warn("Failed to validate user ID."),this.logger.warn("You might be on an older version of Freeday."),!0}});u(this,"checkHealth",async()=>this.api.healthCheck().then(()=>!0).catch(()=>!1));u(this,"notify",(e,s,n={})=>{this.logger.debug({type:e,message:s,options:n})});const s=window,{baseUrl:n,token:i,conversationId:o,userId:c,debug:l=!1}=e,f=de(s)||l;this.config=e,this.api=new ve(i,n),this.logger=new Te(f),this.storage=Re(s),this.userId=c||this.getCachedUserId()||null,this.conversationId=o||null,this.messages=[],this.settings={};const v=pe(n);this.socket=new Se(v,{params:{token:i}}),this.settings={}}};u(R,"init",e=>new R(e)),u(R,"open",()=>window.dispatchEvent(new Event("freeday:open"))),u(R,"close",()=>window.dispatchEvent(new Event("freeday:close"))),u(R,"toggle",()=>window.dispatchEvent(new Event("freeday:toggle"))),u(R,"restart",()=>window.dispatchEvent(new Event("freeday:restart")));let X=R;const oe=window,Ie=oe.Freeday&&oe.Freeday.config||{},{token:ae,userId:Ae,baseUrl:Le,greeting:Oe,debug:je,onSetUserId:Ne,onSetConversationId:Me,onSetWidgetSettings:Pe,onPresenceSync:De}=Ie;if(!ae)throw new Error("An account token is required to start Freeday!");X.init({token:ae,userId:Ae,baseUrl:Le,greeting:Oe,debug:je,onSetUserId:Ne,onSetConversationId:Me,onSetWidgetSettings:Pe,onPresenceSync:De})})();
{
"name": "@freeday-ai/webchat-sdk",
"description": "Freeday webchat sdk",
"version": "0.0.1-alpha.12",
"version": "0.0.1-alpha.13",
"author": "freeday",

@@ -6,0 +6,0 @@ "license": "MIT",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc