@origonai/web-chat-sdk 0.2.0 → 0.2.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.
@@ -1,50 +1,50 @@
1
- import { fetchEventSource as ne } from "@microsoft/fetch-event-source";
2
- function W() {
1
+ import { fetchEventSource as se } from "@microsoft/fetch-event-source";
2
+ function K() {
3
3
  const e = Date.now(), t = new Uint8Array(16);
4
4
  crypto.getRandomValues(t), t[0] = e >> 40 & 255, t[1] = e >> 32 & 255, t[2] = e >> 24 & 255, t[3] = e >> 16 & 255, t[4] = e >> 8 & 255, t[5] = e & 255, t[6] = t[6] & 15 | 112, t[8] = t[8] & 63 | 128;
5
- const o = [...t].map((a) => a.toString(16).padStart(2, "0")).join("");
6
- return `${o.slice(0, 8)}-${o.slice(8, 12)}-${o.slice(12, 16)}-${o.slice(
5
+ const s = [...t].map((a) => a.toString(16).padStart(2, "0")).join("");
6
+ return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(
7
7
  16,
8
8
  20
9
- )}-${o.slice(20)}`;
9
+ )}-${s.slice(20)}`;
10
10
  }
11
- function te() {
11
+ function re() {
12
12
  if (localStorage.getItem("chatDeviceId"))
13
13
  return localStorage.getItem("chatDeviceId");
14
- const e = W();
14
+ const e = K();
15
15
  return localStorage.setItem("chatDeviceId", e), e;
16
16
  }
17
- async function oe(e) {
17
+ async function ae(e) {
18
18
  return new Promise((t) => setTimeout(t, e));
19
19
  }
20
- function se(e) {
20
+ function ce(e) {
21
21
  let t;
22
22
  try {
23
- const o = new URL(e);
24
- t = `https://${o.hostname}${o.pathname}/sse`;
25
- } catch (o) {
23
+ const s = new URL(e);
24
+ t = `https://${s.hostname}${s.pathname}/sse`;
25
+ } catch (s) {
26
26
  }
27
27
  return t;
28
28
  }
