@origonai/web-chat-sdk 1.0.11 → 1.0.13

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.
@@ -1,5 +1,5 @@
1
- import { fetchEventSource as ge } from "@microsoft/fetch-event-source";
2
- function j() {
1
+ import { fetchEventSource as Ee } from "@microsoft/fetch-event-source";
2
+ function de() {
3
3
  const e = Date.now(), n = new Uint8Array(16);
4
4
  crypto.getRandomValues(n), n[0] = e >> 40 & 255, n[1] = e >> 32 & 255, n[2] = e >> 24 & 255, n[3] = e >> 16 & 255, n[4] = e >> 8 & 255, n[5] = e & 255, n[6] = n[6] & 15 | 112, n[8] = n[8] & 63 | 128;
5
5
  const o = [...n].map((r) => r.toString(16).padStart(2, "0")).join("");
@@ -8,25 +8,25 @@ function j() {
8
8
  20
9
9
  )}-${o.slice(20)}`;
10
10
  }
11
- function fe() {
11
+ function ye() {
12
12
  if (localStorage.getItem("chatDeviceId"))
13
13
  return localStorage.getItem("chatDeviceId");
14
- const e = j();
14
+ const e = de();
15
15
  return localStorage.setItem("chatDeviceId", e), e;
16
16
  }
17
- async function pe(e) {
17
+ async function be(e) {
18
18
  return new Promise((n) => setTimeout(n, e));
19
19
  }
20
- function me(e) {
20
+ function Te(e) {
21
21
  let n;
22
22
  try {
23
23
  const o = new URL(e);
24
- n = `https://${o.hostname}${o.pathname}/sse`;
24
+ n = `https://${o.hostname}${o.pathname}/sse${o.search}`;
25
25
  } catch (o) {
26
26
  }
27
27
  return n;
28
28
  }
