@opencx/widget 2.6.0 → 2.6.1

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.
Files changed (99) hide show
  1. package/dist/api-BwKgAJ6p.cjs +2 -0
  2. package/dist/api-BwKgAJ6p.cjs.map +1 -0
  3. package/dist/api-DRZ9vPwy.js +1360 -0
  4. package/dist/api-DRZ9vPwy.js.map +1 -0
  5. package/dist/basic.cjs +85 -85
  6. package/dist/basic.cjs.map +1 -1
  7. package/dist/basic.js +13350 -12831
  8. package/dist/basic.js.map +1 -1
  9. package/dist/core/client/api.d.ts +368 -40
  10. package/dist/core/client/chat.d.ts +27 -19
  11. package/dist/core/client/config.d.ts +13 -3
  12. package/dist/core/client/contact.d.ts +2 -12
  13. package/dist/core/sdk/index.d.ts +11 -0
  14. package/dist/core/types/helpers.d.ts +3 -0
  15. package/dist/core/types/index.d.ts +6 -6
  16. package/dist/core/types/messages.d.ts +20 -9
  17. package/dist/core/types/schemas-v2.d.ts +10 -713
  18. package/dist/index-B5YLfjom.cjs +18 -0
  19. package/dist/index-B5YLfjom.cjs.map +1 -0
  20. package/dist/index-EZN9_jan.js +1219 -0
  21. package/dist/index-EZN9_jan.js.map +1 -0
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.js +22 -1071
  25. package/dist/index.js.map +1 -1
  26. package/dist/react-web/core-integration/ChatProvider.d.ts +101 -0
  27. package/dist/react-web/core-integration/components.d.ts +11 -0
  28. package/dist/react-web/core-integration/hooks/useChatMessages.d.ts +64 -0
  29. package/dist/react-web/core-integration/hooks/useChatSession.d.ts +77 -0
  30. package/dist/react-web/core-integration/hooks/useConfig.d.ts +1 -0
  31. package/dist/react-web/core-integration/hooks/useContact.d.ts +11 -0
  32. package/dist/react-web/core-integration/hooks/useLocale.d.ts +4 -0
  33. package/dist/react-web/core-integration/hooks/usePreludeData.d.ts +36 -0
  34. package/dist/react-web/core-integration/hooks/usePubsub.d.ts +2 -0
  35. package/dist/react-web/{hooks → core-integration/hooks}/useUploadFiles.d.ts +2 -2
  36. package/dist/react-web/{hooks → core-integration/hooks}/useVote.d.ts +2 -2
  37. package/dist/react-web/core-integration/hooks.d.ts +9 -0
  38. package/dist/react-web/core-integration/index.d.ts +2 -0
  39. package/dist/react-web/index.d.ts +4 -10
  40. package/dist/react-web/types/components.d.ts +6 -3
  41. package/dist/react-web/types/index.d.ts +3 -2
  42. package/dist/react-web/types/options.d.ts +4 -30
  43. package/dist/react.cjs +1 -1
  44. package/dist/react.cjs.map +1 -1
  45. package/dist/react.js +10 -46
  46. package/dist/react.js.map +1 -1
  47. package/dist/src/@components/BotOrAgentMessageGroup.d.ts +1 -2
  48. package/dist/src/@components/BotOrAgentMessageWrapper.d.ts +2 -2
  49. package/dist/src/@components/ChatEvent.component.d.ts +3 -3
  50. package/dist/src/@components/Text.component.d.ts +1 -1
  51. package/dist/src/components/button.d.ts +1 -1
  52. package/dist/src/components/dialog.d.ts +9 -9
  53. package/dist/src/designs/basic/index.d.ts +1 -1
  54. package/dist/style.css +1 -1
  55. package/dist-embed/script.js +119 -124
  56. package/dist-embed/script.js.map +1 -1
  57. package/package.json +7 -4
  58. package/dist/core/tests/utils/create-fetch.test.d.ts +0 -1
  59. package/dist/core/types/schemas.d.ts +0 -543
  60. package/dist/core/utils/create-fetch.d.ts +0 -25
  61. package/dist/core/utils/genId.d.ts +0 -2
  62. package/dist/core/utils/history-to-widget-messages.d.ts +0 -4
  63. package/dist/genUuid-C12yFv3j.js +0 -137
  64. package/dist/genUuid-C12yFv3j.js.map +0 -1
  65. package/dist/genUuid-DdeSE04H.cjs +0 -2
  66. package/dist/genUuid-DdeSE04H.cjs.map +0 -1
  67. package/dist/index-C87obATS.js +0 -2616
  68. package/dist/index-C87obATS.js.map +0 -1
  69. package/dist/index-ChwS_h0D.cjs +0 -18
  70. package/dist/index-ChwS_h0D.cjs.map +0 -1
  71. package/dist/package.json.d.ts +0 -158
  72. package/dist/react-web/Root.d.ts +0 -6
  73. package/dist/react-web/hooks/index.d.ts +0 -6
  74. package/dist/react-web/hooks/use-sound.d.ts +0 -13
  75. package/dist/react-web/hooks/use-sound.test.d.ts +0 -1
  76. package/dist/react-web/hooks/use-sync-state.test.d.ts +0 -1
  77. package/dist/react-web/hooks/useAbstractChat.d.ts +0 -157
  78. package/dist/react-web/hooks/useAxiosInstance.d.ts +0 -190
  79. package/dist/react-web/hooks/useSyncState.d.ts +0 -4
  80. package/dist/react-web/hooks/useTimeoutState.d.ts +0 -3
  81. package/dist/react-web/providers/ChatProvider.d.ts +0 -143
  82. package/dist/react-web/providers/ConfigDataProvider.d.ts +0 -62
  83. package/dist/react-web/providers/ContactProvider.d.ts +0 -58
  84. package/dist/react-web/providers/LocalesProvider.d.ts +0 -11
  85. package/dist/react-web/providers/componentRegistry.d.ts +0 -13
  86. package/dist/react-web/providers/use-widget-sfx.d.ts +0 -7
  87. package/dist/react-web/providers/usePreludeData.d.ts +0 -2
  88. package/dist/react-web/utils/debug.d.ts +0 -2
  89. package/dist/react-web/utils/getters.d.ts +0 -24
  90. package/dist/react-web/utils/index.d.ts +0 -1
  91. package/dist/src/hooks/useShouldCollectData.d.ts +0 -3
  92. /package/dist/react-web/{locales → core-integration/locales}/ar.locale.d.ts +0 -0
  93. /package/dist/react-web/{locales → core-integration/locales}/de.locale.d.ts +0 -0
  94. /package/dist/react-web/{locales → core-integration/locales}/en.locale.d.ts +0 -0
  95. /package/dist/react-web/{locales → core-integration/locales}/fr.locale.d.ts +0 -0
  96. /package/dist/react-web/{locales → core-integration/locales}/helper.d.ts +0 -0
  97. /package/dist/react-web/{locales → core-integration/locales}/index.d.ts +0 -0
  98. /package/dist/react-web/{locales → core-integration/locales}/nl.locale.d.ts +0 -0
  99. /package/dist/react-web/{locales → core-integration/locales}/pt.locale.d.ts +0 -0