29
- function re(e) {
29
+ function ie(e) {
30
30
  let t;
31
31
  try {
32
- const o = new URL(e);
33
- t = `wss://${o.hostname}${o.pathname}/wss`;
34
- } catch (o) {
32
+ const s = new URL(e);
33
+ t = `wss://${s.hostname}${s.pathname}/wss`;
34
+ } catch (s) {
35
35
  }
36
36
  return t;
37
37
  }
38
- function ae(e) {
38
+ function le(e) {
39
39
  let t;
40
40
  try {
41
- const o = new URL(e);
42
- t = `wss://${o.hostname}${o.pathname}/audio`;
43
- } catch (o) {
41
+ const s = new URL(e);
42
+ t = `wss://${s.hostname}${s.pathname}/audio`;
43
+ } catch (s) {
44
44
  }
45
45
  return t;
46
46
  }
47
- const T = {
47
+ const w = {
48
48
  ASSISTANT: "assistant",
49
49
  // this can be automated or LLM AI Agent response
50
50
  USER: "user",
@@ -58,13 +58,13 @@ const T = {
58
58
  BOT: "assistant",
59
59
  /** @deprecated Use SUPERVISOR instead */
60
60
  AGENT: "supervisor"
61
- }, J = 1e4, ce = 5e3, b = {
61
+ }, V = 1e4, de = 5e3, T = {
62
62
  MESSAGE: "message",
63
63
  TYPING: "typing",
64
64
  TYPING_STOP: "typingOff",
65
65
  END: "end"
66
66
  };
67
- function ie() {
67
+ function ue() {
68
68
  return {
69
69
  socket: null,
70
70
  previouslyConnected: !1,
@@ -74,112 +74,112 @@ function ie() {
74
74
  socketConnectionTimeout: null
75
75
  };
76
76
  }
77
- let r = ie();
78
- function N() {
77
+ let r = ue();
78
+ function O() {
79
79
  r.pingInterval && (clearInterval(r.pingInterval), r.pingInterval = null);
80
80
  }
81
- function le() {
82
- N(), r.pingInterval = setInterval(() => {
83
- r.socket && r.socket.readyState === WebSocket.OPEN ? O({ type: "ping" }) : N();
84
- }, J);
81
+ function ge() {
82
+ O(), r.pingInterval = setInterval(() => {
83
+ r.socket && r.socket.readyState === WebSocket.OPEN ? U({ type: "ping" }) : O();
84
+ }, V);
85
85
  }
86
- function _() {
87
- N(), r.socketDisconnectedTimeout && (clearTimeout(r.socketDisconnectedTimeout), r.socketDisconnectedTimeout = null), r.socketConnectionTimeout && (clearTimeout(r.socketConnectionTimeout), r.socketConnectionTimeout = null);
86
+ function H() {
87
+ O(), r.socketDisconnectedTimeout && (clearTimeout(r.socketDisconnectedTimeout), r.socketDisconnectedTimeout = null), r.socketConnectionTimeout && (clearTimeout(r.socketConnectionTimeout), r.socketConnectionTimeout = null);
88
88
  }
89
- function K() {
90
- r.socketDisconnected = !1, $("socket");
89
+ function Y() {
90
+ r.socketDisconnected = !1, P("socket");
91
91
  }
92
- function H() {
93
- r.socketDisconnected = !0, $("sse");
92
+ function B() {
93
+ r.socketDisconnected = !0, P("sse");
94
94
  }
95
- function de(e) {
96
- return new Promise((t, o) => {
95
+ function fe(e) {
96
+ return new Promise((t, s) => {
97
97
  if (r.socket && (r.socket.readyState === WebSocket.CONNECTING || r.socket.readyState === WebSocket.OPEN)) {
98
98
  t(r.socket.readyState === WebSocket.OPEN);
99
99
  return;
100
100
  }
101
- const a = U();
101
+ const a = N();
102
102
  if (!a || !a.endpoint) {
103
- o(new Error("SDK not initialized. Please initialize SDK first."));
103
+ s(new Error("SDK not initialized. Please initialize SDK first."));
104
104
  return;
105
105
  }
106
- const d = re(a.endpoint);
106
+ const d = ie(a.endpoint);
107
107
  if (!d) {
108
- o(
108
+ s(
109
109
  new Error(
110
110
  "Invalid endpoint while initializing SDK. Please check the endpoint and try again."
111
111
  )
112
112
  );
113
113
  return;
114
114
  }
115
- const u = D(), c = new URLSearchParams({
115
+ const u = D(), i = new URLSearchParams({
116
116
  externalId: u
117
117
  });
118
- e.sessionId && c.set("sessionId", e.sessionId), e.requestId && c.set("requestId", e.requestId), a.token && c.set("token", a.token);
119
- const p = `${d}?${c.toString()}`;
120
- r.socket = new WebSocket(p), r.socket.onopen = () => {
121
- r.previouslyConnected = !0, K(), O({ type: "ping" }), clearTimeout(r.socketConnectionTimeout), le(), t(!0);
118
+ e.sessionId && i.set("sessionId", e.sessionId), e.requestId && i.set("requestId", e.requestId), a.token && i.set("token", a.token);
119
+ const f = `${d}?${i.toString()}`;
120
+ r.socket = new WebSocket(f), r.socket.onopen = () => {
121
+ r.previouslyConnected = !0, Y(), U({ type: "ping" }), clearTimeout(r.socketConnectionTimeout), ge(), t(!0);
122
122
  }, r.socket.onmessage = (l) => {
123
- const f = JSON.parse(l.data);
124
- ue(f);
123
+ const p = JSON.parse(l.data);
124
+ pe(p);
125
125
  }, r.socket.onerror = (l) => {
126
- $("sse"), o(l);
126
+ P("sse"), s(l);
127
127
  }, r.socket.onclose = (l) => {
128
- l.target === r.socket && (l.code === 1006 && (r.previouslyConnected ? H() : h({
128
+ l.target === r.socket && (l.code === 1006 && (r.previouslyConnected ? B() : k({
129
129
  errorText: "Unable to establish connection",
130
130
  done: !0,
131
131
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
132
- }), clearTimeout(r.socketConnectionTimeout)), r.socket = null, _());
132
+ }), clearTimeout(r.socketConnectionTimeout)), r.socket = null, H());
133
133
  }, r.previouslyConnected || (r.socketConnectionTimeout = setTimeout(() => {
134
- h({
134
+ k({
135
135
  errorText: "Unable to establish connection",
136
136
  done: !0,
137
137
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
138
- }), o(new Error("Socket connection timed out"));
139
- }, ce));
138
+ }), s(new Error("Socket connection timed out"));
139
+ }, de));
140
140
  });
141
141
  }
142
- function O(e) {
143
- r.socketDisconnected || !r.socket || r.socket.send(JSON.stringify({ ...e, eventId: e.eventId || W() }));
142
+ function U(e) {
143
+ r.socketDisconnected || !r.socket || r.socket.send(JSON.stringify({ ...e, eventId: e.eventId || K() }));
144
144
  }
145
- function ue(e) {
145
+ function pe(e) {
146
146
  switch (e.type) {
147
147
  case "pong": {
148
- r.socketDisconnected && K(), r.socketDisconnectedTimeout && clearTimeout(r.socketDisconnectedTimeout), r.socketDisconnectedTimeout = setTimeout(() => {
149
- H();
150
- }, J + 1e3);
148
+ r.socketDisconnected && Y(), r.socketDisconnectedTimeout && clearTimeout(r.socketDisconnectedTimeout), r.socketDisconnectedTimeout = setTimeout(() => {
149
+ B();
150
+ }, V + 1e3);
151
151
  break;
152
152
  }
153
- case b.TYPING: {
154
- F(!0);
153
+ case T.TYPING: {
154
+ _(!0);
155
155
  break;
156
156
  }
157
- case b.TYPING_STOP: {
158
- F(!1);
157
+ case T.TYPING_STOP: {
158
+ _(!1);
159
159
  break;
160
160
  }
161
- case b.MESSAGE: {
162
- const { eventId: t, data: o } = e;
163
- t || h({
164
- ...o,
161
+ case T.MESSAGE: {
162
+ const { eventId: t, data: s } = e;
163
+ t || k({
164
+ ...s,
165
165
  done: !0,
166
166
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
167
167
  });
168
168
  break;
169
169
  }
170
- case b.END: {
171
- V();
170
+ case T.END: {
171
+ Q();
172
172
  break;
173
173
  }
174
174
  }
175
175
  }
176
- function V() {
177
- r.socket && r.socket.close(1e3), r.previouslyConnected = !1, _(), r.socket = null, $("sse");
176
+ function Q() {
177
+ r.socket && r.socket.close(1e3), r.previouslyConnected = !1, H(), r.socket = null, P("sse");
178
178
  }
179
- function ge() {
179
+ function me() {
180
180
  return r.socket !== null && r.socket.readyState === WebSocket.OPEN && !r.socketDisconnected;
181
181
  }
182
- function Y(e = {}) {
182
+ function Z(e = {}) {
183
183
  return {
184
184
  credentials: void 0,
185
185
  authenticated: !1,
@@ -191,154 +191,169 @@ function Y(e = {}) {
191
191
  lastStreamId: void 0,
192
192
  messages: [],
193
193
  callbacks: e,
194
- transport: "sse"
194
+ transport: "sse",
195
+ control: "agent"
195
196
  };
196
197
  }
197
- let s = Y();
198
- function $e(e) {
199
- s.callbacks = { ...s.callbacks, ...e };
198
+ let o = Z();
199
+ function Oe(e) {
200
+ o.callbacks = { ...o.callbacks, ...e };
200
201
  }
201
- function Pe(e) {
202
- s.credentials = e, e.token && (s.authenticated = !0);
202
+ function Ue(e) {
203
+ o.credentials = e, e.token && (o.authenticated = !0);
203
204
  }
204
- function U() {
205
- return s.credentials;
205
+ function N() {
206
+ return o.credentials;
206
207
  }
207
- function pe(e) {
208
- var t, o;
209
- e && e !== s.sessionId && (s.sessionId = e, (o = (t = s.callbacks).onSessionUpdate) == null || o.call(t, e));
208
+ function Se(e) {
209
+ var t, s;
210
+ e && e !== o.sessionId && (o.sessionId = e, (s = (t = o.callbacks).onSessionUpdate) == null || s.call(t, e));
210
211
  }
211
- async function Re(e = {}) {
212
+ async function Ne(e = {}) {
212
213
  try {
213
214
  let t = null;
214
- s.authenticated ? t = s.configData : (t = await Se(s.credentials), s.authenticated = !0, s.configData = t);
215
- let o = [];
216
- e.sessionId && (o = await ke(e.sessionId));
215
+ o.authenticated ? t = o.configData : (t = await Ce(o.credentials), o.authenticated = !0, o.configData = t);
216
+ let s = [];
217
+ e.sessionId && (s = await he(e.sessionId));
217
218
  const a = new URLSearchParams();
218
- return s.credentials.token || a.set("externalId", D()), s.sseUrl = `${se(
219
- s.credentials.endpoint
220
- )}?${a.toString()}`, s.sessionId = e.sessionId, s.messages = o, {
221
- sessionId: s.sessionId,
222
- messages: o,
219
+ return o.credentials.token || a.set("externalId", D()), o.sseUrl = `${ce(
220
+ o.credentials.endpoint
221
+ )}?${a.toString()}`, o.sessionId = e.sessionId, o.messages = s, {
222
+ sessionId: o.sessionId,
223
+ messages: s,
223
224
  configData: t
224
225
  };
225
226
  } catch (t) {
226
- throw B(), t;
227
+ throw j(), t;
227
228
  }
228
229
  }
229
- function Ne() {
230
- B();
230
+ function Me() {
231
+ j();
231
232
  }
232
- function B() {
233
- s.abortController && s.abortController.abort(), V();
234
- const { callbacks: e, credentials: t } = s;
235
- s = Y(e), s.credentials = t;
233
+ function j() {
234
+ o.abortController && o.abortController.abort(), Q();
235
+ const { callbacks: e, credentials: t } = o;
236
+ o = Z(e), o.credentials = t;
236
237
  }
237
238
  function D() {
238
239
  var e;
239
- return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : te();
240
+ return (e = o.credentials) != null && e.externalId ? o.credentials.externalId : re();
240
241
  }
241
- function h(e) {
242
- var t, o;
243
- s.messages = [...s.messages, e], (o = (t = s.callbacks).onMessageAdd) == null || o.call(t, e);
242
+ function k(e) {
243
+ var t, s;
244
+ o.messages = [...o.messages, e], (s = (t = o.callbacks).onMessageAdd) == null || s.call(t, e);
244
245
  }
245
- function F(e) {
246
- var t, o;
247
- (o = (t = s.callbacks).onTyping) == null || o.call(t, e);
246
+ function _(e) {
247
+ var t, s;
248
+ (s = (t = o.callbacks).onTyping) == null || s.call(t, e);
248
249
  }
249
- function $(e) {
250
- var t, o;
251
- s.transport = e, (o = (t = s.callbacks).onTransportUpdate) == null || o.call(t, e);
250
+ function P(e) {
251
+ var t, s;
252
+ o.transport = e, (s = (t = o.callbacks).onTransportUpdate) == null || s.call(t, e);
252
253
  }
253
- function Oe({ text: e, html: t, context: o }) {
254
+ function xe({ text: e, html: t, context: s }) {
254
255
  return new Promise((a, d) => {
255
256
  (async () => {
256
- var u, c, p;
257
+ var u, i, f;
257
258
  try {
258
259
  const l = {
259
- role: T.USER,
260
+ role: w.USER,
260
261
  text: e,
261
262
  html: t,
262
263
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
263
264
  };
264
- if (h(l), await oe(200), s.transport === "socket" && ge()) {
265
- O({
265
+ if (k(l), await ae(200), o.transport === "socket" && me()) {
266
+ U({
266
267
  type: "message",
267
268
  data: {
268
269
  text: e,
269
270
  html: t
270
271
  }
271
- }), a(s.sessionId);
272
+ }), a(o.sessionId);
272
273
  return;
273
274
  }
274
- const f = {
275
- role: T.ASSISTANT,
276
- text: "",
277
- loading: !0
278
- };
279
- h(f);
280
- const m = new URL(s.sseUrl);
281
- s.sessionId && m.searchParams.set("sessionId", s.sessionId), s.requestId && m.searchParams.set("requestId", s.requestId), s.lastStreamId = void 0, s.abortController = new AbortController();
282
- const y = {
275
+ if (o.control === "agent") {
276
+ const g = {
277
+ role: w.ASSISTANT,
278
+ text: "",
279
+ loading: !0
280
+ };
281
+ k(g);
282
+ }
283
+ const p = new URL(o.sseUrl);
284
+ o.sessionId && p.searchParams.set("sessionId", o.sessionId), o.requestId && p.searchParams.set("requestId", o.requestId), o.lastStreamId = void 0, o.abortController = new AbortController();
285
+ const C = {
283
286
  "Content-Type": "application/json"
284
287
  };
285
- (u = s.credentials) != null && u.token && (y.Authorization = `Bearer ${s.credentials.token}`), await ne(m.toString(), {
288
+ (u = o.credentials) != null && u.token && (C.Authorization = `Bearer ${o.credentials.token}`), await se(p.toString(), {
286
289
  method: "POST",
287
- headers: y,
290
+ headers: C,
288
291
  body: JSON.stringify({
289
292
  message: e,
290
293
  html: t,
291
- context: o
294
+ context: s
292
295
  }),
293
- signal: s.abortController.signal,
296
+ signal: o.abortController.signal,
294
297
  openWhenHidden: !0,
295
298
  onopen: async (g) => {
296
299
  if (!g.ok)
297
300
  throw new Error("Failed to send message");
298
301
  },
299
302
  onmessage: (g) => {
300
- var E, M, x, q, L, G, z;
301
- const i = JSON.parse(g.data);
303
+ var E, b, M, x, q, L, G, z, F, W, J;
304
+ const c = JSON.parse(g.data);
302
305
  if (g.event === "connected")
303
- s.sessionId = i.sessionId, s.requestId = i.requestId;
306
+ o.sessionId = c.sessionId, o.requestId = c.requestId;
304
307
  else if (g.event === "upgrade_to_websocket")
305
- de({
306
- sessionId: s.sessionId,
307
- requestId: i.requestId
308
+ fe({
309
+ sessionId: o.sessionId,
310
+ requestId: c.requestId
308
311
  });
309
- else if (i.error) {
310
- const I = i.error && typeof i.error == "string" ? i.error : "Failed to connect to the system", S = s.messages.length - 1, C = {
311
- ...s.messages[S],
312
+ else if (c.control)
313
+ o.control = c.control, (b = (E = o.callbacks).onControlUpdate) == null || b.call(E, c.control);
314
+ else if (c.error) {
315
+ const h = c.error && typeof c.error == "string" ? c.error : "Failed to connect to the system", S = o.messages.length - 1, m = {
316
+ ...o.messages[S],
312
317
  loading: !1,
313
- errorText: I
318
+ errorText: h
314
319
  };
315
- s.messages = s.messages.map(
316
- (R, ee) => ee === S ? C : R
317
- ), (M = (E = s.callbacks).onMessageUpdate) == null || M.call(E, S, C), d(new Error(I));
318
- } else if (i.message !== void 0) {
319
- if (i.streamId !== void 0) {
320
- if (s.lastStreamId === void 0)
321
- s.lastStreamId = i.streamId;
322
- else if (i.streamId !== s.lastStreamId) {
323
- s.lastStreamId = i.streamId;
324
- const C = {
325
- role: T.ASSISTANT,
320
+ o.messages = o.messages.map(
321
+ ($, oe) => oe === S ? m : $
322
+ ), (x = (M = o.callbacks).onMessageUpdate) == null || x.call(M, S, m), d(new Error(h));
323
+ } else if (c.message !== void 0) {
324
+ if (c.role === w.SUPERVISOR) {
325
+ const m = {
326
+ role: w.SUPERVISOR,
327
+ text: c.message,
328
+ sources: c.sources,
329
+ done: !0
330
+ };
331
+ k(m), a(o.sessionId), o.sessionId = (q = c.session_id) != null ? q : o.sessionId, o.requestId = (L = c.requestId) != null ? L : o.requestId;
332
+ return;
333
+ }
334
+ if (c.streamId !== void 0) {
335
+ if (o.lastStreamId === void 0)
336
+ o.lastStreamId = c.streamId;
337
+ else if (c.streamId !== o.lastStreamId) {
338
+ o.lastStreamId = c.streamId;
339
+ const m = {
340
+ role: w.ASSISTANT,
326
341
  text: "",
327
342
  loading: !0
328
343
  };
329
- h(C);
344
+ k(m);
330
345
  }
331
346
  }
332
- const I = s.messages.length - 1, S = s.messages[I], P = {
347
+ const h = o.messages.length - 1, S = o.messages[h], R = {
333
348
  ...S,
334
349
  loading: !1,
335
- text: (S.text || "") + i.message,
336
- sources: i.sources,
337
- done: (x = i.done) != null ? x : S.done
350
+ text: (S.text || "") + c.message,
351
+ sources: c.sources,
352
+ done: (G = c.done) != null ? G : S.done
338
353
  };
339
- s.messages = s.messages.map(
340
- (C, R) => R === I ? P : C
341
- ), (L = (q = s.callbacks).onMessageUpdate) == null || L.call(q, I, P), i.done && a(s.sessionId), s.sessionId = (G = i.session_id) != null ? G : s.sessionId, s.requestId = (z = i.requestId) != null ? z : s.requestId;
354
+ o.messages = o.messages.map(
355
+ (m, $) => $ === h ? R : m
356
+ ), (F = (z = o.callbacks).onMessageUpdate) == null || F.call(z, h, R), c.done && a(o.sessionId), o.sessionId = (W = c.session_id) != null ? W : o.sessionId, o.requestId = (J = c.requestId) != null ? J : o.requestId;
342
357
  }
343
358
  },
344
359
  onerror: (g) => {
@@ -347,73 +362,73 @@ function Oe({ text: e, html: t, context: o }) {
347
362
  openWhenHidden: !0
348
363
  });
349
364
  } catch (l) {
350
- const f = "Failed to connect to the system", m = s.messages.length - 1, y = s.messages[m], g = {
351
- ...y,
365
+ const p = "Failed to connect to the system", C = o.messages.length - 1, g = o.messages[C], c = {
366
+ ...g,
352
367
  loading: !1,
353
- errorText: y.done ? void 0 : l.message || f,
368
+ errorText: g.done ? void 0 : l.message || p,
354
369
  done: !0
355
370
  };
356
- s.messages = s.messages.map(
357
- (i, E) => E === m ? g : i
358
- ), (p = (c = s.callbacks).onMessageUpdate) == null || p.call(c, m, g), d(l);
371
+ o.messages = o.messages.map(
372
+ (E, b) => b === C ? c : E
373
+ ), (f = (i = o.callbacks).onMessageUpdate) == null || f.call(i, C, c), d(l);
359
374
  }
360
375
  })();
361
376
  });
362
377
  }
363
- const fe = "Something went wrong initializing the chat", me = "Chat SDK not initialized";
364
- async function Se(e) {
365
- const { endpoint: t } = e, o = `${t}/config`, a = await fetch(o, {
378
+ const ke = "Something went wrong initializing the chat", Ie = "Chat SDK not initialized";
379
+ async function Ce(e) {
380
+ const { endpoint: t } = e, s = `${t}/config`, a = await fetch(s, {
366
381
  method: "GET",
367
382
  headers: {
368
383
  "Content-Type": "application/json"
369
384
  }
370
385
  });
371
386
  if (!a.ok) {
372
- const c = await a.json();
373
- throw new Error((c == null ? void 0 : c.error) || fe);
387
+ const i = await a.json();
388
+ throw new Error((i == null ? void 0 : i.error) || ke);
374
389
  }
375
390
  return (await a.json()).data;
376
391
  }
377
- async function Ue() {
392
+ async function qe() {
378
393
  const e = new URLSearchParams({
379
394
  externalId: D()
380
- }), t = await Q(`/sessions?${e.toString()}`, "GET");
395
+ }), t = await X(`/sessions?${e.toString()}`, "GET");
381
396
  if (!t.ok)
382
397
  throw new Error("Unable to load history, please try again later");
383
398
  return t.json();
384
399
  }
385
- async function ke(e) {
400
+ async function he(e) {
386
401
  var u;
387
402
  const t = new URLSearchParams({
388
403
  sessionId: e
389
- }), o = await Q(`/session?${t.toString()}`, "GET");
390
- if (!o.ok)
404
+ }), s = await X(`/session?${t.toString()}`, "GET");
405
+ if (!s.ok)
391
406
  throw new Error("Unable to load messages, please try again later");
392
- const a = await o.json();
393
- return ((u = a == null ? void 0 : a.sessionHistory) != null ? u : []).map((c) => ({
394
- id: c.id,
395
- text: c.text,
396
- role: c.youtubeVideo ? T.ASSISTANT : c.role,
397
- timestamp: c.timestamp,
398
- video: c.youtubeVideo,
399
- channel: c.channel,
407
+ const a = await s.json();
408
+ return ((u = a == null ? void 0 : a.sessionHistory) != null ? u : []).map((i) => ({
409
+ id: i.id,
410
+ text: i.text,
411
+ role: i.youtubeVideo ? w.ASSISTANT : i.role,
412
+ timestamp: i.timestamp,
413
+ video: i.youtubeVideo,
414
+ channel: i.channel,
400
415
  done: !0
401
416
  }));
402
417
  }
403
- async function Q(e, t = "GET", o = null) {
404
- const a = U(), { endpoint: d, token: u } = a || {};
418
+ async function X(e, t = "GET", s = null) {
419
+ const a = N(), { endpoint: d, token: u } = a || {};
405
420
  if (!d)
406
- throw new Error(me);
407
- const c = `${d}${e}`, p = {
421
+ throw new Error(Ie);
422
+ const i = `${d}${e}`, f = {
408
423
  "Content-Type": "application/json"
409
424
  };
410
- return u && (p.Authorization = `Bearer ${u}`), fetch(c, {
411
- headers: p,
425
+ return u && (f.Authorization = `Bearer ${u}`), fetch(i, {
426
+ headers: f,
412
427
  method: t,
413
- body: o ? JSON.stringify(o) : null
428
+ body: s ? JSON.stringify(s) : null
414
429
  });
415
430
  }
416
- function Z(e = {}) {
431
+ function ee(e = {}) {
417
432
  return {
418
433
  sessionId: void 0,
419
434
  socket: null,
@@ -431,30 +446,30 @@ function Z(e = {}) {
431
446
  pendingRemoteIceCandidates: []
432
447
  };
433
448
  }
434
- let n = Z();
435
- const Ie = {
449
+ let n = ee();
450
+ const we = {
436
451
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }]
437
452
  };
438
- function Me(e) {
453
+ function Le(e) {
439
454
  n.callbacks = { ...n.callbacks, ...e };
440
455
  }
441
- function j() {
456
+ function ne() {
442
457
  n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((t) => t.stop()), n.localStream = null), n.remoteStream && (n.remoteStream = null), n.remoteAudio && (n.remoteAudio.srcObject = null, n.remoteAudio.parentNode && n.remoteAudio.parentNode.removeChild(n.remoteAudio), n.remoteAudio = null), n.socket && (n.socket.close(), n.socket = null), A();
443
458
  const e = n.callbacks;
444
- n = Z(e);
459
+ n = ee(e);
445
460
  }
446
- function k(e) {
447
- var t, o;
448
- n.callStatus = e, (o = (t = n.callbacks).onCallStatus) == null || o.call(t, e);
461
+ function I(e) {
462
+ var t, s;
463
+ n.callStatus = e, (s = (t = n.callbacks).onCallStatus) == null || s.call(t, e);
449
464
  }
450
465
  function v(e) {
451
- var t, o;
452
- (o = (t = n.callbacks).onCallError) == null || o.call(t, e);
466
+ var t, s;
467
+ (s = (t = n.callbacks).onCallError) == null || s.call(t, e);
453
468
  }
454
469
  function A() {
455
470
  n.pingInterval && (clearInterval(n.pingInterval), n.pingInterval = null);
456
471
  }
457
- function Ce() {
472
+ function ye() {
458
473
  A(), n.pingInterval = setInterval(() => {
459
474
  if (n.socket && n.socket.readyState === WebSocket.OPEN) {
460
475
  n.pingCount++;
@@ -463,18 +478,18 @@ function Ce() {
463
478
  timestamp: Date.now(),
464
479
  count: n.pingCount
465
480
  };
466
- w(e);
481
+ y(e);
467
482
  } else
468
483
  A();
469
484
  }, 1e4);
470
485
  }
471
- function he() {
486
+ function Ee() {
472
487
  n.lastPongTime = Date.now();
473
488
  }
474
- function w(e) {
489
+ function y(e) {
475
490
  n.socket && n.socket.readyState === WebSocket.OPEN && n.socket.send(JSON.stringify(e));
476
491
  }
477
- async function we() {
492
+ async function be() {
478
493
  try {
479
494
  n.localStream = await navigator.mediaDevices.getUserMedia({
480
495
  audio: !0,
@@ -484,11 +499,11 @@ async function we() {
484
499
  throw e;
485
500
  }
486
501
  }
487
- function ye() {
488
- n.peerConnection = new RTCPeerConnection(Ie), n.peerConnection.onicecandidate = (e) => {
502
+ function Te() {
503
+ n.peerConnection = new RTCPeerConnection(we), n.peerConnection.onicecandidate = (e) => {
489
504
  if (e.candidate) {
490
505
  const t = JSON.stringify(e.candidate);
491
- n.peerConnection && n.peerConnection.remoteDescription ? w({
506
+ n.peerConnection && n.peerConnection.remoteDescription ? y({
492
507
  type: "ice",
493
508
  data: {
494
509
  candidate: t
@@ -501,90 +516,90 @@ function ye() {
501
516
  });
502
517
  }, n.peerConnection.onconnectionstatechange = () => {
503
518
  const e = n.peerConnection.connectionState;
504
- e === "connected" ? k("connected") : (e === "disconnected" || e === "closed") && (k("disconnected"), X());
519
+ e === "connected" ? I("connected") : (e === "disconnected" || e === "closed") && (I("disconnected"), te());
505
520
  }, n.peerConnection.oniceconnectionstatechange = () => {
506
521
  };
507
522
  }
508
- function Ee(e) {
509
- return new Promise((t, o) => {
523
+ function ve(e) {
524
+ return new Promise((t, s) => {
510
525
  if (n.socket && (n.socket.readyState === WebSocket.CONNECTING || n.socket.readyState === WebSocket.OPEN)) {
511
526
  t(n.socket.readyState === WebSocket.OPEN);
512
527
  return;
513
528
  }
514
- const a = U();
529
+ const a = N();
515
530
  if (!a || !a.endpoint) {
516
- o(new Error("SDK not initialized. Please initialize SDK first."));
531
+ s(new Error("SDK not initialized. Please initialize SDK first."));
517
532
  return;
518
533
  }
519
- const d = ae(a.endpoint);
534
+ const d = le(a.endpoint);
520
535
  if (!d) {
521
- o(
536
+ s(
522
537
  new Error(
523
538
  "Invalid endpoint while initializing SDK. Please check the endpoint and try again."
524
539
  )
525
540
  );
526
541
  return;
527
542
  }
528
- const u = D(), c = new URLSearchParams({
543
+ const u = D(), i = new URLSearchParams({
529
544
  externalId: u
530
545
  });
531
- e.sessionId && c.set("sessionId", e.sessionId), a.token && c.set("token", a.token);
532
- const p = `${d}?${c.toString()}`;
533
- n.socket = new WebSocket(p), n.socket.onopen = (l) => {
534
- Ce(), t(!0);
546
+ e.sessionId && i.set("sessionId", e.sessionId), a.token && i.set("token", a.token);
547
+ const f = `${d}?${i.toString()}`;
548
+ n.socket = new WebSocket(f), n.socket.onopen = (l) => {
549
+ ye(), t(!0);
535
550
  }, n.socket.onmessage = (l) => {
536
- const f = JSON.parse(l.data);
537
- be(f);
551
+ const p = JSON.parse(l.data);
552
+ Ae(p);
538
553
  }, n.socket.onerror = (l) => {
539
- k("error"), v(l.message || "Unable to connect voice"), o(l);
554
+ I("error"), v(l.message || "Unable to connect voice"), s(l);
540
555
  }, n.socket.onclose = (l) => {
541
556
  A();
542
557
  };
543
558
  });
544
559
  }
545
- function be(e) {
560
+ function Ae(e) {
546
561
  switch (e.type) {
547
562
  case "pong":
548
- he();
563
+ Ee();
549
564
  break;
550
565
  case "answer":
551
- Te(e.data);
566
+ De(e.data);
552
567
  break;
553
568
  case "ice":
554
- ve(e.data);
569
+ Pe(e.data);
555
570
  break;
556
571
  case "renegotiationOffer":
557
- Ae(e.data);
572
+ Re(e.data);
558
573
  break;
559
574
  case "end":
560
- X();
575
+ te();
561
576
  break;
562
577
  case "error":
563
- k("error"), v(e.error || "Unable to connect voice");
578
+ I("error"), v(e.error || "Unable to connect voice");
564
579
  break;
565
580
  default:
566
581
  break;
567
582
  }
568
583
  }
569
- async function Te(e) {
584
+ async function De(e) {
570
585
  try {
571
- if (n.sessionId = e.sessionId, pe(e.sessionId), n.peerConnection) {
586
+ if (n.sessionId = e.sessionId, Se(e.sessionId), n.peerConnection) {
572
587
  const t = new RTCSessionDescription({
573
588
  type: "answer",
574
589
  sdp: e.sdp
575
590
  });
576
591
  await n.peerConnection.setRemoteDescription(t);
577
- for (const o of n.localIceCandidates)
578
- w({
592
+ for (const s of n.localIceCandidates)
593
+ y({
579
594
  type: "ice",
580
595
  data: {
581
- candidate: o
596
+ candidate: s
582
597
  }
583
598
  });
584
599
  n.localIceCandidates = [];
585
- for (const o of n.pendingRemoteIceCandidates)
600
+ for (const s of n.pendingRemoteIceCandidates)
586
601
  try {
587
- const a = new RTCIceCandidate(JSON.parse(o));
602
+ const a = new RTCIceCandidate(JSON.parse(s));
588
603
  await n.peerConnection.addIceCandidate(a);
589
604
  } catch (a) {
590
605
  }
@@ -593,7 +608,7 @@ async function Te(e) {
593
608
  } catch (t) {
594
609
  }
595
610
  }
596
- async function ve(e) {
611
+ async function Pe(e) {
597
612
  try {
598
613
  if (n.peerConnection) {
599
614
  if (!n.peerConnection.remoteDescription) {
@@ -606,7 +621,7 @@ async function ve(e) {
606
621
  } catch (t) {
607
622
  }
608
623
  }
609
- async function Ae(e) {
624
+ async function Re(e) {
610
625
  try {
611
626
  if (n.peerConnection) {
612
627
  const t = new RTCSessionDescription({
@@ -614,41 +629,41 @@ async function Ae(e) {
614
629
  sdp: e.sdp
615
630
  });
616
631
  await n.peerConnection.setRemoteDescription(t);
617
- const o = await n.peerConnection.createAnswer();
618
- await n.peerConnection.setLocalDescription(o), w({
632
+ const s = await n.peerConnection.createAnswer();
633
+ await n.peerConnection.setLocalDescription(s), y({
619
634
  type: "renegotiationAnswer",
620
635
  data: {
621
- sdp: o.sdp
636
+ sdp: s.sdp
622
637
  }
623
638
  });
624
639
  }
625
640
  } catch (t) {
626
641
  }
627
642
  }
628
- async function xe(e = {}) {
643
+ async function Ge(e = {}) {
629
644
  try {
630
645
  if (n.callStatus === "connecting" || n.callStatus === "connected")
631
646
  return;
632
- k("connecting"), v(null), n.sessionId = e.sessionId, await we(), ye(), n.localStream.getTracks().forEach((o) => {
633
- n.peerConnection.addTrack(o, n.localStream);
634
- }), await Ee(e);
647
+ I("connecting"), v(null), n.sessionId = e.sessionId, await be(), Te(), n.localStream.getTracks().forEach((s) => {
648
+ n.peerConnection.addTrack(s, n.localStream);
649
+ }), await ve(e);
635
650
  const t = await n.peerConnection.createOffer();
636
- await n.peerConnection.setLocalDescription(t), w({
651
+ await n.peerConnection.setLocalDescription(t), y({
637
652
  type: "offer",
638
653
  data: {
639
654
  sdp: t.sdp
640
655
  }
641
656
  });
642
657
  } catch (t) {
643
- k("error"), v(t.message || "Unable to connect voice"), j();
658
+ I("error"), v(t.message || "Unable to connect voice"), ne();
644
659
  }
645
660
  }
646
- function X() {
647
- w({
661
+ function te() {
662
+ y({
648
663
  type: "end"
649
- }), n.socket && (n.socket.close(), n.socket = null), k("disconnected"), n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((e) => e.stop()), n.localStream = null), j();
664
+ }), n.socket && (n.socket.close(), n.socket = null), I("disconnected"), n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((e) => e.stop()), n.localStream = null), ne();
650
665
  }
651
- function qe() {
666
+ function ze() {
652
667
  if (n.localStream) {
653
668
  const e = n.localStream.getAudioTracks()[0];
654
669
  if (e)
@@ -656,55 +671,55 @@ function qe() {
656
671
  }
657
672
  return !1;
658
673
  }
659
- function Le() {
674
+ function Fe() {
660
675
  return n.localStream;
661
676
  }
662
- function Ge() {
677
+ function We() {
663
678
  return new Promise((e, t) => {
664
679
  if (!n.peerConnection) {
665
680
  t(new Error("no peer connection"));
666
681
  return;
667
682
  }
668
- n.peerConnection.getStats().then((o) => {
669
- o.forEach((a) => {
683
+ n.peerConnection.getStats().then((s) => {
684
+ s.forEach((a) => {
670
685
  a.type == "inbound-rtp" && e(a.totalAudioEnergy);
671
686
  }), t(new Error("no inbound-rtp stats found"));
672
- }).catch((o) => {
673
- t(o);
687
+ }).catch((s) => {
688
+ t(s);
674
689
  });
675
690
  });
676
691
  }
677
- function ze() {
692
+ function Je() {
678
693
  return new Promise((e, t) => {
679
694
  if (!n.peerConnection) {
680
695
  t(new Error("no peer connection"));
681
696
  return;
682
697
  }
683
- n.peerConnection.getStats().then((o) => {
684
- o.forEach((a) => {
698
+ n.peerConnection.getStats().then((s) => {
699
+ s.forEach((a) => {
685
700
  a.type == "outbound-rtp" && e(a.totalAudioEnergy);
686
701
  }), t(new Error("no outbound-rtp stats found"));
687
- }).catch((o) => {
688
- t(o);
702
+ }).catch((s) => {
703
+ t(s);
689
704
  });
690
705
  });
691
706
  }
692
707
  export {
693
- T as MESSAGE_ROLES,
694
- Se as authenticate,
695
- Ne as disconnect,
696
- X as disconnectCall,
697
- Ue as getHistory,
698
- Ge as getInboundAudioEnergy,
699
- Le as getLocalStream,
700
- ke as getMessages,
701
- ze as getOutboundAudioEnergy,
702
- Pe as initialize,
703
- Oe as sendMessage,
704
- Me as setCallCallbacks,
705
- $e as setCallbacks,
706
- xe as startCall,
707
- Re as startChat,
708
- qe as toggleMute
708
+ w as MESSAGE_ROLES,
709
+ Ce as authenticate,
710
+ Me as disconnect,
711
+ te as disconnectCall,
712
+ qe as getHistory,
713
+ We as getInboundAudioEnergy,
714
+ Fe as getLocalStream,
715
+ he as getMessages,
716
+ Je as getOutboundAudioEnergy,
717
+ Ue as initialize,
718
+ xe as sendMessage,
719
+ Le as setCallCallbacks,
720
+ Oe as setCallbacks,
721
+ Ge as startCall,
722
+ Ne as startChat,
723
+ ze as toggleMute
709
724
  };
710
725
  //# sourceMappingURL=origon-chat-sdk.js.map