@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
@@ -0,0 +1,1360 @@
1
+ var ne = Object.defineProperty;
2
+ var Q = (s) => {
3
+ throw TypeError(s);
4
+ };
5
+ var ae = (s, e, t) => e in s ? ne(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
6
+ var h = (s, e, t) => ae(s, typeof e != "symbol" ? e + "" : e, t), V = (s, e, t) => e.has(s) || Q("Cannot " + t);
7
+ var A = (s, e, t) => (V(s, e, "read from private field"), t ? t.call(s) : e.get(s)), G = (s, e, t) => e.has(s) ? Q("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(s) : e.set(s, t), k = (s, e, t, r) => (V(s, e, "write to private field"), r ? r.call(s, t) : e.set(s, t), t);
8
+ import ie from "lodash.isequal";
9
+ import { v4 as oe } from "uuid";
10
+ class M extends Error {
11
+ constructor(e) {
12
+ super(e), this.name = "OpenCXError";
13
+ }
14
+ }
15
+ class _e extends M {
16
+ constructor(e = "Connection failed") {
17
+ super(e), this.name = "ConnectionError";
18
+ }
19
+ }
20
+ class Me extends M {
21
+ constructor(e = "Authentication failed") {
22
+ super(e), this.name = "AuthenticationError";
23
+ }
24
+ }
25
+ class le extends M {
26
+ constructor(e = "Session error occurred") {
27
+ super(e), this.name = "SessionError";
28
+ }
29
+ }
30
+ class Fe extends le {
31
+ constructor(e = "Session not defined") {
32
+ super(e), this.name = "SessionNotDefinedError";
33
+ }
34
+ }
35
+ class ke extends M {
36
+ constructor(e = "Transport error occurred") {
37
+ super(e), this.name = "TransportError";
38
+ }
39
+ }
40
+ class Ne extends M {
41
+ constructor(e = "File upload failed") {
42
+ super(e), this.name = "FileUploadError";
43
+ }
44
+ }
45
+ class ce extends M {
46
+ constructor(e = "Storage is not available") {
47
+ super(e), this.name = "StorageNotAvailableError";
48
+ }
49
+ }
50
+ class je extends M {
51
+ constructor(e = "External ID is not defined") {
52
+ super(e), this.name = "ExternalIdNotDefinedError";
53
+ }
54
+ }
55
+ var ue = /* @__PURE__ */ ((s) => (s.INIT = "init", s.STATE_CHANGE = "stateChange", s.BEFORE_UPDATE = "beforeUpdate", s.AFTER_UPDATE = "afterUpdate", s.DESTROY = "destroy", s.ERROR = "error", s))(ue || {}), C, N;
56
+ class X {
57
+ constructor(e) {
58
+ h(this, "subscribers", /* @__PURE__ */ new Set());
59
+ G(this, C);
60
+ h(this, "initialState");
61
+ G(this, N);
62
+ h(this, "lifecycleListeners", /* @__PURE__ */ new Map());
63
+ h(this, "emitLifecycle", (e, t) => {
64
+ const r = this.lifecycleListeners.get(e);
65
+ if (r) {
66
+ const a = {
67
+ type: e,
68
+ timestamp: Date.now(),
69
+ data: t
70
+ };
71
+ r.forEach((o) => {
72
+ try {
73
+ o(a);
74
+ } catch {
75
+ }
76
+ });
77
+ }
78
+ });
79
+ h(this, "notifySubscribers", (e) => {
80
+ Array.from(this.subscribers).forEach((r) => {
81
+ try {
82
+ r(e);
83
+ } catch (a) {
84
+ this.emitLifecycle("error", { error: a });
85
+ }
86
+ });
87
+ });
88
+ /**
89
+ * Subscribe to state changes
90
+ * @param callback Function to call when state changes
91
+ * @returns Unsubscribe function
92
+ */
93
+ h(this, "subscribe", (e) => (this.subscribers.add(e), () => {
94
+ this.subscribers.delete(e);
95
+ }));
96
+ h(this, "onLifecycle", (e, t) => {
97
+ this.lifecycleListeners.has(e) || this.lifecycleListeners.set(e, /* @__PURE__ */ new Set());
98
+ const r = this.lifecycleListeners.get(e);
99
+ return r.add(t), () => {
100
+ r.delete(t), r.size === 0 && this.lifecycleListeners.delete(e);
101
+ };
102
+ });
103
+ /**
104
+ * Get the current state
105
+ */
106
+ h(this, "getState", () => A(this, C));
107
+ /**
108
+ * Set the state and notify subscribers if the state changes
109
+ * @param newState The new state to set
110
+ */
111
+ h(this, "setState", (e) => {
112
+ this.emitLifecycle("beforeUpdate", {
113
+ previousState: A(this, C),
114
+ nextState: e
115
+ }), ie(A(this, C), e) || (k(this, C, e), k(this, N, Date.now()), this.emitLifecycle("stateChange", { state: e }), this.notifySubscribers(e)), this.emitLifecycle("afterUpdate", { state: e });
116
+ });
117
+ h(this, "setStatePartial", (e) => {
118
+ if (e == null) return;
119
+ const t = { ...A(this, C), ...e };
120
+ this.setState(t);
121
+ });
122
+ /**
123
+ * Clear all subscriptions
124
+ */
125
+ h(this, "clear", () => {
126
+ this.emitLifecycle(
127
+ "destroy"
128
+ /* DESTROY */
129
+ ), this.subscribers = /* @__PURE__ */ new Set(), this.lifecycleListeners = /* @__PURE__ */ new Map();
130
+ });
131
+ h(this, "reset", () => {
132
+ this.setState(this.initialState);
133
+ });
134
+ h(this, "lastUpdated", () => A(this, N));
135
+ k(this, C, e), this.initialState = e, k(this, N, Date.now()), this.emitLifecycle("init", { initialState: A(this, C) });
136
+ }
137
+ }
138
+ C = new WeakMap(), N = new WeakMap();
139
+ function qe(s) {
140
+ return new X(s);
141
+ }
142
+ function L(s) {
143
+ if (!s) return !1;
144
+ try {
145
+ return typeof s.isAvailable == "function" ? s.isAvailable() : !0;
146
+ } catch {
147
+ return !1;
148
+ }
149
+ }
150
+ async function Y(s, e) {
151
+ try {
152
+ return { success: !0, result: await s(), error: null };
153
+ } catch (t) {
154
+ return {
155
+ success: !1,
156
+ result: null,
157
+ error: {
158
+ message: t instanceof Error ? t.message || "Unknown error" : (t == null ? void 0 : t.toString()) || "Unknown error",
159
+ code: "STORAGE_OPERATION_FAILED",
160
+ context: e
161
+ }
162
+ };
163
+ }
164
+ }
165
+ function $e(s = {}) {
166
+ const {
167
+ level: e = "info",
168
+ prefix: t = "[openCx]",
169
+ enabled: r = !0
170
+ } = s;
171
+ let a = e;
172
+ const o = {
173
+ debug: 0,
174
+ info: 1,
175
+ warn: 2,
176
+ error: 3
177
+ };
178
+ function c(i) {
179
+ return r && o[i] >= o[a];
180
+ }
181
+ function n(i) {
182
+ return `${t} ${i}`;
183
+ }
184
+ function m(i) {
185
+ return i.map((l) => {
186
+ if (l instanceof Error)
187
+ return {
188
+ name: l.name,
189
+ message: l.message,
190
+ stack: l.stack
191
+ };
192
+ if (typeof l == "object")
193
+ try {
194
+ return JSON.stringify(l, null, 2);
195
+ } catch {
196
+ return l;
197
+ }
198
+ return l;
199
+ });
200
+ }
201
+ return {
202
+ debug(i, ...l) {
203
+ c("debug") && console.debug(n(i), ...m(l));
204
+ },
205
+ info(i, ...l) {
206
+ c("info") && console.info(n(i), ...m(l));
207
+ },
208
+ warn(i, ...l) {
209
+ c("warn") && console.warn(n(i), ...m(l));
210
+ },
211
+ error(i, ...l) {
212
+ c("error") && console.error(n(i), ...m(l));
213
+ },
214
+ setLevel(i) {
215
+ a = i;
216
+ }
217
+ };
218
+ }
219
+ function fe(s) {
220
+ if (!s) return !1;
221
+ try {
222
+ return typeof s.isAvailable == "function" ? s.isAvailable() : !0;
223
+ } catch {
224
+ return !1;
225
+ }
226
+ }
227
+ async function de(s, e) {
228
+ try {
229
+ return await s(), { success: !0, error: null };
230
+ } catch (t) {
231
+ return {
232
+ success: !1,
233
+ error: {
234
+ message: t instanceof Error ? t.message || "Unknown error" : (t == null ? void 0 : t.toString()) || "Unknown error",
235
+ code: "AUDIO_OPERATION_FAILED",
236
+ context: e
237
+ }
238
+ };
239
+ }
240
+ }
241
+ function B() {
242
+ return oe();
243
+ }
244
+ function ge({ config: s }, e) {
245
+ const t = new X({
246
+ contact: null,
247
+ loading: { isLoading: !1, reason: null },
248
+ error: { hasError: !1 }
249
+ });
250
+ function r() {
251
+ var c;
252
+ return !((c = t.getState().contact) != null && c.id) && s.getConfig().collectUserData ? {
253
+ should: !0,
254
+ reason: "No contact id and collectUserData is true"
255
+ } : {
256
+ should: !1
257
+ };
258
+ }
259
+ async function a() {
260
+ try {
261
+ t.setStatePartial({
262
+ loading: { isLoading: !0, reason: "cleaning_up" },
263
+ error: { hasError: !1 }
264
+ }), t.setState({
265
+ contact: null,
266
+ loading: { isLoading: !1, reason: null },
267
+ error: { hasError: !1 }
268
+ }), t.clear();
269
+ } catch (o) {
270
+ t.setStatePartial({
271
+ error: {
272
+ hasError: !0,
273
+ message: o instanceof Error ? o.message : "Failed to cleanup contact data",
274
+ code: "CONTACT_CLEANUP_FAILED"
275
+ }
276
+ });
277
+ } finally {
278
+ t.setStatePartial({
279
+ loading: { isLoading: !1, reason: null }
280
+ });
281
+ }
282
+ }
283
+ return {
284
+ contactState: t,
285
+ shouldCollectData: r,
286
+ cleanup: a
287
+ };
288
+ }
289
+ const J = {
290
+ SESSION: 1e4,
291
+ // every 10 seconds
292
+ MESSAGES: 5e3
293
+ // every 5 seconds
294
+ };
295
+ function me(s) {
296
+ const e = {
297
+ id: s.publicId,
298
+ timestamp: s.sentAt || "",
299
+ attachments: s.attachments || void 0
300
+ };
301
+ return s.sender.kind === "user" ? {
302
+ ...e,
303
+ type: "FROM_USER",
304
+ content: s.content.text || "",
305
+ deliveredAt: s.sentAt || ""
306
+ } : s.sender.kind === "agent" ? {
307
+ id: s.publicId,
308
+ type: "FROM_AGENT",
309
+ component: "agent_message",
310
+ data: {
311
+ message: s.content.text || ""
312
+ },
313
+ timestamp: s.sentAt || "",
314
+ attachments: s.attachments || void 0
315
+ } : {
316
+ ...e,
317
+ type: "FROM_BOT",
318
+ component: "bot_message",
319
+ agent: {
320
+ id: null,
321
+ name: s.sender.name || "",
322
+ isAi: s.sender.kind === "ai",
323
+ avatar: s.sender.avatar || null
324
+ },
325
+ data: {
326
+ message: s.content.text
327
+ }
328
+ };
329
+ }
330
+ function Se(s, e, t, r, a) {
331
+ async function o(i) {
332
+ var b;
333
+ const l = e.getState().messages, g = (b = e.getState().messages.at(-1)) == null ? void 0 : b.timestamp, { data: u } = await s.getSessionHistory(
334
+ i.id,
335
+ g
336
+ );
337
+ if (u && u.length > 0) {
338
+ const w = u.map(me).filter(
339
+ (D) => !l.some((S) => S.id === D.id)
340
+ );
341
+ w.length > 0 && (t == null || t.debug("Adding new messages to state", {
342
+ count: w.length,
343
+ messageIds: w.map((S) => S.id),
344
+ messageTypes: w.map((S) => S.type)
345
+ }), r != null && r.getConfig().settings.useSoundEffects && (a != null && a.audio) && fe(a.audio) && w.filter(
346
+ (P) => P.type === "FROM_BOT"
347
+ ).length > 0 && await de(
348
+ () => a.audio.playNotification(),
349
+ "Failed to play notification sound for new messages"
350
+ ), e.setStatePartial({
351
+ messages: [...l, ...w]
352
+ }));
353
+ }
354
+ }
355
+ function c(i, l) {
356
+ return {
357
+ id: B(),
358
+ type: "FROM_USER",
359
+ content: i,
360
+ deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
361
+ attachments: l,
362
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
363
+ };
364
+ }
365
+ function n(i) {
366
+ if (i.success && i.autopilotResponse)
367
+ return {
368
+ type: "FROM_BOT",
369
+ id: i.autopilotResponse.id || B(),
370
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
371
+ component: "bot_message",
372
+ data: {
373
+ message: i.autopilotResponse.value.content
374
+ }
375
+ };
376
+ if (i.success && i.uiResponse) {
377
+ const l = i.uiResponse.value;
378
+ return {
379
+ type: "FROM_BOT",
380
+ id: B(),
381
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
382
+ component: l.name,
383
+ data: l.request_response
384
+ };
385
+ }
386
+ return null;
387
+ }
388
+ function m(i) {
389
+ return {
390
+ type: "FROM_BOT",
391
+ id: B(),
392
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
393
+ component: "TEXT",
394
+ data: {
395
+ message: i,
396
+ variant: "error"
397
+ }
398
+ };
399
+ }
400
+ return {
401
+ fetchHistoryMessages: o,
402
+ toUserMessage: c,
403
+ toBotMessage: n,
404
+ addErrorMessage: m
405
+ };
406
+ }
407
+ function he(s, e, t, r, a, o) {
408
+ var v, p;
409
+ let c = null;
410
+ const n = (v = o.platform) == null ? void 0 : v.logger, m = (p = o.platform) == null ? void 0 : p.storage, i = () => a.getConfig().settings.persistSession;
411
+ if (i() && !L(m))
412
+ throw new ce();
413
+ i() && !a.getConfig().user.external_id && (n == null || n.error(
414
+ "session persistence is enabled but external id is not defined"
415
+ ));
416
+ const { token: l, user: g } = a.getConfig(), u = `${g.external_id ?? g.email ?? "unknown"}:${l}:session`;
417
+ async function b() {
418
+ n == null || n.debug("Restoring session from storage", {
419
+ sessionStorageKey: u,
420
+ stroageAvailable: L(m)
421
+ }), L(m) && Y(async () => {
422
+ n == null || n.debug("Attempting to restore session from storage");
423
+ const d = await m.getItem(u);
424
+ if (d) {
425
+ const f = JSON.parse(d);
426
+ n == null || n.info("Session restored from storage", {
427
+ sessionId: f.id
428
+ }), e.setState(f), await r.fetchHistoryMessages(f), D();
429
+ }
430
+ }, "Error restoring session from storage");
431
+ }
432
+ function w() {
433
+ n == null || n.debug("Setting up session persistence", {
434
+ sessionStorageKey: u,
435
+ stroageAvailable: L(m)
436
+ }), L(m) && e.subscribe(async (d) => {
437
+ try {
438
+ d ? (await m.setItem(u, JSON.stringify(d)), n == null || n.debug("Session persisted to storage", {
439
+ sessionId: d.id
440
+ })) : (await m.removeItem(u), n == null || n.debug("Session removed from storage"));
441
+ } catch (f) {
442
+ n == null || n.error("Error persisting session:", f), t.setStatePartial({
443
+ error: {
444
+ hasError: !0,
445
+ message: f instanceof Error ? f.message : "Failed to persist session",
446
+ code: "SESSION_PERSISTENCE_FAILED"
447
+ }
448
+ });
449
+ }
450
+ });
451
+ }
452
+ function D() {
453
+ if (c) return;
454
+ n == null || n.debug("Starting polling");
455
+ const d = [];
456
+ d.push(
457
+ setInterval(async () => {
458
+ const f = e.getState();
459
+ if (f != null && f.id)
460
+ try {
461
+ const E = /* @__PURE__ */ new Date();
462
+ t.setStatePartial({
463
+ polling: {
464
+ ...t.getState().polling,
465
+ session: {
466
+ isPolling: !0,
467
+ lastPollTime: E.toISOString(),
468
+ nextPollTime: new Date(
469
+ E.getTime() + J.SESSION
470
+ ).toISOString(),
471
+ error: { hasError: !1 }
472
+ }
473
+ }
474
+ });
475
+ const { data: q } = await s.getSession(f.id);
476
+ q && e.setState(q), t.setStatePartial({
477
+ polling: {
478
+ ...t.getState().polling,
479
+ session: {
480
+ ...t.getState().polling.session,
481
+ isPolling: !1
482
+ }
483
+ }
484
+ });
485
+ } catch (E) {
486
+ n == null || n.error("Error polling session:", E), t.setStatePartial({
487
+ polling: {
488
+ ...t.getState().polling,
489
+ session: {
490
+ ...t.getState().polling.session,
491
+ isPolling: !1,
492
+ error: {
493
+ hasError: !0,
494
+ message: E instanceof Error ? E.message : "Failed to poll session",
495
+ code: "SESSION_POLLING_FAILED"
496
+ }
497
+ }
498
+ }
499
+ });
500
+ }
501
+ }, J.SESSION)
502
+ ), d.push(
503
+ setInterval(async () => {
504
+ const f = e.getState();
505
+ if (f != null && f.id)
506
+ try {
507
+ const E = /* @__PURE__ */ new Date();
508
+ t.setStatePartial({
509
+ polling: {
510
+ ...t.getState().polling,
511
+ messages: {
512
+ isPolling: !0,
513
+ lastPollTime: E.toISOString(),
514
+ nextPollTime: new Date(
515
+ E.getTime() + J.MESSAGES
516
+ ).toISOString(),
517
+ error: { hasError: !1 }
518
+ }
519
+ }
520
+ }), await r.fetchHistoryMessages(f), t.setStatePartial({
521
+ polling: {
522
+ ...t.getState().polling,
523
+ messages: {
524
+ ...t.getState().polling.messages,
525
+ isPolling: !1
526
+ }
527
+ }
528
+ });
529
+ } catch (E) {
530
+ n == null || n.error("Error polling messages:", E), t.setStatePartial({
531
+ polling: {
532
+ ...t.getState().polling,
533
+ messages: {
534
+ ...t.getState().polling.messages,
535
+ isPolling: !1,
536
+ error: {
537
+ hasError: !0,
538
+ message: E instanceof Error ? E.message : "Failed to poll messages",
539
+ code: "MESSAGES_POLLING_FAILED"
540
+ }
541
+ }
542
+ }
543
+ });
544
+ }
545
+ }, J.MESSAGES)
546
+ ), c = () => {
547
+ n == null || n.debug("Stopping polling"), d.forEach(clearInterval), t.setStatePartial({
548
+ polling: {
549
+ session: {
550
+ isPolling: !1,
551
+ lastPollTime: null,
552
+ nextPollTime: null,
553
+ error: { hasError: !1 }
554
+ },
555
+ messages: {
556
+ isPolling: !1,
557
+ lastPollTime: null,
558
+ nextPollTime: null,
559
+ error: { hasError: !1 }
560
+ }
561
+ }
562
+ });
563
+ };
564
+ }
565
+ async function S() {
566
+ n == null || n.info("Creating new session"), t.setStatePartial({
567
+ loading: { isLoading: !0, reason: "creating_session" },
568
+ error: { hasError: !1 }
569
+ });
570
+ const { data: d, error: f } = await s.createSession();
571
+ if (d)
572
+ return n == null || n.info("Session created successfully", { sessionId: d.id }), e.setState(d), t.setStatePartial({
573
+ loading: { isLoading: !1, reason: null }
574
+ }), D(), d;
575
+ n == null || n.error("Failed to create session:", f);
576
+ const E = {
577
+ hasError: !0,
578
+ message: f instanceof Error ? f.message : "Failed to create session",
579
+ code: "SESSION_CREATION_FAILED"
580
+ };
581
+ return t.setStatePartial({
582
+ error: E,
583
+ loading: { isLoading: !1, reason: null }
584
+ }), null;
585
+ }
586
+ async function P() {
587
+ var f;
588
+ const d = e.getState();
589
+ if (d != null && d.id)
590
+ try {
591
+ c && (c(), c = null), e.setState(null), i() && m && await m.removeItem(u), t.setState({
592
+ messages: [],
593
+ keyboard: null,
594
+ loading: { isLoading: !1, reason: null },
595
+ error: { hasError: !1 },
596
+ polling: {
597
+ session: {
598
+ isPolling: !1,
599
+ lastPollTime: null,
600
+ nextPollTime: null,
601
+ error: { hasError: !1 }
602
+ },
603
+ messages: {
604
+ isPolling: !1,
605
+ lastPollTime: null,
606
+ nextPollTime: null,
607
+ error: { hasError: !1 }
608
+ }
609
+ }
610
+ }), (f = o.onSessionDestroy) == null || f.call(o);
611
+ } catch (E) {
612
+ t.setStatePartial({
613
+ error: {
614
+ hasError: !0,
615
+ message: E instanceof Error ? E.message : "Failed to clear session",
616
+ code: "SESSION_CLEAR_FAILED"
617
+ }
618
+ });
619
+ }
620
+ }
621
+ function x(d = !1) {
622
+ try {
623
+ c && (c(), c = null), d && i() && L(m) && (console.log("removing session data", u), Y(
624
+ () => m.removeItem(u),
625
+ "Error removing session data"
626
+ )), t.setState({
627
+ messages: [],
628
+ keyboard: null,
629
+ loading: { isLoading: !1, reason: null },
630
+ error: { hasError: !1 },
631
+ polling: {
632
+ session: {
633
+ isPolling: !1,
634
+ lastPollTime: null,
635
+ nextPollTime: null,
636
+ error: { hasError: !1 }
637
+ },
638
+ messages: {
639
+ isPolling: !1,
640
+ lastPollTime: null,
641
+ nextPollTime: null,
642
+ error: { hasError: !1 }
643
+ }
644
+ }
645
+ }), e.setState(null), t.clear(), e.clear();
646
+ } catch (f) {
647
+ t.setStatePartial({
648
+ error: {
649
+ hasError: !0,
650
+ message: f instanceof Error ? f.message : "Failed to cleanup",
651
+ code: "SESSION_CLEAR_FAILED"
652
+ }
653
+ });
654
+ }
655
+ }
656
+ async function T(d) {
657
+ return s.getSession(d);
658
+ }
659
+ async function F() {
660
+ const d = e.getState();
661
+ if (!(d != null && d.id)) return;
662
+ const { data: f } = await T(d.id);
663
+ return f && e.setState(f), f;
664
+ }
665
+ return i() && L(m) && (n == null || n.debug("Initializing session persistence", {
666
+ sessionStorageKey: u,
667
+ stroageAvailable: L(m)
668
+ }), b(), w()), {
669
+ createSession: S,
670
+ clearSession: P,
671
+ cleanup: x,
672
+ startPolling: D,
673
+ fetchSession: T,
674
+ refetchSession: F,
675
+ sessionStorageKey: u
676
+ };
677
+ }
678
+ function ze(s) {
679
+ var b;
680
+ const e = (b = s.platform) == null ? void 0 : b.logger, t = {
681
+ messages: [],
682
+ keyboard: null,
683
+ loading: { isLoading: !1, reason: null },
684
+ error: { hasError: !1 },
685
+ polling: {
686
+ session: {
687
+ isPolling: !1,
688
+ lastPollTime: null,
689
+ nextPollTime: null,
690
+ error: { hasError: !1 }
691
+ },
692
+ messages: {
693
+ isPolling: !1,
694
+ lastPollTime: null,
695
+ nextPollTime: null,
696
+ error: { hasError: !1 }
697
+ }
698
+ }
699
+ }, r = new X(t), {
700
+ contactState: a,
701
+ cleanup: o,
702
+ shouldCollectData: c
703
+ } = ge(
704
+ { config: s.config, api: s.api },
705
+ s.platform
706
+ ), n = new X(null), m = Se(
707
+ s.api,
708
+ r,
709
+ e,
710
+ s.config,
711
+ s.platform
712
+ ), i = he(
713
+ s.api,
714
+ n,
715
+ r,
716
+ m,
717
+ s.config,
718
+ s
719
+ );
720
+ async function l(w, D) {
721
+ var x;
722
+ let S = n.getState(), P = !1;
723
+ if (!(S != null && S.id)) {
724
+ if (e == null || e.debug("No active session, creating new session"), S = await i.createSession(), !S)
725
+ return {
726
+ success: !1,
727
+ createdSession: P
728
+ };
729
+ P = !0;
730
+ }
731
+ S.assignee.kind === "ai" && (S = await i.refetchSession() ?? S);
732
+ try {
733
+ e == null || e.debug("Sending message", { sessionId: S.id }), S.assignee.kind === "ai" ? r.setStatePartial({
734
+ loading: { isLoading: !0, reason: "sending_message_to_bot" },
735
+ error: { hasError: !1 }
736
+ }) : r.setStatePartial({
737
+ loading: { isLoading: !0, reason: "sending_message_to_agent" },
738
+ error: { hasError: !1 }
739
+ });
740
+ const T = m.toUserMessage(
741
+ w.content,
742
+ w.attachments || void 0
743
+ ), F = r.getState().messages;
744
+ r.setStatePartial({
745
+ messages: [...F, T]
746
+ });
747
+ const v = s.config.getConfig(), { data: p } = await s.api.handleMessage(
748
+ {
749
+ uuid: T.id,
750
+ bot_token: v.token,
751
+ headers: v.headers,
752
+ query_params: v.queryParams,
753
+ session_id: S.id,
754
+ user: v.user,
755
+ ...w
756
+ },
757
+ D
758
+ );
759
+ if (p != null && p.success) {
760
+ e == null || e.debug("Message sent successfully");
761
+ const d = m.toBotMessage(p);
762
+ if (d) {
763
+ const f = r.getState().messages;
764
+ r.setStatePartial({
765
+ messages: [...f, d]
766
+ });
767
+ }
768
+ return {
769
+ success: !0,
770
+ createdSession: P,
771
+ botMessage: d
772
+ };
773
+ } else {
774
+ e == null || e.warn("Message send failed", p == null ? void 0 : p.error);
775
+ const d = m.addErrorMessage(
776
+ ((x = p == null ? void 0 : p.error) == null ? void 0 : x.message) || "Unknown error occurred"
777
+ ), f = r.getState().messages;
778
+ return r.setStatePartial({
779
+ messages: [...f, d]
780
+ }), {
781
+ success: !1,
782
+ createdSession: P,
783
+ error: p == null ? void 0 : p.error
784
+ };
785
+ }
786
+ } catch (T) {
787
+ return e == null || e.error("Error sending message:", T), r.setStatePartial({
788
+ error: {
789
+ hasError: !0,
790
+ message: T instanceof Error ? T.message : "Failed to send message",
791
+ code: "MESSAGE_SEND_FAILED"
792
+ }
793
+ }), {
794
+ success: !1,
795
+ createdSession: P,
796
+ error: T
797
+ };
798
+ } finally {
799
+ r.setStatePartial({
800
+ loading: { isLoading: !1, reason: null }
801
+ });
802
+ }
803
+ }
804
+ async function g() {
805
+ await i.clearSession(), await i.createSession();
806
+ }
807
+ const u = () => {
808
+ o(), i.cleanup();
809
+ };
810
+ return {
811
+ chatState: r,
812
+ sessionState: n,
813
+ sendMessage: l,
814
+ createSession: i.createSession,
815
+ clearSession: i.clearSession,
816
+ cleanup: u,
817
+ initialState: t,
818
+ sessionStorageKey: i.sessionStorageKey,
819
+ recreateSession: g,
820
+ contactState: a,
821
+ shouldCollectData: c
822
+ };
823
+ }
824
+ const pe = {
825
+ messageArrived: "https://cloud.opencopilot.so/sfx/notification3.mp3"
826
+ }, Ee = {
827
+ primaryColor: "hsl(211,65%,59%)",
828
+ triggerOffset: "20px"
829
+ }, te = {
830
+ persistSession: !1,
831
+ useSoundEffects: !1
832
+ }, ye = 1e3 * 3;
833
+ function be(s, e, t) {
834
+ const r = e.logger, a = e.storage;
835
+ let o = s ?? te;
836
+ async function c() {
837
+ if (!(!a || !L(a)))
838
+ try {
839
+ r == null || r.debug("Attempting to restore settings from storage");
840
+ const l = await a.getItem(t);
841
+ l && (o = JSON.parse(l), r == null || r.debug("Settings restored from storage", o));
842
+ } catch (l) {
843
+ r == null || r.error("Error restoring settings:", l);
844
+ }
845
+ }
846
+ async function n(l) {
847
+ if (!(!a || !L(a)))
848
+ try {
849
+ await a.setItem(t, JSON.stringify(l)), r == null || r.debug("Settings persisted to storage", l);
850
+ } catch (g) {
851
+ r == null || r.error("Error persisting settings:", g);
852
+ }
853
+ }
854
+ function m(l) {
855
+ o = {
856
+ ...o,
857
+ ...l
858
+ }, n(o);
859
+ }
860
+ function i() {
861
+ return o;
862
+ }
863
+ return c(), {
864
+ getSettings: i,
865
+ updateSettings: m
866
+ };
867
+ }
868
+ function He(s, e) {
869
+ var c, n, m, i, l;
870
+ if (!s.token)
871
+ throw new Error("Token is required");
872
+ if (s.pollingInterval && s.pollingInterval < ye)
873
+ throw new Error("Polling interval must be at least 3 seconds");
874
+ const t = {
875
+ ...s,
876
+ collectUserData: s.collectUserData ?? !1,
877
+ initialMessages: s.initialMessages ?? [],
878
+ apiUrl: s.apiUrl ?? "https://api.open.cx",
879
+ pollingInterval: s.pollingInterval ?? 3e3,
880
+ headers: s.headers ?? {},
881
+ queryParams: s.queryParams ?? {},
882
+ pathParams: s.pathParams ?? {},
883
+ bot: {
884
+ name: ((c = s.bot) == null ? void 0 : c.name) ?? "Bot",
885
+ avatar: ((n = s.bot) == null ? void 0 : n.avatar) ?? null,
886
+ id: ((m = s.bot) == null ? void 0 : m.id) ?? null,
887
+ isAi: ((i = s.bot) == null ? void 0 : i.isAi) ?? !0
888
+ },
889
+ contactToken: s.contactToken,
890
+ debug: s.debug ?? !1,
891
+ language: s.language ?? "en",
892
+ user: s.user ?? {},
893
+ soundEffectFiles: Object.assign({}, pe, s.soundEffectFiles),
894
+ theme: Object.assign({}, Ee, s.theme),
895
+ settings: Object.assign({}, te, s.settings),
896
+ assets: {
897
+ organizationLogo: ((l = s.assets) == null ? void 0 : l.organizationLogo) ?? ""
898
+ }
899
+ }, r = `${t.token}:settings`, { getSettings: a, updateSettings: o } = be(t.settings, e, r);
900
+ return {
901
+ config: t,
902
+ updateSettings: o,
903
+ getConfig: () => ({
904
+ ...t,
905
+ settings: a()
906
+ }),
907
+ getApiConfig: () => ({
908
+ apiUrl: t.apiUrl,
909
+ token: t.token,
910
+ headers: t.headers,
911
+ queryParams: t.queryParams,
912
+ pathParams: t.pathParams
913
+ }),
914
+ getBotConfig: () => t.bot,
915
+ getThemeConfig: () => t.theme,
916
+ getSoundEffects: () => t.soundEffectFiles,
917
+ getUser: () => t.user,
918
+ getLanguage: () => t.language,
919
+ getDebugMode: () => t.debug
920
+ };
921
+ }
922
+ const we = /\{[^{}]+\}/g, Pe = () => {
923
+ var s, e;
924
+ return typeof process == "object" && Number.parseInt((e = (s = process == null ? void 0 : process.versions) == null ? void 0 : s.node) == null ? void 0 : e.substring(0, 2)) >= 18 && process.versions.undici;
925
+ };
926
+ function Te() {
927
+ return Math.random().toString(36).slice(2, 11);
928
+ }
929
+ function Ae(s) {
930
+ let {
931
+ baseUrl: e = "",
932
+ Request: t = globalThis.Request,
933
+ fetch: r = globalThis.fetch,
934
+ querySerializer: a,
935
+ bodySerializer: o,
936
+ headers: c,
937
+ requestInitExt: n = void 0,
938
+ ...m
939
+ } = { ...s };
940
+ n = Pe() ? n : void 0, e = ee(e);
941
+ const i = [];
942
+ async function l(g, u) {
943
+ const {
944
+ baseUrl: b,
945
+ fetch: w = r,
946
+ Request: D = t,
947
+ headers: S,
948
+ params: P = {},
949
+ parseAs: x = "json",
950
+ querySerializer: T,
951
+ bodySerializer: F = o ?? Oe,
952
+ body: v,
953
+ ...p
954
+ } = u || {};
955
+ b && (e = ee(b));
956
+ let d = typeof a == "function" ? a : Z(a);
957
+ T && (d = typeof T == "function" ? T : Z({
958
+ ...typeof a == "object" ? a : {},
959
+ ...T
960
+ }));
961
+ const f = v === void 0 ? void 0 : F(v), E = (
962
+ // with no body, we should not to set Content-Type
963
+ f === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
964
+ f instanceof FormData ? {} : {
965
+ "Content-Type": "application/json"
966
+ }
967
+ ), q = {
968
+ redirect: "follow",
969
+ ...m,
970
+ ...p,
971
+ body: f,
972
+ headers: ve(E, c, S, P.header)
973
+ };
974
+ let $, z, U = new t(Re(g, { baseUrl: e, params: P, querySerializer: d }), q);
975
+ for (const I in p)
976
+ I in U || (U[I] = p[I]);
977
+ if (i.length) {
978
+ $ = Te(), z = Object.freeze({
979
+ baseUrl: e,
980
+ fetch: w,
981
+ parseAs: x,
982
+ querySerializer: d,
983
+ bodySerializer: F
984
+ });
985
+ for (const I of i)
986
+ if (I && typeof I == "object" && typeof I.onRequest == "function") {
987
+ const O = await I.onRequest({
988
+ request: U,
989
+ schemaPath: g,
990
+ params: P,
991
+ options: z,
992
+ id: $
993
+ });
994
+ if (O) {
995
+ if (!(O instanceof t))
996
+ throw new Error("onRequest: must return new Request() when modifying the request");
997
+ U = O;
998
+ }
999
+ }
1000
+ }
1001
+ let y;
1002
+ try {
1003
+ y = await w(U, n);
1004
+ } catch (I) {
1005
+ let O = I;
1006
+ if (i.length)
1007
+ for (let _ = i.length - 1; _ >= 0; _--) {
1008
+ const H = i[_];
1009
+ if (H && typeof H == "object" && typeof H.onError == "function") {
1010
+ const j = await H.onError({
1011
+ request: U,
1012
+ error: O,
1013
+ schemaPath: g,
1014
+ params: P,
1015
+ options: z,
1016
+ id: $
1017
+ });
1018
+ if (j) {
1019
+ if (j instanceof Response) {
1020
+ O = void 0, y = j;
1021
+ break;
1022
+ }
1023
+ if (j instanceof Error) {
1024
+ O = j;
1025
+ continue;
1026
+ }
1027
+ throw new Error("onError: must return new Response() or instance of Error");
1028
+ }
1029
+ }
1030
+ }
1031
+ if (O)
1032
+ throw O;
1033
+ }
1034
+ if (i.length)
1035
+ for (let I = i.length - 1; I >= 0; I--) {
1036
+ const O = i[I];
1037
+ if (O && typeof O == "object" && typeof O.onResponse == "function") {
1038
+ const _ = await O.onResponse({
1039
+ request: U,
1040
+ response: y,
1041
+ schemaPath: g,
1042
+ params: P,
1043
+ options: z,
1044
+ id: $
1045
+ });
1046
+ if (_) {
1047
+ if (!(_ instanceof Response))
1048
+ throw new Error("onResponse: must return new Response() when modifying the response");
1049
+ y = _;
1050
+ }
1051
+ }
1052
+ }
1053
+ if (y.status === 204 || y.headers.get("Content-Length") === "0")
1054
+ return y.ok ? { data: void 0, response: y } : { error: void 0, response: y };
1055
+ if (y.ok)
1056
+ return x === "stream" ? { data: y.body, response: y } : { data: await y[x](), response: y };
1057
+ let K = await y.text();
1058
+ try {
1059
+ K = JSON.parse(K);
1060
+ } catch {
1061
+ }
1062
+ return { error: K, response: y };
1063
+ }
1064
+ return {
1065
+ request(g, u, b) {
1066
+ return l(u, { ...b, method: g.toUpperCase() });
1067
+ },
1068
+ /** Call a GET endpoint */
1069
+ GET(g, u) {
1070
+ return l(g, { ...u, method: "GET" });
1071
+ },
1072
+ /** Call a PUT endpoint */
1073
+ PUT(g, u) {
1074
+ return l(g, { ...u, method: "PUT" });
1075
+ },
1076
+ /** Call a POST endpoint */
1077
+ POST(g, u) {
1078
+ return l(g, { ...u, method: "POST" });
1079
+ },
1080
+ /** Call a DELETE endpoint */
1081
+ DELETE(g, u) {
1082
+ return l(g, { ...u, method: "DELETE" });
1083
+ },
1084
+ /** Call a OPTIONS endpoint */
1085
+ OPTIONS(g, u) {
1086
+ return l(g, { ...u, method: "OPTIONS" });
1087
+ },
1088
+ /** Call a HEAD endpoint */
1089
+ HEAD(g, u) {
1090
+ return l(g, { ...u, method: "HEAD" });
1091
+ },
1092
+ /** Call a PATCH endpoint */
1093
+ PATCH(g, u) {
1094
+ return l(g, { ...u, method: "PATCH" });
1095
+ },
1096
+ /** Call a TRACE endpoint */
1097
+ TRACE(g, u) {
1098
+ return l(g, { ...u, method: "TRACE" });
1099
+ },
1100
+ /** Register middleware */
1101
+ use(...g) {
1102
+ for (const u of g)
1103
+ if (u) {
1104
+ if (typeof u != "object" || !("onRequest" in u || "onResponse" in u || "onError" in u))
1105
+ throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
1106
+ i.push(u);
1107
+ }
1108
+ },
1109
+ /** Unregister middleware */
1110
+ eject(...g) {
1111
+ for (const u of g) {
1112
+ const b = i.indexOf(u);
1113
+ b !== -1 && i.splice(b, 1);
1114
+ }
1115
+ }
1116
+ };
1117
+ }
1118
+ function W(s, e, t) {
1119
+ if (e == null)
1120
+ return "";
1121
+ if (typeof e == "object")
1122
+ throw new Error(
1123
+ "Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these."
1124
+ );
1125
+ return `${s}=${(t == null ? void 0 : t.allowReserved) === !0 ? e : encodeURIComponent(e)}`;
1126
+ }
1127
+ function se(s, e, t) {
1128
+ if (!e || typeof e != "object")
1129
+ return "";
1130
+ const r = [], a = {
1131
+ simple: ",",
1132
+ label: ".",
1133
+ matrix: ";"
1134
+ }[t.style] || "&";
1135
+ if (t.style !== "deepObject" && t.explode === !1) {
1136
+ for (const n in e)
1137
+ r.push(n, t.allowReserved === !0 ? e[n] : encodeURIComponent(e[n]));
1138
+ const c = r.join(",");
1139
+ switch (t.style) {
1140
+ case "form":
1141
+ return `${s}=${c}`;
1142
+ case "label":
1143
+ return `.${c}`;
1144
+ case "matrix":
1145
+ return `;${s}=${c}`;
1146
+ default:
1147
+ return c;
1148
+ }
1149
+ }
1150
+ for (const c in e) {
1151
+ const n = t.style === "deepObject" ? `${s}[${c}]` : c;
1152
+ r.push(W(n, e[c], t));
1153
+ }
1154
+ const o = r.join(a);
1155
+ return t.style === "label" || t.style === "matrix" ? `${a}${o}` : o;
1156
+ }
1157
+ function re(s, e, t) {
1158
+ if (!Array.isArray(e))
1159
+ return "";
1160
+ if (t.explode === !1) {
1161
+ const o = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[t.style] || ",", c = (t.allowReserved === !0 ? e : e.map((n) => encodeURIComponent(n))).join(o);
1162
+ switch (t.style) {
1163
+ case "simple":
1164
+ return c;
1165
+ case "label":
1166
+ return `.${c}`;
1167
+ case "matrix":
1168
+ return `;${s}=${c}`;
1169
+ default:
1170
+ return `${s}=${c}`;
1171
+ }
1172
+ }
1173
+ const r = { simple: ",", label: ".", matrix: ";" }[t.style] || "&", a = [];
1174
+ for (const o of e)
1175
+ t.style === "simple" || t.style === "label" ? a.push(t.allowReserved === !0 ? o : encodeURIComponent(o)) : a.push(W(s, o, t));
1176
+ return t.style === "label" || t.style === "matrix" ? `${r}${a.join(r)}` : a.join(r);
1177
+ }
1178
+ function Z(s) {
1179
+ return function(t) {
1180
+ const r = [];
1181
+ if (t && typeof t == "object")
1182
+ for (const a in t) {
1183
+ const o = t[a];
1184
+ if (o != null) {
1185
+ if (Array.isArray(o)) {
1186
+ if (o.length === 0)
1187
+ continue;
1188
+ r.push(
1189
+ re(a, o, {
1190
+ style: "form",
1191
+ explode: !0,
1192
+ ...s == null ? void 0 : s.array,
1193
+ allowReserved: (s == null ? void 0 : s.allowReserved) || !1
1194
+ })
1195
+ );
1196
+ continue;
1197
+ }
1198
+ if (typeof o == "object") {
1199
+ r.push(
1200
+ se(a, o, {
1201
+ style: "deepObject",
1202
+ explode: !0,
1203
+ ...s == null ? void 0 : s.object,
1204
+ allowReserved: (s == null ? void 0 : s.allowReserved) || !1
1205
+ })
1206
+ );
1207
+ continue;
1208
+ }
1209
+ r.push(W(a, o, s));
1210
+ }
1211
+ }
1212
+ return r.join("&");
1213
+ };
1214
+ }
1215
+ function Ie(s, e) {
1216
+ let t = s;
1217
+ for (const r of s.match(we) ?? []) {
1218
+ let a = r.substring(1, r.length - 1), o = !1, c = "simple";
1219
+ if (a.endsWith("*") && (o = !0, a = a.substring(0, a.length - 1)), a.startsWith(".") ? (c = "label", a = a.substring(1)) : a.startsWith(";") && (c = "matrix", a = a.substring(1)), !e || e[a] === void 0 || e[a] === null)
1220
+ continue;
1221
+ const n = e[a];
1222
+ if (Array.isArray(n)) {
1223
+ t = t.replace(r, re(a, n, { style: c, explode: o }));
1224
+ continue;
1225
+ }
1226
+ if (typeof n == "object") {
1227
+ t = t.replace(r, se(a, n, { style: c, explode: o }));
1228
+ continue;
1229
+ }
1230
+ if (c === "matrix") {
1231
+ t = t.replace(r, `;${W(a, n)}`);
1232
+ continue;
1233
+ }
1234
+ t = t.replace(r, c === "label" ? `.${encodeURIComponent(n)}` : encodeURIComponent(n));
1235
+ }
1236
+ return t;
1237
+ }
1238
+ function Oe(s) {
1239
+ return s instanceof FormData ? s : JSON.stringify(s);
1240
+ }
1241
+ function Re(s, e) {
1242
+ var a;
1243
+ let t = `${e.baseUrl}${s}`;
1244
+ (a = e.params) != null && a.path && (t = Ie(t, e.params.path));
1245
+ let r = e.querySerializer(e.params.query ?? {});
1246
+ return r.startsWith("?") && (r = r.substring(1)), r && (t += `?${r}`), t;
1247
+ }
1248
+ function ve(...s) {
1249
+ const e = new Headers();
1250
+ for (const t of s) {
1251
+ if (!t || typeof t != "object")
1252
+ continue;
1253
+ const r = t instanceof Headers ? t.entries() : Object.entries(t);
1254
+ for (const [a, o] of r)
1255
+ if (o === null)
1256
+ e.delete(a);
1257
+ else if (Array.isArray(o))
1258
+ for (const c of o)
1259
+ e.append(a, c);
1260
+ else o !== void 0 && e.set(a, o);
1261
+ }
1262
+ return e;
1263
+ }
1264
+ function ee(s) {
1265
+ return s.endsWith("/") ? s.substring(0, s.length - 1) : s;
1266
+ }
1267
+ const Le = (s) => {
1268
+ console.log(s.error);
1269
+ }, Ce = (s) => {
1270
+ const e = Ae({
1271
+ baseUrl: s.baseUrl
1272
+ }), t = {
1273
+ onRequest: s.onRequest,
1274
+ onResponse: s.onResponse,
1275
+ onError: s.onError || Le
1276
+ };
1277
+ return e.use(t), e;
1278
+ };
1279
+ var R;
1280
+ class Ge {
1281
+ constructor(e) {
1282
+ G(this, R);
1283
+ h(this, "me", async () => await A(this, R).GET("/backend/widget/v2/me"));
1284
+ h(this, "widgetPrelude", async () => await A(this, R).GET("/backend/widget/v2/prelude", {
1285
+ params: { header: { "X-Bot-Token": this.options.config.token } }
1286
+ }));
1287
+ h(this, "handleMessage", async (e, t) => await A(this, R).POST("/backend/widget/v2/chat/send", {
1288
+ body: e,
1289
+ signal: t
1290
+ }));
1291
+ h(this, "getSessionHistory", async (e, t) => {
1292
+ const r = t ? { lastMessageTimestamp: t } : void 0;
1293
+ return await A(this, R).GET(
1294
+ "/backend/widget/v2/session/history/{sessionId}",
1295
+ { params: { path: { sessionId: e }, query: r } }
1296
+ );
1297
+ });
1298
+ h(this, "createSession", async () => await A(this, R).POST("/backend/widget/v2/create-session"));
1299
+ h(this, "getSession", async (e) => await A(this, R).GET("/backend/widget/v2/session/{sessionId}", {
1300
+ params: { path: { sessionId: e } }
1301
+ }));
1302
+ h(this, "uploadFile", async ({
1303
+ file: e,
1304
+ abortSignal: t
1305
+ }) => {
1306
+ const r = new FormData();
1307
+ return r.append("file", e.file), await A(this, R).POST("/backend/widget/v2/upload", {
1308
+ params: { query: { fileId: e.id, sessionId: "" } },
1309
+ body: r,
1310
+ signal: t,
1311
+ headers: {
1312
+ "Content-Type": "multipart/form-data"
1313
+ }
1314
+ });
1315
+ });
1316
+ h(this, "vote", async (e) => await A(this, R).POST("/backend/widget/v2/chat/vote", { body: e }));
1317
+ this.options = e;
1318
+ const t = this.options.config.user, r = {
1319
+ claim: "",
1320
+ value: ""
1321
+ };
1322
+ t != null && t.email ? (r.claim = "email", r.value = t.email) : t != null && t.phone && (r.claim = "phone", r.value = t.phone), k(this, R, Ce({
1323
+ baseUrl: this.options.config.apiUrl,
1324
+ onRequest: ({ request: a }) => {
1325
+ a.headers.set("X-Bot-Token", this.options.config.token), a.headers.set(
1326
+ "X-Consumer-Id",
1327
+ `${r.claim}:${r.value}`
1328
+ ), a.headers.set("Content-Type", "application/json"), a.headers.set("Accept", "application/json"), this.options.config.contactToken && a.headers.set(
1329
+ "Authorization",
1330
+ `Bearer ${this.options.config.contactToken}`
1331
+ );
1332
+ }
1333
+ }));
1334
+ }
1335
+ }
1336
+ R = new WeakMap();
1337
+ export {
1338
+ Ge as A,
1339
+ _e as C,
1340
+ je as E,
1341
+ Ne as F,
1342
+ ue as L,
1343
+ M as O,
1344
+ X as P,
1345
+ le as S,
1346
+ ke as T,
1347
+ ge as a,
1348
+ He as b,
1349
+ ze as c,
1350
+ $e as d,
1351
+ Me as e,
1352
+ Fe as f,
1353
+ ce as g,
1354
+ qe as h,
1355
+ L as i,
1356
+ fe as j,
1357
+ de as k,
1358
+ Y as s
1359
+ };
1360
+ //# sourceMappingURL=api-DRZ9vPwy.js.map