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