@opencx/widget 3.0.47 → 3.0.48

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.
@@ -0,0 +1,604 @@
1
+ import F from "axios";
2
+ import O from "openapi-fetch";
3
+ import _ from "lodash.isequal";
4
+ import { v4 as R } from "uuid";
5
+ const D = (h) => {
6
+ console.log(h.error);
7
+ }, L = (h) => {
8
+ const n = O({
9
+ baseUrl: h.baseUrl
10
+ }), i = {
11
+ onRequest: h.onRequest,
12
+ onResponse: h.onResponse,
13
+ onError: h.onError || D
14
+ };
15
+ return n.use(i), n;
16
+ };
17
+ class k {
18
+ constructor({
19
+ config: n
20
+ }) {
21
+ var a;
22
+ this.constructClientOptions = (t) => {
23
+ const s = this.config.apiUrl || "https://api.open.cx", e = {
24
+ "X-Bot-Token": this.config.token,
25
+ "Content-Type": "application/json",
26
+ Accept: "application/json",
27
+ Authorization: t ? `Bearer ${t}` : void 0
28
+ };
29
+ return { baseUrl: s, headers: e };
30
+ }, this.createOpenAPIClient = ({
31
+ baseUrl: t,
32
+ headers: s
33
+ }) => L({
34
+ baseUrl: t,
35
+ onRequest: ({ request: e }) => {
36
+ Object.entries(s).forEach(([o, l]) => {
37
+ l && e.headers.set(o, l);
38
+ });
39
+ }
40
+ }), this.createAxiosUploadClient = ({
41
+ baseUrl: t,
42
+ headers: s
43
+ }) => F.create({
44
+ baseURL: `${t}/backend/widget/v2/upload`,
45
+ headers: s
46
+ }), this.setAuthToken = (t) => {
47
+ const { baseUrl: s, headers: e } = this.constructClientOptions(t);
48
+ this.client = this.createOpenAPIClient({ baseUrl: s, headers: e }), this.uploadFileClient = this.createAxiosUploadClient({ baseUrl: s, headers: e });
49
+ }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
50
+ params: { header: { "X-Bot-Token": this.config.token } }
51
+ }), this.widgetPrelude = async () => await this.client.GET("/backend/widget/v2/prelude", {
52
+ params: { header: { "X-Bot-Token": this.config.token } }
53
+ }), this.sendMessage = async (t, s) => await this.client.POST("/backend/widget/v2/chat/send", {
54
+ body: t,
55
+ signal: s
56
+ }), this.createUnverifiedContact = async (t) => await this.client.POST(
57
+ "/backend/widget/v2/contact/create-unverified",
58
+ {
59
+ params: { header: { "x-bot-token": this.config.token } },
60
+ body: t
61
+ }
62
+ ), this.createSession = async (t) => await this.client.POST("/backend/widget/v2/create-session", {
63
+ body: t
64
+ }), this.pollSessionAndHistory = async ({
65
+ sessionId: t,
66
+ lastMessageTimestamp: s,
67
+ abortSignal: e
68
+ }) => {
69
+ const o = s ? { lastMessageTimestamp: s } : void 0;
70
+ return await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
71
+ params: { path: { sessionId: t }, query: o },
72
+ signal: e
73
+ });
74
+ }, this.getSessions = async ({
75
+ cursor: t,
76
+ filters: s,
77
+ abortSignal: e
78
+ }) => await this.client.GET("/backend/widget/v2/sessions", {
79
+ params: { query: { cursor: t, filters: JSON.stringify(s) } },
80
+ signal: e
81
+ }), this.uploadFile = async (t, s = {}) => {
82
+ const e = new FormData();
83
+ e.append("file", t.file);
84
+ const { data: o } = await this.uploadFileClient.post("", e, {
85
+ headers: {
86
+ "Content-Type": "multipart/form-data"
87
+ },
88
+ ...s
89
+ });
90
+ return o;
91
+ }, this.vote = async (t) => await this.client.POST("/backend/widget/v2/chat/vote", { body: t }), this.config = n;
92
+ const { baseUrl: i, headers: c } = this.constructClientOptions(
93
+ (a = n.user) == null ? void 0 : a.token
94
+ );
95
+ this.client = this.createOpenAPIClient({ baseUrl: i, headers: c }), this.uploadFileClient = this.createAxiosUploadClient({ baseUrl: i, headers: c });
96
+ }
97
+ }
98
+ class v {
99
+ constructor(n) {
100
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (i) => {
101
+ _(this.state, i) || (this.state = i, this.notifySubscribers(i));
102
+ }, this.setPartial = (i) => {
103
+ if (i == null) return;
104
+ const c = { ...this.state, ...i };
105
+ this.set(c);
106
+ }, this.reset = () => {
107
+ this.set(this.initialState);
108
+ }, this.notifySubscribers = (i) => {
109
+ Array.from(this.subscribers).forEach((a) => {
110
+ try {
111
+ a(i);
112
+ } catch (t) {
113
+ console.error(t);
114
+ }
115
+ });
116
+ }, this.subscribe = (i) => (this.subscribers.add(i), () => {
117
+ this.subscribers.delete(i);
118
+ }), this.state = n, this.initialState = n;
119
+ }
120
+ }
121
+ class M {
122
+ constructor() {
123
+ this.state = new v({
124
+ isPolling: !1,
125
+ isError: !1
126
+ }), this.abortController = new AbortController(), this.reset = () => {
127
+ var n;
128
+ this.abortController.abort("Resetting poller"), (n = this.stopPolling) == null || n.call(this), this.stopPolling = null;
129
+ }, this.stopPolling = null, this.startPolling = (n, i) => {
130
+ if (this.stopPolling) return;
131
+ const c = [], a = async () => {
132
+ this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
133
+ try {
134
+ await n(this.abortController.signal);
135
+ } catch (t) {
136
+ if (this.abortController.signal.aborted)
137
+ return;
138
+ console.error("Failed to poll:", t), this.state.setPartial({ isError: !0 });
139
+ } finally {
140
+ this.state.setPartial({ isPolling: !1 });
141
+ }
142
+ this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : c.push(setTimeout(a, i));
143
+ };
144
+ a(), this.stopPolling = () => {
145
+ c.forEach(clearTimeout), this.state.reset();
146
+ };
147
+ };
148
+ }
149
+ }
150
+ class B {
151
+ constructor({
152
+ api: n,
153
+ config: i,
154
+ sessionCtx: c,
155
+ messageCtx: a,
156
+ sessionPollingIntervalSeconds: t
157
+ }) {
158
+ this.poller = new M(), this.registerPolling = () => {
159
+ this.sessionCtx.sessionState.subscribe(({ session: s }) => {
160
+ s != null && s.id ? this.poller.startPolling(async (e) => {
161
+ this.hackAndSlash(s.id, e);
162
+ }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
163
+ });
164
+ }, this.hackAndSlash = async (s, e) => {
165
+ var g;
166
+ this.messageCtx.state.get().messages.length === 0 && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
167
+ const o = this.messageCtx.state.get().messages, l = o.length > 0 ? (g = o[o.length - 1]) == null ? void 0 : g.timestamp : void 0, { data: r } = await this.api.pollSessionAndHistory({
168
+ sessionId: s,
169
+ abortSignal: e,
170
+ lastMessageTimestamp: l
171
+ });
172
+ if (r != null && r.session && this.sessionCtx.sessionState.setPartial({ session: r.session }), r != null && r.history && r.history.length > 0) {
173
+ const f = this.messageCtx.state.get().messages, p = r.history.map(this.mapHistoryToMessage).filter(
174
+ (m) => !f.some((S) => S.id === m.id)
175
+ );
176
+ this.messageCtx.state.setPartial({
177
+ messages: [...f, ...p]
178
+ });
179
+ }
180
+ this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
181
+ }, this.mapHistoryToMessage = (s) => {
182
+ var l, r;
183
+ const e = {
184
+ id: s.publicId,
185
+ timestamp: s.sentAt || "",
186
+ attachments: s.attachments || void 0
187
+ };
188
+ if (s.sender.kind === "user")
189
+ return {
190
+ ...e,
191
+ type: "FROM_USER",
192
+ content: s.content.text || "",
193
+ deliveredAt: s.sentAt || ""
194
+ };
195
+ if (s.sender.kind === "agent")
196
+ return {
197
+ ...e,
198
+ type: "FROM_AGENT",
199
+ component: "agent_message",
200
+ data: {
201
+ message: s.content.text || ""
202
+ },
203
+ agent: {
204
+ name: s.sender.name || "",
205
+ avatar: s.sender.avatar || "",
206
+ id: null,
207
+ isAi: !1
208
+ }
209
+ };
210
+ const o = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
211
+ return {
212
+ ...e,
213
+ type: "FROM_BOT",
214
+ component: "bot_message",
215
+ agent: {
216
+ id: null,
217
+ name: ((l = this.config.bot) == null ? void 0 : l.name) || "",
218
+ isAi: !0,
219
+ avatar: ((r = this.config.bot) == null ? void 0 : r.avatar) || ""
220
+ },
221
+ data: {
222
+ message: s.content.text || "",
223
+ action: o ? { name: o.actionName, data: o.result } : void 0
224
+ }
225
+ };
226
+ }, this.api = n, this.config = i, this.sessionCtx = c, this.messageCtx = a, this.sessionPollingIntervalSeconds = t, this.registerPolling();
227
+ }
228
+ }
229
+ class q {
230
+ constructor({
231
+ config: n,
232
+ api: i,
233
+ storageCtx: c
234
+ }) {
235
+ var a;
236
+ this.shouldCollectData = () => {
237
+ var t;
238
+ return !!(!((t = this.state.get().contact) != null && t.token) && this.config.collectUserData);
239
+ }, this.autoCreateUnverifiedUserIfNotExists = async () => {
240
+ var t, s, e, o, l, r, g, f, p, m, S, b;
241
+ if (!((t = this.config.user) != null && t.token)) {
242
+ if (this.config.collectUserData && !((e = (s = this.config.user) == null ? void 0 : s.data) != null && e.email)) {
243
+ if ((o = this.config.extraDataCollectionFields) != null && o.length)
244
+ return;
245
+ const C = await ((l = this.storageCtx) == null ? void 0 : l.getContactToken());
246
+ C && await this.setUnverifiedContact(C);
247
+ return;
248
+ }
249
+ if (!((g = (r = this.config.user) == null ? void 0 : r.data) != null && g.email)) {
250
+ const C = await ((f = this.storageCtx) == null ? void 0 : f.getContactToken());
251
+ if (C) {
252
+ await this.setUnverifiedContact(C);
253
+ return;
254
+ }
255
+ }
256
+ await this.createUnverifiedContact({
257
+ name: ((m = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : m.name) || "Anonymous",
258
+ email: (b = (S = this.config.user) == null ? void 0 : S.data) == null ? void 0 : b.email
259
+ });
260
+ }
261
+ }, this.createUnverifiedContact = async (t, s) => {
262
+ this.state.setPartial({ extraCollectedData: s });
263
+ try {
264
+ this.state.setPartial({
265
+ isCreatingUnverifiedContact: !0,
266
+ isErrorCreatingUnverifiedContact: !1
267
+ });
268
+ const { data: e } = await this.api.createUnverifiedContact(t);
269
+ e != null && e.token ? await this.setUnverifiedContact(e.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
270
+ } finally {
271
+ this.state.setPartial({ isCreatingUnverifiedContact: !1 });
272
+ }
273
+ }, this.setUnverifiedContact = async (t) => {
274
+ var o, l, r, g;
275
+ const s = await ((o = this.storageCtx) == null ? void 0 : o.getExternalContactId()), e = ((l = this.config.user) == null ? void 0 : l.externalId) || s || R();
276
+ this.api.setAuthToken(t), await ((r = this.storageCtx) == null ? void 0 : r.setContactToken(t)), await ((g = this.storageCtx) == null ? void 0 : g.setExternalContactId(e)), this.state.setPartial({ contact: { token: t, externalId: e } });
277
+ }, this.config = n, this.storageCtx = c, this.api = i, this.state = new v({
278
+ contact: (a = n.user) != null && a.token ? {
279
+ token: n.user.token,
280
+ // Set optional externalId from config... not local storage
281
+ externalId: n.user.externalId
282
+ } : null,
283
+ extraCollectedData: void 0,
284
+ isCreatingUnverifiedContact: !1,
285
+ isErrorCreatingUnverifiedContact: !1
286
+ }), this.autoCreateUnverifiedUserIfNotExists();
287
+ }
288
+ }
289
+ function I() {
290
+ return R();
291
+ }
292
+ class $ {
293
+ constructor({
294
+ api: n,
295
+ contactCtx: i,
296
+ sessionsPollingIntervalSeconds: c
297
+ }) {
298
+ this.sessionsRefresher = new M(), this.sessionState = new v({
299
+ session: null,
300
+ isCreatingSession: !1
301
+ }), this.sessionsState = new v({
302
+ data: [],
303
+ cursor: void 0,
304
+ isLastPage: !1,
305
+ didStartInitialFetch: !1,
306
+ /**
307
+ * Initialize this as `true` so it always starts loading until the first fetch is done
308
+ */
309
+ isInitialFetchLoading: !0
310
+ }), this.reset = async () => {
311
+ this.sessionState.reset();
312
+ }, this.registerSessionsRefresherWrapper = () => {
313
+ var a;
314
+ // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
315
+ (a = this.contactCtx.state.get().contact) != null && a.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: t }) => {
316
+ t != null && t.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
317
+ });
318
+ }, this.registerSessionsRefresher = () => {
319
+ this.sessionsRefresher.startPolling(async () => {
320
+ this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
321
+ }, this.sessionsPollingIntervalSeconds * 1e3);
322
+ }, this.createSession = async () => {
323
+ var e;
324
+ this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
325
+ const a = (e = this.contactCtx.state.get().contact) == null ? void 0 : e.externalId, { data: t, error: s } = await this.api.createSession({
326
+ customData: a ? {
327
+ external_id: a
328
+ } : void 0
329
+ });
330
+ return t ? (this.sessionState.setPartial({ session: t, isCreatingSession: !1 }), t) : (console.error("Failed to create session:", s), null);
331
+ }, this.loadMoreSessions = async () => {
332
+ if (this.sessionsState.get().isLastPage) return;
333
+ const { data: a } = await this.getSessions({
334
+ cursor: this.sessionsState.get().cursor
335
+ });
336
+ if (a) {
337
+ const s = [...this.sessionsState.get().data, ...a.items].filter(
338
+ (e, o, l) => o === l.findIndex((r) => e.id === r.id)
339
+ );
340
+ this.sessionsState.setPartial({
341
+ data: s,
342
+ cursor: a.next || void 0,
343
+ isLastPage: a.next === null
344
+ });
345
+ }
346
+ }, this.getSessions = async ({ cursor: a }) => {
347
+ var s, e;
348
+ if (!((s = this.contactCtx.state.get().contact) != null && s.token)) return { data: null };
349
+ const t = (e = this.contactCtx.state.get().contact) == null ? void 0 : e.externalId;
350
+ return await this.api.getSessions({
351
+ cursor: a,
352
+ filters: t ? {
353
+ external_id: t
354
+ } : {}
355
+ });
356
+ }, this.refreshSessions = async () => {
357
+ const { data: a } = await this.getSessions({ cursor: void 0 });
358
+ if (!a) return;
359
+ const t = [...a.items, ...this.sessionsState.get().data].filter(
360
+ (s, e, o) => e === o.findIndex((l) => s.id === l.id)
361
+ );
362
+ this.sessionsState.setPartial({ data: t });
363
+ }, this.api = n, this.contactCtx = i, this.sessionsPollingIntervalSeconds = c, this.registerSessionsRefresherWrapper();
364
+ }
365
+ }
366
+ class j {
367
+ constructor({
368
+ config: n,
369
+ api: i,
370
+ sessionCtx: c,
371
+ contactCtx: a
372
+ }) {
373
+ this.state = new v({
374
+ messages: [],
375
+ isSendingMessage: !1,
376
+ lastAIResMightSolveUserIssue: !1,
377
+ isInitialFetchLoading: !1
378
+ }), this.sendMessageAbortController = new AbortController(), this.reset = () => {
379
+ this.sendMessageAbortController.abort("Resetting chat"), this.state.reset();
380
+ }, this.sendMessage = async (t) => {
381
+ var r, g, f, p, m, S, b, C, U;
382
+ if (!t.content.trim() && (!t.attachments || t.attachments.length === 0)) {
383
+ console.warn("Cannot send an empty message of no content or attachments");
384
+ return;
385
+ }
386
+ const s = this.state.get().isSendingMessage, e = ((r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.assignee.kind) === "ai", o = this.state.get().messages, l = o.length > 0 ? o[o.length - 1] : void 0;
387
+ if (e && s || // If last message is from user, then bot response did not arrive yet
388
+ e && (l == null ? void 0 : l.type) === "FROM_USER") {
389
+ console.warn("Cannot send messages while awaiting AI response");
390
+ return;
391
+ }
392
+ this.sendMessageAbortController = new AbortController(), this.state.setPartial({ lastAIResMightSolveUserIssue: !1 });
393
+ try {
394
+ this.state.setPartial({ isSendingMessage: !0 });
395
+ const w = this.toUserMessage(
396
+ t.content.trim(),
397
+ t.attachments || void 0
398
+ ), E = this.state.get().messages;
399
+ if (this.state.setPartial({
400
+ messages: [...E, w]
401
+ }), !((g = this.sessionCtx.sessionState.get().session) != null && g.id)) {
402
+ if (!await this.sessionCtx.createSession()) {
403
+ console.error("Failed to create session");
404
+ return;
405
+ }
406
+ this.sessionCtx.refreshSessions();
407
+ }
408
+ const y = (f = this.sessionCtx.sessionState.get().session) == null ? void 0 : f.id;
409
+ if (!y) return;
410
+ const { data: d } = await this.api.sendMessage(
411
+ {
412
+ uuid: w.id,
413
+ bot_token: this.config.token,
414
+ headers: this.config.headers,
415
+ query_params: this.config.queryParams,
416
+ session_id: y,
417
+ user: (p = this.config.user) == null ? void 0 : p.data,
418
+ content: w.content,
419
+ attachments: t.attachments
420
+ },
421
+ this.sendMessageAbortController.signal
422
+ );
423
+ if (d != null && d.success) {
424
+ const x = this.toBotMessage(d);
425
+ if (x) {
426
+ const P = this.state.get().messages;
427
+ if (!!P.some(
428
+ (T) => T.id === x.id
429
+ )) {
430
+ this.state.setPartial({
431
+ lastAIResMightSolveUserIssue: ((m = d.autopilotResponse) == null ? void 0 : m.mightSolveUserIssue) || ((S = d.uiResponse) == null ? void 0 : S.mightSolveUserIssue)
432
+ });
433
+ return;
434
+ }
435
+ this.state.setPartial({
436
+ messages: [...P, x],
437
+ lastAIResMightSolveUserIssue: ((b = d.autopilotResponse) == null ? void 0 : b.mightSolveUserIssue) || ((C = d.uiResponse) == null ? void 0 : C.mightSolveUserIssue)
438
+ });
439
+ }
440
+ } else {
441
+ const x = this.toBotErrorMessage(
442
+ ((U = d == null ? void 0 : d.error) == null ? void 0 : U.message) || "Unknown error occurred"
443
+ ), P = this.state.get().messages;
444
+ this.state.setPartial({
445
+ messages: [...P, x]
446
+ });
447
+ }
448
+ } catch (w) {
449
+ this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", w);
450
+ } finally {
451
+ this.state.setPartial({ isSendingMessage: !1 });
452
+ }
453
+ }, this.toUserMessage = (t, s) => {
454
+ const e = (() => {
455
+ const o = this.contactCtx.state.get().extraCollectedData;
456
+ return this.state.get().messages.length === 0 && o && Object.keys(o).length > 0 ? `${Object.entries(o).filter(([r, g]) => !!g).map(([r, g]) => `${r}: ${g}`).join(`
457
+ `)}
458
+
459
+ ${t}` : t;
460
+ })();
461
+ return {
462
+ id: I(),
463
+ type: "FROM_USER",
464
+ content: e,
465
+ deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
466
+ attachments: s,
467
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
468
+ };
469
+ }, this.toBotMessage = (t) => {
470
+ var s;
471
+ return t.success && t.autopilotResponse ? {
472
+ type: "FROM_BOT",
473
+ id: t.autopilotResponse.id || I(),
474
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
475
+ component: "bot_message",
476
+ agent: this.config.bot ? {
477
+ name: this.config.bot.name || "",
478
+ isAi: !0,
479
+ avatar: this.config.bot.avatar || "",
480
+ id: null
481
+ } : void 0,
482
+ data: {
483
+ message: t.autopilotResponse.value.content,
484
+ action: (s = t.uiResponse) != null && s.value.name ? {
485
+ name: t.uiResponse.value.name,
486
+ data: t.uiResponse.value.request_response
487
+ } : void 0
488
+ }
489
+ } : null;
490
+ }, this.toBotErrorMessage = (t) => ({
491
+ type: "FROM_BOT",
492
+ id: I(),
493
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
494
+ component: "TEXT",
495
+ data: {
496
+ message: t,
497
+ variant: "error",
498
+ action: void 0
499
+ }
500
+ }), this.config = n, this.api = i, this.sessionCtx = c, this.contactCtx = a;
501
+ }
502
+ }
503
+ class N {
504
+ constructor({
505
+ config: n,
506
+ contactCtx: i,
507
+ sessionCtx: c,
508
+ resetChat: a
509
+ }) {
510
+ this.registerRoutingListener = () => {
511
+ this.contactCtx.state.subscribe(({ contact: t }) => {
512
+ t != null && t.token && this.state.get().screen === "welcome" && this.state.setPartial({ screen: "sessions" });
513
+ }), this.sessionCtx.sessionsState.subscribe(
514
+ ({ isInitialFetchLoading: t, data: s }) => {
515
+ var e;
516
+ s.length || ((e = this.config.router) == null ? void 0 : e.goToChatIfNoSessions) !== !1 && !t && this.state.get().screen !== "chat" && this.toChatScreen();
517
+ }
518
+ );
519
+ }, this.toSessionsScreen = () => {
520
+ this.resetChat(), this.state.setPartial({ screen: "sessions" });
521
+ }, this.toChatScreen = (t) => {
522
+ if (this.resetChat(), t) {
523
+ const s = this.sessionCtx.sessionsState.get().data.find((e) => e.id === t);
524
+ if (!s) return;
525
+ this.sessionCtx.sessionState.setPartial({ session: s });
526
+ }
527
+ this.state.setPartial({ screen: "chat" });
528
+ }, this.state = new v({
529
+ screen: i.shouldCollectData() ? "welcome" : "sessions"
530
+ }), this.config = n, this.contactCtx = i, this.sessionCtx = c, this.resetChat = a, this.registerRoutingListener();
531
+ }
532
+ }
533
+ class G {
534
+ constructor({ storage: n }) {
535
+ this.KEYS = {
536
+ contactToken: "opencx__widget__contactToken",
537
+ externalContactId: "opencx__widget__externalContactId"
538
+ }, this.setContactToken = async (i) => {
539
+ await this.storage.set(this.KEYS.contactToken, i);
540
+ }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken), this.setExternalContactId = async (i) => {
541
+ await this.storage.set(this.KEYS.externalContactId, i);
542
+ }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId), this.storage = n;
543
+ }
544
+ }
545
+ const u = class u {
546
+ constructor({
547
+ config: n,
548
+ storage: i
549
+ }) {
550
+ if (this.resetChat = () => {
551
+ this.sessionCtx.reset(), this.messageCtx.reset();
552
+ }, !u.pollingIntervalsSeconds)
553
+ throw Error(
554
+ "Widget polling values are not defined, did you call WidgetCtx.initialize()"
555
+ );
556
+ this.config = n, this.api = new k({ config: n }), this.storageCtx = i ? new G({ storage: i }) : void 0, this.contactCtx = new q({
557
+ api: this.api,
558
+ config: this.config,
559
+ storageCtx: this.storageCtx
560
+ }), this.sessionCtx = new $({
561
+ api: this.api,
562
+ contactCtx: this.contactCtx,
563
+ sessionsPollingIntervalSeconds: u.pollingIntervalsSeconds.sessions
564
+ }), this.messageCtx = new j({
565
+ config: this.config,
566
+ api: this.api,
567
+ sessionCtx: this.sessionCtx,
568
+ contactCtx: this.contactCtx
569
+ }), this.activeSessionPollingCtx = new B({
570
+ api: this.api,
571
+ config: this.config,
572
+ sessionCtx: this.sessionCtx,
573
+ messageCtx: this.messageCtx,
574
+ sessionPollingIntervalSeconds: u.pollingIntervalsSeconds.session
575
+ }), this.routerCtx = new N({
576
+ config: this.config,
577
+ contactCtx: this.contactCtx,
578
+ sessionCtx: this.sessionCtx,
579
+ resetChat: this.resetChat
580
+ });
581
+ }
582
+ };
583
+ u.pollingIntervalsSeconds = null, u.initialize = async ({
584
+ config: n,
585
+ storage: i
586
+ }) => {
587
+ var a, t;
588
+ const c = await new k({
589
+ config: n
590
+ }).getExternalWidgetConfig();
591
+ return u.pollingIntervalsSeconds = {
592
+ session: ((a = c.data) == null ? void 0 : a.sessionPollingIntervalSeconds) || 10,
593
+ sessions: ((t = c.data) == null ? void 0 : t.sessionsPollingIntervalSeconds) || 60
594
+ }, new u({
595
+ config: n,
596
+ storage: i
597
+ });
598
+ };
599
+ let A = u;
600
+ export {
601
+ v as P,
602
+ A as W
603
+ };
604
+ //# sourceMappingURL=widget.ctx-CaItHAmP.js.map