package/dist/index.js CHANGED
@@ -1,1074 +1,25 @@
1
- var j = Object.defineProperty;
2
- var k = (s) => {
3
- throw TypeError(s);
4
- };
5
- var B = (s, e, t) => e in s ? j(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
6
- var E = (s, e, t) => B(s, typeof e != "symbol" ? e + "" : e, t), $ = (s, e, t) => e.has(s) || k("Cannot " + t);
7
- var h = (s, e, t) => ($(s, e, "read from private field"), t ? t.call(s) : e.get(s)), N = (s, e, t) => e.has(s) ? k("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(s) : e.set(s, t), _ = (s, e, t, n) => ($(s, e, "write to private field"), n ? n.call(s, t) : e.set(s, t), t);
8
- import H from "lodash.isequal";
9
- import { g as F } from "./genUuid-C12yFv3j.js";
10
- import { M as ye, c as Pe } from "./genUuid-C12yFv3j.js";
11
- import "whatwg-fetch";
12
- var J = /* @__PURE__ */ ((s) => (s.INIT = "init", s.STATE_CHANGE = "stateChange", s.BEFORE_UPDATE = "beforeUpdate", s.AFTER_UPDATE = "afterUpdate", s.DESTROY = "destroy", s.ERROR = "error", s))(J || {}), P, v;
13
- class U {
14
- constructor(e) {
15
- E(this, "subscribers", /* @__PURE__ */ new Set());
16
- N(this, P);
17
- E(this, "initialState");
18
- N(this, v);
19
- E(this, "lifecycleListeners", /* @__PURE__ */ new Map());
20
- E(this, "emitLifecycle", (e, t) => {
21
- const n = this.lifecycleListeners.get(e);
22
- if (n) {
23
- const f = {
24
- type: e,
25
- timestamp: Date.now(),
26
- data: t
27
- };
28
- n.forEach((i) => {
29
- try {
30
- i(f);
31
- } catch (r) {
32
- console.error("Error in lifecycle listener:", r);
33
- }
34
- });
35
- }
36
- });
37
- E(this, "notifySubscribers", (e) => {
38
- Array.from(this.subscribers).forEach((n) => {
39
- try {
40
- n(e);
41
- } catch (f) {
42
- this.emitLifecycle("error", { error: f }), console.error("Error in subscriber:", f);
43
- }
44
- });
45
- });
46
- /**
47
- * Subscribe to state changes
48
- * @param callback Function to call when state changes
49
- * @returns Unsubscribe function
50
- */
51
- E(this, "subscribe", (e) => (this.subscribers.add(e), () => {
52
- this.subscribers.delete(e);
53
- }));
54
- E(this, "onLifecycle", (e, t) => {
55
- this.lifecycleListeners.has(e) || this.lifecycleListeners.set(e, /* @__PURE__ */ new Set());
56
- const n = this.lifecycleListeners.get(e);
57
- return n.add(t), () => {
58
- n.delete(t), n.size === 0 && this.lifecycleListeners.delete(e);
59
- };
60
- });
61
- /**
62
- * Get the current state
63
- */
64
- E(this, "getState", () => h(this, P));
65
- /**
66
- * Set the state and notify subscribers if the state changes
67
- * @param newState The new state to set
68
- */
69
- E(this, "setState", (e) => {
70
- this.emitLifecycle("beforeUpdate", {
71
- previousState: h(this, P),
72
- nextState: e
73
- }), H(h(this, P), e) || (_(this, P, e), _(this, v, Date.now()), this.emitLifecycle("stateChange", { state: e }), this.notifySubscribers(e)), this.emitLifecycle("afterUpdate", { state: e });
74
- });
75
- E(this, "setStatePartial", (e) => {
76
- if (e == null) return;
77
- const t = { ...h(this, P), ...e };
78
- this.setState(t);
79
- });
80
- /**
81
- * Clear all subscriptions
82
- */
83
- E(this, "clear", () => {
84
- this.emitLifecycle(
85
- "destroy"
86
- /* DESTROY */
87
- ), this.subscribers = /* @__PURE__ */ new Set(), this.lifecycleListeners = /* @__PURE__ */ new Map();
88
- });
89
- E(this, "reset", () => {
90
- this.setState(this.initialState);
91
- });
92
- E(this, "lastUpdated", () => h(this, v));
93
- _(this, P, e), this.initialState = e, _(this, v, Date.now()), this.emitLifecycle("init", { initialState: h(this, P) });
94
- }
95
- }
96
- P = new WeakMap(), v = new WeakMap();
97
- function ae(s) {
98
- return new U(s);
99
- }
100
- class I extends Error {
101
- constructor(e) {
102
- super(e), this.name = "OpenCXError";
103
- }
104
- }
105
- class ne extends I {
106
- constructor(e = "Connection failed") {
107
- super(e), this.name = "ConnectionError";
108
- }
109
- }
110
- class oe extends I {
111
- constructor(e = "Authentication failed") {
112
- super(e), this.name = "AuthenticationError";
113
- }
114
- }
115
- class X extends I {
116
- constructor(e = "Session error occurred") {
117
- super(e), this.name = "SessionError";
118
- }
119
- }
120
- class ie extends X {
121
- constructor(e = "Session not defined") {
122
- super(e), this.name = "SessionNotDefinedError";
123
- }
124
- }
125
- class le extends I {
126
- constructor(e = "Transport error occurred") {
127
- super(e), this.name = "TransportError";
128
- }
129
- }
130
- class ce extends I {
131
- constructor(e = "File upload failed") {
132
- super(e), this.name = "FileUploadError";
133
- }
134
- }
135
- class K extends I {
136
- constructor(e = "Storage is not available") {
137
- super(e), this.name = "StorageNotAvailableError";
138
- }
139
- }
140
- class V extends I {
141
- constructor(e = "External ID is not defined") {
142
- super(e), this.name = "ExternalIdNotDefinedError";
143
- }
144
- }
145
- function L(s) {
146
- if (!s) return !1;
147
- try {
148
- return typeof s.isAvailable == "function" ? s.isAvailable() : !0;
149
- } catch {
150
- return !1;
151
- }
152
- }
153
- async function M(s, e) {
154
- try {
155
- return { success: !0, result: await s(), error: null };
156
- } catch (t) {
157
- return console.error(e, t), {
158
- success: !1,
159
- result: null,
160
- error: {
161
- message: t instanceof Error ? t.message || "Unknown error" : (t == null ? void 0 : t.toString()) || "Unknown error",
162
- code: "STORAGE_OPERATION_FAILED",
163
- context: e
164
- }
165
- };
166
- }
167
- }
168
- function ue(s = {}) {
169
- const {
170
- level: e = "info",
171
- prefix: t = "[openCx]",
172
- enabled: n = !0
173
- } = s;
174
- let f = e;
175
- const i = {
176
- debug: 0,
177
- info: 1,
178
- warn: 2,
179
- error: 3
180
- };
181
- function r(u) {
182
- return n && i[u] >= i[f];
183
- }
184
- function l(u) {
185
- return `${t} ${u}`;
186
- }
187
- function c(u) {
188
- return u.map((a) => {
189
- if (a instanceof Error)
190
- return {
191
- name: a.name,
192
- message: a.message,
193
- stack: a.stack
194
- };
195
- if (typeof a == "object")
196
- try {
197
- return JSON.stringify(a, null, 2);
198
- } catch {
199
- return a;
200
- }
201
- return a;
202
- });
203
- }
204
- return {
205
- debug(u, ...a) {
206
- r("debug") && console.debug(l(u), ...c(a));
207
- },
208
- info(u, ...a) {
209
- r("info") && console.info(l(u), ...c(a));
210
- },
211
- warn(u, ...a) {
212
- r("warn") && console.warn(l(u), ...c(a));
213
- },
214
- error(u, ...a) {
215
- r("error") && console.error(l(u), ...c(a));
216
- },
217
- setLevel(u) {
218
- f = u;
219
- }
220
- };
221
- }
222
- function fe(s) {
223
- if (!s) return !1;
224
- try {
225
- return typeof s.isAvailable == "function" ? s.isAvailable() : !0;
226
- } catch {
227
- return !1;
228
- }
229
- }
230
- async function de(s, e) {
231
- try {
232
- return await s(), { success: !0, error: null };
233
- } catch (t) {
234
- return console.error(e, t), {
235
- success: !1,
236
- error: {
237
- message: t instanceof Error ? t.message || "Unknown error" : (t == null ? void 0 : t.toString()) || "Unknown error",
238
- code: "AUDIO_OPERATION_FAILED",
239
- context: e
240
- }
241
- };
242
- }
243
- }
244
- const D = {
245
- SESSION: 1e4,
246
- // every 10 seconds
247
- MESSAGES: 5e3
248
- // every 5 seconds
249
- };
250
- function G(s) {
251
- const e = {
252
- id: s.publicId,
253
- timestamp: s.sentAt || "",
254
- attachments: s.attachments || void 0
255
- };
256
- return s.sender.kind === "user" ? {
257
- ...e,
258
- type: "FROM_USER",
259
- content: s.content.text || "",
260
- deliveredAt: s.sentAt || ""
261
- } : s.sender.kind === "agent" ? {
262
- id: s.publicId,
263
- type: "FROM_AGENT",
264
- component: s.type,
265
- data: {
266
- text: s.content.text
267
- },
268
- timestamp: s.sentAt || "",
269
- attachments: s.attachments || void 0
270
- } : {
271
- ...e,
272
- type: "FROM_BOT",
273
- component: "TEXT",
274
- agent: {
275
- id: null,
276
- name: s.sender.name || "",
277
- is_ai: s.sender.kind === "ai",
278
- profile_picture: s.sender.avatar
279
- },
280
- data: {
281
- message: s.content.text
282
- }
283
- };
284
- }
285
- function z(s, e, t) {
286
- async function n(l) {
287
- var o;
288
- const c = e.getState().messages;
289
- if (c.length === 0) {
290
- t == null || t.debug("No messages yet, fetching all history", { sessionId: l.id });
291
- const m = await s.getSessionHistory(l.id, "");
292
- m && m.length > 0 && e.setStatePartial({
293
- messages: m.map(G)
294
- });
295
- return;
296
- }
297
- const u = (o = e.getState().messages.at(-1)) == null ? void 0 : o.timestamp;
298
- t == null || t.debug("Fetching history messages after timestamp", {
299
- sessionId: l.id,
300
- lastMessageTimestamp: u,
301
- currentMessageCount: c.length
302
- });
303
- const a = await s.getSessionHistory(l.id, u);
304
- if (a && a.length > 0) {
305
- const m = a.map(G).filter((p) => !c.some((y) => y.id === p.id));
306
- m.length > 0 && (t == null || t.debug("Adding new messages to state", {
307
- count: m.length,
308
- messageIds: m.map((p) => p.id),
309
- messageTypes: m.map((p) => p.type)
310
- }), e.setStatePartial({
311
- messages: [...c, ...m]
312
- }));
313
- }
314
- }
315
- function f(l, c) {
316
- return {
317
- id: F(),
318
- type: "FROM_USER",
319
- content: l,
320
- deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
321
- attachments: c,
322
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
323
- };
324
- }
325
- function i(l) {
326
- if (l.success && l.autopilotResponse)
327
- return {
328
- type: "FROM_BOT",
329
- id: l.autopilotResponse.id || F(),
330
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
331
- component: "TEXT",
332
- data: {
333
- message: l.autopilotResponse.value.content
334
- }
335
- };
336
- if (l.success && l.uiResponse) {
337
- const c = l.uiResponse.value;
338
- return {
339
- type: "FROM_BOT",
340
- id: F(),
341
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
342
- component: c.name,
343
- data: c.request_response
344
- };
345
- }
346
- return null;
347
- }
348
- function r(l) {
349
- return {
350
- type: "FROM_BOT",
351
- id: F(),
352
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
353
- component: "TEXT",
354
- data: {
355
- message: l,
356
- variant: "error"
357
- }
358
- };
359
- }
360
- return {
361
- fetchHistoryMessages: n,
362
- addUserMessage: f,
363
- addBotMessage: i,
364
- addErrorMessage: r
365
- };
366
- }
367
- function Y(s, e, t, n, f, i) {
368
- var O, x;
369
- const r = (O = i.platform) == null ? void 0 : O.logger;
370
- let l = null;
371
- const c = (x = i.platform) == null ? void 0 : x.storage, u = f.getSettings().persistSession;
372
- if (u && !L(c))
373
- throw new K();
374
- if (u && !f.getConfig().user.external_id)
375
- throw new V("session persistence is enabled but external id is not defined");
376
- const a = `${f.getConfig().user.external_id}:${f.getConfig().token}:session`;
377
- async function o() {
378
- if (c)
379
- try {
380
- r == null || r.debug("Attempting to restore session from storage");
381
- const d = await c.getItem(a);
382
- if (d) {
383
- const g = JSON.parse(d);
384
- r == null || r.info("Session restored from storage", { sessionId: g.id }), e.setState(g), await n.fetchHistoryMessages(g), p();
385
- }
386
- } catch (d) {
387
- r == null || r.error("Error restoring session from storage:", d);
388
- }
389
- }
390
- function m() {
391
- c && (r == null || r.debug("Setting up session persistence"), e.subscribe(async (d) => {
392
- try {
393
- d ? (await c.setItem(a, JSON.stringify(d)), r == null || r.debug("Session persisted to storage", { sessionId: d.id })) : (await c.removeItem(a), r == null || r.debug("Session removed from storage"));
394
- } catch (g) {
395
- r == null || r.error("Error persisting session:", g), t.setStatePartial({
396
- error: {
397
- hasError: !0,
398
- message: g instanceof Error ? g.message : "Failed to persist session",
399
- code: "SESSION_PERSISTENCE_FAILED"
400
- }
401
- });
402
- }
403
- }));
404
- }
405
- function p() {
406
- if (l) return;
407
- r == null || r.debug("Starting polling");
408
- const d = [];
409
- d.push(
410
- setInterval(async () => {
411
- const g = e.getState();
412
- if (g != null && g.id)
413
- try {
414
- const S = /* @__PURE__ */ new Date();
415
- t.setStatePartial({
416
- polling: {
417
- ...t.getState().polling,
418
- session: {
419
- isPolling: !0,
420
- lastPollTime: S.toISOString(),
421
- nextPollTime: new Date(S.getTime() + D.SESSION).toISOString(),
422
- error: { hasError: !1 }
423
- }
424
- }
425
- });
426
- const R = await s.getSession(g.id);
427
- R && e.setState(R), t.setStatePartial({
428
- polling: {
429
- ...t.getState().polling,
430
- session: {
431
- ...t.getState().polling.session,
432
- isPolling: !1
433
- }
434
- }
435
- });
436
- } catch (S) {
437
- r == null || r.error("Error polling session:", S), t.setStatePartial({
438
- polling: {
439
- ...t.getState().polling,
440
- session: {
441
- ...t.getState().polling.session,
442
- isPolling: !1,
443
- error: {
444
- hasError: !0,
445
- message: S instanceof Error ? S.message : "Failed to poll session",
446
- code: "SESSION_POLLING_FAILED"
447
- }
448
- }
449
- }
450
- });
451
- }
452
- }, D.SESSION)
453
- ), d.push(
454
- setInterval(async () => {
455
- const g = e.getState();
456
- if (g != null && g.id)
457
- try {
458
- const S = /* @__PURE__ */ new Date();
459
- t.setStatePartial({
460
- polling: {
461
- ...t.getState().polling,
462
- messages: {
463
- isPolling: !0,
464
- lastPollTime: S.toISOString(),
465
- nextPollTime: new Date(S.getTime() + D.MESSAGES).toISOString(),
466
- error: { hasError: !1 }
467
- }
468
- }
469
- }), await n.fetchHistoryMessages(g), t.setStatePartial({
470
- polling: {
471
- ...t.getState().polling,
472
- messages: {
473
- ...t.getState().polling.messages,
474
- isPolling: !1
475
- }
476
- }
477
- });
478
- } catch (S) {
479
- r == null || r.error("Error polling messages:", S), t.setStatePartial({
480
- polling: {
481
- ...t.getState().polling,
482
- messages: {
483
- ...t.getState().polling.messages,
484
- isPolling: !1,
485
- error: {
486
- hasError: !0,
487
- message: S instanceof Error ? S.message : "Failed to poll messages",
488
- code: "MESSAGES_POLLING_FAILED"
489
- }
490
- }
491
- }
492
- });
493
- }
494
- }, D.MESSAGES)
495
- ), l = () => {
496
- r == null || r.debug("Stopping polling"), d.forEach(clearInterval), t.setStatePartial({
497
- polling: {
498
- session: {
499
- isPolling: !1,
500
- lastPollTime: null,
501
- nextPollTime: null,
502
- error: { hasError: !1 }
503
- },
504
- messages: {
505
- isPolling: !1,
506
- lastPollTime: null,
507
- nextPollTime: null,
508
- error: { hasError: !1 }
509
- }
510
- }
511
- });
512
- };
513
- }
514
- async function y() {
515
- try {
516
- r == null || r.info("Creating new session"), t.setStatePartial({
517
- loading: { isLoading: !0, reason: "creating_session" },
518
- error: { hasError: !1 }
519
- });
520
- const d = await s.createSession();
521
- return r == null || r.info("Session created successfully", { sessionId: d.id }), e.setState(d), p(), d;
522
- } catch (d) {
523
- r == null || r.error("Failed to create session:", d);
524
- const g = {
525
- hasError: !0,
526
- message: d instanceof Error ? d.message : "Failed to create session",
527
- code: "SESSION_CREATION_FAILED"
528
- };
529
- return t.setStatePartial({ error: g }), null;
530
- } finally {
531
- t.setStatePartial({
532
- loading: { isLoading: !1, reason: null }
533
- });
534
- }
535
- }
536
- async function C() {
537
- var g;
538
- const d = e.getState();
539
- if (d != null && d.id)
540
- try {
541
- l && (l(), l = null), e.setState(null), u && c && await c.removeItem(a), t.setState({
542
- messages: [],
543
- keyboard: null,
544
- loading: { isLoading: !1, reason: null },
545
- error: { hasError: !1 },
546
- polling: {
547
- session: {
548
- isPolling: !1,
549
- lastPollTime: null,
550
- nextPollTime: null,
551
- error: { hasError: !1 }
552
- },
553
- messages: {
554
- isPolling: !1,
555
- lastPollTime: null,
556
- nextPollTime: null,
557
- error: { hasError: !1 }
558
- }
559
- }
560
- }), (g = i.onSessionDestroy) == null || g.call(i);
561
- } catch (S) {
562
- console.error("Error clearing session:", S), t.setStatePartial({
563
- error: {
564
- hasError: !0,
565
- message: S instanceof Error ? S.message : "Failed to clear session",
566
- code: "SESSION_CLEAR_FAILED"
567
- }
568
- });
569
- }
570
- }
571
- function A(d = !1) {
572
- try {
573
- l && (l(), l = null), d && u && c && L(c) && c.removeItem(a), t.setState({
574
- messages: [],
575
- keyboard: null,
576
- loading: { isLoading: !1, reason: null },
577
- error: { hasError: !1 },
578
- polling: {
579
- session: {
580
- isPolling: !1,
581
- lastPollTime: null,
582
- nextPollTime: null,
583
- error: { hasError: !1 }
584
- },
585
- messages: {
586
- isPolling: !1,
587
- lastPollTime: null,
588
- nextPollTime: null,
589
- error: { hasError: !1 }
590
- }
591
- }
592
- }), e.setState(null), t.clear(), e.clear();
593
- } catch (g) {
594
- console.error("Error in cleanup:", g), t.setStatePartial({
595
- error: {
596
- hasError: !0,
597
- message: g instanceof Error ? g.message : "Failed to cleanup",
598
- code: "SESSION_CLEAR_FAILED"
599
- }
600
- });
601
- }
602
- }
603
- async function w(d) {
604
- return s.getSession(d);
605
- }
606
- async function T() {
607
- const d = e.getState();
608
- if (!(d != null && d.id)) return;
609
- const g = await w(d.id);
610
- return g && e.setState(g), g;
611
- }
612
- return u && L(c) && (o(), m()), {
613
- createSession: y,
614
- clearSession: C,
615
- cleanup: A,
616
- startPolling: p,
617
- fetchSession: w,
618
- refetchSession: T,
619
- sessionStorageKey: a
620
- };
621
- }
622
- function ge(s) {
623
- var c;
624
- const e = (c = s.platform) == null ? void 0 : c.logger, t = {
625
- messages: [],
626
- keyboard: null,
627
- loading: { isLoading: !1, reason: null },
628
- error: { hasError: !1 },
629
- polling: {
630
- session: {
631
- isPolling: !1,
632
- lastPollTime: null,
633
- nextPollTime: null,
634
- error: { hasError: !1 }
635
- },
636
- messages: {
637
- isPolling: !1,
638
- lastPollTime: null,
639
- nextPollTime: null,
640
- error: { hasError: !1 }
641
- }
642
- }
643
- }, n = new U(t), f = new U(null), i = z(s.api, n, e), r = Y(
644
- s.api,
645
- f,
646
- n,
647
- i,
648
- s.config,
649
- s
650
- );
651
- async function l(u, a) {
652
- var p;
653
- let o = f.getState(), m = !1;
654
- if (!(o != null && o.id)) {
655
- if (e == null || e.debug("No active session, creating new session"), o = await r.createSession(), !o) return {
656
- success: !1,
657
- createdSession: m
658
- };
659
- m = !0;
660
- }
661
- o.assignee.kind === "ai" && (o = await r.refetchSession() ?? o);
662
- try {
663
- e == null || e.debug("Sending message", { sessionId: o.id }), o.assignee.kind === "ai" ? n.setStatePartial({
664
- loading: { isLoading: !0, reason: "sending_message_to_bot" },
665
- error: { hasError: !1 }
666
- }) : n.setStatePartial({
667
- loading: { isLoading: !0, reason: "sending_message_to_agent" },
668
- error: { hasError: !1 }
669
- });
670
- const y = i.addUserMessage(u.content, u.attachments || void 0), C = n.getState().messages;
671
- n.setStatePartial({
672
- messages: [...C, y]
673
- });
674
- const A = s.config.getConfig(), w = await s.api.handleMessage({
675
- uuid: u.uuid || F(),
676
- bot_token: A.token,
677
- headers: A.headers,
678
- query_params: A.queryParams,
679
- session_id: o.id,
680
- user: A.user,
681
- ...u
682
- }, a);
683
- if (w.success) {
684
- e == null || e.debug("Message sent successfully");
685
- const T = i.addBotMessage(w);
686
- if (T) {
687
- const O = n.getState().messages;
688
- n.setStatePartial({
689
- messages: [...O, T]
690
- });
691
- }
692
- return {
693
- success: !0,
694
- createdSession: m,
695
- botMessage: T
696
- };
697
- } else {
698
- e == null || e.warn("Message send failed", w.error);
699
- const T = i.addErrorMessage(((p = w.error) == null ? void 0 : p.message) || "Unknown error occurred"), O = n.getState().messages;
700
- return n.setStatePartial({
701
- messages: [...O, T]
702
- }), {
703
- success: !1,
704
- createdSession: m,
705
- error: w.error
706
- };
707
- }
708
- } catch (y) {
709
- return e == null || e.error("Error sending message:", y), n.setStatePartial({
710
- error: {
711
- hasError: !0,
712
- message: y instanceof Error ? y.message : "Failed to send message",
713
- code: "MESSAGE_SEND_FAILED"
714
- }
715
- }), {
716
- success: !1,
717
- createdSession: m,
718
- error: y
719
- };
720
- } finally {
721
- n.setStatePartial({
722
- loading: { isLoading: !1, reason: null }
723
- });
724
- }
725
- }
726
- return {
727
- chatState: n,
728
- sessionState: f,
729
- sendMessage: l,
730
- createSession: r.createSession,
731
- clearSession: r.clearSession,
732
- cleanup: r.cleanup,
733
- initialState: t,
734
- sessionStorageKey: r.sessionStorageKey
735
- };
736
- }
737
- function me(s) {
738
- const e = s.config.getConfig();
739
- s.config.getConfig;
740
- const t = `${e.token}:contact:${e.user.external_id}`, n = L(s.platform.storage) ? s.platform.storage : void 0;
741
- let f = null;
742
- n && M(
743
- async () => {
744
- const a = await n.getItem(t);
745
- return a ? JSON.parse(a) : null;
746
- },
747
- "Error loading contact from storage"
748
- ).then((a) => {
749
- a.success && (f = a.result);
750
- });
751
- const i = new U({
752
- contact: f,
753
- loading: { isLoading: !1, reason: null },
754
- error: { hasError: !1 }
755
- });
756
- L(n) && i.subscribe((a) => {
757
- M(
758
- async () => {
759
- a.contact ? await n.setItem(t, JSON.stringify(a.contact)) : n.removeItem(t);
760
- },
761
- "Error persisting contact state"
762
- ).then((o) => {
763
- o.success || i.setStatePartial({
764
- error: {
765
- hasError: !0,
766
- message: o.error.message,
767
- code: "CONTACT_PERSISTENCE_FAILED"
768
- }
769
- });
770
- });
771
- });
772
- async function r() {
773
- try {
774
- if (i.setStatePartial({
775
- loading: { isLoading: !0, reason: "loading_contact" },
776
- error: { hasError: !1 }
777
- }), n) {
778
- const a = await M(
779
- async () => {
780
- const o = await n.getItem(t);
781
- return o ? JSON.parse(o) : null;
782
- },
783
- "Error loading contact"
784
- );
785
- if (!a.success)
786
- throw a.error;
787
- return i.setStatePartial({
788
- contact: a.result,
789
- error: { hasError: !1 }
790
- }), a.result;
791
- }
792
- return i.getState().contact;
793
- } catch (a) {
794
- return i.setStatePartial({
795
- error: {
796
- hasError: !0,
797
- message: a instanceof Error ? a.message : "Failed to load contact",
798
- code: "CONTACT_LOAD_FAILED"
799
- }
800
- }), null;
801
- } finally {
802
- i.setStatePartial({
803
- loading: { isLoading: !1, reason: null }
804
- });
805
- }
806
- }
807
- async function l(a) {
808
- try {
809
- i.setStatePartial({
810
- loading: { isLoading: !0, reason: "saving_contact" },
811
- error: { hasError: !1 }
812
- });
813
- const o = i.getState().contact, m = {
814
- id: a.id || (o == null ? void 0 : o.id) || "",
815
- name: a.name ?? (o == null ? void 0 : o.name) ?? null,
816
- created_at: a.created_at || (o == null ? void 0 : o.created_at) || (/* @__PURE__ */ new Date()).toISOString(),
817
- avatar_url: a.avatar_url ?? (o == null ? void 0 : o.avatar_url) ?? null,
818
- email: a.email ?? (o == null ? void 0 : o.email) ?? null
819
- };
820
- if (L(n)) {
821
- const p = await M(
822
- () => n.setItem(t, JSON.stringify(m)),
823
- "Error saving contact"
824
- );
825
- if (!p.success)
826
- throw p.error;
827
- }
828
- return i.setStatePartial({
829
- contact: m,
830
- error: { hasError: !1 }
831
- }), m;
832
- } catch (o) {
833
- return i.setStatePartial({
834
- error: {
835
- hasError: !0,
836
- message: o instanceof Error ? o.message : "Failed to save contact",
837
- code: "CONTACT_SAVE_FAILED"
838
- }
839
- }), null;
840
- } finally {
841
- i.setStatePartial({
842
- loading: { isLoading: !1, reason: null }
843
- });
844
- }
845
- }
846
- function c() {
847
- var o;
848
- return !((o = i.getState().contact) != null && o.id) && e.collectUserData ? {
849
- should: !0,
850
- reason: "No contact id and collectUserData is true"
851
- } : {
852
- should: !1
853
- };
854
- }
855
- async function u() {
856
- try {
857
- if (i.setStatePartial({
858
- loading: { isLoading: !0, reason: "cleaning_up" },
859
- error: { hasError: !1 }
860
- }), n) {
861
- const a = await M(
862
- () => n.removeItem(t),
863
- "Error removing contact data"
864
- );
865
- if (!a.success)
866
- throw a.error;
867
- }
868
- i.setState({
869
- contact: null,
870
- loading: { isLoading: !1, reason: null },
871
- error: { hasError: !1 }
872
- }), i.clear();
873
- } catch (a) {
874
- console.error("Error cleaning up contact:", a), i.setStatePartial({
875
- error: {
876
- hasError: !0,
877
- message: a instanceof Error ? a.message : "Failed to cleanup contact data",
878
- code: "CONTACT_CLEANUP_FAILED"
879
- }
880
- });
881
- } finally {
882
- i.setStatePartial({
883
- loading: { isLoading: !1, reason: null }
884
- });
885
- }
886
- }
887
- return {
888
- contactState: i,
889
- shouldCollectData: c,
890
- loadContact: r,
891
- saveContact: l,
892
- cleanup: u
893
- };
894
- }
895
- const Q = {
896
- messageArrived: "https://cloud.opencopilot.so/sfx/notification3.mp3"
897
- }, q = {
898
- primaryColor: "hsl(211,65%,59%)",
899
- triggerOffset: "20px"
900
- }, W = 1e3 * 3;
901
- function Se(s) {
902
- var t, n, f, i, r, l, c, u, a;
903
- if (!s.token)
904
- throw new Error("Token is required");
905
- if (s.pollingInterval && s.pollingInterval < W)
906
- throw new Error("Polling interval must be at least 3 seconds");
907
- const e = {
908
- ...s,
909
- collectUserData: s.collectUserData ?? !1,
910
- apiUrl: s.apiUrl ?? "https://api.open.cx/backend",
911
- pollingInterval: s.pollingInterval ?? 3e3,
912
- headers: s.headers ?? {},
913
- queryParams: s.queryParams ?? {},
914
- pathParams: s.pathParams ?? {},
915
- bot: {
916
- name: ((t = s.bot) == null ? void 0 : t.name) ?? "Bot",
917
- avatarUrl: (n = s.bot) == null ? void 0 : n.avatarUrl,
918
- id: ((f = s.bot) == null ? void 0 : f.id) ?? null,
919
- is_ai: ((i = s.bot) == null ? void 0 : i.is_ai) ?? !0
920
- },
921
- contactToken: s.contactToken,
922
- debug: s.debug ?? !1,
923
- language: s.language ?? "en",
924
- user: s.user ?? {},
925
- soundEffectFiles: {
926
- messageArrived: ((r = s.soundEffectFiles) == null ? void 0 : r.messageArrived) ?? Q.messageArrived
927
- },
928
- theme: {
929
- primaryColor: ((l = s.theme) == null ? void 0 : l.primaryColor) ?? q.primaryColor,
930
- triggerOffset: ((c = s.theme) == null ? void 0 : c.triggerOffset) ?? q.triggerOffset
931
- },
932
- settings: {
933
- persistSession: ((u = s.settings) == null ? void 0 : u.persistSession) ?? !1,
934
- useSoundEffects: ((a = s.settings) == null ? void 0 : a.useSoundEffects) ?? !1
935
- }
936
- };
937
- return {
938
- getConfig: () => e,
939
- getApiConfig: () => ({
940
- apiUrl: e.apiUrl,
941
- token: e.token,
942
- headers: e.headers,
943
- queryParams: e.queryParams,
944
- pathParams: e.pathParams
945
- }),
946
- getBotConfig: () => e.bot,
947
- getThemeConfig: () => e.theme,
948
- getSettings: () => e.settings,
949
- getSoundEffects: () => e.soundEffectFiles,
950
- getUser: () => e.user,
951
- getLanguage: () => e.language,
952
- getDebugMode: () => e.debug
953
- };
954
- }
955
- function Z(s = {}, e = globalThis.fetch) {
956
- const t = [], n = [], f = [], i = async (r, l = {}) => {
957
- let c = {
958
- ...s,
959
- ...l,
960
- headers: {
961
- ...s.headers,
962
- ...l.headers
963
- }
964
- };
965
- try {
966
- for (const m of t)
967
- c = await m(c);
968
- const u = c.params ? "?" + new URLSearchParams(c.params).toString() : "", a = c.baseURL ? `${c.baseURL}${r}${u}`.replace(/([^:]\/)\/+/g, "$1") : `${r}${u}`;
969
- let o = await e(a, c);
970
- for (const m of n)
971
- o = await m(o);
972
- return o;
973
- } catch (u) {
974
- let a = u;
975
- for (const o of f)
976
- a = await o(a);
977
- throw a;
978
- }
979
- };
980
- return i.interceptors = {
981
- request: {
982
- use: (r) => (t.push(r), t.length - 1),
983
- eject: (r) => {
984
- t.splice(r, 1);
985
- }
986
- },
987
- response: {
988
- use: (r, l) => (n.push(r), l && f.push(l), n.length - 1),
989
- eject: (r) => {
990
- n.splice(r, 1), f.splice(r, 1);
991
- }
992
- }
993
- }, i;
994
- }
995
- var b;
996
- class pe {
997
- constructor(e) {
998
- N(this, b);
999
- this.options = e;
1000
- const t = this.options.config.user, n = {
1001
- claim: "",
1002
- value: ""
1003
- };
1004
- t != null && t.email ? (n.claim = "email", n.value = t.email) : t != null && t.phone && (n.claim = "phone", n.value = t.phone);
1005
- const f = {
1006
- "X-Bot-Token": this.options.config.token,
1007
- "X-Consumer-Id": `${n.claim}:${n.value}`,
1008
- "Content-Type": "application/json",
1009
- Accept: "application/json"
1010
- };
1011
- this.options.config.contactToken && (f.Authorization = `Bearer ${this.options.config.contactToken}`), _(this, b, Z({
1012
- baseURL: `${this.options.config.apiUrl}/widget/v2`,
1013
- headers: f
1014
- }));
1015
- }
1016
- async me() {
1017
- return (await h(this, b).call(this, "/me")).json();
1018
- }
1019
- async widgetPrelude() {
1020
- return (await h(this, b).call(this, "/prelude")).json();
1021
- }
1022
- async handleMessage(e, t) {
1023
- return (await h(this, b).call(this, "/chat/send", {
1024
- method: "POST",
1025
- body: JSON.stringify(e),
1026
- signal: t
1027
- })).json();
1028
- }
1029
- async getSessionHistory(e, t) {
1030
- const n = new URLSearchParams({
1031
- lastMessageTimestamp: t || ""
1032
- }), f = `/session/history/${e}?${n.toString()}`;
1033
- return (await h(this, b).call(this, f, {
1034
- method: "GET"
1035
- })).json();
1036
- }
1037
- async createSession() {
1038
- return (await h(this, b).call(this, "/create-session", {
1039
- method: "POST"
1040
- })).json();
1041
- }
1042
- async getSession(e) {
1043
- return (await h(this, b).call(this, `/session/${e}`, {
1044
- method: "GET"
1045
- })).json();
1046
- }
1047
- }
1048
- b = new WeakMap();
1
+ import { A as e, e as o, C as s, E as t, F as i, L as n, O as l, P as E, S as c, f as b, g as f, T as A, c as S, b as d, a as g, d as p, h as u, j as C, i as v, k as O, s as h } from "./api-DRZ9vPwy.js";
1049
2
  export {
1050
- pe as ApiCaller,
1051
- oe as AuthenticationError,
1052
- ne as ConnectionError,
1053
- V as ExternalIdNotDefinedError,
1054
- ce as FileUploadError,
1055
- J as LifecycleEvent,
1056
- ye as MessageTypeEnum,
1057
- I as OpenCXError,
1058
- U as PubSub,
1059
- X as SessionError,
1060
- ie as SessionNotDefinedError,
1061
- K as StorageNotAvailableError,
1062
- le as TransportError,
1063
- Pe as chatAttachmentSchema,
1064
- ge as createChat,
1065
- Se as createConfig,
1066
- me as createContact,
1067
- ue as createLogger,
1068
- ae as createPubSub,
1069
- fe as isAudioAvailable,
1070
- L as isStorageAvailable,
1071
- de as safeAudioOperation,
1072
- M as safeStorageOperation
3
+ e as ApiCaller,
4
+ o as AuthenticationError,
5
+ s as ConnectionError,
6
+ t as ExternalIdNotDefinedError,
7
+ i as FileUploadError,
8
+ n as LifecycleEvent,
9
+ l as OpenCXError,
10
+ E as PubSub,
11
+ c as SessionError,
12
+ b as SessionNotDefinedError,
13
+ f as StorageNotAvailableError,
14
+ A as TransportError,
15
+ S as createChat,
16
+ d as createConfig,
17
+ g as createContact,
18
+ p as createLogger,
19
+ u as createPubSub,
20
+ C as isAudioAvailable,
21
+ v as isStorageAvailable,
22
+ O as safeAudioOperation,
23
+ h as safeStorageOperation
1073
24
  };
1074
25
  //# sourceMappingURL=index.js.map