@opencx/widget-core 4.0.8 → 4.0.10

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.
@@ -184,6 +184,11 @@ export declare const TestUtils: {
184
184
  [key: string]: unknown;
185
185
  } | null;
186
186
  exit_mode_prompt?: string;
187
+ action_form_submitted_prompt?: string;
188
+ initial_messages?: {
189
+ uuid: string;
190
+ content: string;
191
+ }[];
187
192
  };
188
193
  signal: AbortSignal | undefined;
189
194
  }, `${string}/${string}`>> | undefined): void;
@@ -141,6 +141,11 @@ export declare class ApiCaller {
141
141
  [key: string]: unknown;
142
142
  } | null;
143
143
  exit_mode_prompt?: string;
144
+ action_form_submitted_prompt?: string;
145
+ initial_messages?: {
146
+ uuid: string;
147
+ content: string;
148
+ }[];
144
149
  };
145
150
  signal: AbortSignal | undefined;
146
151
  }, `${string}/${string}`>>;
@@ -147,6 +147,22 @@ export interface paths {
147
147
  patch?: never;
148
148
  trace?: never;
149
149
  };
150
+ '/backend/widget/v2/upload/v2': {
151
+ parameters: {
152
+ query?: never;
153
+ header?: never;
154
+ path?: never;
155
+ cookie?: never;
156
+ };
157
+ get?: never;
158
+ put?: never;
159
+ post: operations['uploadFileV2'];
160
+ delete?: never;
161
+ options?: never;
162
+ head?: never;
163
+ patch?: never;
164
+ trace?: never;
165
+ };
150
166
  '/backend/widget/v2/chat/vote': {
151
167
  parameters: {
152
168
  query?: never;
@@ -195,6 +211,22 @@ export interface paths {
195
211
  patch?: never;
196
212
  trace?: never;
197
213
  };
214
+ '/backend/widget/v2/action/execute': {
215
+ parameters: {
216
+ query?: never;
217
+ header?: never;
218
+ path?: never;
219
+ cookie?: never;
220
+ };
221
+ get?: never;
222
+ put?: never;
223
+ post: operations['executeAction'];
224
+ delete?: never;
225
+ options?: never;
226
+ head?: never;
227
+ patch?: never;
228
+ trace?: never;
229
+ };
198
230
  }
199
231
  export type webhooks = Record<string, never>;
200
232
  export interface components {
@@ -245,6 +277,30 @@ export interface components {
245
277
  fileName: string;
246
278
  fileUrl: string;
247
279
  };
280
+ WidgetActionFormSubmissionInputDto: {
281
+ sessionId: string;
282
+ formMessageId: string;
283
+ actionId: string;
284
+ request: {
285
+ queryParams?: {
286
+ [key: string]: string;
287
+ };
288
+ pathParams?: {
289
+ [key: string]: string;
290
+ };
291
+ bodyParams?: {
292
+ [key: string]: unknown;
293
+ };
294
+ headers?: {
295
+ [key: string]: string;
296
+ };
297
+ };
298
+ };
299
+ WidgetActionFormSubmissionOutputDto: {
300
+ action: {
301
+ response?: unknown;
302
+ };
303
+ };
248
304
  WidgetConfigDto: {
249
305
  sessionsPollingIntervalSeconds: number;
250
306
  sessionPollingIntervalSeconds: number;
@@ -285,6 +341,18 @@ export interface components {
285
341
  actionName: string;
286
342
  args?: unknown;
287
343
  result?: unknown;
344
+ action: {
345
+ name: string;
346
+ id: string;
347
+ openapi?: {
348
+ openapi_spec_id?: string;
349
+ operation_spec?: unknown;
350
+ operation_id?: string;
351
+ operation_method?: string;
352
+ };
353
+ metadata?: unknown;
354
+ required_form_submission?: boolean;
355
+ };
288
356
  }[] | null;
289
357
  attachments?: {
290
358
  id: string;
@@ -377,6 +445,12 @@ export interface components {
377
445
  } | null;
378
446
  /** @description If there is an active mode, it will be exited and the prompt will be given to the AI for a customized response */
379
447
  exit_mode_prompt?: string;
448
+ /** @description A prompt to be given to the AI for a customized response, should be used after an action form is submitted */
449
+ action_form_submitted_prompt?: string;
450
+ initial_messages?: {
451
+ uuid: string;
452
+ content: string;
453
+ }[];
380
454
  };
381
455
  WidgetSendMessageOutputDto: {
382
456
  /** @enum {boolean} */
@@ -411,6 +485,18 @@ export interface components {
411
485
  };
412
486
  mightSolveUserIssue: boolean;
413
487
  };
488
+ formSubmission?: {
489
+ name: string;
490
+ id: string;
491
+ openapi?: {
492
+ openapi_spec_id?: string;
493
+ operation_spec?: unknown;
494
+ operation_id?: string;
495
+ operation_method?: string;
496
+ };
497
+ metadata?: unknown;
498
+ required_form_submission?: boolean;
499
+ };
414
500
  sessionIsHandedOff?: boolean;
415
501
  /** @description WidgetSession */
416
502
  session?: {
@@ -483,6 +569,18 @@ export interface components {
483
569
  actionName: string;
484
570
  args?: unknown;
485
571
  result?: unknown;
572
+ action: {
573
+ name: string;
574
+ id: string;
575
+ openapi?: {
576
+ openapi_spec_id?: string;
577
+ operation_spec?: unknown;
578
+ operation_id?: string;
579
+ operation_method?: string;
580
+ };
581
+ metadata?: unknown;
582
+ required_form_submission?: boolean;
583
+ };
486
584
  }[] | null;
487
585
  attachments?: {
488
586
  id: string;
@@ -827,6 +925,39 @@ export interface operations {
827
925
  };
828
926
  };
829
927
  };
928
+ uploadFileV2: {
929
+ parameters: {
930
+ query?: never;
931
+ header?: never;
932
+ path?: never;
933
+ cookie?: never;
934
+ };
935
+ /** @description The file to upload */
936
+ requestBody: {
937
+ content: {
938
+ 'multipart/form-data': components['schemas']['FileUploadDto'];
939
+ };
940
+ };
941
+ responses: {
942
+ 200: {
943
+ headers: {
944
+ [name: string]: unknown;
945
+ };
946
+ content: {
947
+ 'application/json': components['schemas']['UploadWidgetFileResponseDto'];
948
+ };
949
+ };
950
+ /** @description Internal Server Error */
951
+ 500: {
952
+ headers: {
953
+ [name: string]: unknown;
954
+ };
955
+ content: {
956
+ 'application/json': components['schemas']['ErrorDto'];
957
+ };
958
+ };
959
+ };
960
+ };
830
961
  voteMessage: {
831
962
  parameters: {
832
963
  query?: never;
@@ -925,4 +1056,36 @@ export interface operations {
925
1056
  };
926
1057
  };
927
1058
  };
1059
+ executeAction: {
1060
+ parameters: {
1061
+ query?: never;
1062
+ header?: never;
1063
+ path?: never;
1064
+ cookie?: never;
1065
+ };
1066
+ requestBody: {
1067
+ content: {
1068
+ 'application/json': components['schemas']['WidgetActionFormSubmissionInputDto'];
1069
+ };
1070
+ };
1071
+ responses: {
1072
+ 200: {
1073
+ headers: {
1074
+ [name: string]: unknown;
1075
+ };
1076
+ content: {
1077
+ 'application/json': components['schemas']['WidgetActionFormSubmissionOutputDto'];
1078
+ };
1079
+ };
1080
+ /** @description Internal Server Error */
1081
+ 500: {
1082
+ headers: {
1083
+ [name: string]: unknown;
1084
+ };
1085
+ content: {
1086
+ 'application/json': components['schemas']['ErrorDto'];
1087
+ };
1088
+ };
1089
+ };
1090
+ };
928
1091
  }
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=require("openapi-fetch"),O=require("lodash.isequal"),U=require("uuid"),F=d=>{console.log(d.error)},D=d=>{const n=M({baseUrl:d.baseUrl}),o={onRequest:d.onRequest,onResponse:d.onResponse,onError:d.onError||F};return n.use(o),n};class E{constructor({config:n}){var g,e;this.userToken=null,this.constructClientOptions=t=>{const s=this.config.apiUrl||"https://api.open.cx",i={"X-Bot-Token":this.config.token,"Content-Type":"application/json",Accept:"application/json",Authorization:t?`Bearer ${t}`:void 0};return{baseUrl:s,headers:i}},this.createOpenAPIClient=({baseUrl:t,headers:s})=>D({baseUrl:t,onRequest:({request:i})=>{Object.entries(s).forEach(([r,a])=>{a&&i.headers.set(r,a)})}}),this.setAuthToken=t=>{this.userToken=t;const{baseUrl:s,headers:i}=this.constructClientOptions(t);this.client=this.createOpenAPIClient({baseUrl:s,headers:i})},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(t,s)=>await this.client.POST("/backend/widget/v2/chat/send",{body:t,signal:s}),this.createUnverifiedContact=async t=>await this.client.POST("/backend/widget/v2/contact/create-unverified",{params:{header:{"x-bot-token":this.config.token}},body:t}),this.createSession=async t=>await this.client.POST("/backend/widget/v2/create-session",{body:t}),this.pollSessionAndHistory=async({sessionId:t,lastMessageTimestamp:s,abortSignal:i})=>{const r=s?{lastMessageTimestamp:s}:void 0;return await this.client.GET("/backend/widget/v2/poll/{sessionId}",{params:{path:{sessionId:t},query:r},signal:i})},this.getSessions=async({cursor:t,filters:s,abortSignal:i})=>await this.client.GET("/backend/widget/v2/sessions",{params:{query:{cursor:t,filters:JSON.stringify(s)}},signal:i}),this.uploadFile=async({file:t,abortSignal:s,onProgress:i})=>new Promise((r,a)=>{var m;const h=new FormData;h.append("file",t);const l=new XMLHttpRequest;if(s&&(s.addEventListener("abort",()=>{l.abort(),a(new DOMException("Aborted","AbortError"))}),s.aborted)){a(new DOMException("Aborted","AbortError"));return}l.upload.addEventListener("progress",u=>{if(u.lengthComputable&&i){const x=Math.round(u.loaded/u.total*100);i(x)}}),l.addEventListener("load",()=>{if(l.status>=200&&l.status<300)try{const u=JSON.parse(l.responseText);r(u)}catch(u){a(new Error(`Failed to parse response: ${u}`))}else a(new Error(`Upload failed with status: ${l.status}`))}),l.addEventListener("error",()=>{a(new Error("Network error occurred"))}),l.addEventListener("timeout",()=>{a(new Error("Upload timed out"))});const{baseUrl:C}=this.constructClientOptions(this.userToken),p=`${C}/backend/widget/v2/upload`;l.open("POST",p),l.setRequestHeader("X-Bot-Token",this.config.token),this.userToken??((m=this.config.user)==null?void 0:m.token)?l.setRequestHeader("Authorization",`Bearer ${this.userToken}`):console.error("User token not set"),l.send(h)}),this.vote=async t=>await this.client.POST("/backend/widget/v2/chat/vote",{body:t}),this.resolveSession=async(t,s)=>await this.client.POST("/backend/widget/v2/session/resolve",{body:t,signal:s}),this.createStateCheckpoint=async t=>await this.client.POST("/backend/widget/v2/checkpoint",{body:t}),this.config=n,this.userToken=((g=n.user)==null?void 0:g.token)||null;const{baseUrl:o,headers:c}=this.constructClientOptions((e=n.user)==null?void 0:e.token);this.client=this.createOpenAPIClient({baseUrl:o,headers:c})}}class w{constructor(n){this.subscribers=new Set,this.get=()=>this.state,this.set=o=>{O(this.state,o)||(this.state=o,this.notifySubscribers(o))},this.setPartial=o=>{if(o==null)return;const c={...this.state,...o};this.set(c)},this.reset=()=>{this.set(this.initialState)},this.notifySubscribers=o=>{Array.from(this.subscribers).forEach(g=>{try{g(o)}catch(e){console.error(e)}})},this.subscribe=o=>(this.subscribers.add(o),()=>{this.subscribers.delete(o)}),this.state=n,this.initialState=n}}class R{constructor(){this.state=new w({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,o)=>{if(this.stopPolling)return;const c=[],g=async()=>{this.abortController=new AbortController,this.state.setPartial({isPolling:!0});try{await n(this.abortController.signal)}catch(e){if(this.abortController.signal.aborted)return;console.error("Failed to poll:",e),this.state.setPartial({isError:!0})}finally{this.state.setPartial({isPolling:!1})}this.abortController.signal.aborted?console.log("Poller aborted, not scheduling anymore"):c.push(setTimeout(g,o))};g(),this.stopPolling=()=>{c.forEach(clearTimeout),this.state.reset()}}}}function _(d){try{const n=d();return n instanceof Promise?n.then(o=>({data:o})).catch(o=>({error:o})):{data:n}}catch(n){return{error:n}}}class L{constructor({api:n,config:o,sessionCtx:c,messageCtx:g,sessionPollingIntervalSeconds:e}){this.poller=new R,this.registerPolling=()=>{this.sessionCtx.sessionState.subscribe(({session:t})=>{t!=null&&t.id?this.poller.startPolling(async s=>{this.hackAndSlash(t.id,s)},this.sessionPollingIntervalSeconds*1e3):this.poller.reset()})},this.hackAndSlash=async(t,s)=>{var h;this.messageCtx.state.get().messages.length===0&&this.messageCtx.state.setPartial({isInitialFetchLoading:!0});const i=this.messageCtx.state.get().messages,r=i.length>0?((h=i[i.length-1])==null?void 0:h.timestamp)??void 0:void 0,{data:a}=await this.api.pollSessionAndHistory({sessionId:t,abortSignal:s,lastMessageTimestamp:r});if(a!=null&&a.session&&(this.sessionCtx.sessionState.setPartial({session:a.session}),this.sessionCtx.setSessions([a.session])),a!=null&&a.history&&a.history.length>0){const l=this.messageCtx.state.get().messages,C=a.history.map(this.mapHistoryToMessage).filter(S=>!l.some(p=>p.id===S.id));this.messageCtx.state.setPartial({messages:[...l,...C]})}this.messageCtx.state.get().isInitialFetchLoading&&this.messageCtx.state.setPartial({isInitialFetchLoading:!1})},this.mapHistoryToMessage=t=>{var r,a;const s={id:t.publicId,timestamp:t.sentAt||"",attachments:t.attachments||void 0};if(t.sender.kind==="user")return{...s,type:"FROM_USER",content:t.content.text||"",deliveredAt:t.sentAt||""};if(t.sender.kind==="agent")return{...s,type:"FROM_AGENT",component:"agent_message",data:{message:t.content.text||""},agent:{name:t.sender.name||"",avatar:t.sender.avatar||"",id:null,isAi:!1}};const i=t.actionCalls&&t.actionCalls.length>0?t.actionCalls[t.actionCalls.length-1]:void 0;return{...s,type:"FROM_BOT",component:"bot_message",agent:{id:null,name:((r=this.config.bot)==null?void 0:r.name)||"",isAi:!0,avatar:((a=this.config.bot)==null?void 0:a.avatar)||""},data:{message:t.content.text||"",action:i?{name:i.actionName,data:this.extractActionResult(i)}:void 0}}},this.extractActionResult=t=>{const s=t.result;if(s===null||typeof s!="object")return s;if("responseBodyText"in s&&typeof s.responseBodyText=="string"){const i=s.responseBodyText,r=_(()=>JSON.parse(i)).data;if(r)return r}return t.result},this.api=n,this.config=o,this.sessionCtx=c,this.messageCtx=g,this.sessionPollingIntervalSeconds=e,this.registerPolling()}}class B{constructor({config:n,api:o,storageCtx:c}){var g;this.shouldCollectData=()=>{var e;return!!(!((e=this.state.get().contact)!=null&&e.token)&&this.config.collectUserData)},this.autoCreateUnverifiedUserIfNotExists=async()=>{var e,t,s,i,r,a,h,l,C,S,p,b,m,u;if(!((e=this.config.user)!=null&&e.token)){if(this.config.collectUserData&&!((s=(t=this.config.user)==null?void 0:t.data)!=null&&s.email)){if((i=this.config.extraDataCollectionFields)!=null&&i.length)return;const x=await((r=this.storageCtx)==null?void 0:r.getContactToken());x&&await this.setUnverifiedContact(x);return}if(!((h=(a=this.config.user)==null?void 0:a.data)!=null&&h.email)){const x=await((l=this.storageCtx)==null?void 0:l.getContactToken());if(x){await this.setUnverifiedContact(x);return}}await this.createUnverifiedContact({email:(S=(C=this.config.user)==null?void 0:C.data)==null?void 0:S.email,non_verified_name:((b=(p=this.config.user)==null?void 0:p.data)==null?void 0:b.name)||"Anonymous",non_verified_custom_data:(u=(m=this.config.user)==null?void 0:m.data)==null?void 0:u.customData})}},this.createUnverifiedContact=async(e,t)=>{this.state.setPartial({extraCollectedData:t});try{this.state.setPartial({isCreatingUnverifiedContact:!0,isErrorCreatingUnverifiedContact:!1});const{data:s}=await this.api.createUnverifiedContact(e);s!=null&&s.token?await this.setUnverifiedContact(s.token):this.state.setPartial({isErrorCreatingUnverifiedContact:!0})}finally{this.state.setPartial({isCreatingUnverifiedContact:!1})}},this.setUnverifiedContact=async e=>{var i,r,a,h;const t=await((i=this.storageCtx)==null?void 0:i.getExternalContactId()),s=((r=this.config.user)==null?void 0:r.externalId)||t||U.v4();this.api.setAuthToken(e),await((a=this.storageCtx)==null?void 0:a.setContactToken(e)),await((h=this.storageCtx)==null?void 0:h.setExternalContactId(s)),this.state.setPartial({contact:{token:e,externalId:s}})},this.config=n,this.storageCtx=c,this.api=o,this.state=new w({contact:(g=n.user)!=null&&g.token?{token:n.user.token,externalId:n.user.externalId}:null,extraCollectedData:void 0,isCreatingUnverifiedContact:!1,isErrorCreatingUnverifiedContact:!1}),this.autoCreateUnverifiedUserIfNotExists()}}function y(){return U.v4()}class q{constructor({config:n,api:o,contactCtx:c,sessionsPollingIntervalSeconds:g}){this.sessionsRefresher=new R,this.sessionState=new w({session:null,isCreatingSession:!1,isResolvingSession:!1}),this.sessionsState=new w({data:[],cursor:void 0,isLastPage:!1,didStartInitialFetch:!1,isInitialFetchLoading:!0}),this.reset=async()=>{this.sessionState.reset()},this.registerSessionsRefresherWrapper=()=>{var e;(e=this.contactCtx.state.get().contact)!=null&&e.token&&!this.sessionsState.get().didStartInitialFetch?this.registerSessionsRefresher():this.contactCtx.state.subscribe(({contact:t})=>{t!=null&&t.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 r;this.sessionState.setPartial({session:null,isCreatingSession:!0});const e=(r=this.contactCtx.state.get().contact)==null?void 0:r.externalId,t={...this.config.sessionCustomData,...e?{external_id:e}:{}},{data:s,error:i}=await this.api.createSession({customData:Object.keys(t).length>0?t:void 0});return s?(this.sessionState.setPartial({session:s,isCreatingSession:!1}),s):(this.sessionState.setPartial({isCreatingSession:!1}),console.error("Failed to create session:",i),null)},this.loadMoreSessions=async()=>{if(this.sessionsState.get().isLastPage)return;const{data:e}=await this.getSessions({cursor:this.sessionsState.get().cursor});if(e){const s=[...this.sessionsState.get().data,...e.items].filter((i,r,a)=>r===a.findIndex(h=>i.id===h.id));this.sessionsState.setPartial({data:s,cursor:e.next||void 0,isLastPage:e.next===null})}},this.getSessions=async({cursor:e})=>{var s,i;if(!((s=this.contactCtx.state.get().contact)!=null&&s.token))return{data:null};const t=(i=this.contactCtx.state.get().contact)==null?void 0:i.externalId;return await this.api.getSessions({cursor:e,filters:t?{external_id:t}:{}})},this.setSessions=e=>{const t=[...e,...this.sessionsState.get().data].filter((s,i,r)=>i===r.findIndex(a=>s.id===a.id));this.sessionsState.setPartial({data:t})},this.refreshSessions=async()=>{const{data:e}=await this.getSessions({cursor:void 0});e&&this.setSessions(e.items)},this.resolveSession=async()=>{const e=this.sessionState.get().session;if(!e||!e.isOpened)return{success:!1,error:"Session is not opened"};this.sessionState.setPartial({isResolvingSession:!0});const{data:t,error:s}=await this.api.resolveSession({session_id:e.id});return t?(this.sessionState.setPartial({session:t,isResolvingSession:!1}),{success:!0,data:t}):(this.sessionState.setPartial({isResolvingSession:!1}),{success:!1,error:s})},this.createStateCheckpoint=async e=>{var r;const t=(r=this.sessionState.get().session)==null?void 0:r.id;if(!t)return;const{data:s,error:i}=await this.api.createStateCheckpoint({session_id:t,payload:e});return s?{data:s}:{success:!1,error:i}},this.config=n,this.api=o,this.contactCtx=c,this.sessionsPollingIntervalSeconds=g,this.registerSessionsRefresherWrapper()}}class ${constructor({config:n,api:o,sessionCtx:c,contactCtx:g}){this.state=new w({messages:[],isSendingMessage:!1,lastAIResMightSolveUserIssue:!1,isInitialFetchLoading:!1}),this.sendMessageAbortController=new AbortController,this.reset=()=>{this.sendMessageAbortController.abort("Resetting chat"),this.state.reset()},this.sendMessage=async e=>{var t,s,i,r,a,h,l,C;try{if(!e.content.trim()&&(!e.attachments||e.attachments.length===0)){console.warn("Cannot send an empty message of no content or attachments");return}const S=this.state.get().isSendingMessage,p=((t=this.sessionCtx.sessionState.get().session)==null?void 0:t.assignee.kind)==="ai",b=this.state.get().messages,m=b.length>0?b[b.length-1]:void 0;if(p&&S||p&&(m==null?void 0:m.type)==="FROM_USER"){console.warn("Cannot send messages while awaiting AI response");return}this.sendMessageAbortController=new AbortController,this.state.setPartial({lastAIResMightSolveUserIssue:!1}),this.state.setPartial({isSendingMessage:!0});const u=this.toUserMessage(e.content.trim(),e.attachments||void 0),x=this.state.get().messages;if(this.state.setPartial({messages:[...x,u]}),!((s=this.sessionCtx.sessionState.get().session)!=null&&s.id)){if(!await this.sessionCtx.createSession()){console.error("Failed to create session");return}this.sessionCtx.refreshSessions()}const T=(i=this.sessionCtx.sessionState.get().session)==null?void 0:i.id;if(!T)return;const{data:f}=await this.api.sendMessage({uuid:u.id,bot_token:this.config.token,headers:this.config.headers,query_params:this.config.queryParams,body_properties:this.config.bodyProperties,session_id:T,content:u.content,attachments:e.attachments,clientContext:this.config.context,custom_data:{...this.config.messageCustomData||{},...e.customData||{}},language:this.config.language,exit_mode_prompt:e.exitModePrompt},this.sendMessageAbortController.signal);if(f!=null&&f.success){const P=this.toBotMessage(f);if(P){const k=this.state.get().messages;if(!!k.some(A=>A.id===P.id)){this.state.setPartial({lastAIResMightSolveUserIssue:((r=f.autopilotResponse)==null?void 0:r.mightSolveUserIssue)||((a=f.uiResponse)==null?void 0:a.mightSolveUserIssue)});return}this.state.setPartial({messages:[...k,P],lastAIResMightSolveUserIssue:((h=f.autopilotResponse)==null?void 0:h.mightSolveUserIssue)||((l=f.uiResponse)==null?void 0:l.mightSolveUserIssue)})}f.session&&this.sessionCtx.sessionState.setPartial({session:f.session})}else{const P=this.toBotErrorMessage(((C=f==null?void 0:f.error)==null?void 0:C.message)||"Unknown error occurred"),k=this.state.get().messages;this.state.setPartial({messages:[...k,P]})}}catch(S){this.sendMessageAbortController.signal.aborted||console.error("Failed to send message:",S)}finally{this.state.setPartial({isSendingMessage:!1})}},this.toUserMessage=(e,t)=>{const s=(()=>{const i=this.contactCtx.state.get().extraCollectedData;return this.state.get().messages.length===0&&i&&Object.keys(i).length>0?`${Object.entries(i).filter(([a,h])=>!!h).map(([a,h])=>`${a}: ${h}`).join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("openapi-fetch"),B=require("lodash.isequal"),O=require("uuid"),L=d=>{console.log(d.error)},q=d=>{const n=_({baseUrl:d.baseUrl}),o={onRequest:d.onRequest,onResponse:d.onResponse,onError:d.onError||L};return n.use(o),n};class A{constructor({config:n}){var g,e;this.userToken=null,this.constructClientOptions=t=>{const s=this.config.apiUrl||"https://api.open.cx",i={"X-Bot-Token":this.config.token,"Content-Type":"application/json",Accept:"application/json",Authorization:t?`Bearer ${t}`:void 0};return{baseUrl:s,headers:i}},this.createOpenAPIClient=({baseUrl:t,headers:s})=>q({baseUrl:t,onRequest:({request:i})=>{Object.entries(s).forEach(([r,a])=>{a&&i.headers.set(r,a)})}}),this.setAuthToken=t=>{this.userToken=t;const{baseUrl:s,headers:i}=this.constructClientOptions(t);this.client=this.createOpenAPIClient({baseUrl:s,headers:i})},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(t,s)=>await this.client.POST("/backend/widget/v2/chat/send",{body:t,signal:s}),this.createUnverifiedContact=async t=>await this.client.POST("/backend/widget/v2/contact/create-unverified",{params:{header:{"x-bot-token":this.config.token}},body:t}),this.createSession=async t=>await this.client.POST("/backend/widget/v2/create-session",{body:t}),this.pollSessionAndHistory=async({sessionId:t,lastMessageTimestamp:s,abortSignal:i})=>{const r=s?{lastMessageTimestamp:s}:void 0;return await this.client.GET("/backend/widget/v2/poll/{sessionId}",{params:{path:{sessionId:t},query:r},signal:i})},this.getSessions=async({cursor:t,filters:s,abortSignal:i})=>await this.client.GET("/backend/widget/v2/sessions",{params:{query:{cursor:t,filters:JSON.stringify(s)}},signal:i}),this.uploadFile=async({file:t,abortSignal:s,onProgress:i})=>new Promise((r,a)=>{var b;const h=new FormData;h.append("file",t);const l=new XMLHttpRequest;if(s&&(s.addEventListener("abort",()=>{l.abort(),a(new DOMException("Aborted","AbortError"))}),s.aborted)){a(new DOMException("Aborted","AbortError"));return}l.upload.addEventListener("progress",f=>{if(f.lengthComputable&&i){const S=Math.round(f.loaded/f.total*100);i(S)}}),l.addEventListener("load",()=>{if(l.status>=200&&l.status<300)try{const f=JSON.parse(l.responseText);r(f)}catch(f){a(new Error(`Failed to parse response: ${f}`))}else a(new Error(`Upload failed with status: ${l.status}`))}),l.addEventListener("error",()=>{a(new Error("Network error occurred"))}),l.addEventListener("timeout",()=>{a(new Error("Upload timed out"))});const{baseUrl:p}=this.constructClientOptions(this.userToken),m=`${p}/backend/widget/v2/upload`;l.open("POST",m),l.setRequestHeader("X-Bot-Token",this.config.token),this.userToken??((b=this.config.user)==null?void 0:b.token)?l.setRequestHeader("Authorization",`Bearer ${this.userToken}`):console.error("User token not set"),l.send(h)}),this.vote=async t=>await this.client.POST("/backend/widget/v2/chat/vote",{body:t}),this.resolveSession=async(t,s)=>await this.client.POST("/backend/widget/v2/session/resolve",{body:t,signal:s}),this.createStateCheckpoint=async t=>await this.client.POST("/backend/widget/v2/checkpoint",{body:t}),this.config=n,this.userToken=((g=n.user)==null?void 0:g.token)||null;const{baseUrl:o,headers:c}=this.constructClientOptions((e=n.user)==null?void 0:e.token);this.client=this.createOpenAPIClient({baseUrl:o,headers:c})}}class P{constructor(n){this.subscribers=new Set,this.get=()=>this.state,this.set=o=>{B(this.state,o)||(this.state=o,this.notifySubscribers(o))},this.setPartial=o=>{if(o==null)return;const c={...this.state,...o};this.set(c)},this.reset=()=>{this.set(this.initialState)},this.notifySubscribers=o=>{Array.from(this.subscribers).forEach(g=>{try{g(o)}catch(e){console.error(e)}})},this.subscribe=o=>(this.subscribers.add(o),()=>{this.subscribers.delete(o)}),this.state=n,this.initialState=n}}class F{constructor(){this.state=new P({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,o)=>{if(this.stopPolling)return;const c=[],g=async()=>{this.abortController=new AbortController,this.state.setPartial({isPolling:!0});try{await n(this.abortController.signal)}catch(e){if(this.abortController.signal.aborted)return;console.error("Failed to poll:",e),this.state.setPartial({isError:!0})}finally{this.state.setPartial({isPolling:!1})}this.abortController.signal.aborted?console.log("Poller aborted, not scheduling anymore"):c.push(setTimeout(g,o))};g(),this.stopPolling=()=>{c.forEach(clearTimeout),this.state.reset()}}}}function $(d){try{const n=d();return n instanceof Promise?n.then(o=>({data:o})).catch(o=>({error:o})):{data:n}}catch(n){return{error:n}}}class N{constructor({api:n,config:o,sessionCtx:c,messageCtx:g,sessionPollingIntervalSeconds:e}){this.poller=new F,this.registerPolling=()=>{this.sessionCtx.sessionState.subscribe(({session:t})=>{t!=null&&t.id?this.poller.startPolling(async s=>{this.hackAndSlash(t.id,s)},this.sessionPollingIntervalSeconds*1e3):this.poller.reset()})},this.hackAndSlash=async(t,s)=>{var h;this.messageCtx.state.get().messages.length===0&&this.messageCtx.state.setPartial({isInitialFetchLoading:!0});const i=this.messageCtx.state.get().messages,r=i.length>0?((h=i[i.length-1])==null?void 0:h.timestamp)??void 0:void 0,{data:a}=await this.api.pollSessionAndHistory({sessionId:t,abortSignal:s,lastMessageTimestamp:r});if(a!=null&&a.session&&(this.sessionCtx.sessionState.setPartial({session:a.session}),this.sessionCtx.setSessions([a.session])),a!=null&&a.history&&a.history.length>0){const l=this.messageCtx.state.get().messages,p=a.history.map(this.mapHistoryToMessage).filter(v=>!l.some(m=>m.id===v.id));this.messageCtx.state.setPartial({messages:[...l,...p]})}this.messageCtx.state.get().isInitialFetchLoading&&this.messageCtx.state.setPartial({isInitialFetchLoading:!1})},this.mapHistoryToMessage=t=>{var r,a;const s={id:t.publicId,timestamp:t.sentAt||"",attachments:t.attachments||void 0};if(t.sender.kind==="user")return{...s,type:"FROM_USER",content:t.content.text||"",deliveredAt:t.sentAt||""};if(t.sender.kind==="agent")return{...s,type:"FROM_AGENT",component:"agent_message",data:{message:t.content.text||""},agent:{name:t.sender.name||"",avatar:t.sender.avatar||"",id:null,isAi:!1}};const i=t.actionCalls&&t.actionCalls.length>0?t.actionCalls[t.actionCalls.length-1]:void 0;return{...s,type:"FROM_BOT",component:"bot_message",agent:{id:null,name:((r=this.config.bot)==null?void 0:r.name)||"",isAi:!0,avatar:((a=this.config.bot)==null?void 0:a.avatar)||""},data:{message:t.content.text||"",action:i?{name:i.actionName,data:this.extractActionResult(i)}:void 0}}},this.extractActionResult=t=>{const s=t.result;if(s===null||typeof s!="object")return s;if("responseBodyText"in s&&typeof s.responseBodyText=="string"){const i=s.responseBodyText,r=$(()=>JSON.parse(i)).data;if(r)return r}return t.result},this.api=n,this.config=o,this.sessionCtx=c,this.messageCtx=g,this.sessionPollingIntervalSeconds=e,this.registerPolling()}}class H{constructor({config:n,api:o,storageCtx:c}){var g;this.shouldCollectData=()=>{var e;return!!(!((e=this.state.get().contact)!=null&&e.token)&&this.config.collectUserData)},this.autoCreateUnverifiedUserIfNotExists=async()=>{var e,t,s,i,r,a,h,l,p,v,m,w,b,f;if(!((e=this.config.user)!=null&&e.token)){if(this.config.collectUserData&&!((s=(t=this.config.user)==null?void 0:t.data)!=null&&s.email)){if((i=this.config.extraDataCollectionFields)!=null&&i.length)return;const S=await((r=this.storageCtx)==null?void 0:r.getContactToken());S&&await this.setUnverifiedContact(S);return}if(!((h=(a=this.config.user)==null?void 0:a.data)!=null&&h.email)){const S=await((l=this.storageCtx)==null?void 0:l.getContactToken());if(S){await this.setUnverifiedContact(S);return}}await this.createUnverifiedContact({email:(v=(p=this.config.user)==null?void 0:p.data)==null?void 0:v.email,non_verified_name:((w=(m=this.config.user)==null?void 0:m.data)==null?void 0:w.name)||"Anonymous",non_verified_custom_data:(f=(b=this.config.user)==null?void 0:b.data)==null?void 0:f.customData})}},this.createUnverifiedContact=async(e,t)=>{this.state.setPartial({extraCollectedData:t});try{this.state.setPartial({isCreatingUnverifiedContact:!0,isErrorCreatingUnverifiedContact:!1});const{data:s}=await this.api.createUnverifiedContact(e);s!=null&&s.token?await this.setUnverifiedContact(s.token):this.state.setPartial({isErrorCreatingUnverifiedContact:!0})}finally{this.state.setPartial({isCreatingUnverifiedContact:!1})}},this.setUnverifiedContact=async e=>{var i,r,a,h;const t=await((i=this.storageCtx)==null?void 0:i.getExternalContactId()),s=((r=this.config.user)==null?void 0:r.externalId)||t||O.v4();this.api.setAuthToken(e),await((a=this.storageCtx)==null?void 0:a.setContactToken(e)),await((h=this.storageCtx)==null?void 0:h.setExternalContactId(s)),this.state.setPartial({contact:{token:e,externalId:s}})},this.config=n,this.storageCtx=c,this.api=o,this.state=new P({contact:(g=n.user)!=null&&g.token?{token:n.user.token,externalId:n.user.externalId}:null,extraCollectedData:void 0,isCreatingUnverifiedContact:!1,isErrorCreatingUnverifiedContact:!1}),this.autoCreateUnverifiedUserIfNotExists()}}function k(){return O.v4()}class X{constructor({config:n,api:o,contactCtx:c,sessionsPollingIntervalSeconds:g}){this.sessionsRefresher=new F,this.sessionState=new P({session:null,isCreatingSession:!1,isResolvingSession:!1}),this.sessionsState=new P({data:[],cursor:void 0,isLastPage:!1,didStartInitialFetch:!1,isInitialFetchLoading:!0}),this.reset=async()=>{this.sessionState.reset()},this.registerSessionsRefresherWrapper=()=>{var e;(e=this.contactCtx.state.get().contact)!=null&&e.token&&!this.sessionsState.get().didStartInitialFetch?this.registerSessionsRefresher():this.contactCtx.state.subscribe(({contact:t})=>{t!=null&&t.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 r;this.sessionState.setPartial({session:null,isCreatingSession:!0});const e=(r=this.contactCtx.state.get().contact)==null?void 0:r.externalId,t={...this.config.sessionCustomData,...e?{external_id:e}:{}},{data:s,error:i}=await this.api.createSession({customData:Object.keys(t).length>0?t:void 0});return s?(this.sessionState.setPartial({session:s,isCreatingSession:!1}),s):(this.sessionState.setPartial({isCreatingSession:!1}),console.error("Failed to create session:",i),null)},this.loadMoreSessions=async()=>{if(this.sessionsState.get().isLastPage)return;const{data:e}=await this.getSessions({cursor:this.sessionsState.get().cursor});if(e){const s=[...this.sessionsState.get().data,...e.items].filter((i,r,a)=>r===a.findIndex(h=>i.id===h.id));this.sessionsState.setPartial({data:s,cursor:e.next||void 0,isLastPage:e.next===null})}},this.getSessions=async({cursor:e})=>{var s,i;if(!((s=this.contactCtx.state.get().contact)!=null&&s.token))return{data:null};const t=(i=this.contactCtx.state.get().contact)==null?void 0:i.externalId;return await this.api.getSessions({cursor:e,filters:t?{external_id:t}:{}})},this.setSessions=e=>{const t=[...e,...this.sessionsState.get().data].filter((s,i,r)=>i===r.findIndex(a=>s.id===a.id));this.sessionsState.setPartial({data:t})},this.refreshSessions=async()=>{const{data:e}=await this.getSessions({cursor:void 0});e&&this.setSessions(e.items)},this.resolveSession=async()=>{const e=this.sessionState.get().session;if(!e||!e.isOpened)return{success:!1,error:"Session is not opened"};this.sessionState.setPartial({isResolvingSession:!0});const{data:t,error:s}=await this.api.resolveSession({session_id:e.id});return t?(this.sessionState.setPartial({session:t,isResolvingSession:!1}),{success:!0,data:t}):(this.sessionState.setPartial({isResolvingSession:!1}),{success:!1,error:s})},this.createStateCheckpoint=async e=>{var r;const t=(r=this.sessionState.get().session)==null?void 0:r.id;if(!t)return;const{data:s,error:i}=await this.api.createStateCheckpoint({session_id:t,payload:e});return s?{data:s}:{success:!1,error:i}},this.config=n,this.api=o,this.contactCtx=c,this.sessionsPollingIntervalSeconds=g,this.registerSessionsRefresherWrapper()}}class G{constructor({config:n,api:o,sessionCtx:c,contactCtx:g}){this.state=new P({messages:[],isSendingMessage:!1,lastAIResMightSolveUserIssue:!1,isInitialFetchLoading:!1}),this.sendMessageAbortController=new AbortController,this.reset=()=>{this.sendMessageAbortController.abort("Resetting chat"),this.state.reset()},this.sendMessage=async e=>{var t,s,i,r,a,h,l,p,v,m;try{if(!e.content.trim()&&(!e.attachments||e.attachments.length===0)){console.warn("Cannot send an empty message of no content or attachments");return}const w=this.state.get().isSendingMessage,b=((t=this.sessionCtx.sessionState.get().session)==null?void 0:t.assignee.kind)==="ai",f=this.state.get().messages,S=f.length>0?f[f.length-1]:void 0;if(b&&w||b&&(S==null?void 0:S.type)==="FROM_USER"){console.warn("Cannot send messages while awaiting AI response");return}this.sendMessageAbortController=new AbortController,this.state.setPartial({lastAIResMightSolveUserIssue:!1}),this.state.setPartial({isSendingMessage:!0});const E=this.state.get().messages,M=!((s=this.sessionCtx.sessionState.get().session)!=null&&s.id)&&E.length===0&&((i=this.config.advancedInitialMessages)==null?void 0:i.some(u=>u.persistent)),R=M?(this.config.advancedInitialMessages||[]).filter(u=>u.persistent).map(u=>({id:k(),component:"bot_message",type:"FROM_BOT",timestamp:new Date().toISOString(),data:{message:u.message}})):[],y=this.toUserMessage(e.content.trim(),e.attachments||void 0);if(this.state.setPartial({messages:[...R,...E,y]}),!((r=this.sessionCtx.sessionState.get().session)!=null&&r.id)){if(!await this.sessionCtx.createSession()){console.error("Failed to create session");return}this.sessionCtx.refreshSessions()}const U=(a=this.sessionCtx.sessionState.get().session)==null?void 0:a.id;if(!U)return;const{data:C}=await this.api.sendMessage({uuid:y.id,bot_token:this.config.token,headers:this.config.headers,query_params:this.config.queryParams,body_properties:this.config.bodyProperties,session_id:U,content:y.content,attachments:e.attachments,clientContext:this.config.context,custom_data:{...this.config.messageCustomData||{},...e.customData||{}},language:this.config.language,exit_mode_prompt:e.exitModePrompt,initial_messages:M?R.map(u=>({uuid:u.id,content:u.data.message})):void 0},this.sendMessageAbortController.signal);if(C!=null&&C.success){const u=this.toBotMessage(C);if(u){const I=this.state.get().messages;if(!!I.some(D=>D.id===u.id)){this.state.setPartial({lastAIResMightSolveUserIssue:((h=C.autopilotResponse)==null?void 0:h.mightSolveUserIssue)||((l=C.uiResponse)==null?void 0:l.mightSolveUserIssue)});return}this.state.setPartial({messages:[...I,u],lastAIResMightSolveUserIssue:((p=C.autopilotResponse)==null?void 0:p.mightSolveUserIssue)||((v=C.uiResponse)==null?void 0:v.mightSolveUserIssue)})}C.session&&this.sessionCtx.sessionState.setPartial({session:C.session})}else{const u=this.toBotErrorMessage(((m=C==null?void 0:C.error)==null?void 0:m.message)||"Unknown error occurred"),I=this.state.get().messages;this.state.setPartial({messages:[...I,u]})}}catch(w){this.sendMessageAbortController.signal.aborted||console.error("Failed to send message:",w)}finally{this.state.setPartial({isSendingMessage:!1})}},this.toUserMessage=(e,t)=>{const s=(()=>{const i=this.contactCtx.state.get().extraCollectedData;return this.state.get().messages.length===0&&i&&Object.keys(i).length>0?`${Object.entries(i).filter(([a,h])=>!!h).map(([a,h])=>`${a}: ${h}`).join(`
2
2
  `)}
3
3
 
4
- ${e}`:e})();return{id:y(),type:"FROM_USER",content:s,deliveredAt:new Date().toISOString(),attachments:t,timestamp:new Date().toISOString()}},this.toBotMessage=e=>{var t;return e.success&&e.autopilotResponse?{type:"FROM_BOT",id:e.autopilotResponse.id||y(),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:e.autopilotResponse.value.content,action:(t=e.uiResponse)!=null&&t.value.name?{name:e.uiResponse.value.name,data:e.uiResponse.value.request_response}:void 0}}:null},this.toBotErrorMessage=e=>({type:"FROM_BOT",id:y(),timestamp:new Date().toISOString(),component:"TEXT",data:{message:e,variant:"error",action:void 0}}),this.config=n,this.api=o,this.sessionCtx=c,this.contactCtx=g}}class N{constructor({config:n,contactCtx:o,sessionCtx:c,resetChat:g}){var e;this.registerRoutingListener=()=>{this.contactCtx.state.subscribe(({contact:t})=>{var s;t!=null&&t.token&&this.state.get().screen==="welcome"&&this.state.setPartial({screen:(s=this.config.router)!=null&&s.chatScreenOnly?"chat":"sessions"})}),this.sessionCtx.sessionsState.subscribe(({isInitialFetchLoading:t,data:s})=>{var i,r,a,h;if((i=this.config.router)!=null&&i.chatScreenOnly&&!((r=this.sessionCtx.sessionState.get().session)!=null&&r.id)){const l=(a=s.find(C=>C.isOpened))==null?void 0:a.id;return l?this.toChatScreen(l):void 0}s.length||((h=this.config.router)==null?void 0:h.goToChatIfNoSessions)!==!1&&!t&&this.state.get().screen!=="chat"&&this.toChatScreen()})},this.toSessionsScreen=()=>{this.resetChat(),this.state.setPartial({screen:"sessions"})},this.toChatScreen=t=>{if(this.resetChat(),t){const s=this.sessionCtx.sessionsState.get().data.find(i=>i.id===t);if(!s)return;this.sessionCtx.sessionState.setPartial({session:s})}this.state.setPartial({screen:"chat"})},this.config=n,this.contactCtx=o,this.sessionCtx=c,this.resetChat=g,this.state=new w({screen:this.contactCtx.shouldCollectData()?"welcome":(e=this.config.router)!=null&&e.chatScreenOnly?"chat":"sessions"}),this.registerRoutingListener()}}class H{constructor({storage:n,config:o}){this.KEYS={contactToken:c=>`opencx-widget:org-token-${c}:contact-token`,externalContactId:c=>`opencx-widget:org-token-${c}:external-contact-id`},this.setContactToken=async c=>{await this.storage.set(this.KEYS.contactToken(this.config.token),c)},this.getContactToken=async()=>this.storage.get(this.KEYS.contactToken(this.config.token)),this.setExternalContactId=async c=>{await this.storage.set(this.KEYS.externalContactId(this.config.token),c)},this.getExternalContactId=async()=>this.storage.get(this.KEYS.externalContactId(this.config.token)),this.storage=n,this.config=o}}const v=class v{constructor({config:n,storage:o,modes:c}){if(this.modes=[],this.resetChat=()=>{this.sessionCtx.reset(),this.messageCtx.reset()},!v.pollingIntervalsSeconds)throw Error("Widget polling values are not defined, did you call WidgetCtx.initialize()");this.config=n,this.api=new E({config:n}),this.storageCtx=o?new H({storage:o,config:n}):void 0,this.modes=c,this.contactCtx=new B({api:this.api,config:this.config,storageCtx:this.storageCtx}),this.sessionCtx=new q({config:this.config,api:this.api,contactCtx:this.contactCtx,sessionsPollingIntervalSeconds:v.pollingIntervalsSeconds.sessions}),this.messageCtx=new $({config:this.config,api:this.api,sessionCtx:this.sessionCtx,contactCtx:this.contactCtx}),this.activeSessionPollingCtx=new L({api:this.api,config:this.config,sessionCtx:this.sessionCtx,messageCtx:this.messageCtx,sessionPollingIntervalSeconds:v.pollingIntervalsSeconds.session}),this.routerCtx=new N({config:this.config,contactCtx:this.contactCtx,sessionCtx:this.sessionCtx,resetChat:this.resetChat})}};v.pollingIntervalsSeconds=null,v.initialize=async({config:n,storage:o})=>{var g,e,t;const c=await new E({config:n}).getExternalWidgetConfig();return v.pollingIntervalsSeconds={session:((g=c.data)==null?void 0:g.sessionPollingIntervalSeconds)||10,sessions:((e=c.data)==null?void 0:e.sessionsPollingIntervalSeconds)||60},new v({config:n,storage:o,modes:((t=c.data)==null?void 0:t.modes)||[]})};let I=v;function X(d,n){console.error(`Missing case for ${d} in ${n}`)}exports.PrimitiveState=w;exports.WidgetCtx=I;exports.isExhaustive=X;
4
+ ${e}`:e})();return{id:k(),type:"FROM_USER",content:s,deliveredAt:new Date().toISOString(),attachments:t,timestamp:new Date().toISOString()}},this.toBotMessage=e=>{var t;return e.success&&e.autopilotResponse?{type:"FROM_BOT",id:e.autopilotResponse.id||k(),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:e.autopilotResponse.value.content,action:(t=e.uiResponse)!=null&&t.value.name?{name:e.uiResponse.value.name,data:e.uiResponse.value.request_response}:void 0}}:null},this.toBotErrorMessage=e=>({type:"FROM_BOT",id:k(),timestamp:new Date().toISOString(),component:"TEXT",data:{message:e,variant:"error",action:void 0}}),this.config=n,this.api=o,this.sessionCtx=c,this.contactCtx=g}}class K{constructor({config:n,contactCtx:o,sessionCtx:c,resetChat:g}){var e;this.registerRoutingListener=()=>{this.contactCtx.state.subscribe(({contact:t})=>{var s;t!=null&&t.token&&this.state.get().screen==="welcome"&&this.state.setPartial({screen:(s=this.config.router)!=null&&s.chatScreenOnly?"chat":"sessions"})}),this.sessionCtx.sessionsState.subscribe(({isInitialFetchLoading:t,data:s})=>{var i,r,a,h;if((i=this.config.router)!=null&&i.chatScreenOnly&&!((r=this.sessionCtx.sessionState.get().session)!=null&&r.id)){const l=(a=s.find(p=>p.isOpened))==null?void 0:a.id;return l?this.toChatScreen(l):void 0}s.length||((h=this.config.router)==null?void 0:h.goToChatIfNoSessions)!==!1&&!t&&this.state.get().screen!=="chat"&&this.toChatScreen()})},this.toSessionsScreen=()=>{this.resetChat(),this.state.setPartial({screen:"sessions"})},this.toChatScreen=t=>{if(this.resetChat(),t){const s=this.sessionCtx.sessionsState.get().data.find(i=>i.id===t);if(!s)return;this.sessionCtx.sessionState.setPartial({session:s})}this.state.setPartial({screen:"chat"})},this.config=n,this.contactCtx=o,this.sessionCtx=c,this.resetChat=g,this.state=new P({screen:this.contactCtx.shouldCollectData()?"welcome":(e=this.config.router)!=null&&e.chatScreenOnly?"chat":"sessions"}),this.registerRoutingListener()}}class Y{constructor({storage:n,config:o}){this.KEYS={contactToken:c=>`opencx-widget:org-token-${c}:contact-token`,externalContactId:c=>`opencx-widget:org-token-${c}:external-contact-id`},this.setContactToken=async c=>{await this.storage.set(this.KEYS.contactToken(this.config.token),c)},this.getContactToken=async()=>this.storage.get(this.KEYS.contactToken(this.config.token)),this.setExternalContactId=async c=>{await this.storage.set(this.KEYS.externalContactId(this.config.token),c)},this.getExternalContactId=async()=>this.storage.get(this.KEYS.externalContactId(this.config.token)),this.storage=n,this.config=o}}const x=class x{constructor({config:n,storage:o,modes:c}){if(this.modes=[],this.resetChat=()=>{this.sessionCtx.reset(),this.messageCtx.reset()},!x.pollingIntervalsSeconds)throw Error("Widget polling values are not defined, did you call WidgetCtx.initialize()");this.config=n,this.api=new A({config:n}),this.storageCtx=o?new Y({storage:o,config:n}):void 0,this.modes=c,this.contactCtx=new H({api:this.api,config:this.config,storageCtx:this.storageCtx}),this.sessionCtx=new X({config:this.config,api:this.api,contactCtx:this.contactCtx,sessionsPollingIntervalSeconds:x.pollingIntervalsSeconds.sessions}),this.messageCtx=new G({config:this.config,api:this.api,sessionCtx:this.sessionCtx,contactCtx:this.contactCtx}),this.activeSessionPollingCtx=new N({api:this.api,config:this.config,sessionCtx:this.sessionCtx,messageCtx:this.messageCtx,sessionPollingIntervalSeconds:x.pollingIntervalsSeconds.session}),this.routerCtx=new K({config:this.config,contactCtx:this.contactCtx,sessionCtx:this.sessionCtx,resetChat:this.resetChat})}};x.pollingIntervalsSeconds=null,x.initialize=async({config:n,storage:o})=>{var g,e,t;const c=await new A({config:n}).getExternalWidgetConfig();return x.pollingIntervalsSeconds={session:((g=c.data)==null?void 0:g.sessionPollingIntervalSeconds)||10,sessions:((e=c.data)==null?void 0:e.sessionsPollingIntervalSeconds)||60},new x({config:n,storage:o,modes:((t=c.data)==null?void 0:t.modes)||[]})};let T=x;function j(d,n){console.error(`Missing case for ${d} in ${n}`)}exports.PrimitiveState=P;exports.WidgetCtx=T;exports.isExhaustive=j;
5
5
  //# sourceMappingURL=index.cjs.map