@echo-sdk/view 0.1.0

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.
@@ -0,0 +1,1755 @@
1
+ var he, b, We, J, ke, je, ze, Qe, we, me, fe, Oe, ne = {}, Be = [], ut = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, ue = Array.isArray;
2
+ function Q(e, t) {
3
+ for (var n in t) e[n] = t[n];
4
+ return e;
5
+ }
6
+ function be(e) {
7
+ e && e.parentNode && e.parentNode.removeChild(e);
8
+ }
9
+ function dt(e, t, n) {
10
+ var r, o, i, s = {};
11
+ for (i in t) i == "key" ? r = t[i] : i == "ref" ? o = t[i] : s[i] = t[i];
12
+ if (arguments.length > 2 && (s.children = arguments.length > 3 ? he.call(arguments, 2) : n), typeof e == "function" && e.defaultProps != null) for (i in e.defaultProps) s[i] === void 0 && (s[i] = e.defaultProps[i]);
13
+ return oe(e, s, r, o, null);
14
+ }
15
+ function oe(e, t, n, r, o) {
16
+ var i = { type: e, props: t, key: n, ref: r, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: o ?? ++We, __i: -1, __u: 0 };
17
+ return o == null && b.vnode != null && b.vnode(i), i;
18
+ }
19
+ function re(e) {
20
+ return e.children;
21
+ }
22
+ function se(e, t) {
23
+ this.props = e, this.context = t;
24
+ }
25
+ function X(e, t) {
26
+ if (t == null) return e.__ ? X(e.__, e.__i + 1) : null;
27
+ for (var n; t < e.__k.length; t++) if ((n = e.__k[t]) != null && n.__e != null) return n.__e;
28
+ return typeof e.type == "function" ? X(e) : null;
29
+ }
30
+ function Ke(e) {
31
+ var t, n;
32
+ if ((e = e.__) != null && e.__c != null) {
33
+ for (e.__e = e.__c.base = null, t = 0; t < e.__k.length; t++) if ((n = e.__k[t]) != null && n.__e != null) {
34
+ e.__e = e.__c.base = n.__e;
35
+ break;
36
+ }
37
+ return Ke(e);
38
+ }
39
+ }
40
+ function pe(e) {
41
+ (!e.__d && (e.__d = !0) && J.push(e) && !ce.__r++ || ke != b.debounceRendering) && ((ke = b.debounceRendering) || je)(ce);
42
+ }
43
+ function ce() {
44
+ for (var e, t, n, r, o, i, s, h = 1; J.length; ) J.length > h && J.sort(ze), e = J.shift(), h = J.length, e.__d && (n = void 0, r = void 0, o = (r = (t = e).__v).__e, i = [], s = [], t.__P && ((n = Q({}, r)).__v = r.__v + 1, b.vnode && b.vnode(n), xe(t.__P, n, r, t.__n, t.__P.namespaceURI, 32 & r.__u ? [o] : null, i, o ?? X(r), !!(32 & r.__u), s), n.__v = r.__v, n.__.__k[n.__i] = n, Je(i, n, s), r.__e = r.__ = null, n.__e != o && Ke(n)));
45
+ ce.__r = 0;
46
+ }
47
+ function Ve(e, t, n, r, o, i, s, h, u, l, _) {
48
+ var a, g, d, C, I, w, p, f = r && r.__k || Be, A = t.length;
49
+ for (u = _t(n, t, f, u, A), a = 0; a < A; a++) (d = n.__k[a]) != null && (g = d.__i == -1 ? ne : f[d.__i] || ne, d.__i = a, w = xe(e, d, g, o, i, s, h, u, l, _), C = d.__e, d.ref && g.ref != d.ref && (g.ref && Se(g.ref, null, d), _.push(d.ref, d.__c || C, d)), I == null && C != null && (I = C), (p = !!(4 & d.__u)) || g.__k === d.__k ? u = Ge(d, u, e, p) : typeof d.type == "function" && w !== void 0 ? u = w : C && (u = C.nextSibling), d.__u &= -7);
50
+ return n.__e = I, u;
51
+ }
52
+ function _t(e, t, n, r, o) {
53
+ var i, s, h, u, l, _ = n.length, a = _, g = 0;
54
+ for (e.__k = new Array(o), i = 0; i < o; i++) (s = t[i]) != null && typeof s != "boolean" && typeof s != "function" ? (typeof s == "string" || typeof s == "number" || typeof s == "bigint" || s.constructor == String ? s = e.__k[i] = oe(null, s, null, null, null) : ue(s) ? s = e.__k[i] = oe(re, { children: s }, null, null, null) : s.constructor == null && s.__b > 0 ? s = e.__k[i] = oe(s.type, s.props, s.key, s.ref ? s.ref : null, s.__v) : e.__k[i] = s, u = i + g, s.__ = e, s.__b = e.__b + 1, (l = s.__i = gt(s, n, u, a)) != -1 && (a--, (h = n[l]) && (h.__u |= 2)), h == null || h.__v == null ? (l == -1 && (o > _ ? g-- : o < _ && g++), typeof s.type != "function" && (s.__u |= 4)) : l != u && (l == u - 1 ? g-- : l == u + 1 ? g++ : (l > u ? g-- : g++, s.__u |= 4))) : e.__k[i] = null;
55
+ if (a) for (i = 0; i < _; i++) (h = n[i]) != null && (2 & h.__u) == 0 && (h.__e == r && (r = X(h)), Xe(h, h));
56
+ return r;
57
+ }
58
+ function Ge(e, t, n, r) {
59
+ var o, i;
60
+ if (typeof e.type == "function") {
61
+ for (o = e.__k, i = 0; o && i < o.length; i++) o[i] && (o[i].__ = e, t = Ge(o[i], t, n, r));
62
+ return t;
63
+ }
64
+ e.__e != t && (r && (t && e.type && !t.parentNode && (t = X(e)), n.insertBefore(e.__e, t || null)), t = e.__e);
65
+ do
66
+ t = t && t.nextSibling;
67
+ while (t != null && t.nodeType == 8);
68
+ return t;
69
+ }
70
+ function gt(e, t, n, r) {
71
+ var o, i, s, h = e.key, u = e.type, l = t[n], _ = l != null && (2 & l.__u) == 0;
72
+ if (l === null && h == null || _ && h == l.key && u == l.type) return n;
73
+ if (r > (_ ? 1 : 0)) {
74
+ for (o = n - 1, i = n + 1; o >= 0 || i < t.length; ) if ((l = t[s = o >= 0 ? o-- : i++]) != null && (2 & l.__u) == 0 && h == l.key && u == l.type) return s;
75
+ }
76
+ return -1;
77
+ }
78
+ function $e(e, t, n) {
79
+ t[0] == "-" ? e.setProperty(t, n ?? "") : e[t] = n == null ? "" : typeof n != "number" || ut.test(t) ? n : n + "px";
80
+ }
81
+ function ie(e, t, n, r, o) {
82
+ var i, s;
83
+ e: if (t == "style") if (typeof n == "string") e.style.cssText = n;
84
+ else {
85
+ if (typeof r == "string" && (e.style.cssText = r = ""), r) for (t in r) n && t in n || $e(e.style, t, "");
86
+ if (n) for (t in n) r && n[t] == r[t] || $e(e.style, t, n[t]);
87
+ }
88
+ else if (t[0] == "o" && t[1] == "n") i = t != (t = t.replace(Qe, "$1")), s = t.toLowerCase(), t = s in e || t == "onFocusOut" || t == "onFocusIn" ? s.slice(2) : t.slice(2), e.l || (e.l = {}), e.l[t + i] = n, n ? r ? n.u = r.u : (n.u = we, e.addEventListener(t, i ? fe : me, i)) : e.removeEventListener(t, i ? fe : me, i);
89
+ else {
90
+ if (o == "http://www.w3.org/2000/svg") t = t.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
91
+ else if (t != "width" && t != "height" && t != "href" && t != "list" && t != "form" && t != "tabIndex" && t != "download" && t != "rowSpan" && t != "colSpan" && t != "role" && t != "popover" && t in e) try {
92
+ e[t] = n ?? "";
93
+ break e;
94
+ } catch {
95
+ }
96
+ typeof n == "function" || (n == null || n === !1 && t[4] != "-" ? e.removeAttribute(t) : e.setAttribute(t, t == "popover" && n == 1 ? "" : n));
97
+ }
98
+ }
99
+ function Te(e) {
100
+ return function(t) {
101
+ if (this.l) {
102
+ var n = this.l[t.type + e];
103
+ if (t.t == null) t.t = we++;
104
+ else if (t.t < n.u) return;
105
+ return n(b.event ? b.event(t) : t);
106
+ }
107
+ };
108
+ }
109
+ function xe(e, t, n, r, o, i, s, h, u, l) {
110
+ var _, a, g, d, C, I, w, p, f, A, P, M, L, W, O, F, E, v = t.type;
111
+ if (t.constructor != null) return null;
112
+ 128 & n.__u && (u = !!(32 & n.__u), i = [h = t.__e = n.__e]), (_ = b.__b) && _(t);
113
+ e: if (typeof v == "function") try {
114
+ if (p = t.props, f = "prototype" in v && v.prototype.render, A = (_ = v.contextType) && r[_.__c], P = _ ? A ? A.props.value : _.__ : r, n.__c ? w = (a = t.__c = n.__c).__ = a.__E : (f ? t.__c = a = new v(p, P) : (t.__c = a = new se(p, P), a.constructor = v, a.render = ft), A && A.sub(a), a.state || (a.state = {}), a.__n = r, g = a.__d = !0, a.__h = [], a._sb = []), f && a.__s == null && (a.__s = a.state), f && v.getDerivedStateFromProps != null && (a.__s == a.state && (a.__s = Q({}, a.__s)), Q(a.__s, v.getDerivedStateFromProps(p, a.__s))), d = a.props, C = a.state, a.__v = t, g) f && v.getDerivedStateFromProps == null && a.componentWillMount != null && a.componentWillMount(), f && a.componentDidMount != null && a.__h.push(a.componentDidMount);
115
+ else {
116
+ if (f && v.getDerivedStateFromProps == null && p !== d && a.componentWillReceiveProps != null && a.componentWillReceiveProps(p, P), t.__v == n.__v || !a.__e && a.shouldComponentUpdate != null && a.shouldComponentUpdate(p, a.__s, P) === !1) {
117
+ for (t.__v != n.__v && (a.props = p, a.state = a.__s, a.__d = !1), t.__e = n.__e, t.__k = n.__k, t.__k.some(function(q) {
118
+ q && (q.__ = t);
119
+ }), M = 0; M < a._sb.length; M++) a.__h.push(a._sb[M]);
120
+ a._sb = [], a.__h.length && s.push(a);
121
+ break e;
122
+ }
123
+ a.componentWillUpdate != null && a.componentWillUpdate(p, a.__s, P), f && a.componentDidUpdate != null && a.__h.push(function() {
124
+ a.componentDidUpdate(d, C, I);
125
+ });
126
+ }
127
+ if (a.context = P, a.props = p, a.__P = e, a.__e = !1, L = b.__r, W = 0, f) {
128
+ for (a.state = a.__s, a.__d = !1, L && L(t), _ = a.render(a.props, a.state, a.context), O = 0; O < a._sb.length; O++) a.__h.push(a._sb[O]);
129
+ a._sb = [];
130
+ } else do
131
+ a.__d = !1, L && L(t), _ = a.render(a.props, a.state, a.context), a.state = a.__s;
132
+ while (a.__d && ++W < 25);
133
+ a.state = a.__s, a.getChildContext != null && (r = Q(Q({}, r), a.getChildContext())), f && !g && a.getSnapshotBeforeUpdate != null && (I = a.getSnapshotBeforeUpdate(d, C)), F = _, _ != null && _.type === re && _.key == null && (F = Ye(_.props.children)), h = Ve(e, ue(F) ? F : [F], t, n, r, o, i, s, h, u, l), a.base = t.__e, t.__u &= -161, a.__h.length && s.push(a), w && (a.__E = a.__ = null);
134
+ } catch (q) {
135
+ if (t.__v = null, u || i != null) if (q.then) {
136
+ for (t.__u |= u ? 160 : 128; h && h.nodeType == 8 && h.nextSibling; ) h = h.nextSibling;
137
+ i[i.indexOf(h)] = null, t.__e = h;
138
+ } else {
139
+ for (E = i.length; E--; ) be(i[E]);
140
+ ve(t);
141
+ }
142
+ else t.__e = n.__e, t.__k = n.__k, q.then || ve(t);
143
+ b.__e(q, t, n);
144
+ }
145
+ else i == null && t.__v == n.__v ? (t.__k = n.__k, t.__e = n.__e) : h = t.__e = mt(n.__e, t, n, r, o, i, s, u, l);
146
+ return (_ = b.diffed) && _(t), 128 & t.__u ? void 0 : h;
147
+ }
148
+ function ve(e) {
149
+ e && e.__c && (e.__c.__e = !0), e && e.__k && e.__k.forEach(ve);
150
+ }
151
+ function Je(e, t, n) {
152
+ for (var r = 0; r < n.length; r++) Se(n[r], n[++r], n[++r]);
153
+ b.__c && b.__c(t, e), e.some(function(o) {
154
+ try {
155
+ e = o.__h, o.__h = [], e.some(function(i) {
156
+ i.call(o);
157
+ });
158
+ } catch (i) {
159
+ b.__e(i, o.__v);
160
+ }
161
+ });
162
+ }
163
+ function Ye(e) {
164
+ return typeof e != "object" || e == null || e.__b && e.__b > 0 ? e : ue(e) ? e.map(Ye) : Q({}, e);
165
+ }
166
+ function mt(e, t, n, r, o, i, s, h, u) {
167
+ var l, _, a, g, d, C, I, w = n.props || ne, p = t.props, f = t.type;
168
+ if (f == "svg" ? o = "http://www.w3.org/2000/svg" : f == "math" ? o = "http://www.w3.org/1998/Math/MathML" : o || (o = "http://www.w3.org/1999/xhtml"), i != null) {
169
+ for (l = 0; l < i.length; l++) if ((d = i[l]) && "setAttribute" in d == !!f && (f ? d.localName == f : d.nodeType == 3)) {
170
+ e = d, i[l] = null;
171
+ break;
172
+ }
173
+ }
174
+ if (e == null) {
175
+ if (f == null) return document.createTextNode(p);
176
+ e = document.createElementNS(o, f, p.is && p), h && (b.__m && b.__m(t, i), h = !1), i = null;
177
+ }
178
+ if (f == null) w === p || h && e.data == p || (e.data = p);
179
+ else {
180
+ if (i = i && he.call(e.childNodes), !h && i != null) for (w = {}, l = 0; l < e.attributes.length; l++) w[(d = e.attributes[l]).name] = d.value;
181
+ for (l in w) if (d = w[l], l != "children") {
182
+ if (l == "dangerouslySetInnerHTML") a = d;
183
+ else if (!(l in p)) {
184
+ if (l == "value" && "defaultValue" in p || l == "checked" && "defaultChecked" in p) continue;
185
+ ie(e, l, null, d, o);
186
+ }
187
+ }
188
+ for (l in p) d = p[l], l == "children" ? g = d : l == "dangerouslySetInnerHTML" ? _ = d : l == "value" ? C = d : l == "checked" ? I = d : h && typeof d != "function" || w[l] === d || ie(e, l, d, w[l], o);
189
+ if (_) h || a && (_.__html == a.__html || _.__html == e.innerHTML) || (e.innerHTML = _.__html), t.__k = [];
190
+ else if (a && (e.innerHTML = ""), Ve(t.type == "template" ? e.content : e, ue(g) ? g : [g], t, n, r, f == "foreignObject" ? "http://www.w3.org/1999/xhtml" : o, i, s, i ? i[0] : n.__k && X(n, 0), h, u), i != null) for (l = i.length; l--; ) be(i[l]);
191
+ h || (l = "value", f == "progress" && C == null ? e.removeAttribute("value") : C != null && (C !== e[l] || f == "progress" && !C || f == "option" && C != w[l]) && ie(e, l, C, w[l], o), l = "checked", I != null && I != e[l] && ie(e, l, I, w[l], o));
192
+ }
193
+ return e;
194
+ }
195
+ function Se(e, t, n) {
196
+ try {
197
+ if (typeof e == "function") {
198
+ var r = typeof e.__u == "function";
199
+ r && e.__u(), r && t == null || (e.__u = e(t));
200
+ } else e.current = t;
201
+ } catch (o) {
202
+ b.__e(o, n);
203
+ }
204
+ }
205
+ function Xe(e, t, n) {
206
+ var r, o;
207
+ if (b.unmount && b.unmount(e), (r = e.ref) && (r.current && r.current != e.__e || Se(r, null, t)), (r = e.__c) != null) {
208
+ if (r.componentWillUnmount) try {
209
+ r.componentWillUnmount();
210
+ } catch (i) {
211
+ b.__e(i, t);
212
+ }
213
+ r.base = r.__P = null;
214
+ }
215
+ if (r = e.__k) for (o = 0; o < r.length; o++) r[o] && Xe(r[o], t, n || typeof e.type != "function");
216
+ n || be(e.__e), e.__c = e.__ = e.__e = void 0;
217
+ }
218
+ function ft(e, t, n) {
219
+ return this.constructor(e, n);
220
+ }
221
+ function Ie(e, t, n) {
222
+ var r, o, i, s;
223
+ t == document && (t = document.documentElement), b.__ && b.__(e, t), o = (r = !1) ? null : t.__k, i = [], s = [], xe(t, e = t.__k = dt(re, null, [e]), o || ne, ne, t.namespaceURI, o ? null : t.firstChild ? he.call(t.childNodes) : null, i, o ? o.__e : t.firstChild, r, s), Je(i, e, s);
224
+ }
225
+ function pt(e) {
226
+ function t(n) {
227
+ var r, o;
228
+ return this.getChildContext || (r = /* @__PURE__ */ new Set(), (o = {})[t.__c] = this, this.getChildContext = function() {
229
+ return o;
230
+ }, this.componentWillUnmount = function() {
231
+ r = null;
232
+ }, this.shouldComponentUpdate = function(i) {
233
+ this.props.value != i.value && r.forEach(function(s) {
234
+ s.__e = !0, pe(s);
235
+ });
236
+ }, this.sub = function(i) {
237
+ r.add(i);
238
+ var s = i.componentWillUnmount;
239
+ i.componentWillUnmount = function() {
240
+ r && r.delete(i), s && s.call(i);
241
+ };
242
+ }), n.children;
243
+ }
244
+ return t.__c = "__cC" + Oe++, t.__ = e, t.Provider = t.__l = (t.Consumer = function(n, r) {
245
+ return n.children(r);
246
+ }).contextType = t, t;
247
+ }
248
+ he = Be.slice, b = { __e: function(e, t, n, r) {
249
+ for (var o, i, s; t = t.__; ) if ((o = t.__c) && !o.__) try {
250
+ if ((i = o.constructor) && i.getDerivedStateFromError != null && (o.setState(i.getDerivedStateFromError(e)), s = o.__d), o.componentDidCatch != null && (o.componentDidCatch(e, r || {}), s = o.__d), s) return o.__E = o;
251
+ } catch (h) {
252
+ e = h;
253
+ }
254
+ throw e;
255
+ } }, We = 0, se.prototype.setState = function(e, t) {
256
+ var n;
257
+ n = this.__s != null && this.__s != this.state ? this.__s : this.__s = Q({}, this.state), typeof e == "function" && (e = e(Q({}, n), this.props)), e && Q(n, e), e != null && this.__v && (t && this._sb.push(t), pe(this));
258
+ }, se.prototype.forceUpdate = function(e) {
259
+ this.__v && (this.__e = !0, e && this.__h.push(e), pe(this));
260
+ }, se.prototype.render = re, J = [], je = typeof Promise == "function" ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, ze = function(e, t) {
261
+ return e.__v.__b - t.__v.__b;
262
+ }, ce.__r = 0, Qe = /(PointerCapture)$|Capture$/i, we = 0, me = Te(!1), fe = Te(!0), Oe = 0;
263
+ var vt = 0;
264
+ function c(e, t, n, r, o, i) {
265
+ t || (t = {});
266
+ var s, h, u = t;
267
+ if ("ref" in u) for (h in u = {}, t) h == "ref" ? s = t[h] : u[h] = t[h];
268
+ var l = { type: e, props: u, key: n, ref: s, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: --vt, __i: -1, __u: 0, __source: o, __self: i };
269
+ if (typeof e == "function" && (s = e.defaultProps)) for (h in s) u[h] === void 0 && (u[h] = s[h]);
270
+ return b.vnode && b.vnode(l), l;
271
+ }
272
+ var Z, S, ge, Ne, le = 0, Ze = [], T = b, De = T.__b, Re = T.__r, Ae = T.diffed, Me = T.__c, qe = T.unmount, He = T.__;
273
+ function de(e, t) {
274
+ T.__h && T.__h(S, e, le || t), le = 0;
275
+ var n = S.__H || (S.__H = { __: [], __h: [] });
276
+ return e >= n.__.length && n.__.push({}), n.__[e];
277
+ }
278
+ function N(e) {
279
+ return le = 1, yt(nt, e);
280
+ }
281
+ function yt(e, t, n) {
282
+ var r = de(Z++, 2);
283
+ if (r.t = e, !r.__c && (r.__ = [nt(void 0, t), function(h) {
284
+ var u = r.__N ? r.__N[0] : r.__[0], l = r.t(u, h);
285
+ u !== l && (r.__N = [l, r.__[1]], r.__c.setState({}));
286
+ }], r.__c = S, !S.__f)) {
287
+ var o = function(h, u, l) {
288
+ if (!r.__c.__H) return !0;
289
+ var _ = r.__c.__H.__.filter(function(g) {
290
+ return !!g.__c;
291
+ });
292
+ if (_.every(function(g) {
293
+ return !g.__N;
294
+ })) return !i || i.call(this, h, u, l);
295
+ var a = r.__c.props !== h;
296
+ return _.forEach(function(g) {
297
+ if (g.__N) {
298
+ var d = g.__[0];
299
+ g.__ = g.__N, g.__N = void 0, d !== g.__[0] && (a = !0);
300
+ }
301
+ }), i && i.call(this, h, u, l) || a;
302
+ };
303
+ S.__f = !0;
304
+ var i = S.shouldComponentUpdate, s = S.componentWillUpdate;
305
+ S.componentWillUpdate = function(h, u, l) {
306
+ if (this.__e) {
307
+ var _ = i;
308
+ i = void 0, o(h, u, l), i = _;
309
+ }
310
+ s && s.call(this, h, u, l);
311
+ }, S.shouldComponentUpdate = o;
312
+ }
313
+ return r.__N || r.__;
314
+ }
315
+ function et(e, t) {
316
+ var n = de(Z++, 3);
317
+ !T.__s && tt(n.__H, t) && (n.__ = e, n.u = t, S.__H.__h.push(n));
318
+ }
319
+ function Y(e) {
320
+ return le = 5, wt(function() {
321
+ return { current: e };
322
+ }, []);
323
+ }
324
+ function wt(e, t) {
325
+ var n = de(Z++, 7);
326
+ return tt(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;
327
+ }
328
+ function bt(e) {
329
+ var t = S.context[e.__c], n = de(Z++, 9);
330
+ return n.c = e, t ? (n.__ == null && (n.__ = !0, t.sub(S)), t.props.value) : e.__;
331
+ }
332
+ function xt() {
333
+ for (var e; e = Ze.shift(); ) if (e.__P && e.__H) try {
334
+ e.__H.__h.forEach(ae), e.__H.__h.forEach(ye), e.__H.__h = [];
335
+ } catch (t) {
336
+ e.__H.__h = [], T.__e(t, e.__v);
337
+ }
338
+ }
339
+ T.__b = function(e) {
340
+ S = null, De && De(e);
341
+ }, T.__ = function(e, t) {
342
+ e && t.__k && t.__k.__m && (e.__m = t.__k.__m), He && He(e, t);
343
+ }, T.__r = function(e) {
344
+ Re && Re(e), Z = 0;
345
+ var t = (S = e.__c).__H;
346
+ t && (ge === S ? (t.__h = [], S.__h = [], t.__.forEach(function(n) {
347
+ n.__N && (n.__ = n.__N), n.u = n.__N = void 0;
348
+ })) : (t.__h.forEach(ae), t.__h.forEach(ye), t.__h = [], Z = 0)), ge = S;
349
+ }, T.diffed = function(e) {
350
+ Ae && Ae(e);
351
+ var t = e.__c;
352
+ t && t.__H && (t.__H.__h.length && (Ze.push(t) !== 1 && Ne === T.requestAnimationFrame || ((Ne = T.requestAnimationFrame) || St)(xt)), t.__H.__.forEach(function(n) {
353
+ n.u && (n.__H = n.u), n.u = void 0;
354
+ })), ge = S = null;
355
+ }, T.__c = function(e, t) {
356
+ t.some(function(n) {
357
+ try {
358
+ n.__h.forEach(ae), n.__h = n.__h.filter(function(r) {
359
+ return !r.__ || ye(r);
360
+ });
361
+ } catch (r) {
362
+ t.some(function(o) {
363
+ o.__h && (o.__h = []);
364
+ }), t = [], T.__e(r, n.__v);
365
+ }
366
+ }), Me && Me(e, t);
367
+ }, T.unmount = function(e) {
368
+ qe && qe(e);
369
+ var t, n = e.__c;
370
+ n && n.__H && (n.__H.__.forEach(function(r) {
371
+ try {
372
+ ae(r);
373
+ } catch (o) {
374
+ t = o;
375
+ }
376
+ }), n.__H = void 0, t && T.__e(t, n.__v));
377
+ };
378
+ var Pe = typeof requestAnimationFrame == "function";
379
+ function St(e) {
380
+ var t, n = function() {
381
+ clearTimeout(r), Pe && cancelAnimationFrame(t), setTimeout(e);
382
+ }, r = setTimeout(n, 35);
383
+ Pe && (t = requestAnimationFrame(n));
384
+ }
385
+ function ae(e) {
386
+ var t = S, n = e.__c;
387
+ typeof n == "function" && (e.__c = void 0, n()), S = t;
388
+ }
389
+ function ye(e) {
390
+ var t = S;
391
+ e.__c = e.__(), S = t;
392
+ }
393
+ function tt(e, t) {
394
+ return !e || e.length !== t.length || t.some(function(n, r) {
395
+ return n !== e[r];
396
+ });
397
+ }
398
+ function nt(e, t) {
399
+ return typeof t == "function" ? t(e) : t;
400
+ }
401
+ var te = /* @__PURE__ */ ((e) => (e.TEXT = "text", e.IMAGE = "image", e.FILE = "file", e.SYSTEM = "system", e.TYPING = "typing", e.CUSTOM = "custom", e))(te || {}), G = /* @__PURE__ */ ((e) => (e.PENDING = "pending", e.SENT = "sent", e.DELIVERED = "delivered", e.READ = "read", e.FAILED = "failed", e))(G || {}), rt = class {
402
+ constructor(e) {
403
+ this.defaultLogger = (t, n, ...r) => {
404
+ const o = (/* @__PURE__ */ new Date()).toISOString(), i = this.config.prefix ? `[${this.config.prefix}] [${o}] [${t.toUpperCase()}]` : `[ChatBot SDK ${o}] [${t.toUpperCase()}]`;
405
+ switch (t) {
406
+ case "debug":
407
+ console.debug(i, n, ...r);
408
+ break;
409
+ case "info":
410
+ console.info(i, n, ...r);
411
+ break;
412
+ case "warn":
413
+ console.warn(i, n, ...r);
414
+ break;
415
+ case "error":
416
+ console.error(i, n, ...r);
417
+ break;
418
+ }
419
+ }, this.config = {
420
+ enabled: e?.enabled ?? !0,
421
+ level: e?.level ?? "info",
422
+ customLogger: e?.customLogger ?? this.defaultLogger,
423
+ prefix: e?.prefix ?? ""
424
+ };
425
+ }
426
+ shouldLog(e) {
427
+ if (!this.config.enabled) return !1;
428
+ const t = ["debug", "info", "warn", "error"], n = t.indexOf(this.config.level);
429
+ return t.indexOf(e) >= n;
430
+ }
431
+ debug(e, ...t) {
432
+ this.shouldLog("debug") && this.config.customLogger("debug", e, ...t);
433
+ }
434
+ info(e, ...t) {
435
+ this.shouldLog("info") && this.config.customLogger("info", e, ...t);
436
+ }
437
+ warn(e, ...t) {
438
+ this.shouldLog("warn") && this.config.customLogger("warn", e, ...t);
439
+ }
440
+ error(e, ...t) {
441
+ this.shouldLog("error") && this.config.customLogger("error", e, ...t);
442
+ }
443
+ updateConfig(e) {
444
+ this.config = {
445
+ ...this.config,
446
+ ...e
447
+ };
448
+ }
449
+ }, Ct = class {
450
+ constructor(e) {
451
+ this.listeners = {}, this.eventHistory = [], this.maxHistorySize = 100, this.logger = e;
452
+ }
453
+ /**
454
+ * Subscribe to an event
455
+ */
456
+ on(e, t) {
457
+ return this.listeners[e] || (this.listeners[e] = /* @__PURE__ */ new Set()), this.listeners[e].add(t), this.logger.debug(`Event listener added for: ${e}`), () => this.off(e, t);
458
+ }
459
+ /**
460
+ * Subscribe to all events (wildcard)
461
+ */
462
+ onAny(e) {
463
+ return this.listeners["*"] || (this.listeners["*"] = /* @__PURE__ */ new Set()), this.listeners["*"].add(e), this.logger.debug("Wildcard event listener added"), () => this.offAny(e);
464
+ }
465
+ /**
466
+ * Subscribe to an event once
467
+ */
468
+ once(e, t) {
469
+ const n = (r) => {
470
+ t(r), this.off(e, n);
471
+ };
472
+ return this.on(e, n);
473
+ }
474
+ /**
475
+ * Unsubscribe from an event
476
+ */
477
+ off(e, t) {
478
+ const n = this.listeners[e];
479
+ n && (n.delete(t), n.size === 0 && delete this.listeners[e], this.logger.debug(`Event listener removed for: ${e}`));
480
+ }
481
+ /**
482
+ * Unsubscribe from wildcard events
483
+ */
484
+ offAny(e) {
485
+ const t = this.listeners["*"];
486
+ t && (t.delete(e), t.size === 0 && delete this.listeners["*"], this.logger.debug("Wildcard event listener removed"));
487
+ }
488
+ /**
489
+ * Emit an event
490
+ */
491
+ emit(e, t) {
492
+ const n = { type: e, data: t };
493
+ this.eventHistory.push(n), this.eventHistory.length > this.maxHistorySize && this.eventHistory.shift(), this.logger.debug(`Event emitted: ${e}`, t);
494
+ const r = this.listeners[e];
495
+ r && r.forEach((i) => {
496
+ try {
497
+ i(t);
498
+ } catch (s) {
499
+ this.logger.error(`Error in event listener for ${e}:`, s);
500
+ }
501
+ });
502
+ const o = this.listeners["*"];
503
+ o && o.forEach((i) => {
504
+ try {
505
+ i(n);
506
+ } catch (s) {
507
+ this.logger.error("Error in wildcard event listener:", s);
508
+ }
509
+ });
510
+ }
511
+ /**
512
+ * Remove all listeners for a specific event or all events
513
+ */
514
+ removeAllListeners(e) {
515
+ e ? (delete this.listeners[e], this.logger.debug(`All listeners removed for: ${e}`)) : (this.listeners = {}, this.logger.debug("All event listeners removed"));
516
+ }
517
+ /**
518
+ * Get event history
519
+ */
520
+ getEventHistory() {
521
+ return [...this.eventHistory];
522
+ }
523
+ /**
524
+ * Clear event history
525
+ */
526
+ clearEventHistory() {
527
+ this.eventHistory = [], this.logger.debug("Event history cleared");
528
+ }
529
+ /**
530
+ * Get listener count for an event
531
+ */
532
+ listenerCount(e) {
533
+ return this.listeners[e]?.size ?? 0;
534
+ }
535
+ }, Et = class {
536
+ constructor(e = {}, t) {
537
+ this.currentAttempt = 0, this.config = {
538
+ enabled: e.enabled ?? !0,
539
+ maxAttempts: e.maxAttempts ?? 1 / 0,
540
+ baseDelay: e.baseDelay ?? 1e3,
541
+ maxDelay: e.maxDelay ?? 1e4,
542
+ jitter: e.jitter ?? 0.3
543
+ }, this.logger = t;
544
+ }
545
+ /**
546
+ * Check if reconnection should be attempted
547
+ */
548
+ shouldReconnect() {
549
+ return this.config.enabled ? this.currentAttempt >= this.config.maxAttempts ? (this.logger.warn(`Max reconnection attempts (${this.config.maxAttempts}) reached`), !1) : !0 : (this.logger.debug("Reconnection is disabled"), !1);
550
+ }
551
+ /**
552
+ * Calculate next delay with exponential backoff and jitter
553
+ */
554
+ getNextDelay() {
555
+ const e = this.config.baseDelay * Math.pow(2, this.currentAttempt), t = Math.min(e, this.config.maxDelay), n = t * this.config.jitter, r = (Math.random() * 2 - 1) * n, o = Math.max(0, t + r);
556
+ return this.logger.debug(
557
+ `Reconnection delay calculated: ${o.toFixed(0)}ms (attempt ${this.currentAttempt + 1})`
558
+ ), o;
559
+ }
560
+ /**
561
+ * Increment attempt counter
562
+ */
563
+ incrementAttempt() {
564
+ this.currentAttempt++, this.logger.info(`Reconnection attempt ${this.currentAttempt}/${this.config.maxAttempts}`);
565
+ }
566
+ /**
567
+ * Reset attempt counter
568
+ */
569
+ reset() {
570
+ this.logger.debug("Reconnection strategy reset"), this.currentAttempt = 0;
571
+ }
572
+ /**
573
+ * Get current attempt number
574
+ */
575
+ getCurrentAttempt() {
576
+ return this.currentAttempt;
577
+ }
578
+ /**
579
+ * Update configuration
580
+ */
581
+ updateConfig(e) {
582
+ this.config = {
583
+ ...this.config,
584
+ ...e
585
+ }, this.logger.debug("Reconnection config updated", this.config);
586
+ }
587
+ }, kt = class {
588
+ constructor(e) {
589
+ this.queue = [], this.maxQueueSize = 1e3, this.defaultMaxRetries = 3, this.logger = e;
590
+ }
591
+ /**
592
+ * Add a message to the queue
593
+ */
594
+ enqueue(e, t = this.defaultMaxRetries) {
595
+ this.queue.length >= this.maxQueueSize && (this.logger.warn("Message queue is full, removing oldest message"), this.queue.shift());
596
+ const n = {
597
+ message: e,
598
+ timestamp: Date.now(),
599
+ retries: 0,
600
+ maxRetries: t
601
+ };
602
+ this.queue.push(n), this.logger.debug(`Message queued: ${e.id} (queue size: ${this.queue.length})`);
603
+ }
604
+ /**
605
+ * Get all messages from the queue
606
+ */
607
+ dequeueAll() {
608
+ const e = this.queue.map((t) => t.message);
609
+ return this.queue = [], this.logger.info(`Dequeued ${e.length} messages`), e;
610
+ }
611
+ /**
612
+ * Get messages that should be retried
613
+ */
614
+ getRetryableMessages() {
615
+ return this.queue.filter((t) => t.retries < t.maxRetries).map((t) => t.message);
616
+ }
617
+ /**
618
+ * Mark a message as failed (increment retry count)
619
+ */
620
+ markAsFailed(e) {
621
+ const t = this.queue.findIndex((n) => n.message.id === e);
622
+ t !== -1 && (this.queue[t].retries++, this.queue[t].retries >= this.queue[t].maxRetries ? (this.logger.warn(`Message ${e} exceeded max retries, removing from queue`), this.queue.splice(t, 1)) : this.logger.debug(
623
+ `Message ${e} retry count: ${this.queue[t].retries}/${this.queue[t].maxRetries}`
624
+ ));
625
+ }
626
+ /**
627
+ * Remove a message from the queue
628
+ */
629
+ remove(e) {
630
+ const t = this.queue.findIndex((n) => n.message.id === e);
631
+ t !== -1 && (this.queue.splice(t, 1), this.logger.debug(`Message ${e} removed from queue`));
632
+ }
633
+ /**
634
+ * Clear the entire queue
635
+ */
636
+ clear() {
637
+ const e = this.queue.length;
638
+ this.queue = [], this.logger.info(`Message queue cleared (${e} messages removed)`);
639
+ }
640
+ /**
641
+ * Get queue size
642
+ */
643
+ size() {
644
+ return this.queue.length;
645
+ }
646
+ /**
647
+ * Check if queue is empty
648
+ */
649
+ isEmpty() {
650
+ return this.queue.length === 0;
651
+ }
652
+ /**
653
+ * Get all queued messages (without removing them)
654
+ */
655
+ peek() {
656
+ return this.queue.map((e) => e.message);
657
+ }
658
+ /**
659
+ * Set max queue size
660
+ */
661
+ setMaxQueueSize(e) {
662
+ if (e < 1)
663
+ throw new Error("Max queue size must be at least 1");
664
+ for (this.maxQueueSize = e, this.logger.debug(`Max queue size set to ${e}`); this.queue.length > this.maxQueueSize; )
665
+ this.queue.shift();
666
+ }
667
+ }, $t = class {
668
+ constructor(e, t, n, r) {
669
+ this.ws = null, this.eventQueue = [], this.connectionState = "disconnected", this.lastEmittedState = "disconnected", this.reconnectTimer = null, this.heartbeatTimer = null, this.connectionTimeoutTimer = null, this.stateChangeTimer = null, this.pendingAcks = /* @__PURE__ */ new Map(), this.config = e, this.logger = n, this.eventEmitter = r, this.reconnectionStrategy = new Et(t, n), this.messageQueue = new kt(n);
670
+ }
671
+ /**
672
+ * Update configuration
673
+ */
674
+ updateConfig(e) {
675
+ this.config = e;
676
+ }
677
+ /**
678
+ * Connect to WebSocket server
679
+ */
680
+ async connect(e) {
681
+ if (this.ws?.readyState === WebSocket.OPEN) {
682
+ this.logger.warn("WebSocket is already connected");
683
+ return;
684
+ }
685
+ if (this.ws?.readyState === WebSocket.CONNECTING) {
686
+ this.logger.warn("WebSocket is already connecting");
687
+ return;
688
+ }
689
+ return this.updateConnectionState(
690
+ "connecting"
691
+ /* CONNECTING */
692
+ ), this.updateConnectionState(
693
+ "connecting"
694
+ /* CONNECTING */
695
+ ), new Promise((t, n) => {
696
+ try {
697
+ e && (this.username = e);
698
+ let r = this.config.url;
699
+ if (this.username) {
700
+ const o = r.includes("?") ? "&" : "?";
701
+ r = `${r}${o}username=${encodeURIComponent(this.username)}`;
702
+ }
703
+ this.ws = new WebSocket(r, this.config.protocols), this.setupEventHandlers(t, n), this.setupConnectionTimeout(n);
704
+ } catch (r) {
705
+ this.logger.error("Failed to create WebSocket connection:", r), this.handleConnectionError(r), n(r);
706
+ }
707
+ });
708
+ }
709
+ /**
710
+ * Disconnect from WebSocket server
711
+ */
712
+ disconnect() {
713
+ this.logger.info("Disconnecting WebSocket"), this.updateConnectionState(
714
+ "disconnecting"
715
+ /* DISCONNECTING */
716
+ ), this.clearTimers(), this.reconnectionStrategy.reset(), this.ws && (this.ws.close(1e3, "Client disconnect"), this.ws = null), this.updateConnectionState(
717
+ "disconnected"
718
+ /* DISCONNECTED */
719
+ );
720
+ }
721
+ /**
722
+ * Send a raw event through WebSocket
723
+ */
724
+ async sendEvent(e, t) {
725
+ if (this.connectionState !== "connected") {
726
+ this.logger.warn("WebSocket not connected, queuing event"), this.eventQueue.push({ event: e, data: t });
727
+ return;
728
+ }
729
+ try {
730
+ const n = JSON.stringify({ event: e, data: t });
731
+ this.ws?.send(n), this.logger.debug(`Event sent: ${e}`, t);
732
+ } catch (n) {
733
+ throw this.logger.error(`Failed to send event ${e}:`, n), n;
734
+ }
735
+ }
736
+ /**
737
+ * Send a message through WebSocket
738
+ */
739
+ async send(e, t = !0, n = 5e3) {
740
+ if (this.connectionState !== "connected") {
741
+ this.logger.warn("WebSocket not connected, queuing message"), this.messageQueue.enqueue(e);
742
+ return;
743
+ }
744
+ try {
745
+ const r = {
746
+ roomId: e.metadata?.roomId || "general",
747
+ // Default to general if not specified
748
+ message: e.content,
749
+ username: e.sender === "user" ? e.metadata?.username : void 0
750
+ };
751
+ return await this.sendEvent("sendMessage", r), this.eventEmitter.emit("messageSent", {
752
+ message: e,
753
+ timestamp: Date.now()
754
+ }), {
755
+ ackId: "simulated_" + Date.now(),
756
+ messageId: e.id,
757
+ status: "received",
758
+ timestamp: Date.now()
759
+ };
760
+ } catch (r) {
761
+ throw this.logger.error("Failed to send message:", r), this.messageQueue.enqueue(e), r;
762
+ }
763
+ }
764
+ /**
765
+ * Join a room
766
+ */
767
+ async joinRoom(e) {
768
+ this.currentRoom = e, this.logger.info(`Joining room: ${e}`), await this.sendEvent("joinRoom", { roomId: e });
769
+ }
770
+ /**
771
+ * Leave a room
772
+ */
773
+ async leaveRoom(e) {
774
+ await this.sendEvent("leaveRoom", { roomId: e });
775
+ }
776
+ /**
777
+ * Get room info
778
+ */
779
+ async getRoomInfo(e) {
780
+ await this.sendEvent("getRoomInfo", { roomId: e });
781
+ }
782
+ /**
783
+ * Join a specific conversation to receive its stream
784
+ */
785
+ async sendJoinConversation(e) {
786
+ this.logger.info(`Joining conversation stream: ${e}`), await this.sendEvent("joinConversation", { conversationId: e });
787
+ }
788
+ /**
789
+ * Leave a specific conversation stream
790
+ */
791
+ async sendLeaveConversation(e) {
792
+ this.logger.info(`Leaving conversation stream: ${e}`), await this.sendEvent("leaveConversation", { conversationId: e });
793
+ }
794
+ /**
795
+ * Get current connection state
796
+ */
797
+ getConnectionState() {
798
+ return this.connectionState;
799
+ }
800
+ /**
801
+ * Check if connected
802
+ */
803
+ isConnected() {
804
+ return this.connectionState === "connected";
805
+ }
806
+ /**
807
+ * Get message queue
808
+ */
809
+ getMessageQueue() {
810
+ return this.messageQueue;
811
+ }
812
+ /**
813
+ * Setup WebSocket event handlers
814
+ */
815
+ setupEventHandlers(e, t) {
816
+ this.ws && (this.ws.onopen = () => {
817
+ this.logger.info("WebSocket connected"), this.clearConnectionTimeout(), this.updateConnectionState(
818
+ "connected"
819
+ /* CONNECTED */
820
+ ), this.reconnectionStrategy.reset(), this.startHeartbeat(), this.reconnectionStrategy.reset(), this.startHeartbeat(), this.currentRoom && (this.logger.info(`Re-joining room: ${this.currentRoom}`), this.sendEvent("joinRoom", { roomId: this.currentRoom }).catch((n) => {
821
+ this.logger.error(`Failed to re-join room ${this.currentRoom}:`, n);
822
+ })), this.flushMessageQueue(), e && e();
823
+ }, this.ws.onmessage = (n) => {
824
+ this.handleMessage(n.data);
825
+ }, this.ws.onerror = (n) => {
826
+ this.logger.error("WebSocket error:", n);
827
+ const r = new Error("WebSocket error");
828
+ this.eventEmitter.emit("error", {
829
+ error: r,
830
+ timestamp: Date.now(),
831
+ context: "websocket"
832
+ }), this.connectionState === "connecting" && t && t(r);
833
+ }, this.ws.onclose = (n) => {
834
+ this.logger.info(`WebSocket closed: ${n.code} - ${n.reason}`), this.stopHeartbeat(), this.updateConnectionState(
835
+ "disconnected"
836
+ /* DISCONNECTED */
837
+ ), n.code !== 1e3 && this.reconnectionStrategy.shouldReconnect() && this.attemptReconnection();
838
+ });
839
+ }
840
+ /**
841
+ * Handle incoming WebSocket message
842
+ */
843
+ handleMessage(e) {
844
+ try {
845
+ const t = JSON.parse(e), { event: n, data: r } = t;
846
+ switch (this.logger.debug(`Received event: ${n}`, r), n) {
847
+ case "pong":
848
+ this.logger.debug("Heartbeat pong received");
849
+ break;
850
+ case "newMessage":
851
+ const o = {
852
+ id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
853
+ type: "text",
854
+ // Default to text
855
+ content: r.message,
856
+ sender: "user",
857
+ // Or 'other'
858
+ timestamp: new Date(r.timestamp).getTime(),
859
+ status: "delivered",
860
+ metadata: {
861
+ roomId: r.roomId,
862
+ username: r.username
863
+ }
864
+ };
865
+ this.eventEmitter.emit("message", {
866
+ message: o,
867
+ timestamp: Date.now()
868
+ });
869
+ break;
870
+ case "joinedRoom":
871
+ this.eventEmitter.emit("joinedRoom", r);
872
+ break;
873
+ case "userJoined":
874
+ this.eventEmitter.emit("userJoined", r);
875
+ break;
876
+ case "leftRoom":
877
+ this.eventEmitter.emit("leftRoom", r);
878
+ break;
879
+ case "userLeft":
880
+ this.eventEmitter.emit("userLeft", r);
881
+ break;
882
+ case "roomInfo":
883
+ this.eventEmitter.emit("roomInfo", r);
884
+ break;
885
+ case "error":
886
+ this.eventEmitter.emit("error", {
887
+ error: new Error(r.message),
888
+ timestamp: Date.now(),
889
+ context: "server_error"
890
+ });
891
+ break;
892
+ case "agentEvent":
893
+ this.eventEmitter.emit("agentEvent", {
894
+ ...r,
895
+ conversationId: t.conversationId
896
+ });
897
+ break;
898
+ default:
899
+ this.logger.warn(`Unknown event received: ${n}`);
900
+ }
901
+ } catch (t) {
902
+ this.logger.error("Failed to parse message:", t), this.eventEmitter.emit("error", {
903
+ error: t,
904
+ timestamp: Date.now(),
905
+ context: "message_parsing"
906
+ });
907
+ }
908
+ }
909
+ /**
910
+ * Handle message acknowledgement
911
+ */
912
+ // private handleAcknowledgement(ack: MessageAcknowledgement): void {
913
+ // const pending = this.pendingAcks.get(ack.ackId);
914
+ // if (pending) {
915
+ // clearTimeout(pending.timeout);
916
+ // pending.resolve(ack);
917
+ // this.pendingAcks.delete(ack.ackId);
918
+ // this.eventEmitter.emit('acknowledgement', {
919
+ // acknowledgement: ack,
920
+ // timestamp: Date.now(),
921
+ // });
922
+ // // Remove from queue if it was queued
923
+ // if (ack.messageId) {
924
+ // this.messageQueue.remove(ack.messageId);
925
+ // }
926
+ // }
927
+ // }
928
+ /**
929
+ * Wait for message acknowledgement
930
+ */
931
+ // private waitForAcknowledgement(ackId: string, timeout: number): Promise<MessageAcknowledgement> {
932
+ // return new Promise((resolve, reject) => {
933
+ // const timeoutTimer = setTimeout(() => {
934
+ // this.pendingAcks.delete(ackId);
935
+ // reject(new Error(`Acknowledgement timeout for ${ackId}`));
936
+ // }, timeout);
937
+ // this.pendingAcks.set(ackId, {
938
+ // resolve,
939
+ // reject,
940
+ // timeout: timeoutTimer,
941
+ // });
942
+ // });
943
+ // }
944
+ /**
945
+ * Start heartbeat mechanism
946
+ */
947
+ startHeartbeat() {
948
+ const e = this.config.heartbeatInterval ?? 3e4;
949
+ this.heartbeatTimer = setInterval(() => {
950
+ if (this.ws?.readyState === WebSocket.OPEN)
951
+ try {
952
+ this.sendEvent("ping", {}), this.logger.debug("Heartbeat ping sent");
953
+ } catch (t) {
954
+ this.logger.error("Failed to send heartbeat:", t);
955
+ }
956
+ }, e), this.logger.debug(`Heartbeat started with interval: ${e}ms`);
957
+ }
958
+ /**
959
+ * Stop heartbeat mechanism
960
+ */
961
+ stopHeartbeat() {
962
+ this.heartbeatTimer && (clearInterval(this.heartbeatTimer), this.heartbeatTimer = null, this.logger.debug("Heartbeat stopped"));
963
+ }
964
+ /**
965
+ * Setup connection timeout
966
+ */
967
+ setupConnectionTimeout(e) {
968
+ const t = this.config.connectionTimeout ?? 1e4;
969
+ this.connectionTimeoutTimer = setTimeout(() => {
970
+ if (this.connectionState === "connecting") {
971
+ this.logger.error("Connection timeout"), this.ws?.close();
972
+ const n = new Error("Connection timeout");
973
+ this.handleConnectionError(n), e && e(n);
974
+ }
975
+ }, t);
976
+ }
977
+ /**
978
+ * Clear connection timeout
979
+ */
980
+ clearConnectionTimeout() {
981
+ this.connectionTimeoutTimer && (clearTimeout(this.connectionTimeoutTimer), this.connectionTimeoutTimer = null);
982
+ }
983
+ /**
984
+ * Attempt reconnection
985
+ */
986
+ attemptReconnection() {
987
+ if (!this.reconnectionStrategy.shouldReconnect()) {
988
+ this.logger.error("Reconnection failed: max attempts reached"), this.updateConnectionState(
989
+ "failed"
990
+ /* FAILED */
991
+ ), this.eventEmitter.emit("reconnectFailed", {
992
+ state: "failed",
993
+ timestamp: Date.now(),
994
+ attempt: this.reconnectionStrategy.getCurrentAttempt()
995
+ });
996
+ return;
997
+ }
998
+ this.updateConnectionState(
999
+ "reconnecting"
1000
+ /* RECONNECTING */
1001
+ ), this.reconnectionStrategy.incrementAttempt();
1002
+ const e = this.reconnectionStrategy.getNextDelay();
1003
+ this.eventEmitter.emit("reconnecting", {
1004
+ state: "reconnecting",
1005
+ timestamp: Date.now(),
1006
+ attempt: this.reconnectionStrategy.getCurrentAttempt()
1007
+ }), this.reconnectTimer = setTimeout(() => {
1008
+ this.logger.info("Attempting to reconnect..."), this.connect().catch((t) => {
1009
+ this.logger.error("Reconnection attempt failed:", t);
1010
+ });
1011
+ }, e);
1012
+ }
1013
+ /**
1014
+ * Handle connection error
1015
+ */
1016
+ handleConnectionError(e) {
1017
+ this.eventEmitter.emit("error", {
1018
+ error: e,
1019
+ timestamp: Date.now(),
1020
+ context: "connection"
1021
+ }), this.reconnectionStrategy.shouldReconnect() ? this.attemptReconnection() : this.updateConnectionState(
1022
+ "failed"
1023
+ /* FAILED */
1024
+ );
1025
+ }
1026
+ /**
1027
+ * Flush queued messages
1028
+ */
1029
+ flushMessageQueue() {
1030
+ if (this.eventQueue.length > 0) {
1031
+ this.logger.info(`Flushing ${this.eventQueue.length} queued events`);
1032
+ const t = [...this.eventQueue];
1033
+ this.eventQueue = [], t.forEach(({ event: n, data: r }) => {
1034
+ this.sendEvent(n, r).catch((o) => {
1035
+ this.logger.error(`Failed to send queued event ${n}:`, o);
1036
+ });
1037
+ });
1038
+ }
1039
+ const e = this.messageQueue.dequeueAll();
1040
+ e.length > 0 && (this.logger.info(`Flushing ${e.length} queued messages`), e.forEach((t) => {
1041
+ this.send(t, !1).catch((n) => {
1042
+ this.logger.error(`Failed to send queued message ${t.id}:`, n), this.messageQueue.markAsFailed(t.id);
1043
+ });
1044
+ }));
1045
+ }
1046
+ /**
1047
+ * Update connection state
1048
+ */
1049
+ updateConnectionState(e) {
1050
+ const t = this.connectionState;
1051
+ this.connectionState = e, t !== e && this.logger.info(`Connection state changed: ${t} -> ${e}`);
1052
+ const n = this.config.disconnectGracePeriod ?? 0;
1053
+ e === "connected" ? (this.stateChangeTimer && (clearTimeout(this.stateChangeTimer), this.stateChangeTimer = null, this.logger.debug("Reconnected within grace period, suppressing disconnection event")), this.lastEmittedState !== "connected" && this.emitConnectionChange(e)) : this.lastEmittedState === "connected" && n > 0 ? this.stateChangeTimer || (this.logger.debug(`Starting disconnection grace period (${n}ms)`), this.stateChangeTimer = setTimeout(() => {
1054
+ this.stateChangeTimer = null, this.emitConnectionChange(this.connectionState);
1055
+ }, n)) : this.emitConnectionChange(e);
1056
+ }
1057
+ /**
1058
+ * Emit connection change event
1059
+ */
1060
+ emitConnectionChange(e) {
1061
+ this.lastEmittedState !== e && (this.lastEmittedState = e, this.eventEmitter.emit("connection", {
1062
+ state: e,
1063
+ timestamp: Date.now()
1064
+ }));
1065
+ }
1066
+ /**
1067
+ * Clear all timers
1068
+ */
1069
+ clearTimers() {
1070
+ this.reconnectTimer && (clearTimeout(this.reconnectTimer), this.reconnectTimer = null), this.heartbeatTimer && (clearInterval(this.heartbeatTimer), this.heartbeatTimer = null), this.connectionTimeoutTimer && (clearTimeout(this.connectionTimeoutTimer), this.connectionTimeoutTimer = null), this.pendingAcks.forEach((e) => {
1071
+ clearTimeout(e.timeout), e.reject(new Error("Connection closed"));
1072
+ }), this.pendingAcks.clear();
1073
+ }
1074
+ }, Le = () => {
1075
+ const e = "echo_device_hash";
1076
+ try {
1077
+ let t = localStorage.getItem(e);
1078
+ return t || (t = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (n) => {
1079
+ const r = Math.random() * 16 | 0;
1080
+ return (n === "x" ? r : r & 3 | 8).toString(16);
1081
+ }), localStorage.setItem(e, t)), t;
1082
+ } catch {
1083
+ return "unknown-device-" + Date.now();
1084
+ }
1085
+ }, it = class {
1086
+ constructor(e = {}, t) {
1087
+ this.config = {
1088
+ retries: 3,
1089
+ backoff: 1e3,
1090
+ ...e
1091
+ }, this.logger = t;
1092
+ }
1093
+ async get(e, t = {}) {
1094
+ return this.request(e, { method: "GET", headers: t });
1095
+ }
1096
+ async post(e, t, n = {}) {
1097
+ return this.request(e, {
1098
+ method: "POST",
1099
+ headers: { "Content-Type": "application/json", ...n },
1100
+ body: JSON.stringify(t)
1101
+ });
1102
+ }
1103
+ async request(e, t, n = 0) {
1104
+ const r = {
1105
+ ...this.config.headers,
1106
+ ...t.headers
1107
+ };
1108
+ try {
1109
+ const o = await fetch(e, { ...t, headers: r });
1110
+ if (!o.ok) {
1111
+ if (o.status >= 500 && n < (this.config.retries ?? 3))
1112
+ return this.logger?.warn(`Request failed with status ${o.status}. Retrying... (${n + 1}/${this.config.retries})`), await this.delay(this.getErrorDelay(n)), this.request(e, t, n + 1);
1113
+ const i = await o.text();
1114
+ throw new Error(`HTTP Error ${o.status}: ${i}`);
1115
+ }
1116
+ return o.json();
1117
+ } catch (o) {
1118
+ if (n < (this.config.retries ?? 3))
1119
+ return this.logger?.warn(`Request failed with error: ${o}. Retrying... (${n + 1}/${this.config.retries})`), await this.delay(this.getErrorDelay(n)), this.request(e, t, n + 1);
1120
+ throw o;
1121
+ }
1122
+ }
1123
+ getErrorDelay(e) {
1124
+ return (this.config.backoff ?? 1e3) * Math.pow(2, e);
1125
+ }
1126
+ delay(e) {
1127
+ return new Promise((t) => setTimeout(t, e));
1128
+ }
1129
+ };
1130
+ class Tt {
1131
+ constructor(t = "http://localhost:3000") {
1132
+ this.baseUrl = t, this.client = new it({
1133
+ retries: 3,
1134
+ backoff: 1e3
1135
+ }, new rt({ prefix: "ConfigService" }));
1136
+ }
1137
+ async fetchConfig(t, n, r) {
1138
+ const o = `${this.baseUrl}/${t}/api/v1/client/configuration`, i = {
1139
+ "x-api-key": n
1140
+ };
1141
+ r && (i["x-external-id"] = r);
1142
+ try {
1143
+ const s = await this.client.get(o, i);
1144
+ if (s.success && s.data)
1145
+ return s.data.finger_print && localStorage.setItem("echo_finger_print", s.data.finger_print), s.data;
1146
+ throw new Error("Invalid configuration response");
1147
+ } catch (s) {
1148
+ throw console.error("Failed to fetch configuration:", s), s;
1149
+ }
1150
+ }
1151
+ }
1152
+ class It {
1153
+ constructor(t = "http://localhost:3000") {
1154
+ this.baseUrl = t, this.httpClient = new it({
1155
+ // baseURL is not supported in HttpClientConfig
1156
+ });
1157
+ }
1158
+ async getConversations(t, n, r) {
1159
+ const o = {
1160
+ "x-api-key": n
1161
+ };
1162
+ r && (o["x-external-id"] = r);
1163
+ const i = `${this.baseUrl}/${t}/api/v1/client/conversations`;
1164
+ try {
1165
+ return (await this.httpClient.get(i, o)).data;
1166
+ } catch (s) {
1167
+ throw console.error("Failed to get conversations", s), s;
1168
+ }
1169
+ }
1170
+ async createConversation(t, n, r, o, i) {
1171
+ const s = {
1172
+ "x-api-key": n,
1173
+ "Content-Type": "application/json"
1174
+ };
1175
+ o && (s["x-external-id"] = o), i && (s["x-device-hash"] = i);
1176
+ const h = `${this.baseUrl}/${t}/api/v1/client/conversations/new`, u = { prompt: r };
1177
+ try {
1178
+ return (await this.httpClient.post(h, u, s)).data;
1179
+ } catch (l) {
1180
+ throw console.error("Failed to create conversation", l), l;
1181
+ }
1182
+ }
1183
+ async getMessages(t, n, r, o) {
1184
+ const i = {
1185
+ "x-api-key": n
1186
+ };
1187
+ o && (i["x-external-id"] = o);
1188
+ const s = `${this.baseUrl}/${t}/api/v1/client/conversations/${r}/messages`;
1189
+ try {
1190
+ return (await this.httpClient.get(s, i)).data;
1191
+ } catch (h) {
1192
+ throw console.error("Failed to get messages", h), h;
1193
+ }
1194
+ }
1195
+ }
1196
+ const Fe = 5e3, ot = pt(null), Nt = ({ children: e, sdkConfig: t }) => {
1197
+ const [n, r] = N(!1), [o, i] = N("disconnected"), [s, h] = N(!1), [u, l] = N(!0), [_, a] = N(null), [g, d] = N([]), [C, I] = N([]), [w, p] = N(null), [f, A] = N(null), [P, M] = N(!1), [L, W] = N(null), [O, F] = N({}), E = Y(null), v = Y(null), q = Y(null), K = Y(/* @__PURE__ */ new Map()), B = Y(null);
1198
+ if (v.current || (v.current = new rt({ prefix: "EchoSDK" })), !q.current) {
1199
+ const m = "http://localhost:3000";
1200
+ q.current = new It(m);
1201
+ }
1202
+ et(() => {
1203
+ const m = async () => {
1204
+ l(!0), a(null);
1205
+ try {
1206
+ const D = await new Tt().fetchConfig(
1207
+ t.companyUrl,
1208
+ t.apiKey,
1209
+ t.externalId
1210
+ );
1211
+ A(D);
1212
+ const H = await q.current.getConversations(
1213
+ t.companyUrl,
1214
+ t.apiKey,
1215
+ t.externalId
1216
+ );
1217
+ I(H), h(!0), await ct(D, t);
1218
+ } catch (x) {
1219
+ v.current?.error("Initialization failed:", x), a(x.message || "Failed to initialize SDK");
1220
+ } finally {
1221
+ l(!1);
1222
+ }
1223
+ };
1224
+ return t.apiKey && t.companyUrl ? m() : (a("Missing required configuration (apiKey or companyUrl)"), l(!1)), () => {
1225
+ E.current?.disconnect();
1226
+ };
1227
+ }, [t.apiKey, t.companyUrl, t.externalId]);
1228
+ const ct = async (m, x) => {
1229
+ const D = m.finger_print || localStorage.getItem("echo_finger_print") || Le(), H = "ws://localhost:3000", k = new URLSearchParams();
1230
+ k.append("api_key", x.apiKey), k.append("device_hash", D), x.externalId && k.append("external_id", x.externalId), x.authToken && k.append("x-auth-token", x.authToken);
1231
+ const V = `${H}?${k.toString()}`, U = new Ct(v.current), _e = {
1232
+ url: V,
1233
+ heartbeatInterval: 3e4,
1234
+ connectionTimeout: 1e4
1235
+ }, j = {
1236
+ maxAttempts: 1 / 0,
1237
+ baseDelay: 1e3,
1238
+ maxDelay: 3e4
1239
+ }, ee = new $t(
1240
+ _e,
1241
+ j,
1242
+ v.current,
1243
+ U
1244
+ );
1245
+ E.current = ee, U.on("connection", (y) => {
1246
+ r(y.state === "connected"), i(y.state), console.log("connection triggered custom", y.state, B.current), y.state === "connected" && B.current && (v.current?.info(`Reconnected. Re-joining conversation: ${B.current}`), setTimeout(() => {
1247
+ B.current && ee.sendJoinConversation(B.current);
1248
+ }, 1e3));
1249
+ }), U.on("message", (y) => {
1250
+ d(($) => {
1251
+ if ($.some((z) => z.id === y.message.id)) return $;
1252
+ if (y.message.sender === "user") {
1253
+ const z = $.findIndex(
1254
+ (R) => R.sender === "user" && R.status === G.PENDING && R.content === y.message.content
1255
+ );
1256
+ if (z !== -1) {
1257
+ const R = [...$];
1258
+ return R[z] = y.message, R;
1259
+ }
1260
+ }
1261
+ return [...$, y.message];
1262
+ });
1263
+ }), U.on("messageSent", (y) => {
1264
+ d(($) => {
1265
+ if ($.some((R) => R.id === y.message.id)) return $;
1266
+ const z = $.findIndex(
1267
+ (R) => R.sender === "user" && R.status === G.PENDING && R.content === y.message.content
1268
+ );
1269
+ if (z !== -1) {
1270
+ const R = [...$];
1271
+ return R[z] = y.message, R;
1272
+ }
1273
+ return [...$, y.message];
1274
+ });
1275
+ }), U.on("agentEvent", (y) => {
1276
+ if (y.type === "first_response")
1277
+ M(!0), W(y.runId), F(($) => ({ ...$, [y.runId]: [] }));
1278
+ else if (["thought", "action_start", "action_end"].includes(y.type))
1279
+ M(!0), W(($) => $ || y.runId), F(($) => ({
1280
+ ...$,
1281
+ [y.runId]: [...$[y.runId] || [], y]
1282
+ }));
1283
+ else if (y.type === "final_response" && (M(!1), W(null), y.content)) {
1284
+ const $ = {
1285
+ id: y.messageId || Date.now().toString(),
1286
+ content: y.content,
1287
+ sender: "bot",
1288
+ // 'bot' matches MessageSender
1289
+ type: te.TEXT,
1290
+ status: G.DELIVERED,
1291
+ timestamp: Date.now(),
1292
+ metadata: {
1293
+ roomId: y.conversationId,
1294
+ runId: y.runId
1295
+ }
1296
+ };
1297
+ d((z) => [...z, $]);
1298
+ }
1299
+ }), await ee.connect();
1300
+ }, Ce = async (m) => {
1301
+ const x = w;
1302
+ if (K.current.has(m) && (clearTimeout(K.current.get(m)), K.current.delete(m), v.current?.info(`Cancelled pending leave for conversation: ${m}`)), x && x !== m) {
1303
+ const D = setTimeout(() => {
1304
+ E.current && E.current.sendLeaveConversation(x).catch((H) => v.current?.error(`Failed to leave conversation ${x}`, H)), K.current.delete(x);
1305
+ }, Fe);
1306
+ K.current.set(x, D);
1307
+ }
1308
+ l(!0);
1309
+ try {
1310
+ const H = (await q.current.getMessages(
1311
+ t.companyUrl,
1312
+ t.apiKey,
1313
+ m,
1314
+ t.externalId
1315
+ )).map((k) => ({
1316
+ id: k.id,
1317
+ content: k.content,
1318
+ sender: k.role === "user" ? "user" : "bot",
1319
+ type: te.TEXT,
1320
+ status: G.DELIVERED,
1321
+ timestamp: new Date(k.created_at).getTime(),
1322
+ metadata: { roomId: m }
1323
+ }));
1324
+ d((k) => {
1325
+ const V = k.filter((j) => j.metadata?.roomId === m), U = new Set(H.map((j) => j.id)), _e = V.filter((j) => !U.has(j.id));
1326
+ return [...H, ..._e].sort((j, ee) => j.timestamp - ee.timestamp);
1327
+ }), p(m), B.current = m, E.current && await E.current.sendJoinConversation(m);
1328
+ } catch (D) {
1329
+ v.current?.error("Failed to load conversation", D);
1330
+ } finally {
1331
+ l(!1);
1332
+ }
1333
+ }, lt = () => {
1334
+ const m = w;
1335
+ if (m) {
1336
+ const x = setTimeout(() => {
1337
+ E.current && E.current.sendLeaveConversation(m).catch((D) => v.current?.error(`Failed to leave conversation ${m}`, D)), K.current.delete(m);
1338
+ }, Fe);
1339
+ K.current.set(m, x);
1340
+ }
1341
+ p(null), B.current = null, d([]), M(!1), W(null), F({});
1342
+ }, Ee = async (m) => {
1343
+ const x = Date.now().toString(), D = {
1344
+ id: x,
1345
+ content: m,
1346
+ sender: "user",
1347
+ type: te.TEXT,
1348
+ status: G.PENDING,
1349
+ timestamp: Date.now(),
1350
+ metadata: {}
1351
+ };
1352
+ d([D]), M(!0);
1353
+ try {
1354
+ const H = f?.finger_print || localStorage.getItem("echo_finger_print") || Le(), k = await q.current?.createConversation(
1355
+ t.companyUrl,
1356
+ t.apiKey,
1357
+ m,
1358
+ t.externalId,
1359
+ H
1360
+ );
1361
+ if (!k)
1362
+ throw new Error("Failed to create conversation");
1363
+ I((V) => [k, ...V]), p(k.id), B.current = k.id, d((V) => V.filter(
1364
+ (U) => U.id === x || U.metadata?.roomId === k.id
1365
+ )), E.current && await E.current.sendJoinConversation(k.id), await Ce(k.id);
1366
+ } catch (H) {
1367
+ v.current?.error("Failed to create conversation", H), a("Failed to start new conversation");
1368
+ } finally {
1369
+ l(!1);
1370
+ }
1371
+ }, ht = async (m) => {
1372
+ if (!w) {
1373
+ await Ee(m);
1374
+ return;
1375
+ }
1376
+ if (!E.current) return;
1377
+ const x = {
1378
+ id: Date.now().toString(),
1379
+ content: m,
1380
+ sender: "user",
1381
+ type: te.TEXT,
1382
+ status: G.PENDING,
1383
+ timestamp: Date.now(),
1384
+ metadata: {
1385
+ roomId: w
1386
+ }
1387
+ };
1388
+ d((D) => [...D, x]), await E.current.sendEvent("sendMessage", {
1389
+ conversationId: w,
1390
+ message: m
1391
+ });
1392
+ };
1393
+ return /* @__PURE__ */ c(ot.Provider, { value: {
1394
+ isConnected: n,
1395
+ connectionState: o,
1396
+ isInitialized: s,
1397
+ isLoading: u,
1398
+ error: _,
1399
+ config: f,
1400
+ messages: g,
1401
+ conversations: C,
1402
+ activeConversationId: w,
1403
+ isStreaming: P,
1404
+ activeRunId: L,
1405
+ streamedThoughts: O,
1406
+ sendMessage: ht,
1407
+ joinRoom: async (m) => {
1408
+ await E.current?.joinRoom(m);
1409
+ },
1410
+ // Legacy?
1411
+ leaveRoom: async (m) => {
1412
+ await E.current?.leaveRoom(m);
1413
+ },
1414
+ // Legacy?
1415
+ loadConversation: Ce,
1416
+ createNewChat: lt,
1417
+ startNewConversation: Ee
1418
+ }, children: e });
1419
+ }, st = () => {
1420
+ const e = bt(ot);
1421
+ if (!e)
1422
+ throw new Error("useChat must be used within a ChatProvider");
1423
+ return e;
1424
+ }, Dt = () => /* @__PURE__ */ c("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", children: [
1425
+ /* @__PURE__ */ c("circle", { cx: "12", cy: "12", r: "1" }),
1426
+ /* @__PURE__ */ c("circle", { cx: "19", cy: "12", r: "1" }),
1427
+ /* @__PURE__ */ c("circle", { cx: "5", cy: "12", r: "1" })
1428
+ ] }), at = ({ size: e = 20 }) => /* @__PURE__ */ c("svg", { width: e, height: e, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", children: [
1429
+ /* @__PURE__ */ c("line", { x1: "18", y1: "6", x2: "6", y2: "18" }),
1430
+ /* @__PURE__ */ c("line", { x1: "6", y1: "6", x2: "18", y2: "18" })
1431
+ ] }), Rt = () => /* @__PURE__ */ c("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", children: [
1432
+ /* @__PURE__ */ c("line", { x1: "22", y1: "2", x2: "11", y2: "13" }),
1433
+ /* @__PURE__ */ c("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
1434
+ ] }), At = () => /* @__PURE__ */ c("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", children: /* @__PURE__ */ c("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }) }), Mt = () => /* @__PURE__ */ c("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", children: [
1435
+ /* @__PURE__ */ c("path", { d: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" }),
1436
+ /* @__PURE__ */ c("polyline", { points: "14 2 14 8 20 8" }),
1437
+ /* @__PURE__ */ c("line", { x1: "12", y1: "18", x2: "12", y2: "12" }),
1438
+ /* @__PURE__ */ c("line", { x1: "9", y1: "15", x2: "15", y2: "15" })
1439
+ ] }), qt = () => /* @__PURE__ */ c("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", children: [
1440
+ /* @__PURE__ */ c("circle", { cx: "12", cy: "12", r: "10" }),
1441
+ /* @__PURE__ */ c("path", { d: "M8 14s1.5 2 4 2 4-2 4-2" }),
1442
+ /* @__PURE__ */ c("line", { x1: "9", y1: "9", x2: "9.01", y2: "9" }),
1443
+ /* @__PURE__ */ c("line", { x1: "15", y1: "9", x2: "15.01", y2: "9" })
1444
+ ] }), Ht = () => /* @__PURE__ */ c("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", children: [
1445
+ /* @__PURE__ */ c("line", { x1: "19", y1: "12", x2: "5", y2: "12" }),
1446
+ /* @__PURE__ */ c("polyline", { points: "12 19 5 12 12 5" })
1447
+ ] }), Pt = ({ title: e = "Annie Smith", greeting: t, connectionStatus: n = "connected", onToggleSidebar: r, onCloseChat: o, showBackButton: i, onBack: s }) => /* @__PURE__ */ c("div", { class: "echo-header", children: [
1448
+ i && /* @__PURE__ */ c("button", { className: "echo-back-btn", onClick: s, style: "background: none; border: none; color: white; cursor: pointer; opacity: 0.9; padding: 4px; margin-right: 2px;", children: /* @__PURE__ */ c(Ht, {}) }),
1449
+ /* @__PURE__ */ c("div", { class: "echo-avatar", children: [
1450
+ /* @__PURE__ */ c("img", { src: "https://api.dicebear.com/7.x/avataaars/svg?seed=Annie", alt: "Avatar", style: "width: 100%; height: 100%; border-radius: 50%;" }),
1451
+ /* @__PURE__ */ c("div", { style: {
1452
+ position: "absolute",
1453
+ bottom: "0",
1454
+ right: "0",
1455
+ width: "10px",
1456
+ height: "10px",
1457
+ borderRadius: "50%",
1458
+ backgroundColor: ((u) => {
1459
+ switch (u) {
1460
+ case "connected":
1461
+ return "#10b981";
1462
+ // green
1463
+ case "reconnecting":
1464
+ return "#f59e0b";
1465
+ // amber
1466
+ case "disconnected":
1467
+ return "#ef4444";
1468
+ // red
1469
+ default:
1470
+ return "#9ca3af";
1471
+ }
1472
+ })(n),
1473
+ border: "2px solid white"
1474
+ }, title: n })
1475
+ ] }),
1476
+ /* @__PURE__ */ c("div", { class: "echo-header-info", children: [
1477
+ /* @__PURE__ */ c("h3", { class: "echo-header-title", children: e }),
1478
+ !i && /* @__PURE__ */ c("p", { class: "echo-header-subtitle", children: t || "We typically reply in a few minute" })
1479
+ ] }),
1480
+ /* @__PURE__ */ c("button", { class: "echo-menu-btn", onClick: r, style: "background: none; border: none; color: white; cursor: pointer; opacity: 0.8; padding: 4px;", children: /* @__PURE__ */ c(Dt, {}) }),
1481
+ /* @__PURE__ */ c("button", { class: "echo-close-btn", onClick: o, style: "background: none; border: none; color: white; cursor: pointer; opacity: 0.8; margin-left: 8px;", children: /* @__PURE__ */ c(at, {}) })
1482
+ ] }), Ue = ({ events: e, isExpanded: t = !1 }) => {
1483
+ const [n, r] = N(t);
1484
+ return e.length === 0 ? null : /* @__PURE__ */ c("div", { className: "echo-thought-chain", children: [
1485
+ /* @__PURE__ */ c(
1486
+ "div",
1487
+ {
1488
+ className: "echo-thought-header",
1489
+ onClick: () => r(!n),
1490
+ role: "button",
1491
+ tabIndex: 0,
1492
+ children: [
1493
+ /* @__PURE__ */ c("span", { className: "echo-thought-icon", children: "🧠" }),
1494
+ /* @__PURE__ */ c("span", { className: "echo-thought-title", children: [
1495
+ "Thinking Process (",
1496
+ e.length,
1497
+ " steps)"
1498
+ ] }),
1499
+ /* @__PURE__ */ c("span", { className: `echo-thought-chevron ${n ? "expanded" : ""}`, children: "â–¼" })
1500
+ ]
1501
+ }
1502
+ ),
1503
+ n && /* @__PURE__ */ c("div", { className: "echo-thought-content", children: e.map((o, i) => /* @__PURE__ */ c("div", { className: `echo-thought-item ${o.type}`, children: [
1504
+ /* @__PURE__ */ c("div", { className: "echo-thought-type", children: Lt(o.type) }),
1505
+ /* @__PURE__ */ c("div", { className: "echo-thought-text", children: o.content })
1506
+ ] }, i)) })
1507
+ ] });
1508
+ }, Lt = (e) => {
1509
+ switch (e) {
1510
+ case "action_start":
1511
+ return "Starting Action";
1512
+ case "action_end":
1513
+ return "Action Completed";
1514
+ case "thought":
1515
+ return "Reasoning";
1516
+ case "error":
1517
+ return "Error";
1518
+ case "first_response":
1519
+ return "Started";
1520
+ default:
1521
+ return e;
1522
+ }
1523
+ }, Ft = ({ messages: e, isStreaming: t, activeRunId: n, streamedThoughts: r }) => {
1524
+ const o = Y(null), i = Y(null);
1525
+ return et(() => {
1526
+ i.current && i.current.scrollIntoView({ behavior: "smooth" });
1527
+ }, [e, t, r]), /* @__PURE__ */ c("div", { className: "echo-message-list", ref: o, children: [
1528
+ e.map((s) => /* @__PURE__ */ c("div", { className: `echo-message ${s.sender === "user" ? "user" : "bot"}`, children: [
1529
+ /* @__PURE__ */ c("div", { className: "echo-message-content", children: s.type === "text" ? s.content : /* @__PURE__ */ c("img", { src: s.content, alt: "sent image", className: "echo-message-image" }) }),
1530
+ /* @__PURE__ */ c("div", { className: "echo-message-time", children: new Date(s.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) }),
1531
+ s.metadata?.runId && r[s.metadata.runId] && /* @__PURE__ */ c(
1532
+ Ue,
1533
+ {
1534
+ events: r[s.metadata.runId],
1535
+ isExpanded: !1
1536
+ }
1537
+ )
1538
+ ] }, s.id)),
1539
+ t && /* @__PURE__ */ c("div", { className: "echo-message bot echo-streaming-container", children: [
1540
+ n && /* @__PURE__ */ c(Ue, { events: r[n] || [], isExpanded: !1 }),
1541
+ /* @__PURE__ */ c("div", { className: "echo-typing-indicator", children: [
1542
+ /* @__PURE__ */ c("span", { children: "." }),
1543
+ /* @__PURE__ */ c("span", { children: "." }),
1544
+ /* @__PURE__ */ c("span", { children: "." })
1545
+ ] })
1546
+ ] }),
1547
+ /* @__PURE__ */ c("div", { ref: i })
1548
+ ] });
1549
+ }, Ut = ({ onSendMessage: e, isLoading: t }) => {
1550
+ const [n, r] = N(""), o = () => {
1551
+ n.trim() && !t && (e(n.trim()), r(""));
1552
+ };
1553
+ return /* @__PURE__ */ c("div", { class: "echo-input-area", children: [
1554
+ /* @__PURE__ */ c(
1555
+ "input",
1556
+ {
1557
+ type: "text",
1558
+ class: "echo-input",
1559
+ placeholder: "Type a Message...",
1560
+ value: n,
1561
+ onInput: (s) => r(s.currentTarget.value),
1562
+ onKeyPress: (s) => {
1563
+ s.key === "Enter" && !t && o();
1564
+ },
1565
+ disabled: t
1566
+ }
1567
+ ),
1568
+ /* @__PURE__ */ c("div", { style: "display: flex; gap: 8px; align-items: center;", children: [
1569
+ /* @__PURE__ */ c("button", { style: "background: none; border: none; cursor: pointer; color: #9ca3af; padding: 4px;", disabled: t, children: /* @__PURE__ */ c(Mt, {}) }),
1570
+ /* @__PURE__ */ c("button", { style: "background: none; border: none; cursor: pointer; color: #9ca3af; padding: 4px;", disabled: t, children: /* @__PURE__ */ c(qt, {}) }),
1571
+ /* @__PURE__ */ c("button", { class: "echo-send-btn", onClick: o, disabled: !n.trim() || t, children: /* @__PURE__ */ c(Rt, {}) })
1572
+ ] })
1573
+ ] });
1574
+ }, Wt = ({
1575
+ conversations: e,
1576
+ activeConversationId: t,
1577
+ onSelectConversation: n,
1578
+ onNewChat: r,
1579
+ isOpen: o
1580
+ }) => o ? /* @__PURE__ */ c("div", { className: "echo-sidebar", children: [
1581
+ /* @__PURE__ */ c("div", { className: "echo-sidebar-header", children: /* @__PURE__ */ c("button", { className: "echo-new-chat-btn", onClick: r, children: "+ New Chat" }) }),
1582
+ /* @__PURE__ */ c("div", { className: "echo-conversation-list", children: e.map((i) => /* @__PURE__ */ c(
1583
+ "div",
1584
+ {
1585
+ className: `echo-conversation-item ${t === i.id ? "active" : ""}`,
1586
+ onClick: () => n(i.id),
1587
+ role: "button",
1588
+ tabIndex: 0,
1589
+ children: [
1590
+ /* @__PURE__ */ c("div", { className: "echo-conversation-summary", children: i.summary || "New Conversation" }),
1591
+ /* @__PURE__ */ c("div", { className: "echo-conversation-date", children: (() => {
1592
+ const s = new Date(i.updated_at || i.created_at), h = /* @__PURE__ */ new Date();
1593
+ return s.getDate() === h.getDate() && s.getMonth() === h.getMonth() && s.getFullYear() === h.getFullYear() ? s.toLocaleTimeString(
1594
+ [],
1595
+ {
1596
+ year: "2-digit",
1597
+ month: "2-digit",
1598
+ day: "2-digit",
1599
+ hour: "2-digit",
1600
+ minute: "2-digit"
1601
+ }
1602
+ ) : s.toLocaleDateString();
1603
+ })() })
1604
+ ]
1605
+ },
1606
+ i.id
1607
+ )) })
1608
+ ] }) : null, jt = ({ config: e, onQuerySelect: t }) => {
1609
+ if (!e) return null;
1610
+ const { display_name: n, example_queries: r } = e, o = r ? r.slice(0, 3) : [];
1611
+ return /* @__PURE__ */ c("div", { className: "echo-home-view", children: [
1612
+ n && /* @__PURE__ */ c("h2", { className: "echo-home-greeting", children: [
1613
+ "Hi ",
1614
+ n,
1615
+ " 👋"
1616
+ ] }),
1617
+ o.length > 0 && /* @__PURE__ */ c("div", { className: "echo-query-list", children: o.map((i, s) => /* @__PURE__ */ c(
1618
+ "button",
1619
+ {
1620
+ className: "echo-query-chip",
1621
+ onClick: () => t(i),
1622
+ children: i
1623
+ },
1624
+ s
1625
+ )) })
1626
+ ] });
1627
+ }, zt = ({ isOpen: e, onClose: t, title: n }) => {
1628
+ const {
1629
+ messages: r,
1630
+ sendMessage: o,
1631
+ config: i,
1632
+ connectionState: s,
1633
+ conversations: h,
1634
+ activeConversationId: u,
1635
+ loadConversation: l,
1636
+ createNewChat: _,
1637
+ startNewConversation: a,
1638
+ isStreaming: g,
1639
+ activeRunId: d,
1640
+ streamedThoughts: C,
1641
+ isInitialized: I,
1642
+ isLoading: w,
1643
+ error: p
1644
+ } = st(), [f, A] = N(!1), P = async (v) => {
1645
+ await o(v);
1646
+ }, M = async (v) => {
1647
+ await l(v), A(!1);
1648
+ }, L = () => {
1649
+ _(), A(!1);
1650
+ }, W = (v) => {
1651
+ a(v);
1652
+ }, O = I && !w && r.length === 0, E = h.find((v) => v.id === u)?.summary || n || i?.brand_name || "Support";
1653
+ return /* @__PURE__ */ c("div", { className: `echo-chat-window ${e ? "open" : ""}`, children: [
1654
+ /* @__PURE__ */ c(
1655
+ Pt,
1656
+ {
1657
+ title: E,
1658
+ greeting: i?.greeting_message,
1659
+ connectionStatus: s,
1660
+ onToggleSidebar: () => A(!f),
1661
+ onCloseChat: t,
1662
+ showBackButton: !!u,
1663
+ onBack: L
1664
+ }
1665
+ ),
1666
+ /* @__PURE__ */ c("div", { className: "echo-chat-body-container", children: [
1667
+ /* @__PURE__ */ c("div", { className: `echo-sidebar-container ${f ? "open" : ""}`, children: /* @__PURE__ */ c(
1668
+ Wt,
1669
+ {
1670
+ conversations: h,
1671
+ activeConversationId: u || void 0,
1672
+ onSelectConversation: M,
1673
+ onNewChat: L,
1674
+ isOpen: f
1675
+ }
1676
+ ) }),
1677
+ /* @__PURE__ */ c("div", { className: "echo-chat-main", children: [
1678
+ p ? /* @__PURE__ */ c("div", { className: "echo-error-message", children: [
1679
+ p,
1680
+ /* @__PURE__ */ c("button", { onClick: () => window.location.reload(), children: "Retry" })
1681
+ ] }) : /* @__PURE__ */ c(re, { children: O ? /* @__PURE__ */ c(jt, { config: i, onQuerySelect: W }) : /* @__PURE__ */ c(
1682
+ Ft,
1683
+ {
1684
+ messages: r,
1685
+ isStreaming: g,
1686
+ activeRunId: d || void 0,
1687
+ streamedThoughts: C
1688
+ }
1689
+ ) }),
1690
+ /* @__PURE__ */ c(Ut, { onSendMessage: P, isLoading: w || g })
1691
+ ] })
1692
+ ] })
1693
+ ] });
1694
+ }, Qt = ({ isOpen: e, onClick: t }) => /* @__PURE__ */ c("button", { class: "echo-launcher", onClick: t, children: e ? /* @__PURE__ */ c(at, { size: 24 }) : /* @__PURE__ */ c(At, {}) }), Ot = ({ config: e }) => {
1695
+ const [t, n] = N(!1), { config: r, isLoading: o, error: i, isInitialized: s } = st();
1696
+ if (i)
1697
+ return r?.environment === "dev" ? /* @__PURE__ */ c("div", { className: "echo-error-toast", style: {
1698
+ position: "fixed",
1699
+ bottom: "20px",
1700
+ right: "20px",
1701
+ background: "red",
1702
+ color: "white",
1703
+ padding: "10px",
1704
+ borderRadius: "5px",
1705
+ zIndex: 1e4
1706
+ }, children: [
1707
+ "Error: ",
1708
+ i
1709
+ ] }) : null;
1710
+ if (!s && o)
1711
+ return null;
1712
+ const h = e.bgColor || r?.primary_color || "#0165d2", u = {
1713
+ "--echo-primary": h,
1714
+ "--echo-primary-gradient": `linear-gradient(135deg, ${h} 0%, ${h} 100%)`,
1715
+ "--echo-background": "#ffffff",
1716
+ "--echo-foreground": "#000000"
1717
+ };
1718
+ return e.width && (u.width = e.width), e.height && (u.height = e.height), /* @__PURE__ */ c(
1719
+ "div",
1720
+ {
1721
+ className: `echo-chat-container ${e.position || "bottom-right"}`,
1722
+ style: u,
1723
+ children: [
1724
+ /* @__PURE__ */ c(
1725
+ zt,
1726
+ {
1727
+ isOpen: t,
1728
+ onClose: () => n(!1),
1729
+ title: r?.brand_name || "Support"
1730
+ }
1731
+ ),
1732
+ /* @__PURE__ */ c(
1733
+ Qt,
1734
+ {
1735
+ isOpen: t,
1736
+ onClick: () => n(!t)
1737
+ }
1738
+ )
1739
+ ]
1740
+ }
1741
+ );
1742
+ }, Bt = (e) => /* @__PURE__ */ c(Nt, { sdkConfig: e, children: /* @__PURE__ */ c(Ot, { config: e }) });
1743
+ function Kt(e, t) {
1744
+ const n = document.createElement("div");
1745
+ return e.appendChild(n), Ie(/* @__PURE__ */ c(Bt, { ...t }), n), {
1746
+ destroy: () => {
1747
+ Ie(null, n), n.remove();
1748
+ }
1749
+ };
1750
+ }
1751
+ typeof window < "u" && (window.mountChatPopup = Kt);
1752
+ export {
1753
+ Bt as ChatPopup,
1754
+ Kt as mountChatPopup
1755
+ };