@ownhelp/widget 0.1.1 → 0.1.2

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.
package/dist/lib/index.js CHANGED
@@ -1,22 +1,22 @@
1
- import { jsxs as p, jsx as a, Fragment as xe } from "react/jsx-runtime";
2
- import { useState as w, useRef as $, useCallback as J, useLayoutEffect as ve, useEffect as Z } from "react";
3
- import { createPortal as ke } from "react-dom";
4
- function ue(t) {
1
+ import { jsxs as g, jsx as s, Fragment as Pe } from "react/jsx-runtime";
2
+ import { useState as h, useRef as $, useCallback as Z, useLayoutEffect as Ae, useEffect as z } from "react";
3
+ import { createPortal as Re } from "react-dom";
4
+ function xe(t) {
5
5
  if (typeof t != "string" || t.length > 50) return;
6
6
  const e = t.trim(), r = /^(\+?[0-9 ().-]+?)(?:\s*[xX#]\s*(\d+))?$/.exec(e);
7
7
  if (!r || !/\d/.test(r[1])) return;
8
8
  const n = r[1].replace(/[^+0-9]/g, "");
9
9
  return { display: e, uri: `tel:${n}${r[2] ? `;ext=${r[2]}` : ""}` };
10
10
  }
11
- function ee(t) {
11
+ function oe(t) {
12
12
  if (!t || t.available !== !0 || typeof t.token != "string" || !t.token.trim()) return;
13
13
  const e = { available: !0, token: t.token };
14
14
  typeof t.contact_email == "string" && /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(t.contact_email) && (e.contactEmail = t.contact_email);
15
- const r = ue(t.contact_phone);
15
+ const r = xe(t.contact_phone);
16
16
  return r && (e.contactPhone = r.display), e;
17
17
  }
18
- function Ce(t) {
19
- const e = ee({
18
+ function Le(t) {
19
+ const e = oe({
20
20
  available: !0,
21
21
  token: t?.token,
22
22
  contact_email: t?.contactEmail,
@@ -24,10 +24,10 @@ function Ce(t) {
24
24
  });
25
25
  return {
26
26
  email: e?.contactEmail ? `mailto:${encodeURIComponent(e.contactEmail)}` : void 0,
27
- phone: ue(e?.contactPhone)?.uri
27
+ phone: xe(e?.contactPhone)?.uri
28
28
  };
29
29
  }
30
- function _e() {
30
+ function Oe() {
31
31
  let t = 0;
32
32
  const e = /* @__PURE__ */ new Set();
33
33
  return {
@@ -47,34 +47,34 @@ function _e() {
47
47
  }
48
48
  };
49
49
  }
50
- function Se(t) {
50
+ function ze(t) {
51
51
  let e = "", r = "message", n = [];
52
- function c() {
52
+ function i() {
53
53
  n.length > 0 && t({ event: r, data: n.join(`
54
54
  `) }), r = "message", n = [];
55
55
  }
56
- function k(l) {
57
- if (l === "") {
58
- c();
56
+ function f(u) {
57
+ if (u === "") {
58
+ i();
59
59
  return;
60
60
  }
61
- if (l.startsWith(":"))
61
+ if (u.startsWith(":"))
62
62
  return;
63
- const i = l.indexOf(":"), s = i === -1 ? l : l.slice(0, i);
64
- let d = i === -1 ? "" : l.slice(i + 1);
65
- d.startsWith(" ") && (d = d.slice(1)), s === "event" ? r = d : s === "data" && n.push(d);
63
+ const l = u.indexOf(":"), a = l === -1 ? u : u.slice(0, l);
64
+ let d = l === -1 ? "" : u.slice(l + 1);
65
+ d.startsWith(" ") && (d = d.slice(1)), a === "event" ? r = d : a === "data" && n.push(d);
66
66
  }
67
67
  return {
68
- push(l) {
69
- e += l;
70
- let i;
71
- for (; (i = e.search(/\r\n|\n|\r/)) !== -1; ) {
72
- const s = e.startsWith(`\r
73
- `, i);
74
- if (!s && e[i] === "\r" && i === e.length - 1)
68
+ push(u) {
69
+ e += u;
70
+ let l;
71
+ for (; (l = e.search(/\r\n|\n|\r/)) !== -1; ) {
72
+ const a = e.startsWith(`\r
73
+ `, l);
74
+ if (!a && e[l] === "\r" && l === e.length - 1)
75
75
  return;
76
- const d = e.slice(0, i);
77
- e = e.slice(i + (s ? 2 : 1)), k(d);
76
+ const d = e.slice(0, l);
77
+ e = e.slice(l + (a ? 2 : 1)), f(d);
78
78
  }
79
79
  },
80
80
  /** Call when the stream ends; dispatches nothing that was not terminated by a blank line. */
@@ -83,52 +83,53 @@ function Se(t) {
83
83
  }
84
84
  };
85
85
  }
86
- class h extends Error {
87
- constructor(e, r, n, c) {
88
- super(r), this.name = "ChatError", this.code = e, this.status = n, this.retryAfterSec = c;
86
+ class b extends Error {
87
+ constructor(e, r, n, i) {
88
+ super(r), this.name = "ChatError", this.code = e, this.status = n, this.retryAfterSec = i;
89
89
  }
90
90
  }
91
- const Ee = 3e4;
92
- function de(t) {
91
+ const Me = 3e4;
92
+ function ae(t) {
93
93
  return `${String(t).replace(/\/+$/, "")}/api/chat`;
94
94
  }
95
- async function fe(t) {
95
+ async function ye(t) {
96
96
  let e = `http_${t.status}`, r = `Request failed (${t.status})`;
97
97
  try {
98
- const c = await t.json();
99
- c && c.error && (e = c.error.code || e, r = c.error.message || r);
98
+ const i = await t.json();
99
+ i && i.error && (e = i.error.code || e, r = i.error.message || r);
100
100
  } catch {
101
101
  }
102
102
  const n = Number(t.headers && t.headers.get && t.headers.get("retry-after"));
103
- return new h(e, r, t.status, Number.isFinite(n) && n > 0 ? n : void 0);
103
+ return new b(e, r, t.status, Number.isFinite(n) && n > 0 ? n : void 0);
104
104
  }
105
- async function Ne({
105
+ async function je({
106
106
  apiUrl: t,
107
107
  tenantId: e,
108
108
  message: r,
109
109
  sessionId: n,
110
- signal: c,
111
- onToken: k = () => {
110
+ recordingNotice: i = !1,
111
+ signal: f,
112
+ onToken: u = () => {
112
113
  },
113
- idleTimeoutMs: l = Ee,
114
- fetchImpl: i = (...s) => fetch(...s)
114
+ idleTimeoutMs: l = Me,
115
+ fetchImpl: a = (...d) => fetch(...d)
115
116
  }) {
116
- const s = new AbortController();
117
- let d = !1, N = null;
118
- const P = () => {
119
- l && (clearTimeout(N), N = setTimeout(() => {
120
- d = !0, s.abort();
117
+ const d = new AbortController();
118
+ let A = !1, T = null;
119
+ const M = () => {
120
+ l && (clearTimeout(T), T = setTimeout(() => {
121
+ A = !0, d.abort();
121
122
  }, l));
122
- }, U = () => s.abort();
123
- if (c) {
124
- if (c.aborted)
125
- throw new h("aborted", "Request cancelled");
126
- c.addEventListener("abort", U, { once: !0 });
123
+ }, R = () => d.abort();
124
+ if (f) {
125
+ if (f.aborted)
126
+ throw new b("aborted", "Request cancelled");
127
+ f.addEventListener("abort", R, { once: !0 });
127
128
  }
128
- const q = (f) => f instanceof h ? f : d ? new h("timeout", "The assistant took too long to respond") : s.signal.aborted ? new h("aborted", "Request cancelled") : new h("network_error", "Could not reach the support service");
129
+ const Q = (p) => p instanceof b ? p : A ? new b("timeout", "The assistant took too long to respond") : d.signal.aborted ? new b("aborted", "Request cancelled") : new b("network_error", "Could not reach the support service");
129
130
  try {
130
- P();
131
- const f = await i(de(t), {
131
+ M();
132
+ const p = await a(ae(t), {
132
133
  method: "POST",
133
134
  headers: {
134
135
  "Content-Type": "application/json",
@@ -137,129 +138,142 @@ async function Ne({
137
138
  body: JSON.stringify({
138
139
  tenant_id: e,
139
140
  message: r,
140
- session_id: n
141
+ session_id: n,
142
+ ...i === !0 ? { recording_notice: !0 } : {}
141
143
  }),
142
- signal: s.signal
144
+ signal: d.signal
143
145
  });
144
- if (!f.ok)
145
- throw await fe(f);
146
- if (!(f.headers.get("content-type") || "").includes("text/event-stream") || !f.body) {
147
- const b = await f.json(), g = String(b.answer ?? "");
148
- g && k(g);
149
- const y = ee(b.follow_up);
150
- return { answer: g, sessionId: b.session_id ?? n, ...y ? { followUp: y } : {} };
146
+ if (!p.ok)
147
+ throw await ye(p);
148
+ if (!(p.headers.get("content-type") || "").includes("text/event-stream") || !p.body) {
149
+ const m = await p.json(), x = String(m.answer ?? "");
150
+ x && u(x);
151
+ const y = oe(m.follow_up);
152
+ return { answer: x, sessionId: m.session_id ?? n, ...y ? { followUp: y } : {} };
151
153
  }
152
- let L = "", _ = !1, S, m = null;
153
- const T = Se(({ event: b, data: g }) => {
154
+ let N = "", S = !1, _, C = null;
155
+ const j = ze(({ event: m, data: x }) => {
154
156
  let y = {};
155
157
  try {
156
- y = g ? JSON.parse(g) : {};
158
+ y = x ? JSON.parse(x) : {};
157
159
  } catch {
158
160
  return;
159
161
  }
160
- if (b === "token") {
161
- const I = String(y.text ?? "");
162
- L += I, k(I);
163
- } else b === "error" ? m = new h(
162
+ if (m === "token") {
163
+ const L = String(y.text ?? "");
164
+ N += L, u(L);
165
+ } else m === "error" ? C = new b(
164
166
  y.code || "stream_error",
165
167
  y.message || "The assistant ran into a problem"
166
- ) : b === "done" && (_ = !0, S = ee(y.follow_up));
167
- }), j = f.body.getReader(), C = new TextDecoder();
168
+ ) : m === "done" && (S = !0, _ = oe(y.follow_up));
169
+ }), k = p.body.getReader(), I = new TextDecoder();
168
170
  for (; ; ) {
169
- const { done: b, value: g } = await j.read();
170
- if (b)
171
+ const { done: m, value: x } = await k.read();
172
+ if (m)
171
173
  break;
172
- if (P(), T.push(C.decode(g, { stream: !0 })), m)
173
- throw await j.cancel().catch(() => {
174
- }), m;
175
- if (_) {
176
- await j.cancel().catch(() => {
174
+ if (M(), j.push(I.decode(x, { stream: !0 })), C)
175
+ throw await k.cancel().catch(() => {
176
+ }), C;
177
+ if (S) {
178
+ await k.cancel().catch(() => {
177
179
  });
178
180
  break;
179
181
  }
180
182
  }
181
- if (T.push(C.decode()), T.flush(), m)
182
- throw m;
183
- if (!_)
184
- throw new h("stream_interrupted", "The response ended unexpectedly");
185
- return { answer: L, sessionId: n, ...S ? { followUp: S } : {} };
186
- } catch (f) {
187
- throw q(f);
183
+ if (j.push(I.decode()), j.flush(), C)
184
+ throw C;
185
+ if (!S)
186
+ throw new b("stream_interrupted", "The response ended unexpectedly");
187
+ return { answer: N, sessionId: n, ..._ ? { followUp: _ } : {} };
188
+ } catch (p) {
189
+ throw Q(p);
188
190
  } finally {
189
- clearTimeout(N), c && c.removeEventListener("abort", U);
191
+ clearTimeout(T), f && f.removeEventListener("abort", R);
192
+ }
193
+ }
194
+ async function Ie({ apiUrl: t, tenantId: e, signal: r, fetchImpl: n = (...i) => fetch(...i) }) {
195
+ try {
196
+ const i = await n(`${ae(t)}?tenant_id=${encodeURIComponent(e)}`, {
197
+ method: "GET",
198
+ headers: { Accept: "application/json" },
199
+ signal: r
200
+ });
201
+ return i.ok ? (await i.json())?.record_conversations === !0 : !1;
202
+ } catch {
203
+ return !1;
190
204
  }
191
205
  }
192
- async function Te({
206
+ async function De({
193
207
  apiUrl: t,
194
208
  tenantId: e,
195
209
  sessionId: r,
196
210
  followUpToken: n,
197
- name: c,
198
- email: k,
199
- signal: l,
200
- fetchImpl: i = (...s) => fetch(...s)
211
+ name: i,
212
+ email: f,
213
+ signal: u,
214
+ fetchImpl: l = (...a) => fetch(...a)
201
215
  }) {
202
216
  try {
203
- if (l?.aborted) throw new h("aborted", "Request cancelled");
204
- const s = await i(`${de(t)}/contact`, {
217
+ if (u?.aborted) throw new b("aborted", "Request cancelled");
218
+ const a = await l(`${ae(t)}/contact`, {
205
219
  method: "POST",
206
220
  headers: { "Content-Type": "application/json", Accept: "application/json" },
207
221
  body: JSON.stringify({
208
222
  tenant_id: e,
209
223
  session_id: r,
210
224
  follow_up_token: n,
211
- name: c.trim(),
212
- email: k.trim()
225
+ name: i.trim(),
226
+ email: f.trim()
213
227
  }),
214
- signal: l
228
+ signal: u
215
229
  });
216
- if (!s.ok) throw await fe(s);
217
- if ((await s.json()).status !== "saved") throw new h("invalid_response", "Could not confirm save");
230
+ if (!a.ok) throw await ye(a);
231
+ if ((await a.json()).status !== "saved") throw new b("invalid_response", "Could not confirm save");
218
232
  return { status: "saved" };
219
- } catch (s) {
220
- throw l?.aborted ? new h("aborted", "Request cancelled") : s instanceof h ? s : new h("network_error", "Could not save contact details");
233
+ } catch (a) {
234
+ throw u?.aborted ? new b("aborted", "Request cancelled") : a instanceof b ? a : new b("network_error", "Could not save contact details");
221
235
  }
222
236
  }
223
- const R = /* @__PURE__ */ new Map();
224
- function pe() {
237
+ const P = /* @__PURE__ */ new Map();
238
+ function ve() {
225
239
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `s_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
226
240
  }
227
- function we() {
241
+ function _e() {
228
242
  try {
229
243
  return typeof localStorage < "u" ? localStorage : null;
230
244
  } catch {
231
245
  return null;
232
246
  }
233
247
  }
234
- function ae(t, e = we()) {
248
+ function fe(t, e = _e()) {
235
249
  const r = `support_widget_session:${t}`;
236
- if (R.has(r)) return R.get(r);
250
+ if (P.has(r)) return P.get(r);
237
251
  try {
238
- const c = e ? e.getItem(r) : null;
239
- if (c)
240
- return R.set(r, c), c;
252
+ const i = e ? e.getItem(r) : null;
253
+ if (i)
254
+ return P.set(r, i), i;
241
255
  } catch {
242
256
  }
243
- if (R.has(r))
244
- return R.get(r);
245
- const n = pe();
246
- R.set(r, n);
257
+ if (P.has(r))
258
+ return P.get(r);
259
+ const n = ve();
260
+ P.set(r, n);
247
261
  try {
248
262
  e && e.setItem(r, n);
249
263
  } catch {
250
264
  }
251
265
  return n;
252
266
  }
253
- function $e(t, e = we()) {
254
- const r = `support_widget_session:${t}`, n = pe();
255
- R.set(r, n);
267
+ function qe(t, e = _e()) {
268
+ const r = `support_widget_session:${t}`, n = ve();
269
+ P.set(r, n);
256
270
  try {
257
271
  e?.setItem(r, n);
258
272
  } catch {
259
273
  }
260
274
  return n;
261
275
  }
262
- const he = "The support assistant is temporarily unavailable. Please try again shortly.", se = "Something went wrong. Please try again.", ce = {
276
+ const ke = "The support assistant is temporarily unavailable. Please try again shortly.", he = "Something went wrong. Please try again.", we = {
263
277
  network_error: {
264
278
  message: "We couldn't reach the support service. Please check your connection and try again.",
265
279
  retryable: !0
@@ -271,7 +285,7 @@ const he = "The support assistant is temporarily unavailable. Please try again s
271
285
  },
272
286
  generation_failed: { message: "The assistant ran into a problem. Please try again.", retryable: !0 },
273
287
  stream_error: { message: "The assistant ran into a problem. Please try again.", retryable: !0 },
274
- service_unavailable: { message: he, retryable: !0 },
288
+ service_unavailable: { message: ke, retryable: !0 },
275
289
  message_too_long: {
276
290
  message: "That message is too long. Please shorten it (2000 characters at most) and send it again.",
277
291
  retryable: !1
@@ -280,24 +294,51 @@ const he = "The support assistant is temporarily unavailable. Please try again s
280
294
  unknown_tenant: { message: "The support chat isn't available on this site.", retryable: !1 },
281
295
  origin_not_allowed: { message: "The support chat isn't available on this site.", retryable: !1 }
282
296
  };
283
- function me(t) {
297
+ function Ce(t) {
298
+ const e = Number(t && t.retryAfterSec);
299
+ return !Number.isFinite(e) || e <= 0 ? "a moment" : e > 90 ? `${Math.ceil(e / 60)} minutes` : `${Math.ceil(e)} seconds`;
300
+ }
301
+ function Se(t) {
284
302
  const e = t && t.code;
285
- if (e === "rate_limited") {
286
- const n = Number(t.retryAfterSec);
287
- return { message: `You're sending messages too quickly. Please wait ${Number.isFinite(n) && n > 0 ? n > 90 ? `${Math.ceil(n / 60)} minutes` : `${Math.ceil(n)} seconds` : "a moment"} and try again.`, retryable: !0 };
288
- }
289
- if (e && ce[e])
290
- return ce[e];
303
+ if (e === "rate_limited")
304
+ return {
305
+ message: `You're sending messages too quickly. Please wait ${Ce(t)} and try again.`,
306
+ retryable: !0
307
+ };
308
+ if (e && we[e])
309
+ return we[e];
291
310
  const r = Number(t && t.status);
292
- return r >= 500 ? { message: he, retryable: !0 } : r >= 400 ? { message: se, retryable: !1 } : { message: se, retryable: !0 };
293
- }
294
- function Re(t) {
295
- return me(t).message;
296
- }
297
- function Pe(t) {
298
- return me(t).retryable;
311
+ return r >= 500 ? { message: ke, retryable: !0 } : r >= 400 ? { message: he, retryable: !1 } : { message: he, retryable: !0 };
312
+ }
313
+ const Ue = "Your details could not be saved. Please try again or contact the business directly.", J = "contact the business directly", ne = {
314
+ invalid_request: "Please check your name and email address and try again.",
315
+ origin_not_allowed: `Email follow-up isn't available on this site. Please ${J}.`,
316
+ unknown_tenant: `Email follow-up isn't available on this site. Please ${J}.`,
317
+ invalid_follow_up: `This follow-up form has expired. Please send your message again to get a new one, or ${J}.`,
318
+ contact_already_submitted: `Different contact details were already saved for this conversation. Please ${J} to change them.`,
319
+ service_unavailable: "We couldn't save your details right now. Please try again shortly or contact the business directly.",
320
+ network_error: "We couldn't reach the support service. Please check your connection and try again.",
321
+ timeout: "Saving your details took too long. Please try again."
322
+ };
323
+ function We(t) {
324
+ const e = t && t.code === "aborted" ? "timeout" : t && t.code;
325
+ return e === "rate_limited" ? `Too many attempts. Please wait ${Ce(t)} and try again.` : e && Object.hasOwn(ne, e) ? ne[e] : Number(t && t.status) >= 500 ? ne.service_unavailable : Ue;
326
+ }
327
+ function Fe(t) {
328
+ return Se(t).message;
329
+ }
330
+ function Be(t) {
331
+ return Se(t).retryable;
332
+ }
333
+ const Ye = 120, He = 1.01;
334
+ function Ge({ innerHeight: t, vvHeight: e, vvOffsetTop: r, vvScale: n }) {
335
+ return ![t, e, r, n].every((f) => Number.isFinite(f)) || e <= 0 || n > He ? null : {
336
+ top: Math.max(0, Math.round(r)),
337
+ height: Math.round(e),
338
+ keyboardOpen: t - e >= Ye
339
+ };
299
340
  }
300
- const Ae = `
341
+ const Ve = `
301
342
  :host { all: initial; }
302
343
  .cw-root {
303
344
  --cw-accent: #1f6feb;
@@ -442,6 +483,7 @@ const Ae = `
442
483
  .cw-contact-form .cw-send { padding: 9px; }
443
484
  .cw-contact-form [role="alert"] { color: var(--cw-error); }
444
485
  .cw-new-chat:focus-visible, .cw-contact-form input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
486
+ .cw-notice { padding: 6px 12px; border-top: 1px solid var(--cw-border); background: var(--cw-surface); font-size: 12px; color: var(--cw-muted); text-align: center; }
445
487
  .cw-form {
446
488
  display: flex;
447
489
  gap: 8px;
@@ -471,128 +513,213 @@ const Ae = `
471
513
  .cw-send:disabled { opacity: 0.5; cursor: not-allowed; }
472
514
  .cw-footer { padding: 0 10px 8px; font-size: 11px; color: var(--cw-muted); text-align: center; }
473
515
 
516
+ /* Phones and short landscape screens: the open panel fills the screen. Its box follows the part of
517
+ the screen the keyboard leaves free (--cw-vv-top / --cw-vv-height, set from the visual viewport
518
+ by ChatWidget; 100dvh is the fallback), so the header and greeting stay visible and the input
519
+ sits just above the keyboard. Everything here lives inside the widget's own shadow root. */
520
+ @media (max-width: 640px), (max-height: 500px) {
521
+ .cw-root { bottom: max(16px, env(safe-area-inset-bottom)); }
522
+ .cw-root.cw-right { right: 16px; }
523
+ .cw-root.cw-left { left: 16px; }
524
+
525
+ .cw-root.cw-open,
526
+ .cw-root.cw-open.cw-right,
527
+ .cw-root.cw-open.cw-left {
528
+ top: var(--cw-vv-top, 0px);
529
+ left: 0;
530
+ right: 0;
531
+ bottom: auto;
532
+ height: var(--cw-vv-height, 100dvh);
533
+ }
534
+ .cw-panel {
535
+ width: 100%;
536
+ max-width: none;
537
+ height: 100%;
538
+ max-height: none;
539
+ border: none;
540
+ border-radius: 0;
541
+ box-shadow: none;
542
+ }
543
+ .cw-header {
544
+ padding: 8px 10px;
545
+ padding-top: max(8px, env(safe-area-inset-top));
546
+ gap: 6px;
547
+ touch-action: none;
548
+ }
549
+ .cw-header > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
550
+ .cw-new-chat { min-height: 40px; padding: 0 12px; font-size: 13px; }
551
+ .cw-close { min-width: 44px; min-height: 44px; font-size: 28px; }
552
+ .cw-messages { padding: 12px; font-size: 15px; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
553
+ .cw-msg { max-width: 90%; padding: 9px 13px; }
554
+ .cw-follow-up p, .cw-contact-form label { font-size: 13px; }
555
+ /* 16px stops iOS Safari from zooming the page when a field is focused. */
556
+ .cw-input { font-size: 16px; padding: 10px 12px; }
557
+ .cw-send { min-width: 64px; min-height: 44px; }
558
+ .cw-form { padding: 8px 10px; }
559
+ .cw-footer { padding-bottom: max(8px, env(safe-area-inset-bottom)); touch-action: none; }
560
+ /* With the keyboard up, drop the footer line and its safe-area padding to keep room for messages. */
561
+ .cw-root.cw-kb .cw-footer { display: none; }
562
+ }
563
+
474
564
  @media (prefers-reduced-motion: reduce) {
475
565
  .cw-typing::after { animation: none; }
476
566
  }
477
- `, ie = 2e3, Le = 6e3;
478
- let le = 0;
479
- function V() {
480
- return le += 1, `m${le}`;
567
+ `, me = 2e3, Xe = 6e3;
568
+ let ge = 0;
569
+ function K() {
570
+ return ge += 1, `m${ge}`;
481
571
  }
482
- function Ie({
572
+ function be() {
573
+ try {
574
+ return !window.matchMedia("(pointer: coarse)").matches;
575
+ } catch {
576
+ return !0;
577
+ }
578
+ }
579
+ function Ze({
483
580
  apiUrl: t,
484
581
  tenantId: e,
485
582
  title: r = "Support",
486
583
  greeting: n = "Hi! How can I help you today?",
487
- position: c = "right",
488
- accentColor: k,
489
- defaultOpen: l = !1,
490
- fetchImpl: i
584
+ position: i = "right",
585
+ accentColor: f,
586
+ defaultOpen: u = !1,
587
+ fetchImpl: l
491
588
  }) {
492
- const [s, d] = w(l), [N, P] = w(""), [U, q] = w(!1), [f, A] = w(!1), [L, _] = w(() => [
493
- { id: V(), role: "assistant", text: n, status: "done" }
494
- ]), S = $(null), m = $(null);
495
- m.current || (m.current = _e());
496
- const [T, j] = w(() => ae(e)), [C, b] = w(null), [g, y] = w(""), [I, X] = w(""), [z, D] = w("idle"), [te, W] = w(""), F = $(!1), H = $(!1), re = $(null), Y = $(null), K = $(""), ne = J((o) => {
497
- m.current.reset(), S.current = null, H.current = !1, F.current = !1, K.current = "", j(o ? $e(e) : ae(e)), _([{ id: V(), role: "assistant", text: n, status: "done" }]), P(""), q(!1), A(!1), b(null), y(""), X(""), D("idle"), W(""), Y.current?.focus();
589
+ const [a, d] = h(u), [A, T] = h(""), [M, R] = h(!1), [Q, p] = h(!1), [U, N] = h(() => [
590
+ { id: K(), role: "assistant", text: n, status: "done" }
591
+ ]), S = $(null), _ = $(null);
592
+ _.current || (_.current = Oe());
593
+ const [C, j] = h(() => fe(e)), [k, I] = h(null), [m, x] = h(""), [y, L] = h(""), [O, W] = h("idle"), [se, F] = h(""), B = $(!1), Y = $(!1), ie = $(null), H = $(null), ee = $(""), [G, ce] = h(null), [te, le] = h(!1), de = Z((o) => {
594
+ _.current.reset(), S.current = null, Y.current = !1, B.current = !1, ee.current = "", j(o ? qe(e) : fe(e)), N([{ id: K(), role: "assistant", text: n, status: "done" }]), T(""), R(!1), p(!1), I(null), x(""), L(""), W("idle"), F(""), be() && H.current?.focus();
498
595
  }, [e, n]);
499
- ve(() => {
500
- ne(!1);
501
- }, [e, t]), Z(() => {
502
- const o = re.current;
596
+ Ae(() => {
597
+ de(!1);
598
+ }, [e, t]);
599
+ const ue = !!G?.keyboardOpen;
600
+ z(() => {
601
+ const o = ie.current;
503
602
  o && (o.scrollTop = o.scrollHeight);
504
- }, [L, s]), Z(() => {
505
- s && Y.current && Y.current.focus();
506
- }, [s]), Z(() => () => m.current.reset(), []);
507
- const M = J((o, u) => {
508
- _((v) => v.map((x) => x.id === o ? { ...x, ...u } : x));
509
- }, []), Q = J(
603
+ }, [U, a, ue]), z(() => {
604
+ a && H.current && be() && H.current.focus();
605
+ }, [a]), z(() => {
606
+ const o = typeof window < "u" ? window.visualViewport : null;
607
+ if (!a || !o) {
608
+ ce(null);
609
+ return;
610
+ }
611
+ const c = () => ce(
612
+ Ge({
613
+ innerHeight: window.innerHeight,
614
+ vvHeight: o.height,
615
+ vvOffsetTop: o.offsetTop,
616
+ vvScale: o.scale
617
+ })
618
+ );
619
+ return c(), o.addEventListener("resize", c), o.addEventListener("scroll", c), () => {
620
+ o.removeEventListener("resize", c), o.removeEventListener("scroll", c);
621
+ };
622
+ }, [a]), z(() => () => _.current.reset(), []), z(() => {
623
+ if (le(!1), !a) return;
624
+ const o = new AbortController();
625
+ return Ie({ apiUrl: t, tenantId: e, signal: o.signal, fetchImpl: l }).then((c) => {
626
+ o.signal.aborted || le(c);
627
+ }), () => o.abort();
628
+ }, [a, t, e, l]);
629
+ const D = Z((o, c) => {
630
+ N((v) => v.map((w) => w.id === o ? { ...w, ...c } : w));
631
+ }, []), re = Z(
510
632
  async (o) => {
511
- const u = o.trim().slice(0, ie);
512
- if (!u || H.current)
633
+ const c = o.trim().slice(0, me);
634
+ if (!c || Y.current)
513
635
  return;
514
- H.current = !0, K.current = u;
515
- const v = V();
516
- _((E) => [
636
+ Y.current = !0, ee.current = c;
637
+ const v = K();
638
+ N((E) => [
517
639
  ...E,
518
- { id: V(), role: "user", text: u, status: "done" },
640
+ { id: K(), role: "user", text: c, status: "done" },
519
641
  { id: v, role: "assistant", text: "", status: "streaming" }
520
- ]), P(""), q(!0);
521
- const x = m.current.begin();
522
- S.current = x;
523
- let O = "";
524
- A(!1);
525
- const oe = setTimeout(() => {
526
- x.isCurrent() && A(!0);
527
- }, Le);
642
+ ]), T(""), R(!0);
643
+ const w = _.current.begin();
644
+ S.current = w;
645
+ let q = "";
646
+ p(!1);
647
+ const pe = setTimeout(() => {
648
+ w.isCurrent() && p(!0);
649
+ }, Xe);
528
650
  try {
529
- const E = await Ne({
651
+ const E = await je({
530
652
  apiUrl: t,
531
653
  tenantId: e,
532
- message: u,
533
- sessionId: T,
534
- signal: x.signal,
535
- fetchImpl: i,
536
- onToken: (B) => {
537
- x.isCurrent() && (clearTimeout(oe), A(!1), O += B, M(v, { text: O }));
654
+ message: c,
655
+ sessionId: C,
656
+ // Only true while the recording notice is on screen (see `recording`).
657
+ recordingNotice: te,
658
+ signal: w.signal,
659
+ fetchImpl: l,
660
+ onToken: (X) => {
661
+ w.isCurrent() && (clearTimeout(pe), p(!1), q += X, D(v, { text: q }));
538
662
  }
539
663
  });
540
- if (!x.isCurrent()) return;
541
- M(v, { status: "done" }), E.followUp && (b(E.followUp), W(""));
664
+ if (!w.isCurrent()) return;
665
+ D(v, { status: "done" }), E.followUp && (I(E.followUp), F(""));
542
666
  } catch (E) {
543
- if (!x.isCurrent()) return;
667
+ if (!w.isCurrent()) return;
544
668
  if (E.code === "aborted")
545
- M(v, { status: "done", text: O || "(stopped)" });
669
+ D(v, { status: "done", text: q || "(stopped)" });
546
670
  else {
547
- const B = Re(E);
548
- M(v, {
671
+ const X = Fe(E);
672
+ D(v, {
549
673
  status: "error",
550
- retryable: Pe(E),
551
- text: O ? `${O}
674
+ retryable: Be(E),
675
+ text: q ? `${q}
552
676
 
553
- ${B}` : B
677
+ ${X}` : X
554
678
  });
555
679
  }
556
680
  } finally {
557
- clearTimeout(oe), x.finish(), x.isCurrent() && (S.current = null, H.current = !1, A(!1), q(!1));
681
+ clearTimeout(pe), w.finish(), w.isCurrent() && (S.current = null, Y.current = !1, p(!1), R(!1));
558
682
  }
559
683
  },
560
- [t, e, T, i, M]
561
- ), be = J(() => {
562
- const o = K.current;
563
- o && (_((u) => u.slice(0, -2)), Q(o));
564
- }, [Q]), ge = (o) => {
565
- o.preventDefault(), Q(N);
566
- }, ye = async (o) => {
567
- if (o.preventDefault(), !C || F.current || z === "saved") return;
568
- F.current = !0;
569
- const u = m.current.begin();
570
- D("pending"), W("");
571
- const v = setTimeout(() => u.abort(), 3e4);
684
+ [t, e, C, l, D, te]
685
+ ), Ee = Z(() => {
686
+ const o = ee.current;
687
+ o && (N((c) => c.slice(0, -2)), re(o));
688
+ }, [re]), Te = (o) => {
689
+ o.preventDefault(), re(A);
690
+ }, Ne = async (o) => {
691
+ if (o.preventDefault(), !k || B.current || O === "saved") return;
692
+ B.current = !0;
693
+ const c = _.current.begin();
694
+ W("pending"), F("");
695
+ const v = setTimeout(() => c.abort(), 3e4);
572
696
  try {
573
- await Te({
697
+ await De({
574
698
  apiUrl: t,
575
699
  tenantId: e,
576
- sessionId: T,
577
- followUpToken: C.token,
578
- name: g,
579
- email: I,
580
- signal: u.signal,
581
- fetchImpl: i
582
- }), u.isCurrent() && (D("saved"), y(""), X(""));
583
- } catch {
584
- u.isCurrent() && (D("error"), W("Your details could not be saved. Please try again or contact the business directly."));
700
+ sessionId: C,
701
+ followUpToken: k.token,
702
+ name: m,
703
+ email: y,
704
+ signal: c.signal,
705
+ fetchImpl: l
706
+ }), c.isCurrent() && (W("saved"), x(""), L(""));
707
+ } catch (w) {
708
+ c.isCurrent() && (W("error"), F(We(w)));
585
709
  } finally {
586
- clearTimeout(v), u.finish(), u.isCurrent() && (F.current = !1);
710
+ clearTimeout(v), c.finish(), c.isCurrent() && (B.current = !1);
587
711
  }
588
- }, G = Ce(C);
589
- return /* @__PURE__ */ p("div", { className: `cw-root ${c === "left" ? "cw-left" : "cw-right"}`, style: k ? { "--cw-accent": k } : void 0, children: [
590
- /* @__PURE__ */ a("style", { children: Ae }),
591
- s ? /* @__PURE__ */ p("section", { className: "cw-panel", role: "dialog", "aria-label": r, children: [
592
- /* @__PURE__ */ p("header", { className: "cw-header", children: [
593
- /* @__PURE__ */ a("span", { children: r }),
594
- /* @__PURE__ */ a("button", { type: "button", className: "cw-new-chat", onClick: () => ne(!0), children: "New chat" }),
595
- /* @__PURE__ */ a(
712
+ }, V = Le(k), $e = {
713
+ ...f ? { "--cw-accent": f } : {},
714
+ ...a && G ? { "--cw-vv-top": `${G.top}px`, "--cw-vv-height": `${G.height}px` } : {}
715
+ };
716
+ return /* @__PURE__ */ g("div", { className: `cw-root ${i === "left" ? "cw-left" : "cw-right"}${`${a ? " cw-open" : ""}${a && ue ? " cw-kb" : ""}`}`, style: $e, children: [
717
+ /* @__PURE__ */ s("style", { children: Ve }),
718
+ a ? /* @__PURE__ */ g("section", { className: "cw-panel", role: "dialog", "aria-label": r, children: [
719
+ /* @__PURE__ */ g("header", { className: "cw-header", children: [
720
+ /* @__PURE__ */ s("span", { children: r }),
721
+ /* @__PURE__ */ s("button", { type: "button", className: "cw-new-chat", onClick: () => de(!0), children: "New chat" }),
722
+ /* @__PURE__ */ s(
596
723
  "button",
597
724
  {
598
725
  type: "button",
@@ -603,41 +730,41 @@ ${B}` : B
603
730
  }
604
731
  )
605
732
  ] }),
606
- /* @__PURE__ */ p("div", { className: "cw-messages", ref: re, role: "log", "aria-live": "polite", children: [
607
- L.map((o, u) => {
608
- const v = u === L.length - 1;
609
- return /* @__PURE__ */ p(
733
+ /* @__PURE__ */ g("div", { className: "cw-messages", ref: ie, role: "log", "aria-live": "polite", children: [
734
+ U.map((o, c) => {
735
+ const v = c === U.length - 1;
736
+ return /* @__PURE__ */ g(
610
737
  "div",
611
738
  {
612
739
  className: `cw-msg cw-${o.role}${o.status === "error" ? " cw-error" : ""}`,
613
740
  children: [
614
741
  o.text,
615
- o.status === "streaming" && !o.text ? /* @__PURE__ */ p(xe, { children: [
616
- /* @__PURE__ */ a("span", { className: "cw-typing", "aria-label": "Assistant is typing" }),
617
- f ? /* @__PURE__ */ a("span", { className: "cw-slow", children: "Still working on your answer…" }) : null
742
+ o.status === "streaming" && !o.text ? /* @__PURE__ */ g(Pe, { children: [
743
+ /* @__PURE__ */ s("span", { className: "cw-typing", "aria-label": "Assistant is typing" }),
744
+ Q ? /* @__PURE__ */ s("span", { className: "cw-slow", children: "Still working on your answer…" }) : null
618
745
  ] }) : null,
619
- o.status === "error" && o.retryable !== !1 && v && !U ? /* @__PURE__ */ a("div", { children: /* @__PURE__ */ a("button", { type: "button", className: "cw-retry", onClick: be, children: "Retry" }) }) : null
746
+ o.status === "error" && o.retryable !== !1 && v && !M ? /* @__PURE__ */ s("div", { children: /* @__PURE__ */ s("button", { type: "button", className: "cw-retry", onClick: Ee, children: "Retry" }) }) : null
620
747
  ]
621
748
  },
622
749
  o.id
623
750
  );
624
751
  }),
625
- C ? /* @__PURE__ */ p("section", { className: "cw-follow-up", "aria-label": "Email follow-up", children: [
626
- /* @__PURE__ */ a("strong", { children: "Email follow-up" }),
627
- /* @__PURE__ */ a("p", { children: "Email follow-up is not immediate. For time-sensitive help, contact the business directly." }),
628
- G.phone ? /* @__PURE__ */ p("p", { children: [
752
+ k ? /* @__PURE__ */ g("section", { className: "cw-follow-up", "aria-label": "Email follow-up", children: [
753
+ /* @__PURE__ */ s("strong", { children: "Email follow-up" }),
754
+ /* @__PURE__ */ s("p", { children: "Email follow-up is not immediate. For time-sensitive help, contact the business directly." }),
755
+ V.phone ? /* @__PURE__ */ g("p", { children: [
629
756
  "Call ",
630
- /* @__PURE__ */ a("a", { href: G.phone, target: "_blank", rel: "noopener noreferrer", children: C.contactPhone })
757
+ /* @__PURE__ */ s("a", { href: V.phone, target: "_blank", rel: "noopener noreferrer", children: k.contactPhone })
631
758
  ] }) : null,
632
- G.email ? /* @__PURE__ */ p("p", { children: [
759
+ V.email ? /* @__PURE__ */ g("p", { children: [
633
760
  "Email ",
634
- /* @__PURE__ */ a("a", { href: G.email, target: "_blank", rel: "noopener noreferrer", children: C.contactEmail })
761
+ /* @__PURE__ */ s("a", { href: V.email, target: "_blank", rel: "noopener noreferrer", children: k.contactEmail })
635
762
  ] }) : null,
636
- z === "saved" ? /* @__PURE__ */ a("p", { role: "status", children: "Your details were saved for the team to review and follow up by email." }) : /* @__PURE__ */ p("form", { className: "cw-contact-form", onSubmit: ye, children: [
637
- /* @__PURE__ */ a("p", { children: "Leave your name and email to request follow-up about this conversation." }),
638
- /* @__PURE__ */ p("label", { children: [
763
+ O === "saved" ? /* @__PURE__ */ s("p", { role: "status", children: "Your details were saved for the team to review and follow up by email." }) : /* @__PURE__ */ g("form", { className: "cw-contact-form", onSubmit: Ne, children: [
764
+ /* @__PURE__ */ s("p", { children: "Leave your name and email to request follow-up about this conversation." }),
765
+ /* @__PURE__ */ g("label", { children: [
639
766
  "Name",
640
- /* @__PURE__ */ a(
767
+ /* @__PURE__ */ s(
641
768
  "input",
642
769
  {
643
770
  className: "cw-input",
@@ -645,15 +772,15 @@ ${B}` : B
645
772
  autoComplete: "name",
646
773
  required: !0,
647
774
  maxLength: 100,
648
- value: g,
649
- disabled: z === "pending",
650
- onChange: (o) => y(o.target.value)
775
+ value: m,
776
+ disabled: O === "pending",
777
+ onChange: (o) => x(o.target.value)
651
778
  }
652
779
  )
653
780
  ] }),
654
- /* @__PURE__ */ p("label", { children: [
781
+ /* @__PURE__ */ g("label", { children: [
655
782
  "Email",
656
- /* @__PURE__ */ a(
783
+ /* @__PURE__ */ s(
657
784
  "input",
658
785
  {
659
786
  className: "cw-input",
@@ -662,31 +789,32 @@ ${B}` : B
662
789
  autoComplete: "email",
663
790
  required: !0,
664
791
  maxLength: 254,
665
- value: I,
666
- disabled: z === "pending",
667
- onChange: (o) => X(o.target.value)
792
+ value: y,
793
+ disabled: O === "pending",
794
+ onChange: (o) => L(o.target.value)
668
795
  }
669
796
  )
670
797
  ] }),
671
- te ? /* @__PURE__ */ a("p", { role: "alert", children: te }) : null,
672
- /* @__PURE__ */ a("button", { className: "cw-send", type: "submit", disabled: z === "pending" || !g.trim() || !I.trim(), children: z === "pending" ? "Saving…" : "Request email follow-up" })
798
+ se ? /* @__PURE__ */ s("p", { role: "alert", children: se }) : null,
799
+ /* @__PURE__ */ s("button", { className: "cw-send", type: "submit", disabled: O === "pending" || !m.trim() || !y.trim(), children: O === "pending" ? "Saving…" : "Request email follow-up" })
673
800
  ] })
674
801
  ] }) : null
675
802
  ] }),
676
- /* @__PURE__ */ p("form", { className: "cw-form", onSubmit: ge, children: [
677
- /* @__PURE__ */ a(
803
+ te ? /* @__PURE__ */ s("div", { className: "cw-notice", role: "note", children: "This conversation is recorded to improve the assistant." }) : null,
804
+ /* @__PURE__ */ g("form", { className: "cw-form", onSubmit: Te, children: [
805
+ /* @__PURE__ */ s(
678
806
  "input",
679
807
  {
680
- ref: Y,
808
+ ref: H,
681
809
  className: "cw-input",
682
- value: N,
683
- maxLength: ie,
810
+ value: A,
811
+ maxLength: me,
684
812
  placeholder: "Type your question…",
685
813
  "aria-label": "Your message",
686
- onChange: (o) => P(o.target.value)
814
+ onChange: (o) => T(o.target.value)
687
815
  }
688
816
  ),
689
- U ? /* @__PURE__ */ a(
817
+ M ? /* @__PURE__ */ s(
690
818
  "button",
691
819
  {
692
820
  type: "button",
@@ -694,32 +822,32 @@ ${B}` : B
694
822
  onClick: () => S.current?.abort(),
695
823
  children: "Stop"
696
824
  }
697
- ) : /* @__PURE__ */ a("button", { type: "submit", className: "cw-send", disabled: !N.trim(), children: "Send" })
825
+ ) : /* @__PURE__ */ s("button", { type: "submit", className: "cw-send", disabled: !A.trim(), children: "Send" })
698
826
  ] }),
699
- /* @__PURE__ */ a("div", { className: "cw-footer", children: "AI assistant – answers may contain mistakes." })
700
- ] }) : /* @__PURE__ */ a(
827
+ /* @__PURE__ */ s("div", { className: "cw-footer", children: "AI assistant – answers may contain mistakes." })
828
+ ] }) : /* @__PURE__ */ s(
701
829
  "button",
702
830
  {
703
831
  type: "button",
704
832
  className: "cw-launcher",
705
833
  "aria-label": `Open ${r} chat`,
706
834
  onClick: () => d(!0),
707
- children: /* @__PURE__ */ a("svg", { width: "26", height: "26", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ a("path", { d: "M4 3h16a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H9l-5 4v-4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z" }) })
835
+ children: /* @__PURE__ */ s("svg", { width: "26", height: "26", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ s("path", { d: "M4 3h16a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H9l-5 4v-4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z" }) })
708
836
  }
709
837
  )
710
838
  ] });
711
839
  }
712
- function Oe(t) {
713
- const [e, r] = w(null), [n, c] = w(null);
714
- return Z(() => {
715
- e && c(e.shadowRoot || e.attachShadow({ mode: "open" }));
716
- }, [e]), /* @__PURE__ */ a("div", { ref: r, "data-support-widget": t.tenantId, children: n ? ke(/* @__PURE__ */ a(Ie, { ...t }), n) : null });
840
+ function rt(t) {
841
+ const [e, r] = h(null), [n, i] = h(null);
842
+ return z(() => {
843
+ e && i(e.shadowRoot || e.attachShadow({ mode: "open" }));
844
+ }, [e]), /* @__PURE__ */ s("div", { ref: r, "data-support-widget": t.tenantId, children: n ? Re(/* @__PURE__ */ s(Ze, { ...t }), n) : null });
717
845
  }
718
846
  export {
719
- h as ChatError,
720
- Oe as ChatWidget,
721
- ae as getSessionId,
722
- $e as newSessionId,
723
- Ne as streamChat,
724
- Te as submitContact
847
+ b as ChatError,
848
+ rt as ChatWidget,
849
+ fe as getSessionId,
850
+ qe as newSessionId,
851
+ je as streamChat,
852
+ De as submitContact
725
853
  };