@opencx/widget-core 4.0.24 → 4.0.27

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/index.js CHANGED
@@ -1,15 +1,15 @@
1
- import D from "openapi-fetch";
2
- import L from "lodash.isequal";
3
- import { v4 as O } from "uuid";
4
- const j = (h) => {
1
+ import L from "openapi-fetch";
2
+ import N from "lodash.isequal";
3
+ import { v4 as z } from "uuid";
4
+ const F = (h) => {
5
5
  console.log(h.error);
6
- }, N = (h) => {
7
- const i = D({
6
+ }, B = (h) => {
7
+ const i = L({
8
8
  baseUrl: h.baseUrl
9
9
  }), a = {
10
10
  onRequest: h.onRequest,
11
11
  onResponse: h.onResponse,
12
- onError: h.onError || j
12
+ onError: h.onError || F
13
13
  };
14
14
  return i.use(a), i;
15
15
  };
@@ -27,7 +27,7 @@ class M {
27
27
  }, this.createOpenAPIClient = ({
28
28
  baseUrl: e,
29
29
  headers: t
30
- }) => N({
30
+ }) => B({
31
31
  baseUrl: e,
32
32
  onRequest: ({ request: n }) => {
33
33
  Object.entries(t).forEach(([o, r]) => {
@@ -73,9 +73,9 @@ class M {
73
73
  abortSignal: t,
74
74
  onProgress: n
75
75
  }) => new Promise((o, r) => {
76
- var w;
77
- const l = new FormData();
78
- l.append("file", e);
76
+ var S;
77
+ const c = new FormData();
78
+ c.append("file", e);
79
79
  const u = new XMLHttpRequest();
80
80
  if (t && (t.addEventListener("abort", () => {
81
81
  u.abort(), r(new DOMException("Aborted", "AbortError"));
@@ -83,18 +83,18 @@ class M {
83
83
  r(new DOMException("Aborted", "AbortError"));
84
84
  return;
85
85
  }
86
- u.upload.addEventListener("progress", (m) => {
87
- if (m.lengthComputable && n) {
88
- const C = Math.round(m.loaded / m.total * 100);
89
- n(C);
86
+ u.upload.addEventListener("progress", (f) => {
87
+ if (f.lengthComputable && n) {
88
+ const v = Math.round(f.loaded / f.total * 100);
89
+ n(v);
90
90
  }
91
91
  }), u.addEventListener("load", () => {
92
92
  if (u.status >= 200 && u.status < 300)
93
93
  try {
94
- const m = JSON.parse(u.responseText);
95
- o(m);
96
- } catch (m) {
97
- r(new Error(`Failed to parse response: ${m}`));
94
+ const f = JSON.parse(u.responseText);
95
+ o(f);
96
+ } catch (f) {
97
+ r(new Error(`Failed to parse response: ${f}`));
98
98
  }
99
99
  else
100
100
  r(new Error(`Upload failed with status: ${u.status}`));
@@ -103,31 +103,31 @@ class M {
103
103
  }), u.addEventListener("timeout", () => {
104
104
  r(new Error("Upload timed out"));
105
105
  });
106
- const { baseUrl: _ } = this.constructClientOptions(this.userToken), f = `${_}/backend/widget/v2/upload`;
107
- u.open("POST", f), u.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((w = this.config.user) == null ? void 0 : w.token) ? u.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), u.send(l);
106
+ const { baseUrl: p } = this.constructClientOptions(this.userToken), g = `${p}/backend/widget/v2/upload`;
107
+ u.open("POST", g), u.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((S = this.config.user) == null ? void 0 : S.token) ? u.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), u.send(c);
108
108
  }), this.vote = async (e) => await this.client.POST("/backend/widget/v2/chat/vote", { body: e }), this.resolveSession = async (e, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
109
109
  body: e,
110
110
  signal: t
111
111
  }), this.createStateCheckpoint = async (e) => await this.client.POST("/backend/widget/v2/checkpoint", {
112
112
  body: e
113
113
  }), this.submitCsat = async (e) => await this.client.POST("/backend/widget/v2/submit-csat", { body: e }), this.config = i, this.userToken = ((d = i.user) == null ? void 0 : d.token) || null;
114
- const { baseUrl: a, headers: c } = this.constructClientOptions(
114
+ const { baseUrl: a, headers: l } = this.constructClientOptions(
115
115
  (s = i.user) == null ? void 0 : s.token
116
116
  );
117
- this.client = this.createOpenAPIClient({ baseUrl: a, headers: c });
117
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: l });
118
118
  }
119
119
  }
120
- function B(h, i) {
120
+ function H(h, i) {
121
121
  console.error(`Missing case for ${h} in ${i}`);
122
122
  }
123
123
  class y {
124
124
  constructor(i) {
125
125
  this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
126
- L(this.state, a) || (this.state = a, this.notifySubscribers(a));
126
+ N(this.state, a) || (this.state = a, this.notifySubscribers(a));
127
127
  }, this.setPartial = (a) => {
128
128
  if (a == null) return;
129
- const c = { ...this.state, ...a };
130
- this.set(c);
129
+ const l = { ...this.state, ...a };
130
+ this.set(l);
131
131
  }, this.reset = () => {
132
132
  this.set(this.initialState);
133
133
  }, this.notifySubscribers = (a) => {
@@ -143,7 +143,7 @@ class y {
143
143
  }), this.state = i, this.initialState = i;
144
144
  }
145
145
  }
146
- class R {
146
+ class O {
147
147
  constructor() {
148
148
  this.state = new y({
149
149
  isPolling: !1,
@@ -153,7 +153,7 @@ class R {
153
153
  this.abortController.abort("Resetting poller"), (i = this.stopPolling) == null || i.call(this), this.stopPolling = null;
154
154
  }, this.stopPolling = null, this.startPolling = (i, a) => {
155
155
  if (this.stopPolling) return;
156
- const c = [], d = async () => {
156
+ const l = [], d = async () => {
157
157
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
158
158
  try {
159
159
  await i(this.abortController.signal);
@@ -164,15 +164,15 @@ class R {
164
164
  } finally {
165
165
  this.state.setPartial({ isPolling: !1 });
166
166
  }
167
- this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : c.push(setTimeout(d, a));
167
+ this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : l.push(setTimeout(d, a));
168
168
  };
169
169
  d(), this.stopPolling = () => {
170
- c.forEach(clearTimeout), this.state.reset();
170
+ l.forEach(clearTimeout), this.state.reset();
171
171
  };
172
172
  };
173
173
  }
174
174
  }
175
- function H(h) {
175
+ function R(h) {
176
176
  try {
177
177
  const i = h();
178
178
  return i instanceof Promise ? i.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: i };
@@ -184,11 +184,11 @@ class q {
184
184
  constructor({
185
185
  api: i,
186
186
  config: a,
187
- sessionCtx: c,
187
+ sessionCtx: l,
188
188
  messageCtx: d,
189
189
  sessionPollingIntervalSeconds: s
190
190
  }) {
191
- this.poller = new R(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.registerPolling = () => {
191
+ this.poller = new O(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.registerPolling = () => {
192
192
  this.sessionCtx.sessionState.subscribe(({ session: e }) => {
193
193
  e != null && e.id ? this.poller.startPolling(async (t) => {
194
194
  this.fetchSessionAndHistory({ sessionId: e.id, abortSignal: t });
@@ -214,17 +214,17 @@ class q {
214
214
  }) => {
215
215
  var u;
216
216
  this.messageCtx.state.get().messages.length === 0 && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
217
- const o = this.messageCtx.state.get().messages, r = o.length > 0 ? ((u = o[o.length - 1]) == null ? void 0 : u.timestamp) ?? void 0 : void 0, { data: l } = await this.api.pollSessionAndHistory({
217
+ const o = this.messageCtx.state.get().messages, r = o.length > 0 ? ((u = o[o.length - 1]) == null ? void 0 : u.timestamp) ?? void 0 : void 0, { data: c } = await this.api.pollSessionAndHistory({
218
218
  sessionId: e,
219
219
  abortSignal: t,
220
220
  lastMessageTimestamp: n ? void 0 : r
221
221
  });
222
- if (l != null && l.session && (this.sessionCtx.sessionState.setPartial({ session: l.session }), this.sessionCtx.setSessions([l.session])), l != null && l.history && l.history.length > 0) {
223
- const _ = this.messageCtx.state.get().messages, S = l.history.map(this.mapHistoryToMessage).filter((f) => f !== null).filter(
224
- (f) => !_.some((v) => v.id === f.id)
222
+ if (c != null && c.session && (this.sessionCtx.sessionState.setPartial({ session: c.session }), this.sessionCtx.setSessions([c.session])), c != null && c.history && c.history.length > 0) {
223
+ const p = this.messageCtx.state.get().messages, w = c.history.map(this.mapHistoryToMessage).filter((g) => g !== null).filter(
224
+ (g) => !p.some((C) => C.id === g.id)
225
225
  );
226
226
  this.messageCtx.state.setPartial({
227
- messages: [..._, ...S]
227
+ messages: [...p, ...w]
228
228
  });
229
229
  }
230
230
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
@@ -321,7 +321,7 @@ class q {
321
321
  case "none":
322
322
  return null;
323
323
  default:
324
- return B(
324
+ return H(
325
325
  e.systemMessagePayload,
326
326
  this.constructSystemMessage.name
327
327
  ), null;
@@ -330,44 +330,44 @@ class q {
330
330
  const t = e.result;
331
331
  if (t === null || typeof t != "object") return t;
332
332
  if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
333
- const n = t.responseBodyText, o = H(() => JSON.parse(n)).data;
333
+ const n = t.responseBodyText, o = R(() => JSON.parse(n)).data;
334
334
  if (o) return o;
335
335
  }
336
336
  return e.result;
337
- }, this.api = i, this.config = a, this.sessionCtx = c, this.messageCtx = d, this.sessionPollingIntervalSeconds = s, this.registerPolling();
337
+ }, this.api = i, this.config = a, this.sessionCtx = l, this.messageCtx = d, this.sessionPollingIntervalSeconds = s, this.registerPolling();
338
338
  }
339
339
  }
340
- class Y {
340
+ class V {
341
341
  constructor({
342
342
  config: i,
343
343
  api: a,
344
- storageCtx: c
344
+ storageCtx: l
345
345
  }) {
346
346
  var d;
347
347
  this.shouldCollectData = () => {
348
348
  var s;
349
349
  return !!(!((s = this.state.get().contact) != null && s.token) && this.config.collectUserData);
350
350
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
351
- var s, e, t, n, o, r, l, u, _, S, f, v, w, m;
351
+ var s, e, t, n, o, r, c, u, p, w, g, C, S, f;
352
352
  if (!((s = this.config.user) != null && s.token)) {
353
353
  if (this.config.collectUserData && !((t = (e = this.config.user) == null ? void 0 : e.data) != null && t.email)) {
354
354
  if ((n = this.config.extraDataCollectionFields) != null && n.length)
355
355
  return;
356
- const C = await ((o = this.storageCtx) == null ? void 0 : o.getContactToken());
357
- C && await this.setUnverifiedContact(C);
356
+ const v = await ((o = this.storageCtx) == null ? void 0 : o.getContactToken());
357
+ v && await this.setUnverifiedContact(v);
358
358
  return;
359
359
  }
360
- if (!((l = (r = this.config.user) == null ? void 0 : r.data) != null && l.email)) {
361
- const C = await ((u = this.storageCtx) == null ? void 0 : u.getContactToken());
362
- if (C) {
363
- await this.setUnverifiedContact(C);
360
+ if (!((c = (r = this.config.user) == null ? void 0 : r.data) != null && c.email)) {
361
+ const v = await ((u = this.storageCtx) == null ? void 0 : u.getContactToken());
362
+ if (v) {
363
+ await this.setUnverifiedContact(v);
364
364
  return;
365
365
  }
366
366
  }
367
367
  await this.createUnverifiedContact({
368
- email: (S = (_ = this.config.user) == null ? void 0 : _.data) == null ? void 0 : S.email,
369
- non_verified_name: (v = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : v.name,
370
- non_verified_custom_data: (m = (w = this.config.user) == null ? void 0 : w.data) == null ? void 0 : m.customData
368
+ email: (w = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : w.email,
369
+ non_verified_name: (C = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : C.name,
370
+ non_verified_custom_data: (f = (S = this.config.user) == null ? void 0 : S.data) == null ? void 0 : f.customData
371
371
  });
372
372
  }
373
373
  }, this.createUnverifiedContact = async (s, e) => {
@@ -383,10 +383,10 @@ class Y {
383
383
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
384
384
  }
385
385
  }, this.setUnverifiedContact = async (s) => {
386
- var n, o, r, l;
387
- const e = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), t = ((o = this.config.user) == null ? void 0 : o.externalId) || e || O();
388
- this.api.setAuthToken(s), await ((r = this.storageCtx) == null ? void 0 : r.setContactToken(s)), await ((l = this.storageCtx) == null ? void 0 : l.setExternalContactId(t)), this.state.setPartial({ contact: { token: s, externalId: t } });
389
- }, this.config = i, this.storageCtx = c, this.api = a, this.state = new y({
386
+ var n, o, r, c;
387
+ const e = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), t = ((o = this.config.user) == null ? void 0 : o.externalId) || e || z();
388
+ this.api.setAuthToken(s), await ((r = this.storageCtx) == null ? void 0 : r.setContactToken(s)), await ((c = this.storageCtx) == null ? void 0 : c.setExternalContactId(t)), this.state.setPartial({ contact: { token: s, externalId: t } });
389
+ }, this.config = i, this.storageCtx = l, this.api = a, this.state = new y({
390
390
  contact: (d = i.user) != null && d.token ? {
391
391
  token: i.user.token,
392
392
  // Set optional externalId from config... not local storage
@@ -398,14 +398,14 @@ class Y {
398
398
  }), this.autoCreateUnverifiedUserIfNotExists();
399
399
  }
400
400
  }
401
- function x() {
402
- return O();
401
+ function k() {
402
+ return z();
403
403
  }
404
- class $ {
404
+ class Y {
405
405
  constructor({
406
406
  config: i,
407
407
  api: a,
408
- sessionCtx: c,
408
+ sessionCtx: l,
409
409
  messageCtx: d
410
410
  }) {
411
411
  this.submitCsat = async (s) => {
@@ -413,7 +413,7 @@ class $ {
413
413
  const e = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
414
414
  if (!e)
415
415
  return { data: null, error: "No session id found" };
416
- const t = x();
416
+ const t = k();
417
417
  this.messageCtx.state.setPartial({
418
418
  messages: [
419
419
  ...this.messageCtx.state.get().messages,
@@ -437,17 +437,17 @@ class $ {
437
437
  session_id: e
438
438
  });
439
439
  return { data: n, error: o };
440
- }, this.config = i, this.api = a, this.sessionCtx = c, this.messageCtx = d;
440
+ }, this.config = i, this.api = a, this.sessionCtx = l, this.messageCtx = d;
441
441
  }
442
442
  }
443
- class G {
443
+ class $ {
444
444
  constructor({
445
445
  config: i,
446
446
  api: a,
447
- contactCtx: c,
447
+ contactCtx: l,
448
448
  sessionsPollingIntervalSeconds: d
449
449
  }) {
450
- this.sessionsRefresher = new R(), this.sessionState = new y({
450
+ this.sessionsRefresher = new O(), this.sessionState = new y({
451
451
  session: null,
452
452
  isCreatingSession: !1,
453
453
  isResolvingSession: !1
@@ -472,11 +472,18 @@ class G {
472
472
  this.sessionsRefresher.startPolling(async () => {
473
473
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
474
474
  }, this.sessionsPollingIntervalSeconds * 1e3);
475
- }, this.createSession = async () => {
475
+ }, this.getParsedCustomData = () => Object.fromEntries(
476
+ Object.entries(this.config.sessionCustomData || {}).map(
477
+ ([s, e]) => {
478
+ var t;
479
+ return typeof e == "string" ? [s, e] : typeof e == "boolean" ? [s, e] : typeof e == "number" ? [s, e] : [s, ((t = R(() => JSON.stringify(e))) == null ? void 0 : t.data) || ""];
480
+ }
481
+ )
482
+ ), this.createSession = async () => {
476
483
  var o;
477
484
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
478
485
  const s = (o = this.contactCtx.state.get().contact) == null ? void 0 : o.externalId, e = {
479
- ...this.config.sessionCustomData,
486
+ ...this.getParsedCustomData(),
480
487
  ...s ? { external_id: s } : {}
481
488
  }, { data: t, error: n } = await this.api.createSession({
482
489
  customData: Object.keys(e).length > 0 ? e : void 0
@@ -489,7 +496,7 @@ class G {
489
496
  });
490
497
  if (s) {
491
498
  const t = [...this.sessionsState.get().data, ...s.items].filter(
492
- (n, o, r) => o === r.findIndex((l) => n.id === l.id)
499
+ (n, o, r) => o === r.findIndex((c) => n.id === c.id)
493
500
  );
494
501
  this.sessionsState.setPartial({
495
502
  data: t,
@@ -533,25 +540,26 @@ class G {
533
540
  payload: s
534
541
  });
535
542
  return t != null && t.success ? { success: !0 } : { success: !1 };
536
- }, this.config = i, this.api = a, this.contactCtx = c, this.sessionsPollingIntervalSeconds = d, this.registerSessionsRefresherWrapper();
543
+ }, this.config = i, this.api = a, this.contactCtx = l, this.sessionsPollingIntervalSeconds = d, this.registerSessionsRefresherWrapper();
537
544
  }
538
545
  }
539
546
  class K {
540
547
  constructor({
541
548
  config: i,
542
549
  api: a,
543
- sessionCtx: c,
550
+ sessionCtx: l,
544
551
  contactCtx: d
545
552
  }) {
546
553
  this.state = new y({
547
554
  messages: [],
548
555
  isSendingMessage: !1,
556
+ isSendingMessageToAI: !1,
549
557
  lastAIResMightSolveUserIssue: !1,
550
558
  isInitialFetchLoading: !1
551
559
  }), this.sendMessageAbortController = new AbortController(), this.reset = () => {
552
560
  this.sendMessageAbortController.abort("Resetting chat"), this.state.reset();
553
561
  }, this.sendMessage = async (s) => {
554
- var e, t, n, o, r, l, u, _, S, f;
562
+ var e, t, n, o, r, c, u, p, w;
555
563
  try {
556
564
  if (!s.content.trim() && (!s.attachments || s.attachments.length === 0)) {
557
565
  console.warn(
@@ -559,21 +567,25 @@ class K {
559
567
  );
560
568
  return;
561
569
  }
562
- const v = this.state.get().isSendingMessage, w = ((e = this.sessionCtx.sessionState.get().session) == null ? void 0 : e.assignee.kind) === "ai", m = this.state.get().messages, C = m.length > 0 ? m[m.length - 1] : void 0;
563
- if (w && v || // If last message is from user, then bot response did not arrive yet
564
- w && (C == null ? void 0 : C.type) === "USER") {
570
+ const g = this.sessionCtx.sessionState.get().session, S = (g == null ? void 0 : g.assignee.kind) === "ai", f = this.state.get().isSendingMessageToAI, v = this.state.get().messages.at(-1);
571
+ if (f || // If last message is from user, then bot response did not arrive yet
572
+ S && (v == null ? void 0 : v.type) === "USER") {
565
573
  console.warn("Cannot send messages while awaiting AI response");
566
574
  return;
567
575
  }
568
- this.sendMessageAbortController = new AbortController(), this.state.setPartial({ lastAIResMightSolveUserIssue: !1 }), this.state.setPartial({ isSendingMessage: !0 });
569
- const P = this.state.get().messages, A = !((t = this.sessionCtx.sessionState.get().session) != null && t.id) && P.length === 0 && ((n = this.config.advancedInitialMessages) == null ? void 0 : n.some((g) => g.persistent)), T = A ? (this.config.advancedInitialMessages || []).filter((g) => g.persistent).map(
570
- (g) => ({
571
- id: x(),
576
+ this.sendMessageAbortController = new AbortController(), this.state.setPartial({
577
+ lastAIResMightSolveUserIssue: !1,
578
+ isSendingMessage: !0,
579
+ isSendingMessageToAI: !!S || !g
580
+ });
581
+ const P = this.state.get().messages, A = !((e = this.sessionCtx.sessionState.get().session) != null && e.id) && P.length === 0 && ((t = this.config.advancedInitialMessages) == null ? void 0 : t.some((_) => _.persistent)), T = A ? (this.config.advancedInitialMessages || []).filter((_) => _.persistent).map(
582
+ (_) => ({
583
+ id: k(),
572
584
  component: "bot_message",
573
585
  type: "AI",
574
586
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
575
587
  data: {
576
- message: g.message
588
+ message: _.message
577
589
  }
578
590
  })
579
591
  ) : [], I = this.toUserMessage(
@@ -586,16 +598,16 @@ class K {
586
598
  ...P,
587
599
  I
588
600
  ]
589
- }), !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
601
+ }), !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
590
602
  if (!await this.sessionCtx.createSession()) {
591
603
  console.error("Failed to create session");
592
604
  return;
593
605
  }
594
606
  this.sessionCtx.refreshSessions();
595
607
  }
596
- const E = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
608
+ const E = (o = this.sessionCtx.sessionState.get().session) == null ? void 0 : o.id;
597
609
  if (!E) return;
598
- const { data: p } = await this.api.sendMessage(
610
+ const { data: m } = await this.api.sendMessage(
599
611
  {
600
612
  uuid: I.id,
601
613
  bot_token: this.config.token,
@@ -612,54 +624,57 @@ class K {
612
624
  },
613
625
  language: this.config.language,
614
626
  exit_mode_prompt: s.exitModePrompt,
615
- initial_messages: A ? T.map((g) => ({
616
- uuid: g.id,
617
- content: g.data.message
627
+ initial_messages: A ? T.map((_) => ({
628
+ uuid: _.id,
629
+ content: _.data.message
618
630
  })) : void 0
619
631
  },
620
632
  this.sendMessageAbortController.signal
621
633
  );
622
- if (p != null && p.success) {
623
- const g = this.toBotMessage(p);
624
- if (g) {
625
- const k = this.state.get().messages;
626
- if (!!k.some(
627
- (F) => F.id === g.id
634
+ if (m != null && m.success) {
635
+ const _ = this.toBotMessage(m);
636
+ if (_) {
637
+ const x = this.state.get().messages;
638
+ if (!!x.some(
639
+ (j) => j.id === _.id
628
640
  )) {
629
641
  this.state.setPartial({
630
- lastAIResMightSolveUserIssue: ((l = p.autopilotResponse) == null ? void 0 : l.mightSolveUserIssue) || ((u = p.uiResponse) == null ? void 0 : u.mightSolveUserIssue)
642
+ lastAIResMightSolveUserIssue: ((r = m.autopilotResponse) == null ? void 0 : r.mightSolveUserIssue) || ((c = m.uiResponse) == null ? void 0 : c.mightSolveUserIssue)
631
643
  });
632
644
  return;
633
645
  }
634
646
  this.state.setPartial({
635
- messages: [...k, g],
636
- lastAIResMightSolveUserIssue: ((_ = p.autopilotResponse) == null ? void 0 : _.mightSolveUserIssue) || ((S = p.uiResponse) == null ? void 0 : S.mightSolveUserIssue)
647
+ messages: [...x, _],
648
+ lastAIResMightSolveUserIssue: ((u = m.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((p = m.uiResponse) == null ? void 0 : p.mightSolveUserIssue)
637
649
  });
638
650
  }
639
- p.session && this.sessionCtx.sessionState.setPartial({ session: p.session });
651
+ m.session && this.sessionCtx.sessionState.setPartial({ session: m.session });
640
652
  } else {
641
- const g = this.toBotErrorMessage(
642
- ((f = p == null ? void 0 : p.error) == null ? void 0 : f.message) || "Unknown error occurred"
643
- ), k = this.state.get().messages;
653
+ const _ = this.toBotErrorMessage(
654
+ ((w = m == null ? void 0 : m.error) == null ? void 0 : w.message) || "Unknown error occurred"
655
+ ), x = this.state.get().messages;
644
656
  this.state.setPartial({
645
- messages: [...k, g]
657
+ messages: [...x, _]
646
658
  });
647
659
  }
648
- } catch (v) {
649
- this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", v);
660
+ } catch (g) {
661
+ this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", g);
650
662
  } finally {
651
- this.state.setPartial({ isSendingMessage: !1 });
663
+ this.state.setPartial({
664
+ isSendingMessage: !1,
665
+ isSendingMessageToAI: !1
666
+ });
652
667
  }
653
668
  }, this.toUserMessage = (s, e) => {
654
669
  const t = (() => {
655
670
  const n = this.contactCtx.state.get().extraCollectedData;
656
- return this.state.get().messages.length === 0 && n && Object.keys(n).length > 0 ? `${Object.entries(n).filter(([r, l]) => !!l).map(([r, l]) => `${r}: ${l}`).join(`
671
+ return this.state.get().messages.length === 0 && n && Object.keys(n).length > 0 ? `${Object.entries(n).filter(([r, c]) => !!c).map(([r, c]) => `${r}: ${c}`).join(`
657
672
  `)}
658
673
 
659
674
  ${s}` : s;
660
675
  })();
661
676
  return {
662
- id: x(),
677
+ id: k(),
663
678
  type: "USER",
664
679
  content: t,
665
680
  deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -670,7 +685,7 @@ ${s}` : s;
670
685
  var e;
671
686
  return s.success && s.autopilotResponse ? {
672
687
  type: "AI",
673
- id: s.autopilotResponse.id || x(),
688
+ id: s.autopilotResponse.id || k(),
674
689
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
675
690
  component: "bot_message",
676
691
  agent: this.config.bot ? {
@@ -689,7 +704,7 @@ ${s}` : s;
689
704
  } : null;
690
705
  }, this.toBotErrorMessage = (s) => ({
691
706
  type: "AI",
692
- id: x(),
707
+ id: k(),
693
708
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
694
709
  component: "TEXT",
695
710
  data: {
@@ -697,14 +712,14 @@ ${s}` : s;
697
712
  variant: "error",
698
713
  action: void 0
699
714
  }
700
- }), this.config = i, this.api = a, this.sessionCtx = c, this.contactCtx = d;
715
+ }), this.config = i, this.api = a, this.sessionCtx = l, this.contactCtx = d;
701
716
  }
702
717
  }
703
- class W {
718
+ class G {
704
719
  constructor({
705
720
  config: i,
706
721
  contactCtx: a,
707
- sessionCtx: c,
722
+ sessionCtx: l,
708
723
  resetChat: d
709
724
  }) {
710
725
  var s;
@@ -716,14 +731,14 @@ class W {
716
731
  });
717
732
  }), this.sessionCtx.sessionsState.subscribe(
718
733
  ({ isInitialFetchLoading: e, data: t }) => {
719
- var n, o, r, l;
734
+ var n, o, r, c;
720
735
  if ((n = this.config.router) != null && n.chatScreenOnly && // Do not route to a chat if we are currently inside one already
721
736
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
722
737
  !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
723
- const u = (r = t.find((_) => _.isOpened)) == null ? void 0 : r.id;
738
+ const u = (r = t.find((p) => p.isOpened)) == null ? void 0 : r.id;
724
739
  return u ? this.toChatScreen(u) : void 0;
725
740
  }
726
- t.length || ((l = this.config.router) == null ? void 0 : l.goToChatIfNoSessions) !== !1 && !e && this.state.get().screen !== "chat" && this.toChatScreen();
741
+ t.length || ((c = this.config.router) == null ? void 0 : c.goToChatIfNoSessions) !== !1 && !e && this.state.get().screen !== "chat" && this.toChatScreen();
727
742
  }
728
743
  );
729
744
  }, this.toSessionsScreen = () => {
@@ -735,23 +750,23 @@ class W {
735
750
  this.sessionCtx.sessionState.setPartial({ session: t });
736
751
  }
737
752
  this.state.setPartial({ screen: "chat" });
738
- }, this.config = i, this.contactCtx = a, this.sessionCtx = c, this.resetChat = d, this.state = new y({
753
+ }, this.config = i, this.contactCtx = a, this.sessionCtx = l, this.resetChat = d, this.state = new y({
739
754
  screen: this.contactCtx.shouldCollectData() ? "welcome" : (s = this.config.router) != null && s.chatScreenOnly ? "chat" : "sessions"
740
755
  }), this.registerRoutingListener();
741
756
  }
742
757
  }
743
- class V {
758
+ class J {
744
759
  constructor({
745
760
  storage: i,
746
761
  config: a
747
762
  }) {
748
763
  this.KEYS = {
749
- contactToken: (c) => `opencx-widget:org-token-${c}:contact-token`,
750
- externalContactId: (c) => `opencx-widget:org-token-${c}:external-contact-id`
751
- }, this.setContactToken = async (c) => {
752
- await this.storage.set(this.KEYS.contactToken(this.config.token), c);
753
- }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken(this.config.token)), this.setExternalContactId = async (c) => {
754
- await this.storage.set(this.KEYS.externalContactId(this.config.token), c);
764
+ contactToken: (l) => `opencx-widget:org-token-${l}:contact-token`,
765
+ externalContactId: (l) => `opencx-widget:org-token-${l}:external-contact-id`
766
+ }, this.setContactToken = async (l) => {
767
+ await this.storage.set(this.KEYS.contactToken(this.config.token), l);
768
+ }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken(this.config.token)), this.setExternalContactId = async (l) => {
769
+ await this.storage.set(this.KEYS.externalContactId(this.config.token), l);
755
770
  }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.storage = i, this.config = a;
756
771
  }
757
772
  }
@@ -759,7 +774,7 @@ const b = class b {
759
774
  constructor({
760
775
  config: i,
761
776
  storage: a,
762
- modes: c,
777
+ modes: l,
763
778
  org: d
764
779
  }) {
765
780
  if (this.modes = [], this.resetChat = () => {
@@ -768,11 +783,11 @@ const b = class b {
768
783
  throw Error(
769
784
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
770
785
  );
771
- this.config = i, this.org = d, this.api = new M({ config: i }), this.storageCtx = a ? new V({ storage: a, config: i }) : void 0, this.modes = c, this.contactCtx = new Y({
786
+ this.config = i, this.org = d, this.api = new M({ config: i }), this.storageCtx = a ? new J({ storage: a, config: i }) : void 0, this.modes = l, this.contactCtx = new V({
772
787
  api: this.api,
773
788
  config: this.config,
774
789
  storageCtx: this.storageCtx
775
- }), this.sessionCtx = new G({
790
+ }), this.sessionCtx = new $({
776
791
  config: this.config,
777
792
  api: this.api,
778
793
  contactCtx: this.contactCtx,
@@ -782,7 +797,7 @@ const b = class b {
782
797
  api: this.api,
783
798
  sessionCtx: this.sessionCtx,
784
799
  contactCtx: this.contactCtx
785
- }), this.csatCtx = new $({
800
+ }), this.csatCtx = new Y({
786
801
  config: this.config,
787
802
  api: this.api,
788
803
  sessionCtx: this.sessionCtx,
@@ -793,7 +808,7 @@ const b = class b {
793
808
  sessionCtx: this.sessionCtx,
794
809
  messageCtx: this.messageCtx,
795
810
  sessionPollingIntervalSeconds: b.pollingIntervalsSeconds.session
796
- }), this.routerCtx = new W({
811
+ }), this.routerCtx = new G({
797
812
  config: this.config,
798
813
  contactCtx: this.contactCtx,
799
814
  sessionCtx: this.sessionCtx,
@@ -806,26 +821,26 @@ b.pollingIntervalsSeconds = null, b.initialize = async ({
806
821
  storage: a
807
822
  }) => {
808
823
  var d, s, e;
809
- const c = await new M({
824
+ const l = await new M({
810
825
  config: i
811
826
  }).getExternalWidgetConfig();
812
- if (!c.data)
827
+ if (!l.data)
813
828
  throw new Error("Failed to fetch widget config");
814
829
  return b.pollingIntervalsSeconds = {
815
- session: ((d = c.data) == null ? void 0 : d.sessionPollingIntervalSeconds) || 10,
816
- sessions: ((s = c.data) == null ? void 0 : s.sessionsPollingIntervalSeconds) || 60
830
+ session: ((d = l.data) == null ? void 0 : d.sessionPollingIntervalSeconds) || 10,
831
+ sessions: ((s = l.data) == null ? void 0 : s.sessionsPollingIntervalSeconds) || 60
817
832
  }, new b({
818
833
  config: i,
819
834
  storage: a,
820
- modes: ((e = c.data) == null ? void 0 : e.modes) || [],
835
+ modes: ((e = l.data) == null ? void 0 : e.modes) || [],
821
836
  org: {
822
- id: c.data.org.id,
823
- name: c.data.org.name
837
+ id: l.data.org.id,
838
+ name: l.data.org.name
824
839
  }
825
840
  });
826
841
  };
827
842
  let U = b;
828
- const J = {
843
+ const W = {
829
844
  write_a_message_placeholder: "اكتب رسالة...",
830
845
  your_issue_has_been_resolved: "تم حل مشكلتك!",
831
846
  new_conversation: "محادثة جديدة",
@@ -842,6 +857,22 @@ const J = {
842
857
  back_to_conversations: "العودة إلى المحادثات",
843
858
  closed_conversations: "المحادثات المغلقة"
844
859
  }, X = {
860
+ write_a_message_placeholder: "Skriv en besked...",
861
+ your_issue_has_been_resolved: "Dit problem er løst!",
862
+ new_conversation: "Ny samtale",
863
+ welcome_screen_title: "Velkommen til vores support chat",
864
+ welcome_screen_description: "Vi er her for at hjælpe! Start en samtale, og vi vender tilbage til dig så hurtigt som muligt.",
865
+ your_name_placeholder: "Dit navn",
866
+ your_email_placeholder: "Din e-mailadresse",
867
+ start_chat_button: "Tal med support",
868
+ start_chat_button_loading: "Forbinder...",
869
+ i_need_more_help: "Jeg har brug for mere hjælp",
870
+ this_was_helpful: "Dette var nyttigt",
871
+ optional: "Valgfrit",
872
+ no_conversations_yet: "Ingen samtaler endnu",
873
+ back_to_conversations: "Tilbage til samtaler",
874
+ closed_conversations: "Lukkede samtaler"
875
+ }, Z = {
845
876
  write_a_message_placeholder: "Nachricht schreiben...",
846
877
  your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
847
878
  new_conversation: "Neue Konversation",
@@ -857,7 +888,7 @@ const J = {
857
888
  no_conversations_yet: "noch keine Gespräche",
858
889
  back_to_conversations: "Zurück zur Konversationen",
859
890
  closed_conversations: "Geschlossene Konversationen"
860
- }, Z = {
891
+ }, Q = {
861
892
  write_a_message_placeholder: "Write a message...",
862
893
  your_issue_has_been_resolved: "Your issue has been resolved!",
863
894
  new_conversation: "New conversation",
@@ -873,7 +904,7 @@ const J = {
873
904
  no_conversations_yet: "No conversations yet",
874
905
  back_to_conversations: "Back to conversations",
875
906
  closed_conversations: "Closed conversations"
876
- }, Q = {
907
+ }, ee = {
877
908
  write_a_message_placeholder: "Escribe un mensaje...",
878
909
  your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
879
910
  new_conversation: "Nueva conversación",
@@ -889,7 +920,23 @@ const J = {
889
920
  no_conversations_yet: "Sin conversaciones aún",
890
921
  back_to_conversations: "Volver a conversaciones",
891
922
  closed_conversations: "Conversaciones cerradas"
892
- }, ee = {
923
+ }, te = {
924
+ write_a_message_placeholder: "Kirjoita viesti...",
925
+ your_issue_has_been_resolved: "Ongelmasi on ratkaistu!",
926
+ new_conversation: "Uusi keskustelu",
927
+ welcome_screen_title: "Tervetuloa tukichattiin",
928
+ welcome_screen_description: "Olemme täällä auttamassa! Aloita keskustelu ja palaamme sinulle mahdollisimman pian.",
929
+ your_name_placeholder: "Nimesi",
930
+ your_email_placeholder: "Sähköpostiosoitteesi",
931
+ start_chat_button: "Keskustele tuen kanssa",
932
+ start_chat_button_loading: "Yhdistetään...",
933
+ i_need_more_help: "Tarvitsen lisää apua",
934
+ this_was_helpful: "Tämä oli hyödyllistä",
935
+ optional: "Valinnainen",
936
+ no_conversations_yet: "Ei vielä keskusteluja",
937
+ back_to_conversations: "Takaisin keskusteluihin",
938
+ closed_conversations: "Suljetut keskustelut"
939
+ }, se = {
893
940
  write_a_message_placeholder: "Écrivez un message...",
894
941
  your_issue_has_been_resolved: "Votre problème a été résolu !",
895
942
  new_conversation: "Nouvelle conversation",
@@ -905,7 +952,23 @@ const J = {
905
952
  no_conversations_yet: "Aucune conversation pour le moment",
906
953
  back_to_conversations: "Retour aux conversations",
907
954
  closed_conversations: "Conversations fermées"
908
- }, te = {
955
+ }, ie = {
956
+ write_a_message_placeholder: "Scrivi un messaggio...",
957
+ your_issue_has_been_resolved: "Il tuo problema è stato risolto!",
958
+ new_conversation: "Nuova conversazione",
959
+ welcome_screen_title: "Benvenuto nella nostra chat di supporto",
960
+ welcome_screen_description: "Siamo qui per aiutarti! Inizia una conversazione e ti risponderemo il prima possibile.",
961
+ your_name_placeholder: "Il tuo nome",
962
+ your_email_placeholder: "Il tuo indirizzo email",
963
+ start_chat_button: "Parla con il supporto",
964
+ start_chat_button_loading: "Connessione in corso...",
965
+ i_need_more_help: "Ho bisogno di ulteriore aiuto",
966
+ this_was_helpful: "Questo è stato utile",
967
+ optional: "Opzionale",
968
+ no_conversations_yet: "Nessuna conversazione ancora",
969
+ back_to_conversations: "Torna alle conversazioni",
970
+ closed_conversations: "Conversazioni chiuse"
971
+ }, ne = {
909
972
  write_a_message_placeholder: "Schrijf een bericht...",
910
973
  your_issue_has_been_resolved: "Uw probleem is opgelost!",
911
974
  new_conversation: "Nieuw gesprek",
@@ -921,7 +984,23 @@ const J = {
921
984
  no_conversations_yet: "Nog geen gesprekken",
922
985
  back_to_conversations: "Terug naar gesprekken",
923
986
  closed_conversations: "Afgesloten gesprekken"
924
- }, se = {
987
+ }, ae = {
988
+ write_a_message_placeholder: "Skriv en melding...",
989
+ your_issue_has_been_resolved: "Problemet ditt er løst!",
990
+ new_conversation: "Ny samtale",
991
+ welcome_screen_title: "Velkommen til vår kundestøtte-chat",
992
+ welcome_screen_description: "Vi er her for å hjelpe! Start en samtale så kommer vi tilbake til deg så snart som mulig.",
993
+ your_name_placeholder: "Ditt navn",
994
+ your_email_placeholder: "Din e-postadresse",
995
+ start_chat_button: "Snakk med kundestøtte",
996
+ start_chat_button_loading: "Kobler til...",
997
+ i_need_more_help: "Jeg trenger mer hjelp",
998
+ this_was_helpful: "Dette var nyttig",
999
+ optional: "Valgfritt",
1000
+ no_conversations_yet: "Ingen samtaler ennå",
1001
+ back_to_conversations: "Tilbake til samtaler",
1002
+ closed_conversations: "Lukkede samtaler"
1003
+ }, oe = {
925
1004
  write_a_message_placeholder: "Napisz wiadomość...",
926
1005
  your_issue_has_been_resolved: "Twój problem został rozwiązany!",
927
1006
  new_conversation: "Nowa rozmowa",
@@ -937,7 +1016,7 @@ const J = {
937
1016
  no_conversations_yet: "Jeszcze brak rozmów",
938
1017
  back_to_conversations: "Powrót do rozmów",
939
1018
  closed_conversations: "Zamknięte rozmowy"
940
- }, ie = {
1019
+ }, re = {
941
1020
  write_a_message_placeholder: "Escreva uma mensagem...",
942
1021
  your_issue_has_been_resolved: "Seu problema foi resolvido!",
943
1022
  new_conversation: "Nova conversa",
@@ -953,7 +1032,39 @@ const J = {
953
1032
  no_conversations_yet: "Nenhuma conversa ainda",
954
1033
  back_to_conversations: "Voltar para conversas",
955
1034
  closed_conversations: "Conversas fechadas"
956
- }, ne = {
1035
+ }, le = {
1036
+ write_a_message_placeholder: "Scrie un mesaj...",
1037
+ your_issue_has_been_resolved: "Problema ta a fost rezolvată!",
1038
+ new_conversation: "Conversație nouă",
1039
+ welcome_screen_title: "Bine ai venit la chat-ul nostru de suport",
1040
+ welcome_screen_description: "Suntem aici să te ajutăm! Începe o conversație și îți vom răspunde cât mai curând posibil.",
1041
+ your_name_placeholder: "Numele tău",
1042
+ your_email_placeholder: "Adresa ta de email",
1043
+ start_chat_button: "Vorbește cu suportul",
1044
+ start_chat_button_loading: "Se conectează...",
1045
+ i_need_more_help: "Am nevoie de mai mult ajutor",
1046
+ this_was_helpful: "Acest lucru a fost util",
1047
+ optional: "Opțional",
1048
+ no_conversations_yet: "Încă nu există conversații",
1049
+ back_to_conversations: "Înapoi la conversații",
1050
+ closed_conversations: "Conversații închise"
1051
+ }, ce = {
1052
+ write_a_message_placeholder: "Skriv ett meddelande...",
1053
+ your_issue_has_been_resolved: "Ditt problem har lösts!",
1054
+ new_conversation: "Ny konversation",
1055
+ welcome_screen_title: "Välkommen till vår supportchatt",
1056
+ welcome_screen_description: "Vi är här för att hjälpa! Starta en konversation så återkommer vi till dig så snart som möjligt.",
1057
+ your_name_placeholder: "Ditt namn",
1058
+ your_email_placeholder: "Din e-postadress",
1059
+ start_chat_button: "Prata med support",
1060
+ start_chat_button_loading: "Ansluter...",
1061
+ i_need_more_help: "Jag behöver mer hjälp",
1062
+ this_was_helpful: "Detta var användbart",
1063
+ optional: "Frivilligt",
1064
+ no_conversations_yet: "Inga konversationer ännu",
1065
+ back_to_conversations: "Tillbaka till konversationer",
1066
+ closed_conversations: "Stängda konversationer"
1067
+ }, he = {
957
1068
  write_a_message_placeholder: "Bir mesaj yazın...",
958
1069
  your_issue_has_been_resolved: "Sorununuz çözüldü!",
959
1070
  new_conversation: "Yeni konuşma",
@@ -969,29 +1080,35 @@ const J = {
969
1080
  no_conversations_yet: "Henüz konuşma yok",
970
1081
  back_to_conversations: "Konuşmalara geri dön",
971
1082
  closed_conversations: "Kapatılan konuşmalar"
972
- }, z = {
973
- en: Z,
974
- ar: J,
975
- nl: te,
976
- fr: ee,
977
- de: X,
978
- pt: ie,
979
- es: Q,
980
- tr: ne,
981
- pl: se
982
- }, ae = Object.keys(z);
983
- function he(h) {
984
- return ae.includes(h);
1083
+ }, D = {
1084
+ en: Q,
1085
+ ar: W,
1086
+ nl: ne,
1087
+ fr: se,
1088
+ de: Z,
1089
+ pt: re,
1090
+ es: ee,
1091
+ tr: he,
1092
+ pl: oe,
1093
+ fi: te,
1094
+ it: ie,
1095
+ no: ae,
1096
+ ro: le,
1097
+ da: X,
1098
+ sv: ce
1099
+ }, de = Object.keys(D);
1100
+ function pe(h) {
1101
+ return de.includes(h);
985
1102
  }
986
- function de(h, i, a) {
987
- var c;
988
- return ((c = a == null ? void 0 : a[i]) == null ? void 0 : c[h]) || z[i][h] || "";
1103
+ function fe(h, i, a) {
1104
+ var l;
1105
+ return ((l = a == null ? void 0 : a[i]) == null ? void 0 : l[h]) || D[i][h] || "";
989
1106
  }
990
1107
  export {
991
1108
  y as PrimitiveState,
992
1109
  U as WidgetCtx,
993
- de as getTranslation,
994
- B as isExhaustive,
995
- he as isSupportedLanguage
1110
+ fe as getTranslation,
1111
+ H as isExhaustive,
1112
+ pe as isSupportedLanguage
996
1113
  };
997
1114
  //# sourceMappingURL=index.js.map