@pocketping/widget 0.2.0 → 0.3.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,1735 +0,0 @@
1
- "use strict";
2
- var PocketPing = (() => {
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/index.ts
22
- var index_exports = {};
23
- __export(index_exports, {
24
- close: () => close,
25
- default: () => index_default,
26
- destroy: () => destroy,
27
- getIdentity: () => getIdentity,
28
- identify: () => identify,
29
- init: () => init,
30
- offEvent: () => offEvent,
31
- on: () => on,
32
- onEvent: () => onEvent,
33
- open: () => open,
34
- reset: () => reset,
35
- sendMessage: () => sendMessage,
36
- toggle: () => toggle,
37
- trigger: () => trigger
38
- });
39
-
40
- // ../../node_modules/.pnpm/preact@10.28.2/node_modules/preact/dist/preact.mjs
41
- var n;
42
- var l;
43
- var u;
44
- var t;
45
- var i;
46
- var o;
47
- var r;
48
- var e;
49
- var f;
50
- var c;
51
- var s;
52
- var a;
53
- var h;
54
- var p = {};
55
- var v = [];
56
- var y = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;
57
- var d = Array.isArray;
58
- function w(n2, l3) {
59
- for (var u4 in l3) n2[u4] = l3[u4];
60
- return n2;
61
- }
62
- function g(n2) {
63
- n2 && n2.parentNode && n2.parentNode.removeChild(n2);
64
- }
65
- function _(l3, u4, t3) {
66
- var i3, o3, r3, e3 = {};
67
- for (r3 in u4) "key" == r3 ? i3 = u4[r3] : "ref" == r3 ? o3 = u4[r3] : e3[r3] = u4[r3];
68
- if (arguments.length > 2 && (e3.children = arguments.length > 3 ? n.call(arguments, 2) : t3), "function" == typeof l3 && null != l3.defaultProps) for (r3 in l3.defaultProps) void 0 === e3[r3] && (e3[r3] = l3.defaultProps[r3]);
69
- return m(l3, e3, i3, o3, null);
70
- }
71
- function m(n2, t3, i3, o3, r3) {
72
- var e3 = { type: n2, props: t3, key: i3, ref: o3, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: null == r3 ? ++u : r3, __i: -1, __u: 0 };
73
- return null == r3 && null != l.vnode && l.vnode(e3), e3;
74
- }
75
- function k(n2) {
76
- return n2.children;
77
- }
78
- function x(n2, l3) {
79
- this.props = n2, this.context = l3;
80
- }
81
- function S(n2, l3) {
82
- if (null == l3) return n2.__ ? S(n2.__, n2.__i + 1) : null;
83
- for (var u4; l3 < n2.__k.length; l3++) if (null != (u4 = n2.__k[l3]) && null != u4.__e) return u4.__e;
84
- return "function" == typeof n2.type ? S(n2) : null;
85
- }
86
- function C(n2) {
87
- var l3, u4;
88
- if (null != (n2 = n2.__) && null != n2.__c) {
89
- for (n2.__e = n2.__c.base = null, l3 = 0; l3 < n2.__k.length; l3++) if (null != (u4 = n2.__k[l3]) && null != u4.__e) {
90
- n2.__e = n2.__c.base = u4.__e;
91
- break;
92
- }
93
- return C(n2);
94
- }
95
- }
96
- function M(n2) {
97
- (!n2.__d && (n2.__d = true) && i.push(n2) && !$.__r++ || o != l.debounceRendering) && ((o = l.debounceRendering) || r)($);
98
- }
99
- function $() {
100
- for (var n2, u4, t3, o3, r3, f4, c3, s3 = 1; i.length; ) i.length > s3 && i.sort(e), n2 = i.shift(), s3 = i.length, n2.__d && (t3 = void 0, o3 = void 0, r3 = (o3 = (u4 = n2).__v).__e, f4 = [], c3 = [], u4.__P && ((t3 = w({}, o3)).__v = o3.__v + 1, l.vnode && l.vnode(t3), O(u4.__P, t3, o3, u4.__n, u4.__P.namespaceURI, 32 & o3.__u ? [r3] : null, f4, null == r3 ? S(o3) : r3, !!(32 & o3.__u), c3), t3.__v = o3.__v, t3.__.__k[t3.__i] = t3, N(f4, t3, c3), o3.__e = o3.__ = null, t3.__e != r3 && C(t3)));
101
- $.__r = 0;
102
- }
103
- function I(n2, l3, u4, t3, i3, o3, r3, e3, f4, c3, s3) {
104
- var a3, h4, y3, d3, w3, g2, _2, m3 = t3 && t3.__k || v, b = l3.length;
105
- for (f4 = P(u4, l3, m3, f4, b), a3 = 0; a3 < b; a3++) null != (y3 = u4.__k[a3]) && (h4 = -1 == y3.__i ? p : m3[y3.__i] || p, y3.__i = a3, g2 = O(n2, y3, h4, i3, o3, r3, e3, f4, c3, s3), d3 = y3.__e, y3.ref && h4.ref != y3.ref && (h4.ref && B(h4.ref, null, y3), s3.push(y3.ref, y3.__c || d3, y3)), null == w3 && null != d3 && (w3 = d3), (_2 = !!(4 & y3.__u)) || h4.__k === y3.__k ? f4 = A(y3, f4, n2, _2) : "function" == typeof y3.type && void 0 !== g2 ? f4 = g2 : d3 && (f4 = d3.nextSibling), y3.__u &= -7);
106
- return u4.__e = w3, f4;
107
- }
108
- function P(n2, l3, u4, t3, i3) {
109
- var o3, r3, e3, f4, c3, s3 = u4.length, a3 = s3, h4 = 0;
110
- for (n2.__k = new Array(i3), o3 = 0; o3 < i3; o3++) null != (r3 = l3[o3]) && "boolean" != typeof r3 && "function" != typeof r3 ? ("string" == typeof r3 || "number" == typeof r3 || "bigint" == typeof r3 || r3.constructor == String ? r3 = n2.__k[o3] = m(null, r3, null, null, null) : d(r3) ? r3 = n2.__k[o3] = m(k, { children: r3 }, null, null, null) : void 0 === r3.constructor && r3.__b > 0 ? r3 = n2.__k[o3] = m(r3.type, r3.props, r3.key, r3.ref ? r3.ref : null, r3.__v) : n2.__k[o3] = r3, f4 = o3 + h4, r3.__ = n2, r3.__b = n2.__b + 1, e3 = null, -1 != (c3 = r3.__i = L(r3, u4, f4, a3)) && (a3--, (e3 = u4[c3]) && (e3.__u |= 2)), null == e3 || null == e3.__v ? (-1 == c3 && (i3 > s3 ? h4-- : i3 < s3 && h4++), "function" != typeof r3.type && (r3.__u |= 4)) : c3 != f4 && (c3 == f4 - 1 ? h4-- : c3 == f4 + 1 ? h4++ : (c3 > f4 ? h4-- : h4++, r3.__u |= 4))) : n2.__k[o3] = null;
111
- if (a3) for (o3 = 0; o3 < s3; o3++) null != (e3 = u4[o3]) && 0 == (2 & e3.__u) && (e3.__e == t3 && (t3 = S(e3)), D(e3, e3));
112
- return t3;
113
- }
114
- function A(n2, l3, u4, t3) {
115
- var i3, o3;
116
- if ("function" == typeof n2.type) {
117
- for (i3 = n2.__k, o3 = 0; i3 && o3 < i3.length; o3++) i3[o3] && (i3[o3].__ = n2, l3 = A(i3[o3], l3, u4, t3));
118
- return l3;
119
- }
120
- n2.__e != l3 && (t3 && (l3 && n2.type && !l3.parentNode && (l3 = S(n2)), u4.insertBefore(n2.__e, l3 || null)), l3 = n2.__e);
121
- do {
122
- l3 = l3 && l3.nextSibling;
123
- } while (null != l3 && 8 == l3.nodeType);
124
- return l3;
125
- }
126
- function L(n2, l3, u4, t3) {
127
- var i3, o3, r3, e3 = n2.key, f4 = n2.type, c3 = l3[u4], s3 = null != c3 && 0 == (2 & c3.__u);
128
- if (null === c3 && null == e3 || s3 && e3 == c3.key && f4 == c3.type) return u4;
129
- if (t3 > (s3 ? 1 : 0)) {
130
- for (i3 = u4 - 1, o3 = u4 + 1; i3 >= 0 || o3 < l3.length; ) if (null != (c3 = l3[r3 = i3 >= 0 ? i3-- : o3++]) && 0 == (2 & c3.__u) && e3 == c3.key && f4 == c3.type) return r3;
131
- }
132
- return -1;
133
- }
134
- function T(n2, l3, u4) {
135
- "-" == l3[0] ? n2.setProperty(l3, null == u4 ? "" : u4) : n2[l3] = null == u4 ? "" : "number" != typeof u4 || y.test(l3) ? u4 : u4 + "px";
136
- }
137
- function j(n2, l3, u4, t3, i3) {
138
- var o3, r3;
139
- n: if ("style" == l3) if ("string" == typeof u4) n2.style.cssText = u4;
140
- else {
141
- if ("string" == typeof t3 && (n2.style.cssText = t3 = ""), t3) for (l3 in t3) u4 && l3 in u4 || T(n2.style, l3, "");
142
- if (u4) for (l3 in u4) t3 && u4[l3] == t3[l3] || T(n2.style, l3, u4[l3]);
143
- }
144
- else if ("o" == l3[0] && "n" == l3[1]) o3 = l3 != (l3 = l3.replace(f, "$1")), r3 = l3.toLowerCase(), l3 = r3 in n2 || "onFocusOut" == l3 || "onFocusIn" == l3 ? r3.slice(2) : l3.slice(2), n2.l || (n2.l = {}), n2.l[l3 + o3] = u4, u4 ? t3 ? u4.u = t3.u : (u4.u = c, n2.addEventListener(l3, o3 ? a : s, o3)) : n2.removeEventListener(l3, o3 ? a : s, o3);
145
- else {
146
- if ("http://www.w3.org/2000/svg" == i3) l3 = l3.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
147
- else if ("width" != l3 && "height" != l3 && "href" != l3 && "list" != l3 && "form" != l3 && "tabIndex" != l3 && "download" != l3 && "rowSpan" != l3 && "colSpan" != l3 && "role" != l3 && "popover" != l3 && l3 in n2) try {
148
- n2[l3] = null == u4 ? "" : u4;
149
- break n;
150
- } catch (n3) {
151
- }
152
- "function" == typeof u4 || (null == u4 || false === u4 && "-" != l3[4] ? n2.removeAttribute(l3) : n2.setAttribute(l3, "popover" == l3 && 1 == u4 ? "" : u4));
153
- }
154
- }
155
- function F(n2) {
156
- return function(u4) {
157
- if (this.l) {
158
- var t3 = this.l[u4.type + n2];
159
- if (null == u4.t) u4.t = c++;
160
- else if (u4.t < t3.u) return;
161
- return t3(l.event ? l.event(u4) : u4);
162
- }
163
- };
164
- }
165
- function O(n2, u4, t3, i3, o3, r3, e3, f4, c3, s3) {
166
- var a3, h4, p3, v3, y3, _2, m3, b, S2, C3, M2, $2, P2, A3, H, L2, T3, j3 = u4.type;
167
- if (void 0 !== u4.constructor) return null;
168
- 128 & t3.__u && (c3 = !!(32 & t3.__u), r3 = [f4 = u4.__e = t3.__e]), (a3 = l.__b) && a3(u4);
169
- n: if ("function" == typeof j3) try {
170
- if (b = u4.props, S2 = "prototype" in j3 && j3.prototype.render, C3 = (a3 = j3.contextType) && i3[a3.__c], M2 = a3 ? C3 ? C3.props.value : a3.__ : i3, t3.__c ? m3 = (h4 = u4.__c = t3.__c).__ = h4.__E : (S2 ? u4.__c = h4 = new j3(b, M2) : (u4.__c = h4 = new x(b, M2), h4.constructor = j3, h4.render = E), C3 && C3.sub(h4), h4.state || (h4.state = {}), h4.__n = i3, p3 = h4.__d = true, h4.__h = [], h4._sb = []), S2 && null == h4.__s && (h4.__s = h4.state), S2 && null != j3.getDerivedStateFromProps && (h4.__s == h4.state && (h4.__s = w({}, h4.__s)), w(h4.__s, j3.getDerivedStateFromProps(b, h4.__s))), v3 = h4.props, y3 = h4.state, h4.__v = u4, p3) S2 && null == j3.getDerivedStateFromProps && null != h4.componentWillMount && h4.componentWillMount(), S2 && null != h4.componentDidMount && h4.__h.push(h4.componentDidMount);
171
- else {
172
- if (S2 && null == j3.getDerivedStateFromProps && b !== v3 && null != h4.componentWillReceiveProps && h4.componentWillReceiveProps(b, M2), u4.__v == t3.__v || !h4.__e && null != h4.shouldComponentUpdate && false === h4.shouldComponentUpdate(b, h4.__s, M2)) {
173
- for (u4.__v != t3.__v && (h4.props = b, h4.state = h4.__s, h4.__d = false), u4.__e = t3.__e, u4.__k = t3.__k, u4.__k.some(function(n3) {
174
- n3 && (n3.__ = u4);
175
- }), $2 = 0; $2 < h4._sb.length; $2++) h4.__h.push(h4._sb[$2]);
176
- h4._sb = [], h4.__h.length && e3.push(h4);
177
- break n;
178
- }
179
- null != h4.componentWillUpdate && h4.componentWillUpdate(b, h4.__s, M2), S2 && null != h4.componentDidUpdate && h4.__h.push(function() {
180
- h4.componentDidUpdate(v3, y3, _2);
181
- });
182
- }
183
- if (h4.context = M2, h4.props = b, h4.__P = n2, h4.__e = false, P2 = l.__r, A3 = 0, S2) {
184
- for (h4.state = h4.__s, h4.__d = false, P2 && P2(u4), a3 = h4.render(h4.props, h4.state, h4.context), H = 0; H < h4._sb.length; H++) h4.__h.push(h4._sb[H]);
185
- h4._sb = [];
186
- } else do {
187
- h4.__d = false, P2 && P2(u4), a3 = h4.render(h4.props, h4.state, h4.context), h4.state = h4.__s;
188
- } while (h4.__d && ++A3 < 25);
189
- h4.state = h4.__s, null != h4.getChildContext && (i3 = w(w({}, i3), h4.getChildContext())), S2 && !p3 && null != h4.getSnapshotBeforeUpdate && (_2 = h4.getSnapshotBeforeUpdate(v3, y3)), L2 = a3, null != a3 && a3.type === k && null == a3.key && (L2 = V(a3.props.children)), f4 = I(n2, d(L2) ? L2 : [L2], u4, t3, i3, o3, r3, e3, f4, c3, s3), h4.base = u4.__e, u4.__u &= -161, h4.__h.length && e3.push(h4), m3 && (h4.__E = h4.__ = null);
190
- } catch (n3) {
191
- if (u4.__v = null, c3 || null != r3) if (n3.then) {
192
- for (u4.__u |= c3 ? 160 : 128; f4 && 8 == f4.nodeType && f4.nextSibling; ) f4 = f4.nextSibling;
193
- r3[r3.indexOf(f4)] = null, u4.__e = f4;
194
- } else {
195
- for (T3 = r3.length; T3--; ) g(r3[T3]);
196
- z(u4);
197
- }
198
- else u4.__e = t3.__e, u4.__k = t3.__k, n3.then || z(u4);
199
- l.__e(n3, u4, t3);
200
- }
201
- else null == r3 && u4.__v == t3.__v ? (u4.__k = t3.__k, u4.__e = t3.__e) : f4 = u4.__e = q(t3.__e, u4, t3, i3, o3, r3, e3, c3, s3);
202
- return (a3 = l.diffed) && a3(u4), 128 & u4.__u ? void 0 : f4;
203
- }
204
- function z(n2) {
205
- n2 && n2.__c && (n2.__c.__e = true), n2 && n2.__k && n2.__k.forEach(z);
206
- }
207
- function N(n2, u4, t3) {
208
- for (var i3 = 0; i3 < t3.length; i3++) B(t3[i3], t3[++i3], t3[++i3]);
209
- l.__c && l.__c(u4, n2), n2.some(function(u5) {
210
- try {
211
- n2 = u5.__h, u5.__h = [], n2.some(function(n3) {
212
- n3.call(u5);
213
- });
214
- } catch (n3) {
215
- l.__e(n3, u5.__v);
216
- }
217
- });
218
- }
219
- function V(n2) {
220
- return "object" != typeof n2 || null == n2 || n2.__b && n2.__b > 0 ? n2 : d(n2) ? n2.map(V) : w({}, n2);
221
- }
222
- function q(u4, t3, i3, o3, r3, e3, f4, c3, s3) {
223
- var a3, h4, v3, y3, w3, _2, m3, b = i3.props || p, k3 = t3.props, x2 = t3.type;
224
- if ("svg" == x2 ? r3 = "http://www.w3.org/2000/svg" : "math" == x2 ? r3 = "http://www.w3.org/1998/Math/MathML" : r3 || (r3 = "http://www.w3.org/1999/xhtml"), null != e3) {
225
- for (a3 = 0; a3 < e3.length; a3++) if ((w3 = e3[a3]) && "setAttribute" in w3 == !!x2 && (x2 ? w3.localName == x2 : 3 == w3.nodeType)) {
226
- u4 = w3, e3[a3] = null;
227
- break;
228
- }
229
- }
230
- if (null == u4) {
231
- if (null == x2) return document.createTextNode(k3);
232
- u4 = document.createElementNS(r3, x2, k3.is && k3), c3 && (l.__m && l.__m(t3, e3), c3 = false), e3 = null;
233
- }
234
- if (null == x2) b === k3 || c3 && u4.data == k3 || (u4.data = k3);
235
- else {
236
- if (e3 = e3 && n.call(u4.childNodes), !c3 && null != e3) for (b = {}, a3 = 0; a3 < u4.attributes.length; a3++) b[(w3 = u4.attributes[a3]).name] = w3.value;
237
- for (a3 in b) if (w3 = b[a3], "children" == a3) ;
238
- else if ("dangerouslySetInnerHTML" == a3) v3 = w3;
239
- else if (!(a3 in k3)) {
240
- if ("value" == a3 && "defaultValue" in k3 || "checked" == a3 && "defaultChecked" in k3) continue;
241
- j(u4, a3, null, w3, r3);
242
- }
243
- for (a3 in k3) w3 = k3[a3], "children" == a3 ? y3 = w3 : "dangerouslySetInnerHTML" == a3 ? h4 = w3 : "value" == a3 ? _2 = w3 : "checked" == a3 ? m3 = w3 : c3 && "function" != typeof w3 || b[a3] === w3 || j(u4, a3, w3, b[a3], r3);
244
- if (h4) c3 || v3 && (h4.__html == v3.__html || h4.__html == u4.innerHTML) || (u4.innerHTML = h4.__html), t3.__k = [];
245
- else if (v3 && (u4.innerHTML = ""), I("template" == t3.type ? u4.content : u4, d(y3) ? y3 : [y3], t3, i3, o3, "foreignObject" == x2 ? "http://www.w3.org/1999/xhtml" : r3, e3, f4, e3 ? e3[0] : i3.__k && S(i3, 0), c3, s3), null != e3) for (a3 = e3.length; a3--; ) g(e3[a3]);
246
- c3 || (a3 = "value", "progress" == x2 && null == _2 ? u4.removeAttribute("value") : null != _2 && (_2 !== u4[a3] || "progress" == x2 && !_2 || "option" == x2 && _2 != b[a3]) && j(u4, a3, _2, b[a3], r3), a3 = "checked", null != m3 && m3 != u4[a3] && j(u4, a3, m3, b[a3], r3));
247
- }
248
- return u4;
249
- }
250
- function B(n2, u4, t3) {
251
- try {
252
- if ("function" == typeof n2) {
253
- var i3 = "function" == typeof n2.__u;
254
- i3 && n2.__u(), i3 && null == u4 || (n2.__u = n2(u4));
255
- } else n2.current = u4;
256
- } catch (n3) {
257
- l.__e(n3, t3);
258
- }
259
- }
260
- function D(n2, u4, t3) {
261
- var i3, o3;
262
- if (l.unmount && l.unmount(n2), (i3 = n2.ref) && (i3.current && i3.current != n2.__e || B(i3, null, u4)), null != (i3 = n2.__c)) {
263
- if (i3.componentWillUnmount) try {
264
- i3.componentWillUnmount();
265
- } catch (n3) {
266
- l.__e(n3, u4);
267
- }
268
- i3.base = i3.__P = null;
269
- }
270
- if (i3 = n2.__k) for (o3 = 0; o3 < i3.length; o3++) i3[o3] && D(i3[o3], u4, t3 || "function" != typeof n2.type);
271
- t3 || g(n2.__e), n2.__c = n2.__ = n2.__e = void 0;
272
- }
273
- function E(n2, l3, u4) {
274
- return this.constructor(n2, u4);
275
- }
276
- function G(u4, t3, i3) {
277
- var o3, r3, e3, f4;
278
- t3 == document && (t3 = document.documentElement), l.__ && l.__(u4, t3), r3 = (o3 = "function" == typeof i3) ? null : i3 && i3.__k || t3.__k, e3 = [], f4 = [], O(t3, u4 = (!o3 && i3 || t3).__k = _(k, null, [u4]), r3 || p, p, t3.namespaceURI, !o3 && i3 ? [i3] : r3 ? null : t3.firstChild ? n.call(t3.childNodes) : null, e3, !o3 && i3 ? i3 : r3 ? r3.__e : t3.firstChild, o3, f4), N(e3, u4, f4);
279
- }
280
- n = v.slice, l = { __e: function(n2, l3, u4, t3) {
281
- for (var i3, o3, r3; l3 = l3.__; ) if ((i3 = l3.__c) && !i3.__) try {
282
- if ((o3 = i3.constructor) && null != o3.getDerivedStateFromError && (i3.setState(o3.getDerivedStateFromError(n2)), r3 = i3.__d), null != i3.componentDidCatch && (i3.componentDidCatch(n2, t3 || {}), r3 = i3.__d), r3) return i3.__E = i3;
283
- } catch (l4) {
284
- n2 = l4;
285
- }
286
- throw n2;
287
- } }, u = 0, t = function(n2) {
288
- return null != n2 && void 0 === n2.constructor;
289
- }, x.prototype.setState = function(n2, l3) {
290
- var u4;
291
- u4 = null != this.__s && this.__s != this.state ? this.__s : this.__s = w({}, this.state), "function" == typeof n2 && (n2 = n2(w({}, u4), this.props)), n2 && w(u4, n2), null != n2 && this.__v && (l3 && this._sb.push(l3), M(this));
292
- }, x.prototype.forceUpdate = function(n2) {
293
- this.__v && (this.__e = true, n2 && this.__h.push(n2), M(this));
294
- }, x.prototype.render = k, i = [], r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, e = function(n2, l3) {
295
- return n2.__v.__b - l3.__v.__b;
296
- }, $.__r = 0, f = /(PointerCapture)$|Capture$/i, c = 0, s = F(false), a = F(true), h = 0;
297
-
298
- // ../../node_modules/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.mjs
299
- var t2;
300
- var r2;
301
- var u2;
302
- var i2;
303
- var o2 = 0;
304
- var f2 = [];
305
- var c2 = l;
306
- var e2 = c2.__b;
307
- var a2 = c2.__r;
308
- var v2 = c2.diffed;
309
- var l2 = c2.__c;
310
- var m2 = c2.unmount;
311
- var s2 = c2.__;
312
- function p2(n2, t3) {
313
- c2.__h && c2.__h(r2, n2, o2 || t3), o2 = 0;
314
- var u4 = r2.__H || (r2.__H = { __: [], __h: [] });
315
- return n2 >= u4.__.length && u4.__.push({}), u4.__[n2];
316
- }
317
- function d2(n2) {
318
- return o2 = 1, h2(D2, n2);
319
- }
320
- function h2(n2, u4, i3) {
321
- var o3 = p2(t2++, 2);
322
- if (o3.t = n2, !o3.__c && (o3.__ = [i3 ? i3(u4) : D2(void 0, u4), function(n3) {
323
- var t3 = o3.__N ? o3.__N[0] : o3.__[0], r3 = o3.t(t3, n3);
324
- t3 !== r3 && (o3.__N = [r3, o3.__[1]], o3.__c.setState({}));
325
- }], o3.__c = r2, !r2.__f)) {
326
- var f4 = function(n3, t3, r3) {
327
- if (!o3.__c.__H) return true;
328
- var u5 = o3.__c.__H.__.filter(function(n4) {
329
- return !!n4.__c;
330
- });
331
- if (u5.every(function(n4) {
332
- return !n4.__N;
333
- })) return !c3 || c3.call(this, n3, t3, r3);
334
- var i4 = o3.__c.props !== n3;
335
- return u5.forEach(function(n4) {
336
- if (n4.__N) {
337
- var t4 = n4.__[0];
338
- n4.__ = n4.__N, n4.__N = void 0, t4 !== n4.__[0] && (i4 = true);
339
- }
340
- }), c3 && c3.call(this, n3, t3, r3) || i4;
341
- };
342
- r2.__f = true;
343
- var c3 = r2.shouldComponentUpdate, e3 = r2.componentWillUpdate;
344
- r2.componentWillUpdate = function(n3, t3, r3) {
345
- if (this.__e) {
346
- var u5 = c3;
347
- c3 = void 0, f4(n3, t3, r3), c3 = u5;
348
- }
349
- e3 && e3.call(this, n3, t3, r3);
350
- }, r2.shouldComponentUpdate = f4;
351
- }
352
- return o3.__N || o3.__;
353
- }
354
- function y2(n2, u4) {
355
- var i3 = p2(t2++, 3);
356
- !c2.__s && C2(i3.__H, u4) && (i3.__ = n2, i3.u = u4, r2.__H.__h.push(i3));
357
- }
358
- function A2(n2) {
359
- return o2 = 5, T2(function() {
360
- return { current: n2 };
361
- }, []);
362
- }
363
- function T2(n2, r3) {
364
- var u4 = p2(t2++, 7);
365
- return C2(u4.__H, r3) && (u4.__ = n2(), u4.__H = r3, u4.__h = n2), u4.__;
366
- }
367
- function q2(n2, t3) {
368
- return o2 = 8, T2(function() {
369
- return n2;
370
- }, t3);
371
- }
372
- function j2() {
373
- for (var n2; n2 = f2.shift(); ) if (n2.__P && n2.__H) try {
374
- n2.__H.__h.forEach(z2), n2.__H.__h.forEach(B2), n2.__H.__h = [];
375
- } catch (t3) {
376
- n2.__H.__h = [], c2.__e(t3, n2.__v);
377
- }
378
- }
379
- c2.__b = function(n2) {
380
- r2 = null, e2 && e2(n2);
381
- }, c2.__ = function(n2, t3) {
382
- n2 && t3.__k && t3.__k.__m && (n2.__m = t3.__k.__m), s2 && s2(n2, t3);
383
- }, c2.__r = function(n2) {
384
- a2 && a2(n2), t2 = 0;
385
- var i3 = (r2 = n2.__c).__H;
386
- i3 && (u2 === r2 ? (i3.__h = [], r2.__h = [], i3.__.forEach(function(n3) {
387
- n3.__N && (n3.__ = n3.__N), n3.u = n3.__N = void 0;
388
- })) : (i3.__h.forEach(z2), i3.__h.forEach(B2), i3.__h = [], t2 = 0)), u2 = r2;
389
- }, c2.diffed = function(n2) {
390
- v2 && v2(n2);
391
- var t3 = n2.__c;
392
- t3 && t3.__H && (t3.__H.__h.length && (1 !== f2.push(t3) && i2 === c2.requestAnimationFrame || ((i2 = c2.requestAnimationFrame) || w2)(j2)), t3.__H.__.forEach(function(n3) {
393
- n3.u && (n3.__H = n3.u), n3.u = void 0;
394
- })), u2 = r2 = null;
395
- }, c2.__c = function(n2, t3) {
396
- t3.some(function(n3) {
397
- try {
398
- n3.__h.forEach(z2), n3.__h = n3.__h.filter(function(n4) {
399
- return !n4.__ || B2(n4);
400
- });
401
- } catch (r3) {
402
- t3.some(function(n4) {
403
- n4.__h && (n4.__h = []);
404
- }), t3 = [], c2.__e(r3, n3.__v);
405
- }
406
- }), l2 && l2(n2, t3);
407
- }, c2.unmount = function(n2) {
408
- m2 && m2(n2);
409
- var t3, r3 = n2.__c;
410
- r3 && r3.__H && (r3.__H.__.forEach(function(n3) {
411
- try {
412
- z2(n3);
413
- } catch (n4) {
414
- t3 = n4;
415
- }
416
- }), r3.__H = void 0, t3 && c2.__e(t3, r3.__v));
417
- };
418
- var k2 = "function" == typeof requestAnimationFrame;
419
- function w2(n2) {
420
- var t3, r3 = function() {
421
- clearTimeout(u4), k2 && cancelAnimationFrame(t3), setTimeout(n2);
422
- }, u4 = setTimeout(r3, 35);
423
- k2 && (t3 = requestAnimationFrame(r3));
424
- }
425
- function z2(n2) {
426
- var t3 = r2, u4 = n2.__c;
427
- "function" == typeof u4 && (n2.__c = void 0, u4()), r2 = t3;
428
- }
429
- function B2(n2) {
430
- var t3 = r2;
431
- n2.__c = n2.__(), r2 = t3;
432
- }
433
- function C2(n2, t3) {
434
- return !n2 || n2.length !== t3.length || t3.some(function(t4, r3) {
435
- return t4 !== n2[r3];
436
- });
437
- }
438
- function D2(n2, t3) {
439
- return "function" == typeof t3 ? t3(n2) : t3;
440
- }
441
-
442
- // src/components/styles.ts
443
- function styles(primaryColor, theme) {
444
- const isDark = theme === "dark";
445
- const colors = {
446
- bg: isDark ? "#1f2937" : "#ffffff",
447
- bgSecondary: isDark ? "#374151" : "#f3f4f6",
448
- text: isDark ? "#f9fafb" : "#111827",
449
- textSecondary: isDark ? "#9ca3af" : "#6b7280",
450
- border: isDark ? "#4b5563" : "#e5e7eb",
451
- messageBg: isDark ? "#374151" : "#f3f4f6"
452
- };
453
- return `
454
- #pocketping-container {
455
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
456
- font-size: 14px;
457
- line-height: 1.5;
458
- color: ${colors.text};
459
- }
460
-
461
- .pp-toggle {
462
- position: fixed;
463
- width: 56px;
464
- height: 56px;
465
- border-radius: 50%;
466
- background: ${primaryColor};
467
- color: white;
468
- border: none;
469
- cursor: pointer;
470
- display: flex;
471
- align-items: center;
472
- justify-content: center;
473
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
474
- transition: transform 0.2s, box-shadow 0.2s;
475
- z-index: 9999;
476
- }
477
-
478
- .pp-toggle:hover {
479
- transform: scale(1.05);
480
- box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
481
- }
482
-
483
- .pp-toggle svg {
484
- width: 24px;
485
- height: 24px;
486
- }
487
-
488
- .pp-toggle.pp-bottom-right {
489
- bottom: 20px;
490
- right: 20px;
491
- }
492
-
493
- .pp-toggle.pp-bottom-left {
494
- bottom: 20px;
495
- left: 20px;
496
- }
497
-
498
- .pp-online-dot {
499
- position: absolute;
500
- top: 4px;
501
- right: 4px;
502
- width: 12px;
503
- height: 12px;
504
- background: #22c55e;
505
- border-radius: 50%;
506
- border: 2px solid white;
507
- }
508
-
509
- .pp-window {
510
- position: fixed;
511
- width: 380px;
512
- height: 520px;
513
- max-height: calc(100vh - 100px);
514
- background: ${colors.bg};
515
- border-radius: 16px;
516
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
517
- display: flex;
518
- flex-direction: column;
519
- overflow: hidden;
520
- z-index: 9998;
521
- }
522
-
523
- .pp-window.pp-bottom-right {
524
- bottom: 88px;
525
- right: 20px;
526
- }
527
-
528
- .pp-window.pp-bottom-left {
529
- bottom: 88px;
530
- left: 20px;
531
- }
532
-
533
- @media (max-width: 480px) {
534
- .pp-window {
535
- width: calc(100vw - 20px);
536
- height: calc(100vh - 100px);
537
- bottom: 80px;
538
- right: 10px;
539
- left: 10px;
540
- border-radius: 12px;
541
- }
542
- }
543
-
544
- .pp-header {
545
- display: flex;
546
- align-items: center;
547
- justify-content: space-between;
548
- padding: 16px;
549
- background: ${primaryColor};
550
- color: white;
551
- }
552
-
553
- .pp-header-info {
554
- display: flex;
555
- align-items: center;
556
- gap: 12px;
557
- }
558
-
559
- .pp-avatar {
560
- width: 40px;
561
- height: 40px;
562
- border-radius: 50%;
563
- object-fit: cover;
564
- }
565
-
566
- .pp-header-title {
567
- font-weight: 600;
568
- font-size: 16px;
569
- }
570
-
571
- .pp-header-status {
572
- font-size: 12px;
573
- opacity: 0.9;
574
- display: flex;
575
- align-items: center;
576
- gap: 4px;
577
- }
578
-
579
- .pp-status-dot {
580
- width: 8px;
581
- height: 8px;
582
- border-radius: 50%;
583
- background: rgba(255, 255, 255, 0.5);
584
- }
585
-
586
- .pp-status-dot.pp-online {
587
- background: #22c55e;
588
- }
589
-
590
- .pp-close-btn {
591
- background: transparent;
592
- border: none;
593
- color: white;
594
- cursor: pointer;
595
- padding: 4px;
596
- border-radius: 4px;
597
- opacity: 0.8;
598
- transition: opacity 0.2s;
599
- }
600
-
601
- .pp-close-btn:hover {
602
- opacity: 1;
603
- }
604
-
605
- .pp-close-btn svg {
606
- width: 20px;
607
- height: 20px;
608
- }
609
-
610
- .pp-messages {
611
- flex: 1;
612
- overflow-y: auto;
613
- padding: 16px;
614
- display: flex;
615
- flex-direction: column;
616
- gap: 12px;
617
- }
618
-
619
- .pp-welcome {
620
- text-align: center;
621
- color: ${colors.textSecondary};
622
- padding: 24px;
623
- font-size: 13px;
624
- }
625
-
626
- .pp-message {
627
- max-width: 80%;
628
- padding: 10px 14px;
629
- border-radius: 16px;
630
- word-wrap: break-word;
631
- }
632
-
633
- .pp-message-visitor {
634
- align-self: flex-end;
635
- background: ${primaryColor};
636
- color: white;
637
- border-bottom-right-radius: 4px;
638
- }
639
-
640
- .pp-message-operator,
641
- .pp-message-ai {
642
- align-self: flex-start;
643
- background: ${colors.messageBg};
644
- color: ${colors.text};
645
- border-bottom-left-radius: 4px;
646
- }
647
-
648
- .pp-message-content {
649
- margin-bottom: 4px;
650
- }
651
-
652
- .pp-message-time {
653
- font-size: 11px;
654
- opacity: 0.7;
655
- display: flex;
656
- align-items: center;
657
- gap: 4px;
658
- }
659
-
660
- .pp-ai-badge {
661
- background: rgba(0, 0, 0, 0.1);
662
- padding: 1px 4px;
663
- border-radius: 4px;
664
- font-size: 10px;
665
- font-weight: 600;
666
- }
667
-
668
- .pp-status {
669
- display: inline-flex;
670
- align-items: center;
671
- margin-left: 4px;
672
- }
673
-
674
- .pp-status svg {
675
- width: 14px;
676
- height: 14px;
677
- }
678
-
679
- .pp-check,
680
- .pp-check-double {
681
- stroke: rgba(255, 255, 255, 0.7);
682
- }
683
-
684
- .pp-check-read {
685
- stroke: #34b7f1;
686
- }
687
-
688
- .pp-status-sending .pp-check {
689
- opacity: 0.5;
690
- }
691
-
692
- .pp-typing {
693
- display: flex;
694
- gap: 4px;
695
- padding: 14px 18px;
696
- }
697
-
698
- .pp-typing span {
699
- width: 8px;
700
- height: 8px;
701
- background: ${colors.textSecondary};
702
- border-radius: 50%;
703
- animation: pp-bounce 1.4s infinite ease-in-out both;
704
- }
705
-
706
- .pp-typing span:nth-child(1) { animation-delay: -0.32s; }
707
- .pp-typing span:nth-child(2) { animation-delay: -0.16s; }
708
-
709
- @keyframes pp-bounce {
710
- 0%, 80%, 100% { transform: scale(0); }
711
- 40% { transform: scale(1); }
712
- }
713
-
714
- .pp-input-form {
715
- display: flex;
716
- padding: 12px;
717
- gap: 8px;
718
- border-top: 1px solid ${colors.border};
719
- }
720
-
721
- .pp-input {
722
- flex: 1;
723
- padding: 10px 14px;
724
- border: 1px solid ${colors.border};
725
- border-radius: 20px;
726
- background: ${colors.bg};
727
- color: ${colors.text};
728
- font-size: 14px;
729
- outline: none;
730
- transition: border-color 0.2s;
731
- }
732
-
733
- .pp-input:focus {
734
- border-color: ${primaryColor};
735
- }
736
-
737
- .pp-input::placeholder {
738
- color: ${colors.textSecondary};
739
- }
740
-
741
- .pp-send-btn {
742
- width: 40px;
743
- height: 40px;
744
- border-radius: 50%;
745
- background: ${primaryColor};
746
- color: white;
747
- border: none;
748
- cursor: pointer;
749
- display: flex;
750
- align-items: center;
751
- justify-content: center;
752
- transition: opacity 0.2s;
753
- }
754
-
755
- .pp-send-btn:disabled {
756
- opacity: 0.5;
757
- cursor: not-allowed;
758
- }
759
-
760
- .pp-send-btn svg {
761
- width: 18px;
762
- height: 18px;
763
- }
764
-
765
- .pp-footer {
766
- text-align: center;
767
- padding: 8px;
768
- font-size: 11px;
769
- color: ${colors.textSecondary};
770
- border-top: 1px solid ${colors.border};
771
- }
772
-
773
- .pp-footer a {
774
- color: ${primaryColor};
775
- text-decoration: none;
776
- }
777
-
778
- .pp-footer a:hover {
779
- text-decoration: underline;
780
- }
781
- `;
782
- }
783
-
784
- // ../../node_modules/.pnpm/preact@10.28.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs
785
- var f3 = 0;
786
- function u3(e3, t3, n2, o3, i3, u4) {
787
- t3 || (t3 = {});
788
- var a3, c3, p3 = t3;
789
- if ("ref" in p3) for (c3 in p3 = {}, t3) "ref" == c3 ? a3 = t3[c3] : p3[c3] = t3[c3];
790
- var l3 = { type: e3, props: p3, key: n2, ref: a3, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: --f3, __i: -1, __u: 0, __source: i3, __self: u4 };
791
- if ("function" == typeof e3 && (a3 = e3.defaultProps)) for (c3 in a3) void 0 === p3[c3] && (p3[c3] = a3[c3]);
792
- return l.vnode && l.vnode(l3), l3;
793
- }
794
-
795
- // src/components/ChatWidget.tsx
796
- function ChatWidget({ client: client2, config }) {
797
- const [isOpen, setIsOpen] = d2(false);
798
- const [messages, setMessages] = d2([]);
799
- const [inputValue, setInputValue] = d2("");
800
- const [isTyping, setIsTyping] = d2(false);
801
- const [operatorOnline, setOperatorOnline] = d2(false);
802
- const [isConnected, setIsConnected] = d2(false);
803
- const messagesEndRef = A2(null);
804
- const inputRef = A2(null);
805
- y2(() => {
806
- const unsubOpen = client2.on("openChange", setIsOpen);
807
- const unsubMessage = client2.on("message", () => {
808
- setMessages([...client2.getMessages()]);
809
- });
810
- const unsubTyping = client2.on("typing", (data) => {
811
- setIsTyping(data.isTyping);
812
- });
813
- const unsubPresence = client2.on("presence", (data) => {
814
- setOperatorOnline(data.online);
815
- });
816
- const unsubConnect = client2.on("connect", () => {
817
- setIsConnected(true);
818
- setMessages(client2.getMessages());
819
- setOperatorOnline(client2.getSession()?.operatorOnline ?? false);
820
- });
821
- if (client2.isConnected()) {
822
- setIsConnected(true);
823
- setMessages(client2.getMessages());
824
- setOperatorOnline(client2.getSession()?.operatorOnline ?? false);
825
- }
826
- return () => {
827
- unsubOpen();
828
- unsubMessage();
829
- unsubTyping();
830
- unsubPresence();
831
- unsubConnect();
832
- };
833
- }, [client2]);
834
- y2(() => {
835
- messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
836
- }, [messages]);
837
- y2(() => {
838
- if (isOpen) {
839
- inputRef.current?.focus();
840
- }
841
- }, [isOpen]);
842
- const markMessagesAsRead = q2(() => {
843
- if (!isOpen || !isConnected) return;
844
- const unreadMessages = messages.filter(
845
- (msg) => msg.sender !== "visitor" && msg.status !== "read"
846
- );
847
- if (unreadMessages.length > 0) {
848
- const messageIds = unreadMessages.map((msg) => msg.id);
849
- client2.sendReadStatus(messageIds, "read");
850
- }
851
- }, [isOpen, isConnected, messages, client2]);
852
- y2(() => {
853
- if (!isOpen || !isConnected) return;
854
- const timer = setTimeout(() => {
855
- markMessagesAsRead();
856
- }, 1e3);
857
- return () => clearTimeout(timer);
858
- }, [isOpen, isConnected, messages, markMessagesAsRead]);
859
- y2(() => {
860
- const handleVisibilityChange = () => {
861
- if (document.visibilityState === "visible" && isOpen) {
862
- markMessagesAsRead();
863
- }
864
- };
865
- document.addEventListener("visibilitychange", handleVisibilityChange);
866
- return () => document.removeEventListener("visibilitychange", handleVisibilityChange);
867
- }, [isOpen, markMessagesAsRead]);
868
- y2(() => {
869
- const unsubRead = client2.on(
870
- "read",
871
- () => {
872
- setMessages([...client2.getMessages()]);
873
- }
874
- );
875
- return () => unsubRead();
876
- }, [client2]);
877
- const shouldShow = checkPageVisibility(config);
878
- if (!shouldShow) return null;
879
- const handleSubmit = async (e3) => {
880
- e3.preventDefault();
881
- if (!inputValue.trim()) return;
882
- const content = inputValue;
883
- setInputValue("");
884
- try {
885
- await client2.sendMessage(content);
886
- } catch (err) {
887
- console.error("[PocketPing] Failed to send message:", err);
888
- }
889
- };
890
- const handleInputChange = (e3) => {
891
- const target = e3.target;
892
- setInputValue(target.value);
893
- client2.sendTyping(true);
894
- };
895
- const position = config.position ?? "bottom-right";
896
- const theme = getTheme(config.theme ?? "auto");
897
- const primaryColor = config.primaryColor ?? "#6366f1";
898
- return /* @__PURE__ */ u3(k, { children: [
899
- /* @__PURE__ */ u3("style", { children: styles(primaryColor, theme) }),
900
- /* @__PURE__ */ u3(
901
- "button",
902
- {
903
- class: `pp-toggle pp-${position}`,
904
- onClick: () => client2.toggleOpen(),
905
- "aria-label": isOpen ? "Close chat" : "Open chat",
906
- children: [
907
- isOpen ? /* @__PURE__ */ u3(CloseIcon, {}) : /* @__PURE__ */ u3(ChatIcon, {}),
908
- !isOpen && operatorOnline && /* @__PURE__ */ u3("span", { class: "pp-online-dot" })
909
- ]
910
- }
911
- ),
912
- isOpen && /* @__PURE__ */ u3("div", { class: `pp-window pp-${position} pp-theme-${theme}`, children: [
913
- /* @__PURE__ */ u3("div", { class: "pp-header", children: [
914
- /* @__PURE__ */ u3("div", { class: "pp-header-info", children: [
915
- config.operatorAvatar && /* @__PURE__ */ u3("img", { src: config.operatorAvatar, alt: "", class: "pp-avatar" }),
916
- /* @__PURE__ */ u3("div", { children: [
917
- /* @__PURE__ */ u3("div", { class: "pp-header-title", children: config.operatorName ?? "Support" }),
918
- /* @__PURE__ */ u3("div", { class: "pp-header-status", children: operatorOnline ? /* @__PURE__ */ u3(k, { children: [
919
- /* @__PURE__ */ u3("span", { class: "pp-status-dot pp-online" }),
920
- " Online"
921
- ] }) : /* @__PURE__ */ u3(k, { children: [
922
- /* @__PURE__ */ u3("span", { class: "pp-status-dot" }),
923
- " Away"
924
- ] }) })
925
- ] })
926
- ] }),
927
- /* @__PURE__ */ u3(
928
- "button",
929
- {
930
- class: "pp-close-btn",
931
- onClick: () => client2.setOpen(false),
932
- "aria-label": "Close chat",
933
- children: /* @__PURE__ */ u3(CloseIcon, {})
934
- }
935
- )
936
- ] }),
937
- /* @__PURE__ */ u3("div", { class: "pp-messages", children: [
938
- config.welcomeMessage && messages.length === 0 && /* @__PURE__ */ u3("div", { class: "pp-welcome", children: config.welcomeMessage }),
939
- messages.map((msg) => /* @__PURE__ */ u3(
940
- "div",
941
- {
942
- class: `pp-message pp-message-${msg.sender}`,
943
- children: [
944
- /* @__PURE__ */ u3("div", { class: "pp-message-content", children: msg.content }),
945
- /* @__PURE__ */ u3("div", { class: "pp-message-time", children: [
946
- formatTime(msg.timestamp),
947
- msg.sender === "ai" && /* @__PURE__ */ u3("span", { class: "pp-ai-badge", children: "AI" }),
948
- msg.sender === "visitor" && /* @__PURE__ */ u3("span", { class: `pp-status pp-status-${msg.status ?? "sent"}`, children: /* @__PURE__ */ u3(StatusIcon, { status: msg.status }) })
949
- ] })
950
- ]
951
- },
952
- msg.id
953
- )),
954
- isTyping && /* @__PURE__ */ u3("div", { class: "pp-message pp-message-operator pp-typing", children: [
955
- /* @__PURE__ */ u3("span", {}),
956
- /* @__PURE__ */ u3("span", {}),
957
- /* @__PURE__ */ u3("span", {})
958
- ] }),
959
- /* @__PURE__ */ u3("div", { ref: messagesEndRef })
960
- ] }),
961
- /* @__PURE__ */ u3("form", { class: "pp-input-form", onSubmit: handleSubmit, children: [
962
- /* @__PURE__ */ u3(
963
- "input",
964
- {
965
- ref: inputRef,
966
- type: "text",
967
- class: "pp-input",
968
- placeholder: config.placeholder ?? "Type a message...",
969
- value: inputValue,
970
- onInput: handleInputChange,
971
- disabled: !isConnected
972
- }
973
- ),
974
- /* @__PURE__ */ u3(
975
- "button",
976
- {
977
- type: "submit",
978
- class: "pp-send-btn",
979
- disabled: !inputValue.trim() || !isConnected,
980
- "aria-label": "Send message",
981
- children: /* @__PURE__ */ u3(SendIcon, {})
982
- }
983
- )
984
- ] }),
985
- /* @__PURE__ */ u3("div", { class: "pp-footer", children: [
986
- "Powered by ",
987
- /* @__PURE__ */ u3("a", { href: "https://github.com/pocketping/pocketping", target: "_blank", rel: "noopener", children: "PocketPing" })
988
- ] })
989
- ] })
990
- ] });
991
- }
992
- function checkPageVisibility(config) {
993
- const path = window.location.pathname;
994
- if (config.hideOnPages?.some((pattern) => new RegExp(pattern).test(path))) {
995
- return false;
996
- }
997
- if (config.showOnPages?.length) {
998
- return config.showOnPages.some((pattern) => new RegExp(pattern).test(path));
999
- }
1000
- return true;
1001
- }
1002
- function getTheme(theme) {
1003
- if (theme === "auto") {
1004
- return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
1005
- }
1006
- return theme;
1007
- }
1008
- function formatTime(timestamp) {
1009
- const date = new Date(timestamp);
1010
- return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
1011
- }
1012
- function ChatIcon() {
1013
- return /* @__PURE__ */ u3("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", children: /* @__PURE__ */ u3("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }) });
1014
- }
1015
- function CloseIcon() {
1016
- return /* @__PURE__ */ u3("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", children: [
1017
- /* @__PURE__ */ u3("line", { x1: "18", y1: "6", x2: "6", y2: "18" }),
1018
- /* @__PURE__ */ u3("line", { x1: "6", y1: "6", x2: "18", y2: "18" })
1019
- ] });
1020
- }
1021
- function SendIcon() {
1022
- return /* @__PURE__ */ u3("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", children: [
1023
- /* @__PURE__ */ u3("line", { x1: "22", y1: "2", x2: "11", y2: "13" }),
1024
- /* @__PURE__ */ u3("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
1025
- ] });
1026
- }
1027
- function StatusIcon({ status }) {
1028
- if (!status || status === "sending" || status === "sent") {
1029
- return /* @__PURE__ */ u3("svg", { viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", "stroke-width": "2", class: "pp-check", children: /* @__PURE__ */ u3("polyline", { points: "3 8 7 12 13 4" }) });
1030
- }
1031
- if (status === "delivered") {
1032
- return /* @__PURE__ */ u3("svg", { viewBox: "0 0 20 16", fill: "none", stroke: "currentColor", "stroke-width": "2", class: "pp-check-double", children: [
1033
- /* @__PURE__ */ u3("polyline", { points: "1 8 5 12 11 4" }),
1034
- /* @__PURE__ */ u3("polyline", { points: "7 8 11 12 17 4" })
1035
- ] });
1036
- }
1037
- if (status === "read") {
1038
- return /* @__PURE__ */ u3("svg", { viewBox: "0 0 20 16", fill: "none", stroke: "currentColor", "stroke-width": "2", class: "pp-check-double pp-check-read", children: [
1039
- /* @__PURE__ */ u3("polyline", { points: "1 8 5 12 11 4" }),
1040
- /* @__PURE__ */ u3("polyline", { points: "7 8 11 12 17 4" })
1041
- ] });
1042
- }
1043
- return null;
1044
- }
1045
-
1046
- // src/version.ts
1047
- var VERSION = "0.2.0";
1048
-
1049
- // src/client.ts
1050
- var PocketPingClient = class {
1051
- constructor(config) {
1052
- this.session = null;
1053
- this.ws = null;
1054
- this.isOpen = false;
1055
- this.listeners = /* @__PURE__ */ new Map();
1056
- this.customEventHandlers = /* @__PURE__ */ new Map();
1057
- this.reconnectAttempts = 0;
1058
- this.maxReconnectAttempts = 5;
1059
- this.reconnectTimeout = null;
1060
- this.config = config;
1061
- }
1062
- // ─────────────────────────────────────────────────────────────────
1063
- // Public API
1064
- // ─────────────────────────────────────────────────────────────────
1065
- async connect() {
1066
- const visitorId = this.getOrCreateVisitorId();
1067
- const storedSessionId = this.getStoredSessionId();
1068
- const storedIdentity = this.getStoredIdentity();
1069
- const response = await this.fetch("/connect", {
1070
- method: "POST",
1071
- body: JSON.stringify({
1072
- visitorId,
1073
- sessionId: storedSessionId,
1074
- metadata: {
1075
- url: window.location.href,
1076
- referrer: document.referrer || void 0,
1077
- pageTitle: document.title || void 0,
1078
- userAgent: navigator.userAgent,
1079
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1080
- language: navigator.language,
1081
- screenResolution: `${window.screen.width}x${window.screen.height}`
1082
- },
1083
- // Include stored identity if available
1084
- identity: storedIdentity || void 0
1085
- })
1086
- });
1087
- this.session = {
1088
- sessionId: response.sessionId,
1089
- visitorId: response.visitorId,
1090
- operatorOnline: response.operatorOnline ?? false,
1091
- messages: response.messages ?? [],
1092
- identity: response.identity || storedIdentity || void 0
1093
- };
1094
- this.storeSessionId(response.sessionId);
1095
- this.connectWebSocket();
1096
- this.emit("connect", this.session);
1097
- this.config.onConnect?.(response.sessionId);
1098
- return this.session;
1099
- }
1100
- disconnect() {
1101
- this.ws?.close();
1102
- this.ws = null;
1103
- this.session = null;
1104
- if (this.reconnectTimeout) {
1105
- clearTimeout(this.reconnectTimeout);
1106
- }
1107
- }
1108
- async sendMessage(content) {
1109
- if (!this.session) {
1110
- throw new Error("Not connected");
1111
- }
1112
- const tempId = `temp-${this.generateId()}`;
1113
- const tempMessage = {
1114
- id: tempId,
1115
- sessionId: this.session.sessionId,
1116
- content,
1117
- sender: "visitor",
1118
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1119
- status: "sending"
1120
- };
1121
- this.session.messages.push(tempMessage);
1122
- this.emit("message", tempMessage);
1123
- try {
1124
- const response = await this.fetch("/message", {
1125
- method: "POST",
1126
- body: JSON.stringify({
1127
- sessionId: this.session.sessionId,
1128
- content,
1129
- sender: "visitor"
1130
- })
1131
- });
1132
- const messageIndex = this.session.messages.findIndex((m3) => m3.id === tempId);
1133
- if (messageIndex >= 0) {
1134
- this.session.messages[messageIndex].id = response.messageId;
1135
- this.session.messages[messageIndex].timestamp = response.timestamp;
1136
- this.session.messages[messageIndex].status = "sent";
1137
- this.emit("message", this.session.messages[messageIndex]);
1138
- }
1139
- const message = this.session.messages[messageIndex] || {
1140
- id: response.messageId,
1141
- sessionId: this.session.sessionId,
1142
- content,
1143
- sender: "visitor",
1144
- timestamp: response.timestamp,
1145
- status: "sent"
1146
- };
1147
- this.config.onMessage?.(message);
1148
- return message;
1149
- } catch (error) {
1150
- const messageIndex = this.session.messages.findIndex((m3) => m3.id === tempId);
1151
- if (messageIndex >= 0) {
1152
- this.session.messages.splice(messageIndex, 1);
1153
- this.emit("message", tempMessage);
1154
- }
1155
- throw error;
1156
- }
1157
- }
1158
- async fetchMessages(after) {
1159
- if (!this.session) {
1160
- throw new Error("Not connected");
1161
- }
1162
- const params = new URLSearchParams({
1163
- sessionId: this.session.sessionId
1164
- });
1165
- if (after) {
1166
- params.set("after", after);
1167
- }
1168
- const response = await this.fetch(
1169
- `/messages?${params}`,
1170
- { method: "GET" }
1171
- );
1172
- return response.messages;
1173
- }
1174
- async sendTyping(isTyping = true) {
1175
- if (!this.session) return;
1176
- await this.fetch("/typing", {
1177
- method: "POST",
1178
- body: JSON.stringify({
1179
- sessionId: this.session.sessionId,
1180
- sender: "visitor",
1181
- isTyping
1182
- })
1183
- });
1184
- }
1185
- async sendReadStatus(messageIds, status) {
1186
- if (!this.session || messageIds.length === 0) return;
1187
- try {
1188
- await this.fetch("/read", {
1189
- method: "POST",
1190
- body: JSON.stringify({
1191
- sessionId: this.session.sessionId,
1192
- messageIds,
1193
- status
1194
- })
1195
- });
1196
- for (const msg of this.session.messages) {
1197
- if (messageIds.includes(msg.id)) {
1198
- msg.status = status;
1199
- if (status === "delivered") {
1200
- msg.deliveredAt = (/* @__PURE__ */ new Date()).toISOString();
1201
- } else if (status === "read") {
1202
- msg.readAt = (/* @__PURE__ */ new Date()).toISOString();
1203
- }
1204
- }
1205
- }
1206
- this.emit("readStatusSent", { messageIds, status });
1207
- } catch (err) {
1208
- console.error("[PocketPing] Failed to send read status:", err);
1209
- }
1210
- }
1211
- async getPresence() {
1212
- return this.fetch("/presence", { method: "GET" });
1213
- }
1214
- // ─────────────────────────────────────────────────────────────────
1215
- // User Identity
1216
- // ─────────────────────────────────────────────────────────────────
1217
- /**
1218
- * Identify the current user with metadata
1219
- * Call after user logs in or when user data becomes available
1220
- * @param identity - User identity data with required id field
1221
- * @example
1222
- * PocketPing.identify({
1223
- * id: 'user_123',
1224
- * email: 'john@example.com',
1225
- * name: 'John Doe',
1226
- * plan: 'pro',
1227
- * company: 'Acme Inc'
1228
- * })
1229
- */
1230
- async identify(identity) {
1231
- if (!identity?.id) {
1232
- throw new Error("[PocketPing] identity.id is required");
1233
- }
1234
- this.storeIdentity(identity);
1235
- if (this.session) {
1236
- try {
1237
- await this.fetch("/identify", {
1238
- method: "POST",
1239
- body: JSON.stringify({
1240
- sessionId: this.session.sessionId,
1241
- identity
1242
- })
1243
- });
1244
- this.session.identity = identity;
1245
- this.emit("identify", identity);
1246
- } catch (err) {
1247
- console.error("[PocketPing] Failed to identify:", err);
1248
- throw err;
1249
- }
1250
- }
1251
- }
1252
- /**
1253
- * Reset the user identity and optionally start a new session
1254
- * Call on user logout to clear user data
1255
- * @param options - Optional settings: { newSession: boolean }
1256
- */
1257
- async reset(options) {
1258
- this.clearIdentity();
1259
- if (this.session) {
1260
- this.session.identity = void 0;
1261
- }
1262
- if (options?.newSession) {
1263
- localStorage.removeItem("pocketping_session_id");
1264
- localStorage.removeItem("pocketping_visitor_id");
1265
- this.disconnect();
1266
- await this.connect();
1267
- }
1268
- this.emit("reset", null);
1269
- }
1270
- /**
1271
- * Get the current user identity
1272
- * @returns UserIdentity or null if not identified
1273
- */
1274
- getIdentity() {
1275
- return this.session?.identity || this.getStoredIdentity();
1276
- }
1277
- // ─────────────────────────────────────────────────────────────────
1278
- // State
1279
- // ─────────────────────────────────────────────────────────────────
1280
- getSession() {
1281
- return this.session;
1282
- }
1283
- getMessages() {
1284
- return this.session?.messages ?? [];
1285
- }
1286
- isConnected() {
1287
- return this.session !== null;
1288
- }
1289
- isWidgetOpen() {
1290
- return this.isOpen;
1291
- }
1292
- setOpen(open2) {
1293
- this.isOpen = open2;
1294
- this.emit("openChange", open2);
1295
- if (open2) {
1296
- this.config.onOpen?.();
1297
- } else {
1298
- this.config.onClose?.();
1299
- }
1300
- }
1301
- toggleOpen() {
1302
- this.setOpen(!this.isOpen);
1303
- }
1304
- // ─────────────────────────────────────────────────────────────────
1305
- // Events
1306
- // ─────────────────────────────────────────────────────────────────
1307
- on(event, listener) {
1308
- if (!this.listeners.has(event)) {
1309
- this.listeners.set(event, /* @__PURE__ */ new Set());
1310
- }
1311
- this.listeners.get(event).add(listener);
1312
- return () => {
1313
- this.listeners.get(event)?.delete(listener);
1314
- };
1315
- }
1316
- emit(event, data) {
1317
- this.listeners.get(event)?.forEach((listener) => listener(data));
1318
- }
1319
- // ─────────────────────────────────────────────────────────────────
1320
- // Custom Events (bidirectional)
1321
- // ─────────────────────────────────────────────────────────────────
1322
- /**
1323
- * Trigger a custom event to the backend
1324
- * @param eventName - The name of the event (e.g., 'clicked_pricing', 'viewed_demo')
1325
- * @param data - Optional payload to send with the event
1326
- * @example
1327
- * PocketPing.trigger('clicked_cta', { button: 'signup', page: '/pricing' })
1328
- */
1329
- trigger(eventName, data) {
1330
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1331
- console.warn("[PocketPing] Cannot trigger event: WebSocket not connected");
1332
- return;
1333
- }
1334
- const event = {
1335
- name: eventName,
1336
- data,
1337
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1338
- };
1339
- this.ws.send(JSON.stringify({
1340
- type: "event",
1341
- data: event
1342
- }));
1343
- this.emit(`event:${eventName}`, event);
1344
- }
1345
- /**
1346
- * Subscribe to custom events from the backend
1347
- * @param eventName - The name of the event to listen for (e.g., 'show_offer', 'open_chat')
1348
- * @param handler - Callback function when event is received
1349
- * @returns Unsubscribe function
1350
- * @example
1351
- * const unsubscribe = PocketPing.onEvent('show_offer', (data) => {
1352
- * showPopup(data.message)
1353
- * })
1354
- */
1355
- onEvent(eventName, handler) {
1356
- if (!this.customEventHandlers.has(eventName)) {
1357
- this.customEventHandlers.set(eventName, /* @__PURE__ */ new Set());
1358
- }
1359
- this.customEventHandlers.get(eventName).add(handler);
1360
- return () => {
1361
- this.customEventHandlers.get(eventName)?.delete(handler);
1362
- };
1363
- }
1364
- /**
1365
- * Unsubscribe from a custom event
1366
- * @param eventName - The name of the event
1367
- * @param handler - The handler to remove
1368
- */
1369
- offEvent(eventName, handler) {
1370
- this.customEventHandlers.get(eventName)?.delete(handler);
1371
- }
1372
- emitCustomEvent(event) {
1373
- const handlers = this.customEventHandlers.get(event.name);
1374
- if (handlers) {
1375
- handlers.forEach((handler) => handler(event.data, event));
1376
- }
1377
- this.emit("event", event);
1378
- this.emit(`event:${event.name}`, event);
1379
- }
1380
- // ─────────────────────────────────────────────────────────────────
1381
- // WebSocket
1382
- // ─────────────────────────────────────────────────────────────────
1383
- connectWebSocket() {
1384
- if (!this.session) return;
1385
- const wsUrl = this.config.endpoint.replace(/^http/, "ws").replace(/\/$/, "") + `/stream?sessionId=${this.session.sessionId}`;
1386
- try {
1387
- this.ws = new WebSocket(wsUrl);
1388
- this.ws.onopen = () => {
1389
- this.reconnectAttempts = 0;
1390
- this.emit("wsConnected", null);
1391
- };
1392
- this.ws.onmessage = (event) => {
1393
- try {
1394
- const wsEvent = JSON.parse(event.data);
1395
- this.handleWebSocketEvent(wsEvent);
1396
- } catch (err) {
1397
- console.error("[PocketPing] Failed to parse WS message:", err);
1398
- }
1399
- };
1400
- this.ws.onclose = () => {
1401
- this.emit("wsDisconnected", null);
1402
- this.scheduleReconnect();
1403
- };
1404
- this.ws.onerror = (err) => {
1405
- console.error("[PocketPing] WebSocket error:", err);
1406
- };
1407
- } catch (err) {
1408
- console.warn("[PocketPing] WebSocket unavailable, using polling");
1409
- this.startPolling();
1410
- }
1411
- }
1412
- handleWebSocketEvent(event) {
1413
- switch (event.type) {
1414
- case "message":
1415
- const message = event.data;
1416
- if (this.session) {
1417
- let existingIndex = this.session.messages.findIndex((m3) => m3.id === message.id);
1418
- if (existingIndex < 0 && message.sender === "visitor") {
1419
- existingIndex = this.session.messages.findIndex(
1420
- (m3) => m3.id.startsWith("temp-") && m3.content === message.content && m3.sender === "visitor"
1421
- );
1422
- if (existingIndex >= 0) {
1423
- this.session.messages[existingIndex].id = message.id;
1424
- }
1425
- }
1426
- if (existingIndex < 0 && message.sender !== "visitor") {
1427
- const msgTime = new Date(message.timestamp).getTime();
1428
- existingIndex = this.session.messages.findIndex(
1429
- (m3) => m3.sender === message.sender && m3.content === message.content && Math.abs(new Date(m3.timestamp).getTime() - msgTime) < 2e3
1430
- );
1431
- }
1432
- if (existingIndex >= 0) {
1433
- const existing = this.session.messages[existingIndex];
1434
- if (message.status && message.status !== existing.status) {
1435
- existing.status = message.status;
1436
- if (message.deliveredAt) existing.deliveredAt = message.deliveredAt;
1437
- if (message.readAt) existing.readAt = message.readAt;
1438
- this.emit("read", { messageIds: [message.id], status: message.status });
1439
- }
1440
- } else {
1441
- this.session.messages.push(message);
1442
- this.emit("message", message);
1443
- this.config.onMessage?.(message);
1444
- }
1445
- }
1446
- if (message.sender !== "visitor") {
1447
- this.emit("typing", { isTyping: false });
1448
- }
1449
- break;
1450
- case "typing":
1451
- const typingData = event.data;
1452
- if (typingData.sender !== "visitor") {
1453
- this.emit("typing", { isTyping: typingData.isTyping });
1454
- }
1455
- break;
1456
- case "presence":
1457
- if (this.session) {
1458
- this.session.operatorOnline = event.data.online;
1459
- }
1460
- this.emit("presence", event.data);
1461
- break;
1462
- case "ai_takeover":
1463
- this.emit("aiTakeover", event.data);
1464
- break;
1465
- case "read":
1466
- const readData = event.data;
1467
- if (this.session) {
1468
- for (const msg of this.session.messages) {
1469
- if (readData.messageIds.includes(msg.id)) {
1470
- msg.status = readData.status;
1471
- if (readData.deliveredAt) msg.deliveredAt = readData.deliveredAt;
1472
- if (readData.readAt) msg.readAt = readData.readAt;
1473
- }
1474
- }
1475
- }
1476
- this.emit("read", readData);
1477
- break;
1478
- case "event":
1479
- const customEvent = event.data;
1480
- this.emitCustomEvent(customEvent);
1481
- break;
1482
- case "version_warning":
1483
- const versionWarning = event.data;
1484
- this.handleVersionWarning(versionWarning);
1485
- break;
1486
- }
1487
- }
1488
- // ─────────────────────────────────────────────────────────────────
1489
- // Version Management
1490
- // ─────────────────────────────────────────────────────────────────
1491
- handleVersionWarning(warning) {
1492
- const prefix = "[PocketPing]";
1493
- const upgradeHint = warning.upgradeUrl ? ` Upgrade: ${warning.upgradeUrl}` : " Update your widget to the latest version.";
1494
- switch (warning.severity) {
1495
- case "error":
1496
- console.error(`${prefix} \u{1F6A8} VERSION ERROR: ${warning.message}${upgradeHint}`);
1497
- console.error(`${prefix} Current: ${warning.currentVersion}, Required: ${warning.minVersion || "unknown"}`);
1498
- break;
1499
- case "warning":
1500
- console.warn(`${prefix} \u26A0\uFE0F VERSION WARNING: ${warning.message}${upgradeHint}`);
1501
- console.warn(`${prefix} Current: ${warning.currentVersion}, Latest: ${warning.latestVersion || "unknown"}`);
1502
- break;
1503
- case "info":
1504
- console.info(`${prefix} \u2139\uFE0F ${warning.message}`);
1505
- break;
1506
- }
1507
- this.emit("versionWarning", warning);
1508
- this.config.onVersionWarning?.(warning);
1509
- if (!warning.canContinue) {
1510
- console.error(`${prefix} Widget is incompatible with backend. Please update immediately.`);
1511
- this.disconnect();
1512
- }
1513
- }
1514
- scheduleReconnect() {
1515
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1516
- console.warn("[PocketPing] Max reconnect attempts reached, switching to polling");
1517
- this.startPolling();
1518
- return;
1519
- }
1520
- const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
1521
- this.reconnectAttempts++;
1522
- this.reconnectTimeout = setTimeout(() => {
1523
- this.connectWebSocket();
1524
- }, delay);
1525
- }
1526
- startPolling() {
1527
- const poll = async () => {
1528
- if (!this.session) return;
1529
- try {
1530
- const lastMessageId = this.session.messages[this.session.messages.length - 1]?.id;
1531
- const newMessages = await this.fetchMessages(lastMessageId);
1532
- for (const message of newMessages) {
1533
- if (!this.session.messages.find((m3) => m3.id === message.id)) {
1534
- this.session.messages.push(message);
1535
- this.emit("message", message);
1536
- this.config.onMessage?.(message);
1537
- }
1538
- }
1539
- } catch (err) {
1540
- console.error("[PocketPing] Polling error:", err);
1541
- }
1542
- if (this.session) {
1543
- setTimeout(poll, 3e3);
1544
- }
1545
- };
1546
- poll();
1547
- }
1548
- // ─────────────────────────────────────────────────────────────────
1549
- // HTTP
1550
- // ─────────────────────────────────────────────────────────────────
1551
- async fetch(path, options) {
1552
- const url = this.config.endpoint.replace(/\/$/, "") + path;
1553
- const response = await fetch(url, {
1554
- ...options,
1555
- headers: {
1556
- "Content-Type": "application/json",
1557
- "X-PocketPing-Version": VERSION,
1558
- ...options.headers
1559
- }
1560
- });
1561
- this.checkVersionHeaders(response);
1562
- if (!response.ok) {
1563
- const error = await response.text();
1564
- throw new Error(`PocketPing API error: ${response.status} ${error}`);
1565
- }
1566
- return response.json();
1567
- }
1568
- checkVersionHeaders(response) {
1569
- const versionStatus = response.headers.get("X-PocketPing-Version-Status");
1570
- const minVersion = response.headers.get("X-PocketPing-Min-Version");
1571
- const latestVersion = response.headers.get("X-PocketPing-Latest-Version");
1572
- const versionMessage = response.headers.get("X-PocketPing-Version-Message");
1573
- if (!versionStatus || versionStatus === "ok") {
1574
- return;
1575
- }
1576
- let severity = "info";
1577
- let canContinue = true;
1578
- if (versionStatus === "deprecated") {
1579
- severity = "warning";
1580
- } else if (versionStatus === "unsupported") {
1581
- severity = "error";
1582
- canContinue = false;
1583
- } else if (versionStatus === "outdated") {
1584
- severity = "info";
1585
- }
1586
- const warning = {
1587
- severity,
1588
- message: versionMessage || `Widget version ${VERSION} is ${versionStatus}`,
1589
- currentVersion: VERSION,
1590
- minVersion: minVersion || void 0,
1591
- latestVersion: latestVersion || void 0,
1592
- canContinue,
1593
- upgradeUrl: "https://docs.pocketping.io/widget/installation"
1594
- };
1595
- this.handleVersionWarning(warning);
1596
- }
1597
- // ─────────────────────────────────────────────────────────────────
1598
- // Storage
1599
- // ─────────────────────────────────────────────────────────────────
1600
- getOrCreateVisitorId() {
1601
- const key = "pocketping_visitor_id";
1602
- let visitorId = localStorage.getItem(key);
1603
- if (!visitorId) {
1604
- visitorId = this.generateId();
1605
- localStorage.setItem(key, visitorId);
1606
- }
1607
- return visitorId;
1608
- }
1609
- getStoredSessionId() {
1610
- return localStorage.getItem("pocketping_session_id");
1611
- }
1612
- storeSessionId(sessionId) {
1613
- localStorage.setItem("pocketping_session_id", sessionId);
1614
- }
1615
- getStoredIdentity() {
1616
- try {
1617
- const stored = localStorage.getItem("pocketping_user_identity");
1618
- return stored ? JSON.parse(stored) : null;
1619
- } catch {
1620
- return null;
1621
- }
1622
- }
1623
- storeIdentity(identity) {
1624
- localStorage.setItem("pocketping_user_identity", JSON.stringify(identity));
1625
- }
1626
- clearIdentity() {
1627
- localStorage.removeItem("pocketping_user_identity");
1628
- }
1629
- generateId() {
1630
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`;
1631
- }
1632
- };
1633
-
1634
- // src/index.ts
1635
- var client = null;
1636
- var container = null;
1637
- function init(config) {
1638
- if (client) {
1639
- console.warn("[PocketPing] Already initialized");
1640
- return client;
1641
- }
1642
- if (!config.endpoint) {
1643
- throw new Error("[PocketPing] endpoint is required");
1644
- }
1645
- client = new PocketPingClient(config);
1646
- container = document.createElement("div");
1647
- container.id = "pocketping-container";
1648
- document.body.appendChild(container);
1649
- G(_(ChatWidget, { client, config }), container);
1650
- client.connect().catch((err) => {
1651
- console.error("[PocketPing] Failed to connect:", err);
1652
- });
1653
- return client;
1654
- }
1655
- function destroy() {
1656
- if (container) {
1657
- G(null, container);
1658
- container.remove();
1659
- container = null;
1660
- }
1661
- if (client) {
1662
- client.disconnect();
1663
- client = null;
1664
- }
1665
- }
1666
- function open() {
1667
- client?.setOpen(true);
1668
- }
1669
- function close() {
1670
- client?.setOpen(false);
1671
- }
1672
- function toggle() {
1673
- client?.toggleOpen();
1674
- }
1675
- function sendMessage(content) {
1676
- if (!client) {
1677
- throw new Error("[PocketPing] Not initialized");
1678
- }
1679
- return client.sendMessage(content);
1680
- }
1681
- function trigger(eventName, data) {
1682
- if (!client) {
1683
- console.warn("[PocketPing] Not initialized, cannot trigger event");
1684
- return;
1685
- }
1686
- client.trigger(eventName, data);
1687
- }
1688
- function onEvent(eventName, handler) {
1689
- if (!client) {
1690
- console.warn("[PocketPing] Not initialized, cannot subscribe to event");
1691
- return () => {
1692
- };
1693
- }
1694
- return client.onEvent(eventName, handler);
1695
- }
1696
- function offEvent(eventName, handler) {
1697
- client?.offEvent(eventName, handler);
1698
- }
1699
- async function identify(identity) {
1700
- if (!client) {
1701
- throw new Error("[PocketPing] Not initialized");
1702
- }
1703
- return client.identify(identity);
1704
- }
1705
- async function reset(options) {
1706
- if (!client) {
1707
- console.warn("[PocketPing] Not initialized");
1708
- return;
1709
- }
1710
- return client.reset(options);
1711
- }
1712
- function getIdentity() {
1713
- return client?.getIdentity() || null;
1714
- }
1715
- function on(eventName, handler) {
1716
- if (!client) {
1717
- console.warn("[PocketPing] Not initialized, cannot subscribe to event");
1718
- return () => {
1719
- };
1720
- }
1721
- return client.on(eventName, handler);
1722
- }
1723
- if (typeof document !== "undefined") {
1724
- const script = document.currentScript;
1725
- if (script?.dataset.endpoint) {
1726
- init({
1727
- endpoint: script.dataset.endpoint,
1728
- theme: script.dataset.theme || "auto",
1729
- position: script.dataset.position || "bottom-right"
1730
- });
1731
- }
1732
- }
1733
- var index_default = { init, destroy, open, close, toggle, sendMessage, trigger, onEvent, offEvent, on, identify, reset, getIdentity };
1734
- return __toCommonJS(index_exports);
1735
- })();