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