29
- function Se(e) {
29
+ function ve(e) {
30
30
  let n;
31
31
  try {
32
32
  const o = new URL(e);
@@ -35,7 +35,7 @@ function Se(e) {
35
35
  }
36
36
  return n;
37
37
  }
38
- function ke(e) {
38
+ function Ae(e) {
39
39
  let n;
40
40
  try {
41
41
  const o = new URL(e);
@@ -44,22 +44,24 @@ function ke(e) {
44
44
  }
45
45
  return n;
46
46
  }
47
- const y = {
47
+ const w = {
48
48
  ASSISTANT: "assistant",
49
49
  // this can be automated or LLM AI Agent response
50
50
  USER: "user",
51
51
  // this is widget user
52
52
  SUPERVISOR: "supervisor",
53
53
  // this is human supervisor (ex. Samespace Dock agent, or Resolve human agent)
54
- SYSTEM: "system"
54
+ SYSTEM: "system",
55
55
  // this is system message, for ex "Agent joined" / "Agent left"
56
- }, ee = 1e4, Ie = 5e3, R = {
56
+ TOOL: "tool"
57
+ // tool call loading/result message
58
+ }, ue = 1e4, $e = 5e3, O = {
57
59
  MESSAGE: "message",
58
60
  TYPING: "typing",
59
61
  TYPING_STOP: "typingOff",
60
62
  END: "end"
61
63
  };
62
- function he() {
64
+ function Ue() {
63
65
  return {
64
66
  socket: null,
65
67
  previouslyConnected: !1,
@@ -69,36 +71,36 @@ function he() {
69
71
  socketConnectionTimeout: null
70
72
  };
71
73
  }
72
- let a = he();
73
- function x() {
74
- a.pingInterval && (clearInterval(a.pingInterval), a.pingInterval = null);
74
+ let c = Ue();
75
+ function F() {
76
+ c.pingInterval && (clearInterval(c.pingInterval), c.pingInterval = null);
75
77
  }
76
- function we() {
77
- x(), a.pingInterval = setInterval(() => {
78
- a.socket && a.socket.readyState === WebSocket.OPEN ? q({ type: "ping" }) : x();
79
- }, ee);
78
+ function De() {
79
+ F(), c.pingInterval = setInterval(() => {
80
+ c.socket && c.socket.readyState === WebSocket.OPEN ? G({ type: "ping" }) : F();
81
+ }, ue);
80
82
  }
81
- function ne() {
82
- x(), a.socketDisconnectedTimeout && (clearTimeout(a.socketDisconnectedTimeout), a.socketDisconnectedTimeout = null), a.socketConnectionTimeout && (clearTimeout(a.socketConnectionTimeout), a.socketConnectionTimeout = null);
83
+ function ge() {
84
+ F(), c.socketDisconnectedTimeout && (clearTimeout(c.socketDisconnectedTimeout), c.socketDisconnectedTimeout = null), c.socketConnectionTimeout && (clearTimeout(c.socketConnectionTimeout), c.socketConnectionTimeout = null);
83
85
  }
84
- function te() {
85
- a.socketDisconnected = !1, N("socket");
86
+ function fe() {
87
+ c.socketDisconnected = !1, x("socket");
86
88
  }
87
- function oe() {
88
- a.socketDisconnected = !0, N("sse");
89
+ function pe() {
90
+ c.socketDisconnected = !0, x("sse");
89
91
  }
90
- function Ce(e) {
92
+ function Re(e) {
91
93
  return new Promise((n, o) => {
92
- if (a.socket && (a.socket.readyState === WebSocket.CONNECTING || a.socket.readyState === WebSocket.OPEN)) {
93
- n(a.socket.readyState === WebSocket.OPEN);
94
+ if (c.socket && (c.socket.readyState === WebSocket.CONNECTING || c.socket.readyState === WebSocket.OPEN)) {
95
+ n(c.socket.readyState === WebSocket.OPEN);
94
96
  return;
95
97
  }
96
- const r = b();
98
+ const r = A();
97
99
  if (!r || !r.endpoint) {
98
100
  o(new Error("SDK not initialized. Please initialize SDK first."));
99
101
  return;
100
102
  }
101
- const l = Se(r.endpoint);
103
+ const l = ve(r.endpoint);
102
104
  if (!l) {
103
105
  o(
104
106
  new Error(
@@ -107,74 +109,74 @@ function Ce(e) {
107
109
  );
108
110
  return;
109
111
  }
110
- const d = O(), c = new URLSearchParams({
112
+ const d = M(), a = new URLSearchParams({
111
113
  externalId: d
112
114
  });
113
- e.sessionId && c.set("sessionId", e.sessionId), e.requestId && c.set("requestId", e.requestId), r.token && c.set("token", r.token);
114
- const u = `${l}?${c.toString()}`;
115
- a.socket = new WebSocket(u), a.socket.onopen = () => {
116
- a.previouslyConnected = !0, te(), q({ type: "ping" }), clearTimeout(a.socketConnectionTimeout), we(), n(!0);
117
- }, a.socket.onmessage = (g) => {
118
- const f = JSON.parse(g.data);
119
- Ee(f);
120
- }, a.socket.onerror = (g) => {
121
- N("sse"), o(g);
122
- }, a.socket.onclose = (g) => {
123
- g.target === a.socket && (g.code === 1006 && (a.previouslyConnected ? oe() : h({
115
+ e.sessionId && a.set("sessionId", e.sessionId), e.requestId && a.set("requestId", e.requestId), r.token && a.set("token", r.token);
116
+ const g = `${l}?${a.toString()}`;
117
+ c.socket = new WebSocket(g), c.socket.onopen = () => {
118
+ c.previouslyConnected = !0, fe(), G({ type: "ping" }), clearTimeout(c.socketConnectionTimeout), De(), n(!0);
119
+ }, c.socket.onmessage = (f) => {
120
+ const u = JSON.parse(f.data);
121
+ Oe(u);
122
+ }, c.socket.onerror = (f) => {
123
+ x("sse"), o(f);
124
+ }, c.socket.onclose = (f) => {
125
+ f.target === c.socket && (f.code === 1006 && (c.previouslyConnected ? pe() : E({
124
126
  errorText: "Unable to establish connection",
125
127
  done: !0,
126
128
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
127
- }), clearTimeout(a.socketConnectionTimeout)), a.socket = null, ne());
128
- }, a.previouslyConnected || (a.socketConnectionTimeout = setTimeout(() => {
129
- h({
129
+ }), clearTimeout(c.socketConnectionTimeout)), c.socket = null, ge());
130
+ }, c.previouslyConnected || (c.socketConnectionTimeout = setTimeout(() => {
131
+ E({
130
132
  errorText: "Unable to establish connection",
131
133
  done: !0,
132
134
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
133
135
  }), o(new Error("Socket connection timed out"));
134
- }, Ie));
136
+ }, $e));
135
137
  });
136
138
  }
137
- function q(e) {
138
- a.socketDisconnected || !a.socket || a.socket.send(JSON.stringify({ ...e, eventId: e.eventId || j() }));
139
+ function G(e) {
140
+ c.socketDisconnected || !c.socket || c.socket.send(JSON.stringify({ ...e, eventId: e.eventId || de() }));
139
141
  }
140
- function Ee(e) {
142
+ function Oe(e) {
141
143
  switch (e.type) {
142
144
  case "pong": {
143
- a.socketDisconnected && te(), a.socketDisconnectedTimeout && clearTimeout(a.socketDisconnectedTimeout), a.socketDisconnectedTimeout = setTimeout(() => {
144
- oe();
145
- }, ee + 1e3);
145
+ c.socketDisconnected && fe(), c.socketDisconnectedTimeout && clearTimeout(c.socketDisconnectedTimeout), c.socketDisconnectedTimeout = setTimeout(() => {
146
+ pe();
147
+ }, ue + 1e3);
146
148
  break;
147
149
  }
148
- case R.TYPING: {
149
- Z(!0);
150
+ case O.TYPING: {
151
+ le(!0);
150
152
  break;
151
153
  }
152
- case R.TYPING_STOP: {
153
- Z(!1);
154
+ case O.TYPING_STOP: {
155
+ le(!1);
154
156
  break;
155
157
  }
156
- case R.MESSAGE: {
158
+ case O.MESSAGE: {
157
159
  const { eventId: n, data: o } = e;
158
- n || h({
160
+ n || E({
159
161
  ...o,
160
162
  done: !0,
161
163
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
162
164
  });
163
165
  break;
164
166
  }
165
- case R.END: {
166
- se();
167
+ case O.END: {
168
+ me();
167
169
  break;
168
170
  }
169
171
  }
170
172
  }
171
- function se() {
172
- a.socket && a.socket.close(1e3), a.previouslyConnected = !1, ne(), a.socket = null, N("sse");
173
+ function me() {
174
+ c.socket && c.socket.close(1e3), c.previouslyConnected = !1, ge(), c.socket = null, x("sse");
173
175
  }
174
- function ye() {
175
- return a.socket !== null && a.socket.readyState === WebSocket.OPEN && !a.socketDisconnected;
176
+ function Ne() {
177
+ return c.socket !== null && c.socket.readyState === WebSocket.OPEN && !c.socketDisconnected;
176
178
  }
177
- function re(e = {}) {
179
+ function Se(e = {}) {
178
180
  return {
179
181
  credentials: void 0,
180
182
  authenticated: !1,
@@ -190,34 +192,35 @@ function re(e = {}) {
190
192
  control: "agent"
191
193
  };
192
194
  }
193
- let s = re();
194
- function Ge(e) {
195
+ let s = Se();
196
+ function je(e) {
195
197
  s.callbacks = { ...s.callbacks, ...e };
196
198
  }
197
- function Je(e) {
199
+ function en(e) {
198
200
  s.credentials = e, e.token && (s.authenticated = !0);
199
201
  }
200
- function b() {
202
+ function A() {
201
203
  return s.credentials;
202
204
  }
203
- function be(e) {
205
+ function Pe() {
206
+ return s.configData;
207
+ }
208
+ function Me(e) {
204
209
  var n, o;
205
210
  e && e !== s.sessionId && (s.sessionId = e, (o = (n = s.callbacks).onSessionUpdate) == null || o.call(n, e));
206
211
  }
207
- async function We(e = {}) {
212
+ async function nn(e = {}) {
208
213
  try {
209
214
  let n = null;
210
- s.authenticated ? n = s.configData : (n = await $e(s.credentials), s.authenticated = !0, s.configData = n);
215
+ s.authenticated ? n = s.configData : (n = await qe(s.credentials), s.authenticated = !0, s.configData = n);
211
216
  let o = [], r = "agent";
212
217
  const l = e.fetchSession !== !1;
213
218
  if (e.sessionId && l) {
214
- const c = await De(e.sessionId);
215
- o = c.messages, r = c.control || "agent";
219
+ const a = await ze(e.sessionId);
220
+ o = a.messages, r = a.control || "agent";
216
221
  }
217
- const d = new URLSearchParams();
218
- return s.credentials.token || d.set("externalId", O()), s.sseUrl = `${me(
219
- s.credentials.endpoint
220
- )}?${d.toString()}`, s.sessionId = e.sessionId, s.messages = o, s.control = r, r === "human" && Te({ text: "", html: "" }).catch(() => {
222
+ const d = new URL(Te(s.credentials.endpoint));
223
+ return s.credentials.token || d.searchParams.set("externalId", M()), s.sseUrl = d.toString(), s.sessionId = e.sessionId, s.messages = o, s.control = r, r === "human" && xe({ text: "", html: "" }).catch(() => {
221
224
  }), {
222
225
  sessionId: s.sessionId,
223
226
  messages: o,
@@ -225,81 +228,96 @@ async function We(e = {}) {
225
228
  configData: n
226
229
  };
227
230
  } catch (n) {
228
- throw ae(), n;
231
+ throw ke(), n;
229
232
  }
230
233
  }
231
- function _e() {
232
- ae();
234
+ function tn() {
235
+ ke();
233
236
  }
234
- function ae() {
235
- s.abortController && s.abortController.abort(), se();
237
+ function ke() {
238
+ s.abortController && s.abortController.abort(), me();
236
239
  const { callbacks: e, credentials: n } = s;
237
- s = re(e), s.credentials = n;
240
+ s = Se(e), s.credentials = n;
238
241
  }
239
- function O() {
242
+ function M() {
240
243
  var e;
241
- return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : fe();
244
+ return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : ye();
242
245
  }
243
- function h(e) {
246
+ function E(e) {
244
247
  var n, o;
245
248
  s.messages = [...s.messages, e], (o = (n = s.callbacks).onMessageAdd) == null || o.call(n, e);
246
249
  }
247
- function Z(e) {
250
+ function le(e) {
248
251
  var n, o;
249
252
  (o = (n = s.callbacks).onTyping) == null || o.call(n, e);
250
253
  }
251
- function N(e) {
254
+ function x(e) {
252
255
  var n, o;
253
256
  s.transport = e, (o = (n = s.callbacks).onTransportUpdate) == null || o.call(n, e);
254
257
  }
255
- function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
256
- return new Promise((d, c) => {
258
+ function xe({ text: e, html: n, context: o, attachments: r, type: l, results: d, meta: a, createSystem: g, mode: f = "assist" }) {
259
+ return new Promise((u, h) => {
257
260
  (async () => {
258
- var u, g, f;
261
+ var y, C, J;
259
262
  try {
260
- const I = !e && !n && !(r != null && r.length);
261
- if (!I) {
263
+ if (l === "tool_results" && Array.isArray(d))
264
+ for (const p of d) {
265
+ const i = {
266
+ role: w.TOOL,
267
+ toolCallId: p.toolCallId,
268
+ toolName: p.toolName,
269
+ text: JSON.stringify(p.data),
270
+ done: !0
271
+ };
272
+ E(i);
273
+ }
274
+ if (e || n || (r == null ? void 0 : r.length)) {
262
275
  const p = {
263
- role: y.USER,
276
+ role: w.USER,
264
277
  text: e,
265
278
  html: n,
266
279
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
267
280
  attachments: r,
268
- meta: l
281
+ meta: a
269
282
  };
270
- h(p), await pe(200);
283
+ E(p), await be(200);
271
284
  }
272
- if (s.transport === "socket" && ye()) {
273
- q({
285
+ if (s.transport === "socket" && Ne()) {
286
+ G({
274
287
  type: "message",
275
288
  data: {
276
289
  text: e,
277
290
  html: n
278
291
  }
279
- }), d(s.sessionId);
292
+ }), u(s.sessionId);
280
293
  return;
281
294
  }
282
295
  if (s.control === "agent") {
283
296
  const p = {
284
- role: y.ASSISTANT,
297
+ role: w.ASSISTANT,
285
298
  text: "",
286
299
  loading: !0
287
300
  };
288
- h(p);
301
+ E(p);
289
302
  }
290
- const v = new URL(s.sseUrl);
291
- s.sessionId && v.searchParams.set("sessionId", s.sessionId), s.requestId && v.searchParams.set("requestId", s.requestId), s.lastStreamId = void 0, s.abortController = new AbortController();
292
- const C = {
303
+ const U = new URL(s.sseUrl);
304
+ s.sessionId && U.searchParams.set("sessionId", s.sessionId), s.requestId && U.searchParams.set("requestId", s.requestId), s.lastStreamId = void 0, s.abortController = new AbortController();
305
+ const v = {
293
306
  "Content-Type": "application/json"
294
307
  };
295
- (u = s.credentials) != null && u.token && (C.Authorization = `Bearer ${s.credentials.token}`), await ge(v.toString(), {
308
+ (y = s.credentials) != null && y.token && (v.Authorization = `Bearer ${s.credentials.token}`), await Ee(U.toString(), {
296
309
  method: "POST",
297
- headers: C,
298
- body: I ? l ? JSON.stringify({ meta: l }) : void 0 : JSON.stringify({
299
- message: e,
300
- html: n,
301
- context: o,
302
- attachments: r
310
+ headers: v,
311
+ body: JSON.stringify({
312
+ ...e && { message: e },
313
+ ...n && { html: n },
314
+ ...o && { context: o },
315
+ ...r && { attachments: r },
316
+ ...l && { type: l },
317
+ ...d && { results: d },
318
+ ...a && { meta: a },
319
+ ...g && { createSystem: g },
320
+ mode: f
303
321
  }),
304
322
  signal: s.abortController.signal,
305
323
  openWhenHidden: !0,
@@ -308,45 +326,71 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
308
326
  throw new Error("Failed to send message");
309
327
  },
310
328
  onmessage: (p) => {
311
- var D, A, L, z, F, G, J, W, _, K, H, V, B, Y, Q, X;
329
+ var D, R, W, _, K, B, H, V, Y, Q, X, Z, j, ee, ne, te, oe, se, re, ae, ce, ie;
312
330
  const i = JSON.parse(p.data);
313
331
  if (p.event === "connected")
314
- s.sessionId = i.sessionId, s.requestId = i.requestId, i.control && (s.control = i.control, (A = (D = s.callbacks).onControlUpdate) == null || A.call(D, i.control));
332
+ s.sessionId = i.sessionId, s.requestId = i.requestId, i.control && (s.control = i.control, (R = (D = s.callbacks).onControlUpdate) == null || R.call(D, i.control));
315
333
  else if (p.event === "upgrade_to_websocket")
316
- Ce({
334
+ Re({
317
335
  sessionId: s.sessionId,
318
336
  requestId: i.requestId
319
337
  });
320
338
  else if (p.event === "update")
321
- i.control && (s.control = i.control, (z = (L = s.callbacks).onControlUpdate) == null || z.call(L, i.control));
322
- else if (i.error) {
323
- const m = i.error && typeof i.error == "string" ? i.error : "Failed to connect to the system", k = s.messages.length - 1, S = {
324
- ...s.messages[k],
339
+ i.control && (s.control = i.control, (_ = (W = s.callbacks).onControlUpdate) == null || _.call(W, i.control));
340
+ else if (p.event === "done") {
341
+ const S = s.messages.length - 1, I = {
342
+ ...s.messages[S],
325
343
  loading: !1,
326
- errorText: m
344
+ done: !0
327
345
  };
328
346
  s.messages = s.messages.map(
329
- ($, ue) => ue === k ? S : $
330
- ), (G = (F = s.callbacks).onMessageUpdate) == null || G.call(F, k, S), c(new Error(m));
331
- } else if (p.event === "done") {
332
- const m = s.messages.length - 1, E = {
333
- ...s.messages[m],
347
+ (m, b) => b === S ? I : m
348
+ ), (B = (K = s.callbacks).onMessageUpdate) == null || B.call(K, S, I), u(s.sessionId);
349
+ } else if (p.event === "tool_calls") {
350
+ const S = i.toolCalls || [], k = s.messages.length - 1, I = s.messages[k];
351
+ if (I != null && I.loading) {
352
+ const m = {
353
+ ...I,
354
+ role: w.ASSISTANT,
355
+ text: i.message || "",
356
+ toolCalls: S,
357
+ loading: !1,
358
+ done: !0
359
+ };
360
+ s.messages = s.messages.map(
361
+ (b, z) => z === k ? m : b
362
+ ), (V = (H = s.callbacks).onMessageUpdate) == null || V.call(H, k, m);
363
+ } else {
364
+ const m = {
365
+ role: w.ASSISTANT,
366
+ text: i.message || "",
367
+ toolCalls: S,
368
+ done: !0
369
+ };
370
+ E(m);
371
+ }
372
+ (Q = (Y = s.callbacks).onToolCalls) == null || Q.call(Y, S);
373
+ } else if (p.event === "mode_switch")
374
+ (Z = (X = s.callbacks).onAssistantSwitchMode) == null || Z.call(X, i.mode);
375
+ else if (i.error) {
376
+ const S = i.error && typeof i.error == "string" ? i.error : "Failed to connect to the system", k = s.messages.length - 1, m = {
377
+ ...s.messages[k],
334
378
  loading: !1,
335
- done: !0
379
+ errorText: S
336
380
  };
337
381
  s.messages = s.messages.map(
338
- (S, $) => $ === m ? E : S
339
- ), (W = (J = s.callbacks).onMessageUpdate) == null || W.call(J, m, E), d(s.sessionId);
340
- } else if (i.message !== void 0 || ((_ = i.attachments) == null ? void 0 : _.length) > 0) {
341
- if (i.role === y.SUPERVISOR) {
342
- const S = {
343
- role: y.SUPERVISOR,
382
+ (b, z) => z === k ? m : b
383
+ ), (ee = (j = s.callbacks).onMessageUpdate) == null || ee.call(j, k, m), h(new Error(S));
384
+ } else if (i.message !== void 0 || ((ne = i.attachments) == null ? void 0 : ne.length) > 0) {
385
+ if (i.role === w.SUPERVISOR) {
386
+ const m = {
387
+ role: w.SUPERVISOR,
344
388
  text: i.message,
345
389
  attachments: i.attachments,
346
390
  sources: i.sources,
347
391
  done: !0
348
392
  };
349
- h(S), d(s.sessionId), s.sessionId = (K = i.sessionId) != null ? K : s.sessionId, s.requestId = (H = i.requestId) != null ? H : s.requestId;
393
+ E(m), u(s.sessionId), s.sessionId = (te = i.sessionId) != null ? te : s.sessionId, s.requestId = (oe = i.requestId) != null ? oe : s.requestId;
350
394
  return;
351
395
  }
352
396
  if (i.streamId !== void 0) {
@@ -354,25 +398,25 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
354
398
  s.lastStreamId = i.streamId;
355
399
  else if (i.streamId !== s.lastStreamId) {
356
400
  s.lastStreamId = i.streamId;
357
- const S = {
358
- role: y.ASSISTANT,
401
+ const m = {
402
+ role: w.ASSISTANT,
359
403
  text: "",
360
404
  loading: !0
361
405
  };
362
- h(S);
406
+ E(m);
363
407
  }
364
408
  }
365
- const m = s.messages.length - 1, k = s.messages[m], E = {
409
+ const S = s.messages.length - 1, k = s.messages[S], I = {
366
410
  ...k,
367
411
  loading: !1,
368
412
  text: (k.text || "") + i.message,
369
413
  sources: i.sources,
370
414
  attachments: i.attachments,
371
- done: (V = i.done) != null ? V : k.done
415
+ done: (se = i.done) != null ? se : k.done
372
416
  };
373
417
  s.messages = s.messages.map(
374
- (S, $) => $ === m ? E : S
375
- ), (Y = (B = s.callbacks).onMessageUpdate) == null || Y.call(B, m, E), s.sessionId = (Q = i.sessionId) != null ? Q : s.sessionId, s.requestId = (X = i.requestId) != null ? X : s.requestId;
418
+ (m, b) => b === S ? I : m
419
+ ), (ae = (re = s.callbacks).onMessageUpdate) == null || ae.call(re, S, I), s.sessionId = (ce = i.sessionId) != null ? ce : s.sessionId, s.requestId = (ie = i.requestId) != null ? ie : s.requestId;
376
420
  }
377
421
  },
378
422
  onerror: (p) => {
@@ -380,22 +424,22 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
380
424
  },
381
425
  openWhenHidden: !0
382
426
  });
383
- } catch (I) {
384
- const v = "Failed to connect to the system", C = s.messages.length - 1, p = s.messages[C], i = {
427
+ } catch (q) {
428
+ const U = "Failed to connect to the system", v = s.messages.length - 1, p = s.messages[v], i = {
385
429
  ...p,
386
430
  loading: !1,
387
- errorText: p.done ? void 0 : I.message || v,
431
+ errorText: p.done ? void 0 : q.message || U,
388
432
  done: !0
389
433
  };
390
434
  s.messages = s.messages.map(
391
- (D, A) => A === C ? i : D
392
- ), (f = (g = s.callbacks).onMessageUpdate) == null || f.call(g, C, i), c(I);
435
+ (D, R) => R === v ? i : D
436
+ ), (J = (C = s.callbacks).onMessageUpdate) == null || J.call(C, v, i), h(q);
393
437
  }
394
438
  })();
395
439
  });
396
440
  }
397
- const ve = "Something went wrong initializing the chat", M = "Chat SDK not initialized";
398
- async function $e(e) {
441
+ const Le = "Something went wrong initializing the chat", L = "Chat SDK not initialized";
442
+ async function qe(e) {
399
443
  const { endpoint: n } = e, o = `${n}/config`, r = await fetch(o, {
400
444
  method: "GET",
401
445
  headers: {
@@ -403,102 +447,131 @@ async function $e(e) {
403
447
  }
404
448
  });
405
449
  if (!r.ok) {
406
- const c = await r.json();
407
- throw new Error((c == null ? void 0 : c.error) || ve);
450
+ const a = await r.json();
451
+ throw new Error((a == null ? void 0 : a.error) || Le);
408
452
  }
409
453
  return (await r.json()).data;
410
454
  }
411
- async function Ke() {
455
+ async function on() {
412
456
  const e = new URLSearchParams({
413
- externalId: O()
414
- }), n = await ce(`/sessions?${e.toString()}`, "GET");
457
+ externalId: M()
458
+ }), n = await Ie(`/sessions?${e.toString()}`, "GET");
415
459
  if (!n.ok)
416
460
  throw new Error("Unable to load history, please try again later");
417
461
  return n.json();
418
462
  }
419
- async function De(e) {
420
- var c;
463
+ async function ze(e) {
464
+ var a;
421
465
  const n = new URLSearchParams({
422
466
  sessionId: e
423
- }), o = await ce(`/session?${n.toString()}`, "GET");
467
+ }), o = await Ie(`/session?${n.toString()}`, "GET");
424
468
  if (!o.ok)
425
469
  throw new Error("Unable to load messages, please try again later");
426
- const r = await o.json(), l = r == null ? void 0 : r.control, d = ((c = r == null ? void 0 : r.history) != null ? c : []).map((u) => ({
427
- id: u.id,
428
- text: u.text,
429
- role: u.youtubeVideo ? y.ASSISTANT : u.role,
430
- timestamp: u.timestamp,
431
- video: u.youtubeVideo,
432
- attachments: u.attachments,
433
- channel: u.channel,
470
+ const r = await o.json(), l = r == null ? void 0 : r.control, d = ((a = r == null ? void 0 : r.history) != null ? a : []).map((g) => ({
471
+ ...g,
472
+ role: g.youtubeVideo ? w.ASSISTANT : g.role,
473
+ video: g.youtubeVideo,
434
474
  done: !0
435
475
  }));
436
476
  return { control: l, messages: d };
437
477
  }
438
- function He(e, n, o) {
439
- const r = b(), { endpoint: l, token: d } = r || {};
478
+ function Fe(e) {
479
+ var u, h;
480
+ const n = Pe(), o = n == null ? void 0 : n.attachments;
481
+ if (!o)
482
+ return "Attachments are not enabled";
483
+ const r = e.name || "", l = (u = r.split(".").pop()) == null ? void 0 : u.toLowerCase();
484
+ if (!l)
485
+ return "File type is not supported";
486
+ const d = ["images", "documents", "audio", "videos"];
487
+ let a = null, g = null;
488
+ for (const y of d) {
489
+ const C = o[y];
490
+ if ((h = C == null ? void 0 : C.supportedFileTypes) != null && h.includes(l)) {
491
+ a = y, g = C;
492
+ break;
493
+ }
494
+ }
495
+ if (!a)
496
+ return `File type ".${l}" is not supported`;
497
+ if (!g.enabled)
498
+ return `${a.charAt(0).toUpperCase() + a.slice(1)} attachments are not supported`;
499
+ const f = e.size / (1024 * 1024);
500
+ return g.maxSize && f > g.maxSize ? `${r} size exceeds the maximum allowed size of ${g.maxSize}MB` : null;
501
+ }
502
+ function sn(e, n, o) {
503
+ const r = A(), { endpoint: l, token: d } = r || {};
440
504
  if (!l) {
441
- const f = new Error(M);
442
- return o && o(f, null), null;
505
+ const u = new Error(L);
506
+ return o && o(u, null), null;
507
+ }
508
+ if (!d) {
509
+ const u = Fe(e);
510
+ if (u)
511
+ return o && o(new Error(u), null), null;
443
512
  }
444
- const c = new XMLHttpRequest(), u = new FormData();
445
- u.append("file", e);
446
- const g = `${l}/upload`;
447
- return c.open("POST", g), d && c.setRequestHeader("Authorization", `Bearer ${d}`), n && c.upload.addEventListener("progress", (f) => {
448
- if (f.lengthComputable) {
449
- const I = f.loaded / f.total * 100;
450
- n(I, f.loaded, f.total);
513
+ const a = new XMLHttpRequest(), g = new FormData();
514
+ g.append("file", e);
515
+ const f = `${l}/upload`;
516
+ return a.open("POST", f), d && a.setRequestHeader("Authorization", `Bearer ${d}`), n && a.upload.addEventListener("progress", (u) => {
517
+ if (u.lengthComputable) {
518
+ const h = u.loaded / u.total * 100;
519
+ n(h, u.loaded, u.total);
451
520
  }
452
- }), c.addEventListener("load", () => {
453
- if (c.status >= 200 && c.status < 300)
521
+ }), a.addEventListener("load", () => {
522
+ if (a.status >= 200 && a.status < 300)
454
523
  try {
455
- const f = JSON.parse(c.responseText);
456
- o && o(null, f);
457
- } catch (f) {
524
+ const u = JSON.parse(a.responseText);
525
+ o && o(null, u);
526
+ } catch (u) {
458
527
  o && o(new Error("Failed to parse response"), null);
459
528
  }
460
529
  else
461
- o && o(new Error(`Upload failed with status ${c.status}`), null);
462
- }), c.addEventListener("error", () => {
530
+ o && o(new Error(`Upload failed with status ${a.status}`), null);
531
+ }), a.addEventListener("error", () => {
463
532
  o && o(new Error("Network error during upload"), null);
464
- }), c.addEventListener("abort", () => {
533
+ }), a.addEventListener("abort", () => {
465
534
  o && o(new Error("Upload aborted"), null);
466
- }), c.send(u), c;
535
+ }), a.send(g), a;
467
536
  }
468
- async function Ve(e) {
469
- const n = b(), { endpoint: o, token: r } = n || {};
537
+ async function rn(e) {
538
+ const n = A(), { endpoint: o, token: r } = n || {};
470
539
  if (!o)
471
- throw new Error(M);
540
+ throw new Error(L);
472
541
  const l = `${o}/delete/${e}`, d = {};
473
542
  r && (d.Authorization = `Bearer ${r}`);
474
- const c = await fetch(l, {
543
+ const a = await fetch(l, {
475
544
  method: "DELETE",
476
545
  headers: d
477
546
  });
478
- if (!c.ok)
479
- throw new Error(`Delete failed with status ${c.status}`);
547
+ if (!a.ok)
548
+ throw new Error(`Delete failed with status ${a.status}`);
480
549
  return { success: !0 };
481
550
  }
482
- function Be(e) {
483
- const n = b(), { endpoint: o } = n || {};
551
+ function an(e) {
552
+ const n = A(), { endpoint: o } = n || {};
484
553
  if (!o)
485
- throw new Error(M);
554
+ throw new Error(L);
486
555
  return `${o}/upload/${e}`;
487
556
  }
488
- async function ce(e, n = "GET", o = null) {
489
- const r = b(), { endpoint: l, token: d } = r || {};
557
+ async function Ie(e, n = "GET", o = null) {
558
+ const r = A(), { endpoint: l, token: d } = r || {};
490
559
  if (!l)
491
- throw new Error(M);
492
- const c = `${l}${e}`, u = {
560
+ throw new Error(L);
561
+ const a = new URL(l), [g, f] = e.split("?");
562
+ a.pathname = a.pathname.replace(/\/$/, "") + g, f && new URLSearchParams(f).forEach((y, C) => {
563
+ a.searchParams.append(C, y);
564
+ });
565
+ const u = a.toString(), h = {
493
566
  "Content-Type": "application/json"
494
567
  };
495
- return d && (u.Authorization = `Bearer ${d}`), fetch(c, {
496
- headers: u,
568
+ return d && (h.Authorization = `Bearer ${d}`), fetch(u, {
569
+ headers: h,
497
570
  method: n,
498
571
  body: o ? JSON.stringify(o) : null
499
572
  });
500
573
  }
501
- function ie(e = {}) {
574
+ function he(e = {}) {
502
575
  return {
503
576
  sessionId: void 0,
504
577
  socket: null,
@@ -516,30 +589,30 @@ function ie(e = {}) {
516
589
  pendingRemoteIceCandidates: []
517
590
  };
518
591
  }
519
- let t = ie();
520
- const Ae = {
592
+ let t = he();
593
+ const Ge = {
521
594
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }]
522
595
  };
523
- function Ye(e) {
596
+ function cn(e) {
524
597
  t.callbacks = { ...t.callbacks, ...e };
525
598
  }
526
- function le() {
599
+ function Ce() {
527
600
  t.peerConnection && (t.peerConnection.close(), t.peerConnection = null), t.localStream && (t.localStream.getTracks().forEach((n) => n.stop()), t.localStream = null), t.remoteStream && (t.remoteStream = null), t.remoteAudio && (t.remoteAudio.srcObject = null, t.remoteAudio.parentNode && t.remoteAudio.parentNode.removeChild(t.remoteAudio), t.remoteAudio = null), t.socket && (t.socket.close(), t.socket = null), P();
528
601
  const e = t.callbacks;
529
- t = ie(e);
602
+ t = he(e);
530
603
  }
531
- function w(e) {
604
+ function T(e) {
532
605
  var n, o;
533
606
  t.callStatus = e, (o = (n = t.callbacks).onCallStatus) == null || o.call(n, e);
534
607
  }
535
- function U(e) {
608
+ function N(e) {
536
609
  var n, o;
537
610
  (o = (n = t.callbacks).onCallError) == null || o.call(n, e);
538
611
  }
539
612
  function P() {
540
613
  t.pingInterval && (clearInterval(t.pingInterval), t.pingInterval = null);
541
614
  }
542
- function Re() {
615
+ function Je() {
543
616
  P(), t.pingInterval = setInterval(() => {
544
617
  if (t.socket && t.socket.readyState === WebSocket.OPEN) {
545
618
  t.pingCount++;
@@ -548,18 +621,18 @@ function Re() {
548
621
  timestamp: Date.now(),
549
622
  count: t.pingCount
550
623
  };
551
- T(e);
624
+ $(e);
552
625
  } else
553
626
  P();
554
627
  }, 1e4);
555
628
  }
556
- function Ue() {
629
+ function We() {
557
630
  t.lastPongTime = Date.now();
558
631
  }
559
- function T(e) {
632
+ function $(e) {
560
633
  t.socket && t.socket.readyState === WebSocket.OPEN && t.socket.send(JSON.stringify(e));
561
634
  }
562
- async function Pe() {
635
+ async function _e() {
563
636
  try {
564
637
  t.localStream = await navigator.mediaDevices.getUserMedia({
565
638
  audio: !0,
@@ -569,11 +642,11 @@ async function Pe() {
569
642
  throw e;
570
643
  }
571
644
  }
572
- function Oe() {
573
- t.peerConnection = new RTCPeerConnection(Ae), t.peerConnection.onicecandidate = (e) => {
645
+ function Ke() {
646
+ t.peerConnection = new RTCPeerConnection(Ge), t.peerConnection.onicecandidate = (e) => {
574
647
  if (e.candidate) {
575
648
  const n = JSON.stringify(e.candidate);
576
- t.peerConnection && t.peerConnection.remoteDescription ? T({
649
+ t.peerConnection && t.peerConnection.remoteDescription ? $({
577
650
  type: "ice",
578
651
  data: {
579
652
  candidate: n
@@ -586,22 +659,22 @@ function Oe() {
586
659
  });
587
660
  }, t.peerConnection.onconnectionstatechange = () => {
588
661
  const e = t.peerConnection.connectionState;
589
- e === "connected" ? w("connected") : (e === "disconnected" || e === "closed") && (w("disconnected"), de());
662
+ e === "connected" ? T("connected") : (e === "disconnected" || e === "closed") && (T("disconnected"), we());
590
663
  }, t.peerConnection.oniceconnectionstatechange = () => {
591
664
  };
592
665
  }
593
- function Ne(e) {
666
+ function Be(e) {
594
667
  return new Promise((n, o) => {
595
668
  if (t.socket && (t.socket.readyState === WebSocket.CONNECTING || t.socket.readyState === WebSocket.OPEN)) {
596
669
  n(t.socket.readyState === WebSocket.OPEN);
597
670
  return;
598
671
  }
599
- const r = b();
672
+ const r = A();
600
673
  if (!r || !r.endpoint) {
601
674
  o(new Error("SDK not initialized. Please initialize SDK first."));
602
675
  return;
603
676
  }
604
- const l = ke(r.endpoint);
677
+ const l = Ae(r.endpoint);
605
678
  if (!l) {
606
679
  o(
607
680
  new Error(
@@ -610,54 +683,54 @@ function Ne(e) {
610
683
  );
611
684
  return;
612
685
  }
613
- const d = O(), c = new URLSearchParams({
686
+ const d = M(), a = new URLSearchParams({
614
687
  externalId: d
615
688
  });
616
- e.sessionId && c.set("sessionId", e.sessionId), r.token && c.set("token", r.token);
617
- const u = `${l}?${c.toString()}`;
618
- t.socket = new WebSocket(u), t.socket.onopen = (g) => {
619
- Re(), n(!0);
620
- }, t.socket.onmessage = (g) => {
621
- const f = JSON.parse(g.data);
622
- Me(f);
623
- }, t.socket.onerror = (g) => {
624
- w("error"), U(g.message || "Unable to connect voice"), o(g);
625
- }, t.socket.onclose = (g) => {
689
+ e.sessionId && a.set("sessionId", e.sessionId), r.token && a.set("token", r.token);
690
+ const g = `${l}?${a.toString()}`;
691
+ t.socket = new WebSocket(g), t.socket.onopen = (f) => {
692
+ Je(), n(!0);
693
+ }, t.socket.onmessage = (f) => {
694
+ const u = JSON.parse(f.data);
695
+ He(u);
696
+ }, t.socket.onerror = (f) => {
697
+ T("error"), N(f.message || "Unable to connect voice"), o(f);
698
+ }, t.socket.onclose = (f) => {
626
699
  P();
627
700
  };
628
701
  });
629
702
  }
630
- function Me(e) {
703
+ function He(e) {
631
704
  switch (e.type) {
632
705
  case "pong":
633
- Ue();
706
+ We();
634
707
  break;
635
708
  case "answer":
636
- qe(e.data);
709
+ Ye(e.data);
637
710
  break;
638
711
  case "connected":
639
- xe(e.data);
712
+ Ve(e.data);
640
713
  break;
641
714
  case "ice":
642
- Le(e.data);
715
+ Qe(e.data);
643
716
  break;
644
717
  case "renegotiationOffer":
645
- ze(e.data);
718
+ Xe(e.data);
646
719
  break;
647
720
  case "end":
648
- de();
721
+ we();
649
722
  break;
650
723
  case "error":
651
- w("error"), U(e.error || "Unable to connect voice");
724
+ T("error"), N(e.error || "Unable to connect voice");
652
725
  break;
653
726
  default:
654
727
  break;
655
728
  }
656
729
  }
657
- function xe(e) {
658
- t.sessionId = e.sessionId, be(e.sessionId);
730
+ function Ve(e) {
731
+ t.sessionId = e.sessionId, Me(e.sessionId);
659
732
  }
660
- async function qe(e) {
733
+ async function Ye(e) {
661
734
  try {
662
735
  if (t.peerConnection) {
663
736
  const n = new RTCSessionDescription({
@@ -666,7 +739,7 @@ async function qe(e) {
666
739
  });
667
740
  await t.peerConnection.setRemoteDescription(n);
668
741
  for (const o of t.localIceCandidates)
669
- T({
742
+ $({
670
743
  type: "ice",
671
744
  data: {
672
745
  candidate: o
@@ -684,7 +757,7 @@ async function qe(e) {
684
757
  } catch (n) {
685
758
  }
686
759
  }
687
- async function Le(e) {
760
+ async function Qe(e) {
688
761
  try {
689
762
  if (t.peerConnection) {
690
763
  if (!t.peerConnection.remoteDescription) {
@@ -697,7 +770,7 @@ async function Le(e) {
697
770
  } catch (n) {
698
771
  }
699
772
  }
700
- async function ze(e) {
773
+ async function Xe(e) {
701
774
  try {
702
775
  if (t.peerConnection) {
703
776
  const n = new RTCSessionDescription({
@@ -706,7 +779,7 @@ async function ze(e) {
706
779
  });
707
780
  await t.peerConnection.setRemoteDescription(n);
708
781
  const o = await t.peerConnection.createAnswer();
709
- await t.peerConnection.setLocalDescription(o), T({
782
+ await t.peerConnection.setLocalDescription(o), $({
710
783
  type: "renegotiationAnswer",
711
784
  data: {
712
785
  sdp: o.sdp
@@ -716,30 +789,30 @@ async function ze(e) {
716
789
  } catch (n) {
717
790
  }
718
791
  }
719
- async function Qe(e = {}) {
792
+ async function ln(e = {}) {
720
793
  try {
721
794
  if (t.callStatus === "connecting" || t.callStatus === "connected")
722
795
  return;
723
- w("connecting"), U(null), t.sessionId = e.sessionId, await Pe(), Oe(), t.localStream.getTracks().forEach((o) => {
796
+ T("connecting"), N(null), t.sessionId = e.sessionId, await _e(), Ke(), t.localStream.getTracks().forEach((o) => {
724
797
  t.peerConnection.addTrack(o, t.localStream);
725
- }), await Ne(e);
798
+ }), await Be(e);
726
799
  const n = await t.peerConnection.createOffer();
727
- await t.peerConnection.setLocalDescription(n), T({
800
+ await t.peerConnection.setLocalDescription(n), $({
728
801
  type: "offer",
729
802
  data: {
730
803
  sdp: n.sdp
731
804
  }
732
805
  });
733
806
  } catch (n) {
734
- w("error"), U(n.message || "Unable to connect voice"), le();
807
+ T("error"), N(n.message || "Unable to connect voice"), Ce();
735
808
  }
736
809
  }
737
- function de() {
738
- T({
810
+ function we() {
811
+ $({
739
812
  type: "end"
740
- }), t.socket && (t.socket.close(), t.socket = null), w("disconnected"), t.peerConnection && (t.peerConnection.close(), t.peerConnection = null), t.localStream && (t.localStream.getTracks().forEach((e) => e.stop()), t.localStream = null), le();
813
+ }), t.socket && (t.socket.close(), t.socket = null), T("disconnected"), t.peerConnection && (t.peerConnection.close(), t.peerConnection = null), t.localStream && (t.localStream.getTracks().forEach((e) => e.stop()), t.localStream = null), Ce();
741
814
  }
742
- function Xe() {
815
+ function dn() {
743
816
  if (t.localStream) {
744
817
  const e = t.localStream.getAudioTracks()[0];
745
818
  if (e)
@@ -747,10 +820,10 @@ function Xe() {
747
820
  }
748
821
  return !1;
749
822
  }
750
- function Ze() {
823
+ function un() {
751
824
  return t.localStream;
752
825
  }
753
- function je() {
826
+ function gn() {
754
827
  return new Promise((e, n) => {
755
828
  if (!t.peerConnection) {
756
829
  n(new Error("no peer connection"));
@@ -765,7 +838,7 @@ function je() {
765
838
  });
766
839
  });
767
840
  }
768
- function en() {
841
+ function fn() {
769
842
  return new Promise((e, n) => {
770
843
  if (!t.peerConnection) {
771
844
  n(new Error("no peer connection"));
@@ -781,24 +854,24 @@ function en() {
781
854
  });
782
855
  }
783
856
  export {
784
- y as MESSAGE_ROLES,
785
- $e as authenticate,
786
- Ve as deleteAttachment,
787
- _e as disconnect,
788
- de as disconnectCall,
789
- Be as getAttachment,
790
- Ke as getHistory,
791
- je as getInboundAudioEnergy,
792
- Ze as getLocalStream,
793
- en as getOutboundAudioEnergy,
794
- De as getSession,
795
- Je as initialize,
796
- Te as sendMessage,
797
- Ye as setCallCallbacks,
798
- Ge as setCallbacks,
799
- Qe as startCall,
800
- We as startChat,
801
- Xe as toggleMute,
802
- He as uploadAttachment
857
+ w as MESSAGE_ROLES,
858
+ qe as authenticate,
859
+ rn as deleteAttachment,
860
+ tn as disconnect,
861
+ we as disconnectCall,
862
+ an as getAttachment,
863
+ on as getHistory,
864
+ gn as getInboundAudioEnergy,
865
+ un as getLocalStream,
866
+ fn as getOutboundAudioEnergy,
867
+ ze as getSession,
868
+ en as initialize,
869
+ xe as sendMessage,
870
+ cn as setCallCallbacks,
871
+ je as setCallbacks,
872
+ ln as startCall,
873
+ nn as startChat,
874
+ dn as toggleMute,
875
+ sn as uploadAttachment
803
876
  };
804
877
  //# sourceMappingURL=origon-chat-sdk.js.map