@opencx/widget 3.0.88 → 3.0.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/designs.cjs +352 -19
- package/dist/designs.cjs.map +1 -1
- package/dist/designs.js +35299 -2028
- package/dist/designs.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.cjs.map +1 -1
- package/dist/react.js +16 -17
- package/dist/react.js.map +1 -1
- package/dist/useModes-BAr0RJcP.js +3183 -0
- package/dist/useModes-BAr0RJcP.js.map +1 -0
- package/dist/useModes-C4Sdixy0.cjs +85 -0
- package/dist/useModes-C4Sdixy0.cjs.map +1 -0
- package/dist/{widget.ctx-CC3c7FPb.js → widget.ctx-Db3DyLM5.js} +406 -384
- package/dist/{widget.ctx-CC3c7FPb.js.map → widget.ctx-Db3DyLM5.js.map} +1 -1
- package/dist/widget.ctx-RfaE5VPy.cjs +5 -0
- package/dist/{widget.ctx-HuLTTMAM.cjs.map → widget.ctx-RfaE5VPy.cjs.map} +1 -1
- package/dist-embed/script.js +1 -1
- package/package.json +1 -4
- package/dist/useModes-DSFNdOy3.cjs +0 -2
- package/dist/useModes-DSFNdOy3.cjs.map +0 -1
- package/dist/useModes-DleBrdDK.js +0 -260
- package/dist/useModes-DleBrdDK.js.map +0 -1
- package/dist/widget.ctx-HuLTTMAM.cjs +0 -5
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var Se=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function yt(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function Ds(i){if(i.__esModule)return i;var n=i.default;if(typeof n=="function"){var r=function u(){return this instanceof u?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};r.prototype=n.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(i).forEach(function(u){var c=Object.getOwnPropertyDescriptor(i,u);Object.defineProperty(r,u,c.get?c:{enumerable:!0,get:function(){return i[u]}})}),r}const Fs=/\{[^{}]+\}/g,Ls=()=>{var i,n;return typeof process=="object"&&Number.parseInt((n=(i=process==null?void 0:process.versions)==null?void 0:i.node)==null?void 0:n.substring(0,2))>=18&&process.versions.undici};function $s(){return Math.random().toString(36).slice(2,11)}function zs(i){let{baseUrl:n="",Request:r=globalThis.Request,fetch:u=globalThis.fetch,querySerializer:c,bodySerializer:o,headers:s,requestInitExt:l=void 0,...d}={...i};l=Ls()?l:void 0,n=dt(n);const y=[];async function g(p,f){const{baseUrl:v,fetch:F=u,Request:j=r,headers:q,params:E={},parseAs:b="json",querySerializer:I,bodySerializer:ee=o??Bs,body:_,...D}=f||{};v&&(n=dt(v));let B=typeof c=="function"?c:ft(c);I&&(B=typeof I=="function"?I:ft({...typeof c=="object"?c:{},...I}));const le=_===void 0?void 0:ee(_),fe=le===void 0||le instanceof FormData?{}:{"Content-Type":"application/json"},de={redirect:"follow",...d,...D,body:le,headers:Hs(fe,s,q,E.header)};let te,N,G=new r(ks(p,{baseUrl:n,params:E,querySerializer:B}),de);for(const O in D)O in G||(G[O]=D[O]);if(y.length){te=$s(),N=Object.freeze({baseUrl:n,fetch:F,parseAs:b,querySerializer:B,bodySerializer:ee});for(const O of y)if(O&&typeof O=="object"&&typeof O.onRequest=="function"){const U=await O.onRequest({request:G,schemaPath:p,params:E,options:N,id:te});if(U){if(!(U instanceof r))throw new Error("onRequest: must return new Request() when modifying the request");G=U}}}let T;try{T=await F(G,l)}catch(O){let U=O;if(y.length)for(let K=y.length-1;K>=0;K--){const ue=y[K];if(ue&&typeof ue=="object"&&typeof ue.onError=="function"){const se=await ue.onError({request:G,error:U,schemaPath:p,params:E,options:N,id:te});if(se){if(se instanceof Response){U=void 0,T=se;break}if(se instanceof Error){U=se;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(U)throw U}if(y.length)for(let O=y.length-1;O>=0;O--){const U=y[O];if(U&&typeof U=="object"&&typeof U.onResponse=="function"){const K=await U.onResponse({request:G,response:T,schemaPath:p,params:E,options:N,id:te});if(K){if(!(K instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");T=K}}}if(T.status===204||T.headers.get("Content-Length")==="0")return T.ok?{data:void 0,response:T}:{error:void 0,response:T};if(T.ok)return b==="stream"?{data:T.body,response:T}:{data:await T[b](),response:T};let ge=await T.text();try{ge=JSON.parse(ge)}catch{}return{error:ge,response:T}}return{request(p,f,v){return g(f,{...v,method:p.toUpperCase()})},GET(p,f){return g(p,{...f,method:"GET"})},PUT(p,f){return g(p,{...f,method:"PUT"})},POST(p,f){return g(p,{...f,method:"POST"})},DELETE(p,f){return g(p,{...f,method:"DELETE"})},OPTIONS(p,f){return g(p,{...f,method:"OPTIONS"})},HEAD(p,f){return g(p,{...f,method:"HEAD"})},PATCH(p,f){return g(p,{...f,method:"PATCH"})},TRACE(p,f){return g(p,{...f,method:"TRACE"})},use(...p){for(const f of p)if(f){if(typeof f!="object"||!("onRequest"in f||"onResponse"in f||"onError"in f))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");y.push(f)}},eject(...p){for(const f of p){const v=y.indexOf(f);v!==-1&&y.splice(v,1)}}}}function Re(i,n,r){if(n==null)return"";if(typeof n=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${i}=${(r==null?void 0:r.allowReserved)===!0?n:encodeURIComponent(n)}`}function mt(i,n,r){if(!n||typeof n!="object")return"";const u=[],c={simple:",",label:".",matrix:";"}[r.style]||"&";if(r.style!=="deepObject"&&r.explode===!1){for(const l in n)u.push(l,r.allowReserved===!0?n[l]:encodeURIComponent(n[l]));const s=u.join(",");switch(r.style){case"form":return`${i}=${s}`;case"label":return`.${s}`;case"matrix":return`;${i}=${s}`;default:return s}}for(const s in n){const l=r.style==="deepObject"?`${i}[${s}]`:s;u.push(Re(l,n[s],r))}const o=u.join(c);return r.style==="label"||r.style==="matrix"?`${c}${o}`:o}function bt(i,n,r){if(!Array.isArray(n))return"";if(r.explode===!1){const o={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[r.style]||",",s=(r.allowReserved===!0?n:n.map(l=>encodeURIComponent(l))).join(o);switch(r.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${i}=${s}`;default:return`${i}=${s}`}}const u={simple:",",label:".",matrix:";"}[r.style]||"&",c=[];for(const o of n)r.style==="simple"||r.style==="label"?c.push(r.allowReserved===!0?o:encodeURIComponent(o)):c.push(Re(i,o,r));return r.style==="label"||r.style==="matrix"?`${u}${c.join(u)}`:c.join(u)}function ft(i){return function(r){const u=[];if(r&&typeof r=="object")for(const c in r){const o=r[c];if(o!=null){if(Array.isArray(o)){if(o.length===0)continue;u.push(bt(c,o,{style:"form",explode:!0,...i==null?void 0:i.array,allowReserved:(i==null?void 0:i.allowReserved)||!1}));continue}if(typeof o=="object"){u.push(mt(c,o,{style:"deepObject",explode:!0,...i==null?void 0:i.object,allowReserved:(i==null?void 0:i.allowReserved)||!1}));continue}u.push(Re(c,o,i))}}return u.join("&")}}function qs(i,n){let r=i;for(const u of i.match(Fs)??[]){let c=u.substring(1,u.length-1),o=!1,s="simple";if(c.endsWith("*")&&(o=!0,c=c.substring(0,c.length-1)),c.startsWith(".")?(s="label",c=c.substring(1)):c.startsWith(";")&&(s="matrix",c=c.substring(1)),!n||n[c]===void 0||n[c]===null)continue;const l=n[c];if(Array.isArray(l)){r=r.replace(u,bt(c,l,{style:s,explode:o}));continue}if(typeof l=="object"){r=r.replace(u,mt(c,l,{style:s,explode:o}));continue}if(s==="matrix"){r=r.replace(u,`;${Re(c,l)}`);continue}r=r.replace(u,s==="label"?`.${encodeURIComponent(l)}`:encodeURIComponent(l))}return r}function Bs(i){return i instanceof FormData?i:JSON.stringify(i)}function ks(i,n){var c;let r=`${n.baseUrl}${i}`;(c=n.params)!=null&&c.path&&(r=qs(r,n.params.path));let u=n.querySerializer(n.params.query??{});return u.startsWith("?")&&(u=u.substring(1)),u&&(r+=`?${u}`),r}function Hs(...i){const n=new Headers;for(const r of i){if(!r||typeof r!="object")continue;const u=r instanceof Headers?r.entries():Object.entries(r);for(const[c,o]of u)if(o===null)n.delete(c);else if(Array.isArray(o))for(const s of o)n.append(c,s);else o!==void 0&&n.set(c,o)}return n}function dt(i){return i.endsWith("/")?i.substring(0,i.length-1):i}const Ns=i=>{console.log(i.error)},Gs=i=>{const n=zs({baseUrl:i.baseUrl}),r={onRequest:i.onRequest,onResponse:i.onResponse,onError:i.onError||Ns};return n.use(r),n};class gt{constructor({config:n}){var c,o;this.userToken=null,this.constructClientOptions=s=>{const l=this.config.apiUrl||"https://api.open.cx",d={"X-Bot-Token":this.config.token,"Content-Type":"application/json",Accept:"application/json",Authorization:s?`Bearer ${s}`:void 0};return{baseUrl:l,headers:d}},this.createOpenAPIClient=({baseUrl:s,headers:l})=>Gs({baseUrl:s,onRequest:({request:d})=>{Object.entries(l).forEach(([y,g])=>{g&&d.headers.set(y,g)})}}),this.setAuthToken=s=>{this.userToken=s;const{baseUrl:l,headers:d}=this.constructClientOptions(s);this.client=this.createOpenAPIClient({baseUrl:l,headers:d})},this.getExternalWidgetConfig=async()=>await this.client.GET("/backend/widget/v2/config",{params:{header:{"X-Bot-Token":this.config.token}}}),this.widgetPrelude=async()=>await this.client.GET("/backend/widget/v2/prelude",{params:{header:{"X-Bot-Token":this.config.token}}}),this.sendMessage=async(s,l)=>await this.client.POST("/backend/widget/v2/chat/send",{body:s,signal:l}),this.createUnverifiedContact=async s=>await this.client.POST("/backend/widget/v2/contact/create-unverified",{params:{header:{"x-bot-token":this.config.token}},body:s}),this.createSession=async s=>await this.client.POST("/backend/widget/v2/create-session",{body:s}),this.pollSessionAndHistory=async({sessionId:s,lastMessageTimestamp:l,abortSignal:d})=>{const y=l?{lastMessageTimestamp:l}:void 0;return await this.client.GET("/backend/widget/v2/poll/{sessionId}",{params:{path:{sessionId:s},query:y},signal:d})},this.getSessions=async({cursor:s,filters:l,abortSignal:d})=>await this.client.GET("/backend/widget/v2/sessions",{params:{query:{cursor:s,filters:JSON.stringify(l)}},signal:d}),this.uploadFile=async({file:s,abortSignal:l,onProgress:d})=>new Promise((y,g)=>{var E;const p=new FormData;p.append("file",s);const f=new XMLHttpRequest;if(l&&(l.addEventListener("abort",()=>{f.abort(),g(new DOMException("Aborted","AbortError"))}),l.aborted)){g(new DOMException("Aborted","AbortError"));return}f.upload.addEventListener("progress",b=>{if(b.lengthComputable&&d){const I=Math.round(b.loaded/b.total*100);d(I)}}),f.addEventListener("load",()=>{if(f.status>=200&&f.status<300)try{const b=JSON.parse(f.responseText);y(b)}catch(b){g(new Error(`Failed to parse response: ${b}`))}else g(new Error(`Upload failed with status: ${f.status}`))}),f.addEventListener("error",()=>{g(new Error("Network error occurred"))}),f.addEventListener("timeout",()=>{g(new Error("Upload timed out"))});const{baseUrl:v}=this.constructClientOptions(this.userToken),j=`${v}/backend/widget/v2/upload`;f.open("POST",j),f.setRequestHeader("X-Bot-Token",this.config.token),this.userToken??((E=this.config.user)==null?void 0:E.token)?f.setRequestHeader("Authorization",`Bearer ${this.userToken}`):console.error("User token not set"),f.send(p)}),this.vote=async s=>await this.client.POST("/backend/widget/v2/chat/vote",{body:s}),this.resolveSession=async(s,l)=>await this.client.POST("/backend/widget/v2/session/resolve",{body:s,signal:l}),this.createStateCheckpoint=async s=>await this.client.POST("/backend/widget/v2/checkpoint",{body:s}),this.config=n,this.userToken=((c=n.user)==null?void 0:c.token)||null;const{baseUrl:r,headers:u}=this.constructClientOptions((o=n.user)==null?void 0:o.token);this.client=this.createOpenAPIClient({baseUrl:r,headers:u})}}var Pe={exports:{}};Pe.exports;(function(i,n){var r=200,u="__lodash_hash_undefined__",c=1,o=2,s=9007199254740991,l="[object Arguments]",d="[object Array]",y="[object AsyncFunction]",g="[object Boolean]",p="[object Date]",f="[object Error]",v="[object Function]",F="[object GeneratorFunction]",j="[object Map]",q="[object Number]",E="[object Null]",b="[object Object]",I="[object Promise]",ee="[object Proxy]",_="[object RegExp]",D="[object Set]",B="[object String]",le="[object Symbol]",fe="[object Undefined]",de="[object WeakMap]",te="[object ArrayBuffer]",N="[object DataView]",G="[object Float32Array]",T="[object Float64Array]",ge="[object Int8Array]",O="[object Int16Array]",U="[object Int32Array]",K="[object Uint8Array]",ue="[object Uint8ClampedArray]",se="[object Uint16Array]",Ct="[object Uint32Array]",wt=/[\\^$.*+?()[\]{}|]/g,vt=/^\[object .+?Constructor\]$/,xt=/^(?:0|[1-9]\d*)$/,S={};S[G]=S[T]=S[ge]=S[O]=S[U]=S[K]=S[ue]=S[se]=S[Ct]=!0,S[l]=S[d]=S[te]=S[g]=S[N]=S[p]=S[f]=S[v]=S[j]=S[q]=S[b]=S[_]=S[D]=S[B]=S[de]=!1;var ke=typeof Se=="object"&&Se&&Se.Object===Object&&Se,_t=typeof self=="object"&&self&&self.Object===Object&&self,W=ke||_t||Function("return this")(),He=n&&!n.nodeType&&n,Ne=He&&!0&&i&&!i.nodeType&&i,Ge=Ne&&Ne.exports===He,Ee=Ge&&ke.process,Ke=function(){try{return Ee&&Ee.binding&&Ee.binding("util")}catch{}}(),We=Ke&&Ke.isTypedArray;function Tt(e,t){for(var a=-1,h=e==null?0:e.length,C=0,m=[];++a<h;){var x=e[a];t(x,a,e)&&(m[C++]=x)}return m}function At(e,t){for(var a=-1,h=t.length,C=e.length;++a<h;)e[C+a]=t[a];return e}function It(e,t){for(var a=-1,h=e==null?0:e.length;++a<h;)if(t(e[a],a,e))return!0;return!1}function Pt(e,t){for(var a=-1,h=Array(e);++a<e;)h[a]=t(a);return h}function Rt(e){return function(t){return e(t)}}function Et(e,t){return e.has(t)}function Ot(e,t){return e==null?void 0:e[t]}function Ut(e){var t=-1,a=Array(e.size);return e.forEach(function(h,C){a[++t]=[C,h]}),a}function Mt(e,t){return function(a){return e(t(a))}}function jt(e){var t=-1,a=Array(e.size);return e.forEach(function(h){a[++t]=h}),a}var Dt=Array.prototype,Ft=Function.prototype,Ce=Object.prototype,Oe=W["__core-js_shared__"],Xe=Ft.toString,H=Ce.hasOwnProperty,Je=function(){var e=/[^.]+$/.exec(Oe&&Oe.keys&&Oe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Ye=Ce.toString,Lt=RegExp("^"+Xe.call(H).replace(wt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Qe=Ge?W.Buffer:void 0,we=W.Symbol,Ze=W.Uint8Array,Ve=Ce.propertyIsEnumerable,$t=Dt.splice,ne=we?we.toStringTag:void 0,et=Object.getOwnPropertySymbols,zt=Qe?Qe.isBuffer:void 0,qt=Mt(Object.keys,Object),Ue=he(W,"DataView"),pe=he(W,"Map"),Me=he(W,"Promise"),je=he(W,"Set"),De=he(W,"WeakMap"),ye=he(Object,"create"),Bt=ae(Ue),kt=ae(pe),Ht=ae(Me),Nt=ae(je),Gt=ae(De),tt=we?we.prototype:void 0,Fe=tt?tt.valueOf:void 0;function ie(e){var t=-1,a=e==null?0:e.length;for(this.clear();++t<a;){var h=e[t];this.set(h[0],h[1])}}function Kt(){this.__data__=ye?ye(null):{},this.size=0}function Wt(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}function Xt(e){var t=this.__data__;if(ye){var a=t[e];return a===u?void 0:a}return H.call(t,e)?t[e]:void 0}function Jt(e){var t=this.__data__;return ye?t[e]!==void 0:H.call(t,e)}function Yt(e,t){var a=this.__data__;return this.size+=this.has(e)?0:1,a[e]=ye&&t===void 0?u:t,this}ie.prototype.clear=Kt,ie.prototype.delete=Wt,ie.prototype.get=Xt,ie.prototype.has=Jt,ie.prototype.set=Yt;function X(e){var t=-1,a=e==null?0:e.length;for(this.clear();++t<a;){var h=e[t];this.set(h[0],h[1])}}function Qt(){this.__data__=[],this.size=0}function Zt(e){var t=this.__data__,a=xe(t,e);if(a<0)return!1;var h=t.length-1;return a==h?t.pop():$t.call(t,a,1),--this.size,!0}function Vt(e){var t=this.__data__,a=xe(t,e);return a<0?void 0:t[a][1]}function es(e){return xe(this.__data__,e)>-1}function ts(e,t){var a=this.__data__,h=xe(a,e);return h<0?(++this.size,a.push([e,t])):a[h][1]=t,this}X.prototype.clear=Qt,X.prototype.delete=Zt,X.prototype.get=Vt,X.prototype.has=es,X.prototype.set=ts;function re(e){var t=-1,a=e==null?0:e.length;for(this.clear();++t<a;){var h=e[t];this.set(h[0],h[1])}}function ss(){this.size=0,this.__data__={hash:new ie,map:new(pe||X),string:new ie}}function ns(e){var t=_e(this,e).delete(e);return this.size-=t?1:0,t}function is(e){return _e(this,e).get(e)}function rs(e){return _e(this,e).has(e)}function as(e,t){var a=_e(this,e),h=a.size;return a.set(e,t),this.size+=a.size==h?0:1,this}re.prototype.clear=ss,re.prototype.delete=ns,re.prototype.get=is,re.prototype.has=rs,re.prototype.set=as;function ve(e){var t=-1,a=e==null?0:e.length;for(this.__data__=new re;++t<a;)this.add(e[t])}function os(e){return this.__data__.set(e,u),this}function cs(e){return this.__data__.has(e)}ve.prototype.add=ve.prototype.push=os,ve.prototype.has=cs;function Q(e){var t=this.__data__=new X(e);this.size=t.size}function ls(){this.__data__=new X,this.size=0}function us(e){var t=this.__data__,a=t.delete(e);return this.size=t.size,a}function hs(e){return this.__data__.get(e)}function fs(e){return this.__data__.has(e)}function ds(e,t){var a=this.__data__;if(a instanceof X){var h=a.__data__;if(!pe||h.length<r-1)return h.push([e,t]),this.size=++a.size,this;a=this.__data__=new re(h)}return a.set(e,t),this.size=a.size,this}Q.prototype.clear=ls,Q.prototype.delete=us,Q.prototype.get=hs,Q.prototype.has=fs,Q.prototype.set=ds;function gs(e,t){var a=Te(e),h=!a&&Rs(e),C=!a&&!h&&Le(e),m=!a&&!h&&!C&&ut(e),x=a||h||C||m,A=x?Pt(e.length,String):[],P=A.length;for(var w in e)H.call(e,w)&&!(x&&(w=="length"||C&&(w=="offset"||w=="parent")||m&&(w=="buffer"||w=="byteLength"||w=="byteOffset")||_s(w,P)))&&A.push(w);return A}function xe(e,t){for(var a=e.length;a--;)if(at(e[a][0],t))return a;return-1}function ps(e,t,a){var h=t(e);return Te(e)?h:At(h,a(e))}function me(e){return e==null?e===void 0?fe:E:ne&&ne in Object(e)?vs(e):Ps(e)}function st(e){return be(e)&&me(e)==l}function nt(e,t,a,h,C){return e===t?!0:e==null||t==null||!be(e)&&!be(t)?e!==e&&t!==t:ys(e,t,a,h,nt,C)}function ys(e,t,a,h,C,m){var x=Te(e),A=Te(t),P=x?d:Z(e),w=A?d:Z(t);P=P==l?b:P,w=w==l?b:w;var L=P==b,k=w==b,M=P==w;if(M&&Le(e)){if(!Le(t))return!1;x=!0,L=!1}if(M&&!L)return m||(m=new Q),x||ut(e)?it(e,t,a,h,C,m):Cs(e,t,P,a,h,C,m);if(!(a&c)){var $=L&&H.call(e,"__wrapped__"),z=k&&H.call(t,"__wrapped__");if($||z){var V=$?e.value():e,J=z?t.value():t;return m||(m=new Q),C(V,J,a,h,m)}}return M?(m||(m=new Q),ws(e,t,a,h,C,m)):!1}function ms(e){if(!lt(e)||As(e))return!1;var t=ot(e)?Lt:vt;return t.test(ae(e))}function bs(e){return be(e)&&ct(e.length)&&!!S[me(e)]}function Ss(e){if(!Is(e))return qt(e);var t=[];for(var a in Object(e))H.call(e,a)&&a!="constructor"&&t.push(a);return t}function it(e,t,a,h,C,m){var x=a&c,A=e.length,P=t.length;if(A!=P&&!(x&&P>A))return!1;var w=m.get(e);if(w&&m.get(t))return w==t;var L=-1,k=!0,M=a&o?new ve:void 0;for(m.set(e,t),m.set(t,e);++L<A;){var $=e[L],z=t[L];if(h)var V=x?h(z,$,L,t,e,m):h($,z,L,e,t,m);if(V!==void 0){if(V)continue;k=!1;break}if(M){if(!It(t,function(J,oe){if(!Et(M,oe)&&($===J||C($,J,a,h,m)))return M.push(oe)})){k=!1;break}}else if(!($===z||C($,z,a,h,m))){k=!1;break}}return m.delete(e),m.delete(t),k}function Cs(e,t,a,h,C,m,x){switch(a){case N:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case te:return!(e.byteLength!=t.byteLength||!m(new Ze(e),new Ze(t)));case g:case p:case q:return at(+e,+t);case f:return e.name==t.name&&e.message==t.message;case _:case B:return e==t+"";case j:var A=Ut;case D:var P=h&c;if(A||(A=jt),e.size!=t.size&&!P)return!1;var w=x.get(e);if(w)return w==t;h|=o,x.set(e,t);var L=it(A(e),A(t),h,C,m,x);return x.delete(e),L;case le:if(Fe)return Fe.call(e)==Fe.call(t)}return!1}function ws(e,t,a,h,C,m){var x=a&c,A=rt(e),P=A.length,w=rt(t),L=w.length;if(P!=L&&!x)return!1;for(var k=P;k--;){var M=A[k];if(!(x?M in t:H.call(t,M)))return!1}var $=m.get(e);if($&&m.get(t))return $==t;var z=!0;m.set(e,t),m.set(t,e);for(var V=x;++k<P;){M=A[k];var J=e[M],oe=t[M];if(h)var ht=x?h(oe,J,M,t,e,m):h(J,oe,M,e,t,m);if(!(ht===void 0?J===oe||C(J,oe,a,h,m):ht)){z=!1;break}V||(V=M=="constructor")}if(z&&!V){var Ae=e.constructor,Ie=t.constructor;Ae!=Ie&&"constructor"in e&&"constructor"in t&&!(typeof Ae=="function"&&Ae instanceof Ae&&typeof Ie=="function"&&Ie instanceof Ie)&&(z=!1)}return m.delete(e),m.delete(t),z}function rt(e){return ps(e,Us,xs)}function _e(e,t){var a=e.__data__;return Ts(t)?a[typeof t=="string"?"string":"hash"]:a.map}function he(e,t){var a=Ot(e,t);return ms(a)?a:void 0}function vs(e){var t=H.call(e,ne),a=e[ne];try{e[ne]=void 0;var h=!0}catch{}var C=Ye.call(e);return h&&(t?e[ne]=a:delete e[ne]),C}var xs=et?function(e){return e==null?[]:(e=Object(e),Tt(et(e),function(t){return Ve.call(e,t)}))}:Ms,Z=me;(Ue&&Z(new Ue(new ArrayBuffer(1)))!=N||pe&&Z(new pe)!=j||Me&&Z(Me.resolve())!=I||je&&Z(new je)!=D||De&&Z(new De)!=de)&&(Z=function(e){var t=me(e),a=t==b?e.constructor:void 0,h=a?ae(a):"";if(h)switch(h){case Bt:return N;case kt:return j;case Ht:return I;case Nt:return D;case Gt:return de}return t});function _s(e,t){return t=t??s,!!t&&(typeof e=="number"||xt.test(e))&&e>-1&&e%1==0&&e<t}function Ts(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function As(e){return!!Je&&Je in e}function Is(e){var t=e&&e.constructor,a=typeof t=="function"&&t.prototype||Ce;return e===a}function Ps(e){return Ye.call(e)}function ae(e){if(e!=null){try{return Xe.call(e)}catch{}try{return e+""}catch{}}return""}function at(e,t){return e===t||e!==e&&t!==t}var Rs=st(function(){return arguments}())?st:function(e){return be(e)&&H.call(e,"callee")&&!Ve.call(e,"callee")},Te=Array.isArray;function Es(e){return e!=null&&ct(e.length)&&!ot(e)}var Le=zt||js;function Os(e,t){return nt(e,t)}function ot(e){if(!lt(e))return!1;var t=me(e);return t==v||t==F||t==y||t==ee}function ct(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=s}function lt(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}function be(e){return e!=null&&typeof e=="object"}var ut=We?Rt(We):bs;function Us(e){return Es(e)?gs(e):Ss(e)}function Ms(){return[]}function js(){return!1}i.exports=Os})(Pe,Pe.exports);var Ks=Pe.exports;const Ws=yt(Ks);class ce{constructor(n){this.subscribers=new Set,this.get=()=>this.state,this.set=r=>{Ws(this.state,r)||(this.state=r,this.notifySubscribers(r))},this.setPartial=r=>{if(r==null)return;const u={...this.state,...r};this.set(u)},this.reset=()=>{this.set(this.initialState)},this.notifySubscribers=r=>{Array.from(this.subscribers).forEach(c=>{try{c(r)}catch(o){console.error(o)}})},this.subscribe=r=>(this.subscribers.add(r),()=>{this.subscribers.delete(r)}),this.state=n,this.initialState=n}}class St{constructor(){this.state=new ce({isPolling:!1,isError:!1}),this.abortController=new AbortController,this.reset=()=>{var n;this.abortController.abort("Resetting poller"),(n=this.stopPolling)==null||n.call(this),this.stopPolling=null},this.stopPolling=null,this.startPolling=(n,r)=>{if(this.stopPolling)return;const u=[],c=async()=>{this.abortController=new AbortController,this.state.setPartial({isPolling:!0});try{await n(this.abortController.signal)}catch(o){if(this.abortController.signal.aborted)return;console.error("Failed to poll:",o),this.state.setPartial({isError:!0})}finally{this.state.setPartial({isPolling:!1})}this.abortController.signal.aborted?console.log("Poller aborted, not scheduling anymore"):u.push(setTimeout(c,r))};c(),this.stopPolling=()=>{u.forEach(clearTimeout),this.state.reset()}}}}function Xs(i){try{const n=i();return n instanceof Promise?n.then(r=>({data:r})).catch(r=>({error:r})):{data:n}}catch(n){return{error:n}}}class Js{constructor({api:n,config:r,sessionCtx:u,messageCtx:c,sessionPollingIntervalSeconds:o}){this.poller=new St,this.registerPolling=()=>{this.sessionCtx.sessionState.subscribe(({session:s})=>{s!=null&&s.id?this.poller.startPolling(async l=>{this.hackAndSlash(s.id,l)},this.sessionPollingIntervalSeconds*1e3):this.poller.reset()})},this.hackAndSlash=async(s,l)=>{var p;this.messageCtx.state.get().messages.length===0&&this.messageCtx.state.setPartial({isInitialFetchLoading:!0});const d=this.messageCtx.state.get().messages,y=d.length>0?(p=d[d.length-1])==null?void 0:p.timestamp:void 0,{data:g}=await this.api.pollSessionAndHistory({sessionId:s,abortSignal:l,lastMessageTimestamp:y});if(g!=null&&g.session&&(this.sessionCtx.sessionState.setPartial({session:g.session}),this.sessionCtx.setSessions([g.session])),g!=null&&g.history&&g.history.length>0){const f=this.messageCtx.state.get().messages,v=g.history.map(this.mapHistoryToMessage).filter(F=>!f.some(j=>j.id===F.id));this.messageCtx.state.setPartial({messages:[...f,...v]})}this.messageCtx.state.get().isInitialFetchLoading&&this.messageCtx.state.setPartial({isInitialFetchLoading:!1})},this.mapHistoryToMessage=s=>{var y,g;const l={id:s.publicId,timestamp:s.sentAt||"",attachments:s.attachments||void 0};if(s.sender.kind==="user")return{...l,type:"FROM_USER",content:s.content.text||"",deliveredAt:s.sentAt||""};if(s.sender.kind==="agent")return{...l,type:"FROM_AGENT",component:"agent_message",data:{message:s.content.text||""},agent:{name:s.sender.name||"",avatar:s.sender.avatar||"",id:null,isAi:!1}};const d=s.actionCalls&&s.actionCalls.length>0?s.actionCalls[s.actionCalls.length-1]:void 0;return{...l,type:"FROM_BOT",component:"bot_message",agent:{id:null,name:((y=this.config.bot)==null?void 0:y.name)||"",isAi:!0,avatar:((g=this.config.bot)==null?void 0:g.avatar)||""},data:{message:s.content.text||"",action:d?{name:d.actionName,data:this.extractActionResult(d)}:void 0}}},this.extractActionResult=s=>{const l=s.result;if(l===null||typeof l!="object")return l;if("responseBodyText"in l&&typeof l.responseBodyText=="string"){const d=l.responseBodyText,y=Xs(()=>JSON.parse(d)).data;if(y)return y}return s.result},this.api=n,this.config=r,this.sessionCtx=u,this.messageCtx=c,this.sessionPollingIntervalSeconds=o,this.registerPolling()}}const R=[];for(let i=0;i<256;++i)R.push((i+256).toString(16).slice(1));function Ys(i,n=0){return(R[i[n+0]]+R[i[n+1]]+R[i[n+2]]+R[i[n+3]]+"-"+R[i[n+4]]+R[i[n+5]]+"-"+R[i[n+6]]+R[i[n+7]]+"-"+R[i[n+8]]+R[i[n+9]]+"-"+R[i[n+10]]+R[i[n+11]]+R[i[n+12]]+R[i[n+13]]+R[i[n+14]]+R[i[n+15]]).toLowerCase()}let $e;const Qs=new Uint8Array(16);function Zs(){if(!$e){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");$e=crypto.getRandomValues.bind(crypto)}return $e(Qs)}const Vs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),pt={randomUUID:Vs};function Be(i,n,r){var c;if(pt.randomUUID&&!n&&!i)return pt.randomUUID();i=i||{};const u=i.random??((c=i.rng)==null?void 0:c.call(i))??Zs();if(u.length<16)throw new Error("Random bytes length must be >= 16");return u[6]=u[6]&15|64,u[8]=u[8]&63|128,Ys(u)}class en{constructor({config:n,api:r,storageCtx:u}){var c;this.shouldCollectData=()=>{var o;return!!(!((o=this.state.get().contact)!=null&&o.token)&&this.config.collectUserData)},this.autoCreateUnverifiedUserIfNotExists=async()=>{var o,s,l,d,y,g,p,f,v,F,j,q,E,b;if(!((o=this.config.user)!=null&&o.token)){if(this.config.collectUserData&&!((l=(s=this.config.user)==null?void 0:s.data)!=null&&l.email)){if((d=this.config.extraDataCollectionFields)!=null&&d.length)return;const I=await((y=this.storageCtx)==null?void 0:y.getContactToken());I&&await this.setUnverifiedContact(I);return}if(!((p=(g=this.config.user)==null?void 0:g.data)!=null&&p.email)){const I=await((f=this.storageCtx)==null?void 0:f.getContactToken());if(I){await this.setUnverifiedContact(I);return}}await this.createUnverifiedContact({email:(F=(v=this.config.user)==null?void 0:v.data)==null?void 0:F.email,non_verified_name:((q=(j=this.config.user)==null?void 0:j.data)==null?void 0:q.name)||"Anonymous",non_verified_custom_data:(b=(E=this.config.user)==null?void 0:E.data)==null?void 0:b.customData})}},this.createUnverifiedContact=async(o,s)=>{this.state.setPartial({extraCollectedData:s});try{this.state.setPartial({isCreatingUnverifiedContact:!0,isErrorCreatingUnverifiedContact:!1});const{data:l}=await this.api.createUnverifiedContact(o);l!=null&&l.token?await this.setUnverifiedContact(l.token):this.state.setPartial({isErrorCreatingUnverifiedContact:!0})}finally{this.state.setPartial({isCreatingUnverifiedContact:!1})}},this.setUnverifiedContact=async o=>{var d,y,g,p;const s=await((d=this.storageCtx)==null?void 0:d.getExternalContactId()),l=((y=this.config.user)==null?void 0:y.externalId)||s||Be();this.api.setAuthToken(o),await((g=this.storageCtx)==null?void 0:g.setContactToken(o)),await((p=this.storageCtx)==null?void 0:p.setExternalContactId(l)),this.state.setPartial({contact:{token:o,externalId:l}})},this.config=n,this.storageCtx=u,this.api=r,this.state=new ce({contact:(c=n.user)!=null&&c.token?{token:n.user.token,externalId:n.user.externalId}:null,extraCollectedData:void 0,isCreatingUnverifiedContact:!1,isErrorCreatingUnverifiedContact:!1}),this.autoCreateUnverifiedUserIfNotExists()}}function ze(){return Be()}class tn{constructor({api:n,contactCtx:r,sessionsPollingIntervalSeconds:u}){this.sessionsRefresher=new St,this.sessionState=new ce({session:null,isCreatingSession:!1,isResolvingSession:!1}),this.sessionsState=new ce({data:[],cursor:void 0,isLastPage:!1,didStartInitialFetch:!1,isInitialFetchLoading:!0}),this.reset=async()=>{this.sessionState.reset()},this.registerSessionsRefresherWrapper=()=>{var c;(c=this.contactCtx.state.get().contact)!=null&&c.token&&!this.sessionsState.get().didStartInitialFetch?this.registerSessionsRefresher():this.contactCtx.state.subscribe(({contact:o})=>{o!=null&&o.token&&!this.sessionsState.get().didStartInitialFetch&&this.registerSessionsRefresher()})},this.registerSessionsRefresher=()=>{this.sessionsRefresher.startPolling(async()=>{this.sessionsState.get().didStartInitialFetch===!1&&this.sessionsState.setPartial({didStartInitialFetch:!0}),await this.refreshSessions(),this.sessionsState.get().isInitialFetchLoading===!0&&this.sessionsState.setPartial({isInitialFetchLoading:!1})},this.sessionsPollingIntervalSeconds*1e3)},this.createSession=async()=>{var l;this.sessionState.setPartial({session:null,isCreatingSession:!0});const c=(l=this.contactCtx.state.get().contact)==null?void 0:l.externalId,{data:o,error:s}=await this.api.createSession({customData:c?{external_id:c}:void 0});return o?(this.sessionState.setPartial({session:o,isCreatingSession:!1}),o):(this.sessionState.setPartial({isCreatingSession:!1}),console.error("Failed to create session:",s),null)},this.loadMoreSessions=async()=>{if(this.sessionsState.get().isLastPage)return;const{data:c}=await this.getSessions({cursor:this.sessionsState.get().cursor});if(c){const s=[...this.sessionsState.get().data,...c.items].filter((l,d,y)=>d===y.findIndex(g=>l.id===g.id));this.sessionsState.setPartial({data:s,cursor:c.next||void 0,isLastPage:c.next===null})}},this.getSessions=async({cursor:c})=>{var s,l;if(!((s=this.contactCtx.state.get().contact)!=null&&s.token))return{data:null};const o=(l=this.contactCtx.state.get().contact)==null?void 0:l.externalId;return await this.api.getSessions({cursor:c,filters:o?{external_id:o}:{}})},this.setSessions=c=>{const o=[...c,...this.sessionsState.get().data].filter((s,l,d)=>l===d.findIndex(y=>s.id===y.id));this.sessionsState.setPartial({data:o})},this.refreshSessions=async()=>{const{data:c}=await this.getSessions({cursor:void 0});c&&this.setSessions(c.items)},this.resolveSession=async()=>{const c=this.sessionState.get().session;if(!c||!c.isOpened)return{success:!1,error:"Session is not opened"};this.sessionState.setPartial({isResolvingSession:!0});const{data:o,error:s}=await this.api.resolveSession({session_id:c.id});return o?(this.sessionState.setPartial({session:o,isResolvingSession:!1}),{success:!0,data:o}):(this.sessionState.setPartial({isResolvingSession:!1}),{success:!1,error:s})},this.createStateCheckpoint=async c=>{var d;const o=(d=this.sessionState.get().session)==null?void 0:d.id;if(!o)return;const{data:s,error:l}=await this.api.createStateCheckpoint({session_id:o,payload:c});return s?{data:s}:{success:!1,error:l}},this.api=n,this.contactCtx=r,this.sessionsPollingIntervalSeconds=u,this.registerSessionsRefresherWrapper()}}class sn{constructor({config:n,api:r,sessionCtx:u,contactCtx:c}){this.state=new ce({messages:[],isSendingMessage:!1,lastAIResMightSolveUserIssue:!1,isInitialFetchLoading:!1}),this.sendMessageAbortController=new AbortController,this.reset=()=>{this.sendMessageAbortController.abort("Resetting chat"),this.state.reset()},this.sendMessage=async o=>{var g,p,f,v,F,j,q,E;if(!o.content.trim()&&(!o.attachments||o.attachments.length===0)){console.warn("Cannot send an empty message of no content or attachments");return}const s=this.state.get().isSendingMessage,l=((g=this.sessionCtx.sessionState.get().session)==null?void 0:g.assignee.kind)==="ai",d=this.state.get().messages,y=d.length>0?d[d.length-1]:void 0;if(l&&s||l&&(y==null?void 0:y.type)==="FROM_USER"){console.warn("Cannot send messages while awaiting AI response");return}this.sendMessageAbortController=new AbortController,this.state.setPartial({lastAIResMightSolveUserIssue:!1});try{this.state.setPartial({isSendingMessage:!0});const b=this.toUserMessage(o.content.trim(),o.attachments||void 0),I=this.state.get().messages;if(this.state.setPartial({messages:[...I,b]}),!((p=this.sessionCtx.sessionState.get().session)!=null&&p.id)){if(!await this.sessionCtx.createSession()){console.error("Failed to create session");return}this.sessionCtx.refreshSessions()}const ee=(f=this.sessionCtx.sessionState.get().session)==null?void 0:f.id;if(!ee)return;const{data:_}=await this.api.sendMessage({uuid:b.id,bot_token:this.config.token,headers:this.config.headers,query_params:this.config.queryParams,body_properties:this.config.bodyProperties,session_id:ee,content:b.content,attachments:o.attachments,clientContext:this.config.context,custom_data:{...this.config.messageCustomData||{},...o.customData||{}},language:this.config.language,exit_mode_prompt:o.exitModePrompt},this.sendMessageAbortController.signal);if(_!=null&&_.success){const D=this.toBotMessage(_);if(D){const B=this.state.get().messages;if(!!B.some(fe=>fe.id===D.id)){this.state.setPartial({lastAIResMightSolveUserIssue:((v=_.autopilotResponse)==null?void 0:v.mightSolveUserIssue)||((F=_.uiResponse)==null?void 0:F.mightSolveUserIssue)});return}this.state.setPartial({messages:[...B,D],lastAIResMightSolveUserIssue:((j=_.autopilotResponse)==null?void 0:j.mightSolveUserIssue)||((q=_.uiResponse)==null?void 0:q.mightSolveUserIssue)})}_.session&&this.sessionCtx.sessionState.setPartial({session:_.session})}else{const D=this.toBotErrorMessage(((E=_==null?void 0:_.error)==null?void 0:E.message)||"Unknown error occurred"),B=this.state.get().messages;this.state.setPartial({messages:[...B,D]})}}catch(b){this.sendMessageAbortController.signal.aborted||console.error("Failed to send message:",b)}finally{this.state.setPartial({isSendingMessage:!1})}},this.toUserMessage=(o,s)=>{const l=(()=>{const d=this.contactCtx.state.get().extraCollectedData;return this.state.get().messages.length===0&&d&&Object.keys(d).length>0?`${Object.entries(d).filter(([g,p])=>!!p).map(([g,p])=>`${g}: ${p}`).join(`
|
|
2
|
+
`)}
|
|
3
|
+
|
|
4
|
+
${o}`:o})();return{id:ze(),type:"FROM_USER",content:l,deliveredAt:new Date().toISOString(),attachments:s,timestamp:new Date().toISOString()}},this.toBotMessage=o=>{var s;return o.success&&o.autopilotResponse?{type:"FROM_BOT",id:o.autopilotResponse.id||ze(),timestamp:new Date().toISOString(),component:"bot_message",agent:this.config.bot?{name:this.config.bot.name||"",isAi:!0,avatar:this.config.bot.avatar||"",id:null}:void 0,data:{message:o.autopilotResponse.value.content,action:(s=o.uiResponse)!=null&&s.value.name?{name:o.uiResponse.value.name,data:o.uiResponse.value.request_response}:void 0}}:null},this.toBotErrorMessage=o=>({type:"FROM_BOT",id:ze(),timestamp:new Date().toISOString(),component:"TEXT",data:{message:o,variant:"error",action:void 0}}),this.config=n,this.api=r,this.sessionCtx=u,this.contactCtx=c}}class nn{constructor({config:n,contactCtx:r,sessionCtx:u,resetChat:c}){var o;this.registerRoutingListener=()=>{this.contactCtx.state.subscribe(({contact:s})=>{var l;s!=null&&s.token&&this.state.get().screen==="welcome"&&this.state.setPartial({screen:(l=this.config.router)!=null&&l.chatScreenOnly?"chat":"sessions"})}),this.sessionCtx.sessionsState.subscribe(({isInitialFetchLoading:s,data:l})=>{var d,y,g,p;if((d=this.config.router)!=null&&d.chatScreenOnly&&!((y=this.sessionCtx.sessionState.get().session)!=null&&y.id)){const f=(g=l.find(v=>v.isOpened))==null?void 0:g.id;return f?this.toChatScreen(f):void 0}l.length||((p=this.config.router)==null?void 0:p.goToChatIfNoSessions)!==!1&&!s&&this.state.get().screen!=="chat"&&this.toChatScreen()})},this.toSessionsScreen=()=>{this.resetChat(),this.state.setPartial({screen:"sessions"})},this.toChatScreen=s=>{if(this.resetChat(),s){const l=this.sessionCtx.sessionsState.get().data.find(d=>d.id===s);if(!l)return;this.sessionCtx.sessionState.setPartial({session:l})}this.state.setPartial({screen:"chat"})},this.config=n,this.contactCtx=r,this.sessionCtx=u,this.resetChat=c,this.state=new ce({screen:this.contactCtx.shouldCollectData()?"welcome":(o=this.config.router)!=null&&o.chatScreenOnly?"chat":"sessions"}),this.registerRoutingListener()}}class rn{constructor({storage:n}){this.KEYS={contactToken:"opencx__widget__contactToken",externalContactId:"opencx__widget__externalContactId"},this.setContactToken=async r=>{await this.storage.set(this.KEYS.contactToken,r)},this.getContactToken=async()=>this.storage.get(this.KEYS.contactToken),this.setExternalContactId=async r=>{await this.storage.set(this.KEYS.externalContactId,r)},this.getExternalContactId=async()=>this.storage.get(this.KEYS.externalContactId),this.storage=n}}const Y=class Y{constructor({config:n,storage:r,modes:u}){if(this.modes=[],this.resetChat=()=>{this.sessionCtx.reset(),this.messageCtx.reset()},!Y.pollingIntervalsSeconds)throw Error("Widget polling values are not defined, did you call WidgetCtx.initialize()");this.config=n,this.api=new gt({config:n}),this.storageCtx=r?new rn({storage:r}):void 0,this.modes=u,this.contactCtx=new en({api:this.api,config:this.config,storageCtx:this.storageCtx}),this.sessionCtx=new tn({api:this.api,contactCtx:this.contactCtx,sessionsPollingIntervalSeconds:Y.pollingIntervalsSeconds.sessions}),this.messageCtx=new sn({config:this.config,api:this.api,sessionCtx:this.sessionCtx,contactCtx:this.contactCtx}),this.activeSessionPollingCtx=new Js({api:this.api,config:this.config,sessionCtx:this.sessionCtx,messageCtx:this.messageCtx,sessionPollingIntervalSeconds:Y.pollingIntervalsSeconds.session}),this.routerCtx=new nn({config:this.config,contactCtx:this.contactCtx,sessionCtx:this.sessionCtx,resetChat:this.resetChat})}};Y.pollingIntervalsSeconds=null,Y.initialize=async({config:n,storage:r})=>{var c,o,s;const u=await new gt({config:n}).getExternalWidgetConfig();return Y.pollingIntervalsSeconds={session:((c=u.data)==null?void 0:c.sessionPollingIntervalSeconds)||10,sessions:((o=u.data)==null?void 0:o.sessionsPollingIntervalSeconds)||60},new Y({config:n,storage:r,modes:((s=u.data)==null?void 0:s.modes)||[]})};let qe=Y;exports.PrimitiveState=ce;exports.WidgetCtx=qe;exports.commonjsGlobal=Se;exports.getAugmentedNamespace=Ds;exports.getDefaultExportFromCjs=yt;exports.v4=Be;
|
|
5
|
+
//# sourceMappingURL=widget.ctx-RfaE5VPy.cjs.map
|