@trillet-ai/web-sdk 1.7.0 → 1.9.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.
@@ -0,0 +1,1513 @@
1
+ import {
2
+ TrilletAgent
3
+ } from "../chunk-FSJ42TKR.js";
4
+ import "../chunk-3MH6DJZ6.js";
5
+
6
+ // src/widget/config.ts
7
+ var DEFAULT_ORB_COLOR_1 = "#2792dc";
8
+ var DEFAULT_ORB_COLOR_2 = "#9ce6e6";
9
+ var DEFAULT_COPY = {
10
+ startCallText: "Start a call",
11
+ endCallText: "End call",
12
+ messageText: "Message",
13
+ switchToTextText: "Switch to text mode",
14
+ switchToVoiceText: "Switch to voice mode",
15
+ listeningText: "Listening\u2026",
16
+ speakingText: "Speaking\u2026",
17
+ expandText: "Expand",
18
+ collapseText: "Collapse",
19
+ recaptchaText: "Verify you are human to start"
20
+ };
21
+ var OBSERVED_ATTRIBUTES = [
22
+ "agent-id",
23
+ "signed-url-endpoint",
24
+ "workspace-id",
25
+ "agent-name",
26
+ "call-flow-name",
27
+ "workspace-name",
28
+ "avatar",
29
+ "avatar-image-url",
30
+ // convai alias -> avatar
31
+ "orb-color",
32
+ "avatar-orb-color-1",
33
+ "avatar-orb-color-2",
34
+ "variant",
35
+ "placement",
36
+ "dismissible",
37
+ "action-text",
38
+ "start-call-text",
39
+ "end-call-text",
40
+ "message-text",
41
+ "switch-to-text-text",
42
+ "switch-to-voice-text",
43
+ "listening-text",
44
+ "speaking-text",
45
+ "expand-text",
46
+ "collapse-text",
47
+ "recaptcha-text",
48
+ "mode",
49
+ "variables",
50
+ "dynamic-variables",
51
+ // convai alias -> variables
52
+ "max-call-duration",
53
+ "recaptcha-site-key",
54
+ "disable-banner",
55
+ // convai no-op
56
+ "brand-logo",
57
+ "brand-color",
58
+ "brand-name"
59
+ ];
60
+ var PLACEMENTS = [
61
+ "top-left",
62
+ "top",
63
+ "top-right",
64
+ "bottom-left",
65
+ "bottom",
66
+ "bottom-right"
67
+ ];
68
+ function parseBoolAttr(value) {
69
+ if (value === null) return false;
70
+ return value !== "false";
71
+ }
72
+ function parseJsonAttr(value) {
73
+ if (!value) return void 0;
74
+ try {
75
+ const parsed = JSON.parse(value);
76
+ return parsed && typeof parsed === "object" ? parsed : void 0;
77
+ } catch (e) {
78
+ console.warn("[trillet-widget] Failed to parse JSON attribute:", value);
79
+ return void 0;
80
+ }
81
+ }
82
+ function parseNumberAttr(value) {
83
+ if (!value) return void 0;
84
+ const n = Number(value);
85
+ return Number.isFinite(n) ? n : void 0;
86
+ }
87
+ function resolveVariant(raw) {
88
+ switch (raw) {
89
+ case "expanded":
90
+ case "full":
91
+ return "expanded";
92
+ case "tiny":
93
+ case "compact":
94
+ return "compact";
95
+ default:
96
+ return "compact";
97
+ }
98
+ }
99
+ function configFromElement(el) {
100
+ const get = (name) => el.getAttribute(name);
101
+ const variant = resolveVariant(get("variant"));
102
+ const modeRaw = get("mode");
103
+ const mode = modeRaw === "text" ? "text" : modeRaw === "both" ? "both" : "voice";
104
+ const placementRaw = get("placement");
105
+ const placement = PLACEMENTS.includes(placementRaw) ? placementRaw : "bottom-right";
106
+ const isText = mode === "text";
107
+ const startDefault = isText ? "Start chat" : DEFAULT_COPY.startCallText;
108
+ const endDefault = isText ? "End chat" : DEFAULT_COPY.endCallText;
109
+ const brand = {};
110
+ const brandLogo = get("brand-logo");
111
+ const brandColor = get("brand-color");
112
+ const brandName = get("brand-name");
113
+ if (brandLogo) brand.logo = brandLogo;
114
+ if (brandColor) brand.primaryColor = brandColor;
115
+ if (brandName) brand.name = brandName;
116
+ const orbColor = get("orb-color") || void 0;
117
+ const orbColor1 = get("avatar-orb-color-1") || orbColor || void 0;
118
+ const orbColor2 = get("avatar-orb-color-2") || void 0;
119
+ return {
120
+ agentId: get("agent-id") || "",
121
+ signedUrlEndpoint: get("signed-url-endpoint") || void 0,
122
+ workspaceId: get("workspace-id") || void 0,
123
+ // Header identity overrides — empty string/absent => treated as "not set".
124
+ agentName: get("agent-name") || void 0,
125
+ callFlowName: get("call-flow-name") || void 0,
126
+ workspaceName: get("workspace-name") || void 0,
127
+ // convai `avatar-image-url` is an alias of our `avatar`.
128
+ avatar: get("avatar") || get("avatar-image-url") || void 0,
129
+ orbColor,
130
+ orbColor1,
131
+ orbColor2,
132
+ variant,
133
+ placement,
134
+ dismissible: parseBoolAttr(get("dismissible")),
135
+ actionText: get("action-text") || void 0,
136
+ startCallText: get("start-call-text") || startDefault,
137
+ endCallText: get("end-call-text") || endDefault,
138
+ messageText: get("message-text") || DEFAULT_COPY.messageText,
139
+ switchToTextText: get("switch-to-text-text") || DEFAULT_COPY.switchToTextText,
140
+ switchToVoiceText: get("switch-to-voice-text") || DEFAULT_COPY.switchToVoiceText,
141
+ listeningText: get("listening-text") || DEFAULT_COPY.listeningText,
142
+ speakingText: get("speaking-text") || DEFAULT_COPY.speakingText,
143
+ expandText: get("expand-text") || DEFAULT_COPY.expandText,
144
+ collapseText: get("collapse-text") || DEFAULT_COPY.collapseText,
145
+ recaptchaText: get("recaptcha-text") || DEFAULT_COPY.recaptchaText,
146
+ mode,
147
+ // convai `dynamic-variables` is an alias of our `variables`.
148
+ variables: parseJsonAttr(get("variables") || get("dynamic-variables")),
149
+ maxCallDuration: parseNumberAttr(get("max-call-duration")),
150
+ recaptchaSiteKey: get("recaptcha-site-key") || void 0,
151
+ disableBanner: parseBoolAttr(get("disable-banner")),
152
+ brand
153
+ };
154
+ }
155
+
156
+ // src/widget/styles.ts
157
+ var WIDGET_STYLES = (
158
+ /* css */
159
+ `
160
+ :host {
161
+ /* Positioning: default bottom-right. The host can override by setting
162
+ position-related CSS on the trillet-widget element directly, or via the
163
+ placement attribute (see :host([placement=...]) rules below). */
164
+ position: fixed;
165
+ right: 24px;
166
+ bottom: 24px;
167
+ z-index: 2147483000;
168
+
169
+ /* Theming tokens (overridden at runtime via setProperty). */
170
+ --trillet-accent: #2792dc;
171
+ --trillet-orb-1: #2792dc;
172
+ --trillet-orb-2: #9ce6e6;
173
+ --trillet-surface: #ffffff;
174
+ --trillet-on-surface: #0b0b0f;
175
+ --trillet-muted: #6b7280;
176
+ --trillet-border: rgba(0, 0, 0, 0.08);
177
+ --trillet-shadow: 0 12px 48px rgba(0, 0, 0, 0.20);
178
+
179
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
180
+ font-size: 14px;
181
+ line-height: 1.4;
182
+ color: var(--trillet-on-surface);
183
+ }
184
+
185
+ :host([hidden]) { display: none; }
186
+
187
+ /* ---- placement attribute (fixed positioning on the host element) ----
188
+ Kept in the shadow stylesheet (low specificity) so raw CSS on the
189
+ trillet-widget element still overrides it. */
190
+ :host([placement="bottom-right"]) { top: auto; bottom: 24px; left: auto; right: 24px; }
191
+ :host([placement="bottom-left"]) { top: auto; bottom: 24px; right: auto; left: 24px; }
192
+ :host([placement="bottom"]) { top: auto; bottom: 24px; left: 50%; right: auto; transform: translateX(-50%); }
193
+ :host([placement="top-right"]) { bottom: auto; top: 24px; left: auto; right: 24px; }
194
+ :host([placement="top-left"]) { bottom: auto; top: 24px; right: auto; left: 24px; }
195
+ :host([placement="top"]) { bottom: auto; top: 24px; left: 50%; right: auto; transform: translateX(-50%); }
196
+
197
+ * { box-sizing: border-box; }
198
+
199
+ .tw-root {
200
+ display: flex;
201
+ flex-direction: column;
202
+ align-items: flex-end;
203
+ gap: 12px;
204
+ }
205
+ /* Left/center placements align the launcher + card accordingly. */
206
+ :host([placement="bottom-left"]) .tw-root,
207
+ :host([placement="top-left"]) .tw-root { align-items: flex-start; }
208
+ :host([placement="bottom"]) .tw-root,
209
+ :host([placement="top"]) .tw-root { align-items: center; }
210
+
211
+ /* ---- Floating launcher ---- */
212
+ .tw-launcher {
213
+ display: inline-flex;
214
+ align-items: center;
215
+ gap: 10px;
216
+ padding: 12px 18px;
217
+ border: none;
218
+ border-radius: 999px;
219
+ background: var(--trillet-accent);
220
+ color: #fff;
221
+ font-size: 14px;
222
+ font-weight: 600;
223
+ cursor: pointer;
224
+ box-shadow: var(--trillet-shadow);
225
+ transition: transform 0.15s ease, box-shadow 0.15s ease, opacity 0.15s ease;
226
+ }
227
+ .tw-launcher:hover { transform: translateY(-1px); box-shadow: 0 16px 52px rgba(0, 0, 0, 0.26); }
228
+ .tw-launcher:active { transform: translateY(0); }
229
+ .tw-launcher .tw-launcher-orb {
230
+ width: 20px;
231
+ height: 20px;
232
+ border-radius: 50%;
233
+ background:
234
+ conic-gradient(from 0deg, var(--trillet-orb-1), var(--trillet-orb-2), var(--trillet-orb-1));
235
+ box-shadow: inset 0 0 4px rgba(255, 255, 255, 0.6);
236
+ animation: tw-orb-rotate 8s linear infinite;
237
+ }
238
+ .tw-launcher .tw-launcher-orb-avatar {
239
+ background: none;
240
+ background-size: cover;
241
+ background-position: center;
242
+ animation: none;
243
+ }
244
+
245
+ /* ---- Panel ---- */
246
+ .tw-panel {
247
+ width: 320px;
248
+ max-width: calc(100vw - 32px);
249
+ background: var(--trillet-surface);
250
+ border: 1px solid var(--trillet-border);
251
+ border-radius: 16px;
252
+ box-shadow: var(--trillet-shadow);
253
+ overflow: hidden;
254
+ display: flex;
255
+ flex-direction: column;
256
+ }
257
+ .tw-panel.tw-expanded { width: 380px; }
258
+
259
+ .tw-header {
260
+ display: flex;
261
+ align-items: center;
262
+ gap: 10px;
263
+ padding: 14px 16px;
264
+ border-bottom: 1px solid var(--trillet-border);
265
+ }
266
+ /* Brand slot: customer logo + optional small brand label, stacked. Subordinate to
267
+ the identity title. */
268
+ .tw-brand {
269
+ display: flex;
270
+ align-items: center;
271
+ gap: 6px;
272
+ min-width: 0;
273
+ flex-shrink: 0;
274
+ }
275
+ .tw-brand-logo {
276
+ width: 28px;
277
+ height: 28px;
278
+ border-radius: 8px;
279
+ object-fit: cover;
280
+ }
281
+ /* Small customer brand label (brand.name). Visually subordinate to the identity
282
+ title \u2014 lighter weight, muted color, smaller. Never used as the header title. */
283
+ .tw-brand-name {
284
+ font-weight: 500;
285
+ font-size: 12px;
286
+ color: var(--trillet-muted);
287
+ white-space: nowrap;
288
+ overflow: hidden;
289
+ text-overflow: ellipsis;
290
+ max-width: 120px;
291
+ }
292
+ /* Header title identifying who the user is talking to (agent / call flow /
293
+ workspace name). The primary header identity; truncates long names cleanly. */
294
+ .tw-header-title {
295
+ flex: 1;
296
+ min-width: 0;
297
+ font-weight: 600;
298
+ font-size: 14px;
299
+ color: var(--trillet-on-surface);
300
+ white-space: nowrap;
301
+ overflow: hidden;
302
+ text-overflow: ellipsis;
303
+ }
304
+ .tw-icon-btn {
305
+ border: none;
306
+ background: transparent;
307
+ color: var(--trillet-muted);
308
+ cursor: pointer;
309
+ width: 28px;
310
+ height: 28px;
311
+ border-radius: 8px;
312
+ display: inline-flex;
313
+ align-items: center;
314
+ justify-content: center;
315
+ font-size: 16px;
316
+ line-height: 1;
317
+ }
318
+ .tw-icon-btn:hover { background: rgba(0, 0, 0, 0.05); }
319
+
320
+ .tw-body {
321
+ padding: 20px 16px;
322
+ display: flex;
323
+ flex-direction: column;
324
+ align-items: center;
325
+ gap: 14px;
326
+ }
327
+
328
+ /* ---- Animated 2-color gradient orb / avatar ---- */
329
+ .tw-orb-wrap {
330
+ position: relative;
331
+ width: 96px;
332
+ height: 96px;
333
+ display: flex;
334
+ align-items: center;
335
+ justify-content: center;
336
+ }
337
+ /* Soft aura behind the orb (breathes gently; stronger while speaking). */
338
+ .tw-orb-wrap::before {
339
+ content: '';
340
+ position: absolute;
341
+ width: 78px;
342
+ height: 78px;
343
+ border-radius: 50%;
344
+ background: radial-gradient(circle, var(--trillet-orb-2), transparent 70%);
345
+ opacity: 0.5;
346
+ filter: blur(10px);
347
+ animation: tw-aura 3.2s ease-in-out infinite;
348
+ }
349
+ .tw-orb {
350
+ position: relative;
351
+ width: 72px;
352
+ height: 72px;
353
+ border-radius: 50%;
354
+ background:
355
+ radial-gradient(circle at 30% 28%, var(--trillet-orb-2), transparent 58%),
356
+ conic-gradient(from 0deg, var(--trillet-orb-1), var(--trillet-orb-2), var(--trillet-orb-1));
357
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
358
+ animation: tw-orb-rotate 9s linear infinite;
359
+ }
360
+ /* Glossy highlight so the orb reads as a 3D sphere, not a flat disc. */
361
+ .tw-orb::after {
362
+ content: '';
363
+ position: absolute;
364
+ inset: 0;
365
+ border-radius: 50%;
366
+ background: radial-gradient(circle at 34% 26%, rgba(255, 255, 255, 0.55), transparent 46%);
367
+ }
368
+ /* When an avatar image is provided, show it instead of the gradient. */
369
+ .tw-orb.tw-orb-avatar {
370
+ background: none;
371
+ background-size: cover;
372
+ background-position: center;
373
+ animation: none;
374
+ }
375
+ .tw-orb.tw-orb-avatar::after { display: none; }
376
+
377
+ @keyframes tw-orb-rotate { to { transform: rotate(360deg); } }
378
+ @keyframes tw-aura {
379
+ 0%, 100% { transform: scale(1); opacity: 0.4; }
380
+ 50% { transform: scale(1.16); opacity: 0.66; }
381
+ }
382
+
383
+ /* Connecting: a pulsing ring around the orb. */
384
+ .tw-orb-wrap.tw-connecting::after {
385
+ content: '';
386
+ position: absolute;
387
+ width: 72px;
388
+ height: 72px;
389
+ border-radius: 50%;
390
+ border: 2px solid var(--trillet-orb-1);
391
+ animation: tw-pulse 1.4s ease-out infinite;
392
+ }
393
+ @keyframes tw-pulse {
394
+ 0% { transform: scale(0.85); opacity: 0.7; }
395
+ 100% { transform: scale(1.3); opacity: 0; }
396
+ }
397
+
398
+ /* Listening (live, not speaking): a slow calm breathe. */
399
+ .tw-orb-wrap.tw-listening .tw-orb {
400
+ animation: tw-orb-rotate 9s linear infinite, tw-breathe 3.6s ease-in-out infinite;
401
+ }
402
+ @keyframes tw-breathe {
403
+ 0%, 100% { transform: scale(1); }
404
+ 50% { transform: scale(1.03); }
405
+ }
406
+
407
+ /* Speaking: faster rotation + stronger bob, and a livelier aura. */
408
+ .tw-orb-wrap.tw-speaking .tw-orb {
409
+ animation: tw-orb-rotate 4.5s linear infinite, tw-bob 0.7s ease-in-out infinite alternate;
410
+ }
411
+ .tw-orb-wrap.tw-speaking::before { animation: tw-aura 1.2s ease-in-out infinite; }
412
+ @keyframes tw-bob {
413
+ from { transform: scale(1); }
414
+ to { transform: scale(1.08); }
415
+ }
416
+
417
+ .tw-status {
418
+ font-size: 13px;
419
+ color: var(--trillet-muted);
420
+ min-height: 18px;
421
+ text-align: center;
422
+ }
423
+ .tw-timer {
424
+ font-size: 12px;
425
+ color: var(--trillet-muted);
426
+ font-variant-numeric: tabular-nums;
427
+ }
428
+
429
+ /* ---- BYO reCAPTCHA gate ---- */
430
+ /* The checkbox is a light-DOM node projected in via <slot name="recaptcha"> \u2014 it can't
431
+ render directly in the shadow root (reCAPTCHA v2 hangs there). ::slotted targets that
432
+ projected node. The checkbox iframe is a fixed 304x78; scale it down on narrow panels
433
+ so it doesn't overflow. */
434
+ .tw-recaptcha-slot {
435
+ display: flex;
436
+ justify-content: center;
437
+ width: 100%;
438
+ }
439
+ ::slotted(.tw-recaptcha-mount) {
440
+ display: flex;
441
+ justify-content: center;
442
+ }
443
+ @media (max-width: 340px) {
444
+ ::slotted(.tw-recaptcha-mount) {
445
+ transform: scale(0.85);
446
+ transform-origin: center top;
447
+ }
448
+ }
449
+
450
+ /* ---- Controls ---- */
451
+ .tw-controls {
452
+ display: flex;
453
+ align-items: center;
454
+ gap: 10px;
455
+ width: 100%;
456
+ justify-content: center;
457
+ }
458
+ .tw-controls.tw-controls-stack {
459
+ flex-direction: column;
460
+ gap: 8px;
461
+ }
462
+ .tw-controls-stack .tw-primary-btn { width: 100%; }
463
+ .tw-primary-btn {
464
+ border: none;
465
+ border-radius: 999px;
466
+ padding: 11px 20px;
467
+ font-size: 14px;
468
+ font-weight: 600;
469
+ cursor: pointer;
470
+ background: var(--trillet-accent);
471
+ color: #fff;
472
+ transition: opacity 0.15s ease, transform 0.15s ease, background 0.15s ease;
473
+ }
474
+ .tw-primary-btn:hover { opacity: 0.92; }
475
+ .tw-primary-btn.tw-danger { background: #e5484d; }
476
+ .tw-primary-btn.tw-secondary {
477
+ background: transparent;
478
+ color: var(--trillet-accent);
479
+ border: 1px solid var(--trillet-border);
480
+ }
481
+ .tw-primary-btn.tw-secondary:hover { background: rgba(0, 0, 0, 0.03); opacity: 1; }
482
+ .tw-primary-btn:disabled { opacity: 0.6; cursor: default; }
483
+ /* Subtle modality switch affordance (mode="both"). */
484
+ .tw-switch-btn {
485
+ border: none;
486
+ background: none;
487
+ color: var(--trillet-muted);
488
+ font-size: 12px;
489
+ font-weight: 500;
490
+ cursor: pointer;
491
+ padding: 2px 6px;
492
+ text-decoration: underline;
493
+ text-underline-offset: 2px;
494
+ }
495
+ .tw-switch-btn:hover { color: var(--trillet-accent); }
496
+ .tw-mic-btn {
497
+ border: 1px solid var(--trillet-border);
498
+ background: var(--trillet-surface);
499
+ color: var(--trillet-on-surface);
500
+ border-radius: 50%;
501
+ width: 42px;
502
+ height: 42px;
503
+ cursor: pointer;
504
+ display: inline-flex;
505
+ align-items: center;
506
+ justify-content: center;
507
+ font-size: 18px;
508
+ }
509
+ .tw-mic-btn.tw-muted { color: #e5484d; border-color: #e5484d; }
510
+
511
+ /* ---- Text mode ---- */
512
+ .tw-text-input-row {
513
+ display: flex;
514
+ gap: 8px;
515
+ width: 100%;
516
+ }
517
+ .tw-text-input {
518
+ flex: 1;
519
+ border: 1px solid var(--trillet-border);
520
+ border-radius: 10px;
521
+ padding: 9px 12px;
522
+ font-size: 14px;
523
+ font-family: inherit;
524
+ color: var(--trillet-on-surface);
525
+ background: var(--trillet-surface);
526
+ outline: none;
527
+ }
528
+ .tw-text-input:focus { border-color: var(--trillet-accent); }
529
+ .tw-send-btn {
530
+ border: none;
531
+ border-radius: 10px;
532
+ padding: 0 14px;
533
+ background: var(--trillet-accent);
534
+ color: #fff;
535
+ font-weight: 600;
536
+ cursor: pointer;
537
+ }
538
+
539
+ /* ---- Transcript ---- */
540
+ .tw-transcript {
541
+ width: 100%;
542
+ max-height: 200px;
543
+ overflow-y: auto;
544
+ display: flex;
545
+ flex-direction: column;
546
+ gap: 8px;
547
+ padding-top: 4px;
548
+ border-top: 1px solid var(--trillet-border);
549
+ margin-top: 4px;
550
+ }
551
+
552
+ /* ---- Chat window (text mode) ----
553
+ A fixed-height, internally scrolling thread so the panel does NOT grow as
554
+ messages arrive. Height is a sensible fixed value, capped to the viewport on
555
+ short screens. Rendered (empty) as soon as the chat opens. */
556
+ .tw-chat {
557
+ height: min(380px, 60vh);
558
+ max-height: none;
559
+ overflow-y: auto;
560
+ padding: 10px;
561
+ border: 1px solid var(--trillet-border);
562
+ border-top: 1px solid var(--trillet-border);
563
+ border-radius: 12px;
564
+ margin-top: 0;
565
+ background: rgba(0, 0, 0, 0.015);
566
+ scroll-behavior: smooth;
567
+ }
568
+ /* Faint empty state so the open (message-less) chat doesn't read as broken. */
569
+ .tw-chat-empty {
570
+ margin: auto;
571
+ color: var(--trillet-muted);
572
+ opacity: 0.45;
573
+ font-size: 20px;
574
+ letter-spacing: 2px;
575
+ }
576
+ .tw-msg {
577
+ padding: 8px 12px;
578
+ border-radius: 12px;
579
+ max-width: 85%;
580
+ font-size: 13px;
581
+ white-space: pre-wrap;
582
+ word-break: break-word;
583
+ }
584
+ .tw-msg.tw-user {
585
+ align-self: flex-end;
586
+ background: var(--trillet-accent);
587
+ color: #fff;
588
+ border-bottom-right-radius: 4px;
589
+ }
590
+ .tw-msg.tw-assistant {
591
+ align-self: flex-start;
592
+ background: rgba(0, 0, 0, 0.05);
593
+ color: var(--trillet-on-surface);
594
+ border-bottom-left-radius: 4px;
595
+ }
596
+
597
+ .tw-hidden { display: none !important; }
598
+ `
599
+ );
600
+
601
+ // src/widget/recaptcha.ts
602
+ var RECAPTCHA_SCRIPT_SRC = "https://www.google.com/recaptcha/api.js?render=explicit";
603
+ function getGrecaptcha() {
604
+ return window.grecaptcha;
605
+ }
606
+ var scriptPromise = null;
607
+ function injectScript() {
608
+ if (scriptPromise) return scriptPromise;
609
+ scriptPromise = new Promise((resolve, reject) => {
610
+ const existing = document.querySelector(
611
+ `script[src="${RECAPTCHA_SCRIPT_SRC}"]`
612
+ );
613
+ if (existing) {
614
+ resolve();
615
+ return;
616
+ }
617
+ const script = document.createElement("script");
618
+ script.src = RECAPTCHA_SCRIPT_SRC;
619
+ script.async = true;
620
+ script.defer = true;
621
+ script.onload = () => resolve();
622
+ script.onerror = () => {
623
+ scriptPromise = null;
624
+ reject(new Error("Failed to load Google reCAPTCHA"));
625
+ };
626
+ document.head.appendChild(script);
627
+ });
628
+ return scriptPromise;
629
+ }
630
+ async function loadRecaptcha() {
631
+ await injectScript();
632
+ const grecaptcha = getGrecaptcha();
633
+ if (!grecaptcha) throw new Error("reCAPTCHA loaded but grecaptcha is undefined");
634
+ await new Promise((resolve) => grecaptcha.ready(resolve));
635
+ return grecaptcha;
636
+ }
637
+ async function renderRecaptchaCheckbox(options) {
638
+ const grecaptcha = await loadRecaptcha();
639
+ return grecaptcha.render(options.container, {
640
+ sitekey: options.siteKey,
641
+ // The token is received and dropped on the floor — see the header note.
642
+ callback: () => options.onSolved(),
643
+ "expired-callback": () => options.onExpired(),
644
+ "error-callback": () => options.onExpired()
645
+ });
646
+ }
647
+
648
+ // src/widget/TrilletWidgetElement.ts
649
+ var TrilletWidgetElement = class extends HTMLElement {
650
+ constructor() {
651
+ super();
652
+ this.agent = null;
653
+ this.state = "idle";
654
+ this.open = false;
655
+ // panel open vs. launcher only
656
+ this.micEnabled = true;
657
+ this.speaking = false;
658
+ this.transcripts = [];
659
+ // Human-facing identity of who the user is talking to, delivered on the
660
+ // `connected` event. Drives the header title. Null until a session connects.
661
+ this.display = null;
662
+ // Chosen modality for the current/next session. Only meaningful for mode="both";
663
+ // in voice/text modes resolvedMode() ignores it.
664
+ this.activeMode = null;
665
+ // True while tearing down one modality and reconnecting in the other, so lifecycle
666
+ // events (call-start/conversationStarted) aren't re-emitted for an internal switch.
667
+ this.switching = false;
668
+ // maxCallDuration countdown (UX only — see startConversation()).
669
+ this.durationTimer = null;
670
+ this.remainingSeconds = null;
671
+ this.elapsedSeconds = 0;
672
+ // BYO reCAPTCHA gate (opt-in via recaptcha-site-key). A ONE-TIME gate per session:
673
+ // once solved, it stays solved for the life of this element, so the visitor can
674
+ // start, end and restart conversations without being re-challenged. Never reset on
675
+ // call end — re-challenging per call is friction that buys nothing, since the token
676
+ // is never verified. See ./recaptcha.ts.
677
+ //
678
+ // The checkbox is rendered into a LIGHT-DOM node projected into the panel via a
679
+ // <slot>, not directly in the shadow root. reCAPTCHA v2's anchor iframe hangs on its
680
+ // loading spinner inside a shadow root — its init handshake can't complete across the
681
+ // shadow boundary (verified). Slotting keeps the checkbox in the light DOM (where it
682
+ // works) while displaying it inside the panel. See ensureRecaptchaSlot().
683
+ this.recaptchaSolved = false;
684
+ this.recaptchaSlot = null;
685
+ this.recaptchaWidgetId = null;
686
+ this.root = this.attachShadow({ mode: "open" });
687
+ this.styleEl = document.createElement("style");
688
+ this.styleEl.textContent = WIDGET_STYLES;
689
+ this.container = document.createElement("div");
690
+ this.container.className = "tw-root";
691
+ this.root.appendChild(this.styleEl);
692
+ this.root.appendChild(this.container);
693
+ }
694
+ static get observedAttributes() {
695
+ return OBSERVED_ATTRIBUTES;
696
+ }
697
+ connectedCallback() {
698
+ this.config = configFromElement(this);
699
+ this.syncActiveMode();
700
+ this.applyTheme();
701
+ this.render();
702
+ }
703
+ disconnectedCallback() {
704
+ this.clearDurationTimer();
705
+ this.teardownAgent();
706
+ this.removeRecaptchaSlot();
707
+ }
708
+ attributeChangedCallback() {
709
+ if (!this.isConnected) return;
710
+ this.config = configFromElement(this);
711
+ this.syncActiveMode();
712
+ this.applyTheme();
713
+ this.render();
714
+ }
715
+ // ---- Public element API ----------------------------------------------------
716
+ /**
717
+ * Imperatively start a conversation. Primary headless API (convai-aligned).
718
+ * @param modality - optional; only used in `mode="both"` to pick voice vs text.
719
+ */
720
+ async startConversation(modality) {
721
+ if (this.state === "connecting" || this.state === "live") return;
722
+ this.open = true;
723
+ if (this.needsRecaptcha()) {
724
+ this.render();
725
+ return;
726
+ }
727
+ await this.beginCall(modality);
728
+ }
729
+ /** Imperatively end the active conversation. Primary headless API. */
730
+ endConversation() {
731
+ var _a;
732
+ (_a = this.agent) == null ? void 0 : _a.endCall();
733
+ }
734
+ /** @deprecated Use {@link startConversation}. Kept as a thin alias for back-compat. */
735
+ startCall() {
736
+ return this.startConversation();
737
+ }
738
+ /** @deprecated Use {@link endConversation}. Kept as a thin alias for back-compat. */
739
+ endCall() {
740
+ this.endConversation();
741
+ }
742
+ // ---- Modality helpers ------------------------------------------------------
743
+ /** The concrete modality to run for the current session (`both` -> activeMode). */
744
+ resolvedMode() {
745
+ var _a;
746
+ if (this.config.mode === "both") return (_a = this.activeMode) != null ? _a : "voice";
747
+ return this.config.mode;
748
+ }
749
+ /** Keep activeMode consistent with the configured mode. */
750
+ syncActiveMode() {
751
+ if (this.config.mode === "voice" || this.config.mode === "text") {
752
+ this.activeMode = this.config.mode;
753
+ }
754
+ }
755
+ /** Tear down the current agent cleanly: detach listeners, end the call, drop the ref. */
756
+ teardownAgent() {
757
+ if (!this.agent) return;
758
+ try {
759
+ this.agent.removeAllListeners();
760
+ } catch (e) {
761
+ }
762
+ try {
763
+ this.agent.endCall();
764
+ } catch (e) {
765
+ }
766
+ this.agent = null;
767
+ }
768
+ /**
769
+ * Switch modality mid-session (mode="both"). Because the core binds `mode` at
770
+ * construction, this ends the current `TrilletAgent` and constructs a fresh one in
771
+ * the other modality, rejoining via the same credential path. Transcripts and the
772
+ * duration timer are preserved across the switch; no lifecycle events fire (it's one
773
+ * conversation from the consumer's perspective).
774
+ */
775
+ async switchModality() {
776
+ if (this.config.mode !== "both" || this.state !== "live") return;
777
+ const target = this.resolvedMode() === "voice" ? "text" : "voice";
778
+ this.switching = true;
779
+ this.clearDurationTimer();
780
+ this.speaking = false;
781
+ this.teardownAgent();
782
+ await this.beginCall(target);
783
+ }
784
+ // ---- Credential resolution + call lifecycle --------------------------------
785
+ async beginCall(modality) {
786
+ if (modality) this.activeMode = modality;
787
+ const mode = this.resolvedMode();
788
+ if (!this.switching) this.display = null;
789
+ this.setState("connecting");
790
+ try {
791
+ const agent = new TrilletAgent({
792
+ agentId: this.config.agentId,
793
+ workspaceId: this.config.workspaceId,
794
+ mode,
795
+ variables: this.config.variables
796
+ });
797
+ this.agent = agent;
798
+ this.wireAgentEvents(agent);
799
+ if (this.config.signedUrlEndpoint || this.getRoomDetails) {
800
+ let details;
801
+ if (this.getRoomDetails) {
802
+ details = await this.getRoomDetails();
803
+ } else {
804
+ const res = await fetch(this.config.signedUrlEndpoint, {
805
+ method: "GET",
806
+ headers: { Accept: "application/json" }
807
+ });
808
+ if (!res.ok) {
809
+ throw new Error(`signed-url-endpoint returned ${res.status}`);
810
+ }
811
+ details = await res.json();
812
+ }
813
+ await agent.joinRoom(details);
814
+ } else if (this.roomDetails) {
815
+ await agent.joinRoom(this.roomDetails);
816
+ } else if (this.config.workspaceId) {
817
+ await agent.startPublicCall();
818
+ } else {
819
+ throw new Error(
820
+ "No credential path configured: set signed-url-endpoint, roomDetails/getRoomDetails, or workspace-id"
821
+ );
822
+ }
823
+ } catch (error) {
824
+ this.handleError(error);
825
+ }
826
+ }
827
+ wireAgentEvents(agent) {
828
+ agent.on("connected", (details) => {
829
+ var _a;
830
+ this.display = (_a = details == null ? void 0 : details.display) != null ? _a : null;
831
+ const wasSwitching = this.switching;
832
+ this.setState("live");
833
+ this.startDurationTimer(!wasSwitching);
834
+ this.switching = false;
835
+ });
836
+ agent.on("disconnected", () => {
837
+ this.endLocalCall();
838
+ });
839
+ agent.on("error", (error) => {
840
+ this.handleError(error);
841
+ });
842
+ agent.on("assistantStartedSpeaking", () => {
843
+ this.speaking = true;
844
+ this.render();
845
+ });
846
+ agent.on("assistantStoppedSpeaking", () => {
847
+ this.speaking = false;
848
+ this.render();
849
+ });
850
+ agent.on("transcriptUpdate", (transcripts) => {
851
+ this.transcripts = transcripts;
852
+ this.dispatch("transcript", transcripts);
853
+ this.render();
854
+ });
855
+ }
856
+ endLocalCall() {
857
+ if (this.state === "ended" || this.state === "idle") return;
858
+ this.clearDurationTimer();
859
+ this.dispatch("call-end", this.elapsedSeconds);
860
+ this.dispatch("conversationEnded", this.elapsedSeconds);
861
+ this.setState("ended");
862
+ this.agent = null;
863
+ if (this.config.mode === "both") this.activeMode = null;
864
+ }
865
+ handleError(error) {
866
+ const err = error instanceof Error ? error : new Error(String(error));
867
+ this.clearDurationTimer();
868
+ this.switching = false;
869
+ this.dispatch("error", err);
870
+ this.agent = null;
871
+ if (this.config.mode === "both") this.activeMode = null;
872
+ this.setState("idle");
873
+ }
874
+ // ---- maxCallDuration (UX-ONLY countdown) -----------------------------------
875
+ // NOTE: This is a client-side timer for UX feedback only. Real call-duration
876
+ // enforcement happens server-side (backend web-call route); this timer is
877
+ // trivially bypassable and must not be relied on as a hard cap.
878
+ startDurationTimer(reset = true) {
879
+ this.clearDurationTimer();
880
+ if (reset) {
881
+ this.elapsedSeconds = 0;
882
+ this.remainingSeconds = typeof this.config.maxCallDuration === "number" ? this.config.maxCallDuration : null;
883
+ }
884
+ this.durationTimer = setInterval(() => {
885
+ var _a;
886
+ this.elapsedSeconds += 1;
887
+ if (this.remainingSeconds !== null) {
888
+ this.remainingSeconds -= 1;
889
+ if (this.remainingSeconds <= 0) {
890
+ (_a = this.agent) == null ? void 0 : _a.endCall();
891
+ return;
892
+ }
893
+ }
894
+ this.renderStatus();
895
+ }, 1e3);
896
+ }
897
+ clearDurationTimer() {
898
+ if (this.durationTimer) {
899
+ clearInterval(this.durationTimer);
900
+ this.durationTimer = null;
901
+ }
902
+ }
903
+ // ---- State + DOM events ----------------------------------------------------
904
+ setState(state) {
905
+ const prev = this.state;
906
+ this.state = state;
907
+ if (state === "live" && prev !== "live" && !this.switching) {
908
+ this.dispatch("call-start", void 0);
909
+ this.dispatch("conversationStarted", void 0);
910
+ }
911
+ this.render();
912
+ }
913
+ dispatch(type, detail) {
914
+ this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
915
+ }
916
+ // ---- Theming ----------------------------------------------------------------
917
+ applyTheme() {
918
+ const orb1 = this.config.orbColor1 || DEFAULT_ORB_COLOR_1;
919
+ const orb2 = this.config.orbColor2 || DEFAULT_ORB_COLOR_2;
920
+ this.style.setProperty("--trillet-orb-1", orb1);
921
+ this.style.setProperty("--trillet-orb-2", orb2);
922
+ const accent = this.config.brand.primaryColor || this.config.orbColor1;
923
+ if (accent) {
924
+ this.style.setProperty("--trillet-accent", accent);
925
+ } else {
926
+ this.style.removeProperty("--trillet-accent");
927
+ }
928
+ }
929
+ // ---- Rendering --------------------------------------------------------------
930
+ formatTime(total) {
931
+ const m = Math.floor(total / 60);
932
+ const s = total % 60;
933
+ return `${m}:${s.toString().padStart(2, "0")}`;
934
+ }
935
+ statusText() {
936
+ switch (this.state) {
937
+ case "connecting":
938
+ return "Connecting\u2026";
939
+ case "live":
940
+ return this.speaking ? this.config.speakingText : this.config.listeningText;
941
+ case "ended":
942
+ return "Call ended";
943
+ default:
944
+ return this.config.actionText || "";
945
+ }
946
+ }
947
+ renderStatus() {
948
+ const statusEl = this.root.querySelector(".tw-status");
949
+ if (statusEl) statusEl.textContent = this.statusText();
950
+ const timerEl = this.root.querySelector(".tw-timer");
951
+ if (timerEl) timerEl.textContent = this.timerText();
952
+ }
953
+ timerText() {
954
+ if (this.state !== "live") return "";
955
+ if (this.remainingSeconds !== null) {
956
+ return this.formatTime(Math.max(0, this.remainingSeconds));
957
+ }
958
+ return this.formatTime(this.elapsedSeconds);
959
+ }
960
+ render() {
961
+ this.container.replaceChildren();
962
+ if (!this.open) {
963
+ this.container.appendChild(this.renderLauncher());
964
+ return;
965
+ }
966
+ this.container.appendChild(this.renderPanel());
967
+ }
968
+ renderLauncher() {
969
+ const btn = document.createElement("button");
970
+ btn.className = "tw-launcher";
971
+ btn.type = "button";
972
+ const orb = document.createElement("span");
973
+ orb.className = "tw-launcher-orb";
974
+ if (this.config.avatar) {
975
+ orb.classList.add("tw-launcher-orb-avatar");
976
+ orb.style.backgroundImage = `url("${this.config.avatar}")`;
977
+ }
978
+ btn.appendChild(orb);
979
+ const label = document.createElement("span");
980
+ label.textContent = this.config.actionText || this.config.startCallText;
981
+ btn.appendChild(label);
982
+ btn.addEventListener("click", () => {
983
+ this.open = true;
984
+ this.render();
985
+ });
986
+ return btn;
987
+ }
988
+ renderPanel() {
989
+ const panel = document.createElement("div");
990
+ panel.className = `tw-panel${this.config.variant === "expanded" ? " tw-expanded" : ""}`;
991
+ panel.appendChild(this.renderHeader());
992
+ panel.appendChild(this.renderBody());
993
+ return panel;
994
+ }
995
+ /**
996
+ * The header title identifying who the user is talking to. Each identity value is
997
+ * code-overridable per value: a static `agent-name`/`call-flow-name`/`workspace-name`
998
+ * config value takes precedence over the corresponding backend `display.*` value
999
+ * (which only arrives on `connected`), falling back to it when unset. Resolution:
1000
+ * effectiveAgent = config.agentName ?? display.agent_name
1001
+ * effectiveCallFlow = config.callFlowName ?? display.call_flow_name
1002
+ * effectiveWorkspace = config.workspaceName ?? display.workspace_name
1003
+ * title = effectiveAgent || effectiveCallFlow || effectiveWorkspace || ''
1004
+ * Because the overrides are static config, the title can render pre-call. Note:
1005
+ * `brand.name` is intentionally NOT part of this chain — it renders in the brand
1006
+ * slot only.
1007
+ */
1008
+ headerTitle() {
1009
+ var _a, _b, _c, _d, _e, _f;
1010
+ const effectiveAgent = (_b = this.config.agentName) != null ? _b : (_a = this.display) == null ? void 0 : _a.agent_name;
1011
+ const effectiveCallFlow = (_d = this.config.callFlowName) != null ? _d : (_c = this.display) == null ? void 0 : _c.call_flow_name;
1012
+ const effectiveWorkspace = (_f = this.config.workspaceName) != null ? _f : (_e = this.display) == null ? void 0 : _e.workspace_name;
1013
+ return effectiveAgent || effectiveCallFlow || effectiveWorkspace || "";
1014
+ }
1015
+ renderHeader() {
1016
+ const header = document.createElement("div");
1017
+ header.className = "tw-header";
1018
+ if (this.config.brand.logo || this.config.brand.name) {
1019
+ const brand = document.createElement("div");
1020
+ brand.className = "tw-brand";
1021
+ if (this.config.brand.logo) {
1022
+ const logo = document.createElement("img");
1023
+ logo.className = "tw-brand-logo";
1024
+ logo.src = this.config.brand.logo;
1025
+ logo.alt = this.config.brand.name || "";
1026
+ brand.appendChild(logo);
1027
+ }
1028
+ if (this.config.brand.name) {
1029
+ const brandLabel = document.createElement("span");
1030
+ brandLabel.className = "tw-brand-name";
1031
+ brandLabel.textContent = this.config.brand.name;
1032
+ brandLabel.title = this.config.brand.name;
1033
+ brand.appendChild(brandLabel);
1034
+ }
1035
+ header.appendChild(brand);
1036
+ }
1037
+ const name = document.createElement("div");
1038
+ name.className = "tw-header-title";
1039
+ const title = this.headerTitle();
1040
+ name.textContent = title;
1041
+ if (title) name.title = title;
1042
+ header.appendChild(name);
1043
+ if (this.config.variant === "compact") {
1044
+ const expandBtn = document.createElement("button");
1045
+ expandBtn.className = "tw-icon-btn";
1046
+ expandBtn.type = "button";
1047
+ expandBtn.title = this.config.expandText;
1048
+ expandBtn.textContent = "\u2922";
1049
+ expandBtn.addEventListener("click", () => {
1050
+ this.config = { ...this.config, variant: "expanded" };
1051
+ this.render();
1052
+ });
1053
+ header.appendChild(expandBtn);
1054
+ } else {
1055
+ const collapseBtn = document.createElement("button");
1056
+ collapseBtn.className = "tw-icon-btn";
1057
+ collapseBtn.type = "button";
1058
+ collapseBtn.title = this.config.collapseText;
1059
+ collapseBtn.textContent = "\u2921";
1060
+ collapseBtn.addEventListener("click", () => {
1061
+ this.config = { ...this.config, variant: "compact" };
1062
+ this.render();
1063
+ });
1064
+ header.appendChild(collapseBtn);
1065
+ }
1066
+ if (this.config.dismissible) {
1067
+ const closeBtn = document.createElement("button");
1068
+ closeBtn.className = "tw-icon-btn";
1069
+ closeBtn.type = "button";
1070
+ closeBtn.title = "Close";
1071
+ closeBtn.textContent = "\u2715";
1072
+ closeBtn.addEventListener("click", () => {
1073
+ if (this.state === "live" || this.state === "connecting") {
1074
+ this.endConversation();
1075
+ }
1076
+ this.open = false;
1077
+ this.render();
1078
+ });
1079
+ header.appendChild(closeBtn);
1080
+ }
1081
+ return header;
1082
+ }
1083
+ /** True when a `both` widget is idle/ended with no modality chosen yet. */
1084
+ isBothPreCall() {
1085
+ return this.config.mode === "both" && this.activeMode === null && (this.state === "idle" || this.state === "ended");
1086
+ }
1087
+ // ---- BYO reCAPTCHA gate ----------------------------------------------------
1088
+ /** True when a site key is configured and this session has not solved it yet. */
1089
+ needsRecaptcha() {
1090
+ return Boolean(this.config.recaptchaSiteKey) && !this.recaptchaSolved;
1091
+ }
1092
+ /**
1093
+ * The pre-call gate shown in the panel: orb, prompt, the reCAPTCHA checkbox, and a
1094
+ * disabled start button. The button enables once the checkbox is solved.
1095
+ *
1096
+ * The checkbox itself is projected in via a <slot>: reCAPTCHA v2 hangs inside a
1097
+ * shadow root (its anchor iframe never finishes initializing), so the actual widget
1098
+ * is rendered into a LIGHT-DOM node — a child of the host element — that is assigned
1099
+ * to this slot. It therefore *displays* here inside the panel while its DOM home
1100
+ * stays in the light tree, where reCAPTCHA works. Verified via examples/recaptcha-
1101
+ * isolate.local.html (case C).
1102
+ */
1103
+ renderRecaptchaGate(body) {
1104
+ body.appendChild(this.buildOrb());
1105
+ const status = document.createElement("div");
1106
+ status.className = "tw-status";
1107
+ status.textContent = this.config.recaptchaText;
1108
+ body.appendChild(status);
1109
+ const slot = document.createElement("slot");
1110
+ slot.setAttribute("name", "recaptcha");
1111
+ slot.className = "tw-recaptcha-slot";
1112
+ body.appendChild(slot);
1113
+ const controls = document.createElement("div");
1114
+ controls.className = "tw-controls";
1115
+ const startBtn = document.createElement("button");
1116
+ startBtn.className = "tw-primary-btn";
1117
+ startBtn.type = "button";
1118
+ startBtn.textContent = this.config.startCallText;
1119
+ startBtn.disabled = true;
1120
+ controls.appendChild(startBtn);
1121
+ body.appendChild(controls);
1122
+ this.ensureRecaptchaSlot();
1123
+ }
1124
+ /**
1125
+ * Create the light-DOM node that hosts the reCAPTCHA checkbox and render the checkbox
1126
+ * into it. The node is a child of the host element with `slot="recaptcha"`, so it is
1127
+ * projected into the gate's <slot>. Idempotent: every widget re-render recreates the
1128
+ * <slot> element, but this node (and its iframe) persists in the light DOM untouched,
1129
+ * so the checkbox is rendered exactly once and re-projects automatically.
1130
+ */
1131
+ ensureRecaptchaSlot() {
1132
+ const siteKey = this.config.recaptchaSiteKey;
1133
+ if (!siteKey || this.recaptchaSolved || this.recaptchaSlot) return;
1134
+ const slotted = document.createElement("div");
1135
+ slotted.setAttribute("slot", "recaptcha");
1136
+ slotted.className = "tw-recaptcha-mount";
1137
+ this.appendChild(slotted);
1138
+ this.recaptchaSlot = slotted;
1139
+ this.recaptchaWidgetId = -1;
1140
+ void renderRecaptchaCheckbox({
1141
+ container: slotted,
1142
+ siteKey,
1143
+ onSolved: () => {
1144
+ this.recaptchaSolved = true;
1145
+ this.removeRecaptchaSlot();
1146
+ this.render();
1147
+ },
1148
+ // A solved checkbox expires after ~2 minutes. Google resets its own widget UI in
1149
+ // place, and the slot is still showing, so the visitor can just re-tick it.
1150
+ onExpired: () => {
1151
+ this.recaptchaSolved = false;
1152
+ }
1153
+ }).then((id) => {
1154
+ this.recaptchaWidgetId = id;
1155
+ }).catch((error) => {
1156
+ console.warn("[trillet-widget] reCAPTCHA failed to load; starting without it", error);
1157
+ this.recaptchaSolved = true;
1158
+ this.removeRecaptchaSlot();
1159
+ this.render();
1160
+ });
1161
+ }
1162
+ /** Remove the slotted light-DOM checkbox node. Safe to call when none exists. */
1163
+ removeRecaptchaSlot() {
1164
+ var _a;
1165
+ (_a = this.recaptchaSlot) == null ? void 0 : _a.remove();
1166
+ this.recaptchaSlot = null;
1167
+ if (!this.recaptchaSolved) this.recaptchaWidgetId = null;
1168
+ }
1169
+ renderBody() {
1170
+ const body = document.createElement("div");
1171
+ body.className = "tw-body";
1172
+ if (this.needsRecaptcha() && (this.state === "idle" || this.state === "ended")) {
1173
+ this.renderRecaptchaGate(body);
1174
+ return body;
1175
+ }
1176
+ if (this.isBothPreCall()) {
1177
+ this.renderBothEntry(body);
1178
+ return body;
1179
+ }
1180
+ if (this.resolvedMode() === "text") {
1181
+ this.renderTextBody(body);
1182
+ } else {
1183
+ this.renderVoiceBody(body);
1184
+ }
1185
+ return body;
1186
+ }
1187
+ /** Build the animated gradient orb (or avatar image) reflecting the current state. */
1188
+ buildOrb() {
1189
+ const orbWrap = document.createElement("div");
1190
+ orbWrap.className = "tw-orb-wrap";
1191
+ if (this.state === "connecting") orbWrap.classList.add("tw-connecting");
1192
+ if (this.state === "live") orbWrap.classList.add("tw-listening");
1193
+ if (this.state === "live" && this.speaking) orbWrap.classList.add("tw-speaking");
1194
+ const orb = document.createElement("div");
1195
+ orb.className = "tw-orb";
1196
+ if (this.config.avatar) {
1197
+ orb.classList.add("tw-orb-avatar");
1198
+ orb.style.backgroundImage = `url("${this.config.avatar}")`;
1199
+ }
1200
+ orbWrap.appendChild(orb);
1201
+ return orbWrap;
1202
+ }
1203
+ /** Pre-call panel for mode="both": orb + "Start a call" (voice) and "Message" (text). */
1204
+ renderBothEntry(body) {
1205
+ body.appendChild(this.buildOrb());
1206
+ const controls = document.createElement("div");
1207
+ controls.className = "tw-controls tw-controls-stack";
1208
+ const callBtn = document.createElement("button");
1209
+ callBtn.className = "tw-primary-btn";
1210
+ callBtn.type = "button";
1211
+ callBtn.textContent = this.config.startCallText;
1212
+ callBtn.addEventListener("click", () => {
1213
+ void this.beginCall("voice");
1214
+ });
1215
+ controls.appendChild(callBtn);
1216
+ const msgBtn = document.createElement("button");
1217
+ msgBtn.className = "tw-primary-btn tw-secondary";
1218
+ msgBtn.type = "button";
1219
+ msgBtn.textContent = this.config.messageText;
1220
+ msgBtn.addEventListener("click", () => {
1221
+ void this.beginCall("text");
1222
+ });
1223
+ controls.appendChild(msgBtn);
1224
+ body.appendChild(controls);
1225
+ }
1226
+ /** Voice UI: orb + spoken status + timer + mic/end controls. Never a text input. */
1227
+ renderVoiceBody(body) {
1228
+ body.appendChild(this.buildOrb());
1229
+ const status = document.createElement("div");
1230
+ status.className = "tw-status";
1231
+ status.textContent = this.statusText();
1232
+ body.appendChild(status);
1233
+ const timer = document.createElement("div");
1234
+ timer.className = "tw-timer";
1235
+ timer.textContent = this.timerText();
1236
+ body.appendChild(timer);
1237
+ body.appendChild(this.renderControls());
1238
+ const switchBtn = this.renderSwitchButton();
1239
+ if (switchBtn) body.appendChild(switchBtn);
1240
+ }
1241
+ /** Text/chat UI: conversation thread + message input. Never an orb or "listening" state. */
1242
+ renderTextBody(body) {
1243
+ if (this.state === "idle" || this.state === "ended") {
1244
+ if (this.state === "ended") {
1245
+ const status = document.createElement("div");
1246
+ status.className = "tw-status";
1247
+ status.textContent = "Chat ended";
1248
+ body.appendChild(status);
1249
+ }
1250
+ body.appendChild(this.renderControls());
1251
+ return;
1252
+ }
1253
+ if (this.state === "connecting") {
1254
+ const status = document.createElement("div");
1255
+ status.className = "tw-status";
1256
+ status.textContent = "Connecting\u2026";
1257
+ body.appendChild(status);
1258
+ }
1259
+ body.appendChild(this.renderTranscript());
1260
+ if (this.state === "live") {
1261
+ body.appendChild(this.renderTextInput());
1262
+ }
1263
+ const endBtn = document.createElement("button");
1264
+ endBtn.className = "tw-primary-btn tw-danger";
1265
+ endBtn.type = "button";
1266
+ endBtn.textContent = this.config.endCallText;
1267
+ endBtn.disabled = this.state === "connecting";
1268
+ endBtn.addEventListener("click", () => this.endConversation());
1269
+ body.appendChild(endBtn);
1270
+ const switchBtn = this.renderSwitchButton();
1271
+ if (switchBtn) body.appendChild(switchBtn);
1272
+ }
1273
+ /** In mode="both" during a live session, a control to switch to the other modality. */
1274
+ renderSwitchButton() {
1275
+ if (this.config.mode !== "both" || this.state !== "live") return null;
1276
+ const toText = this.resolvedMode() === "voice";
1277
+ const btn = document.createElement("button");
1278
+ btn.className = "tw-switch-btn";
1279
+ btn.type = "button";
1280
+ btn.textContent = toText ? this.config.switchToTextText : this.config.switchToVoiceText;
1281
+ btn.addEventListener("click", () => {
1282
+ void this.switchModality();
1283
+ });
1284
+ return btn;
1285
+ }
1286
+ renderControls() {
1287
+ const controls = document.createElement("div");
1288
+ controls.className = "tw-controls";
1289
+ if (this.state === "idle" || this.state === "ended") {
1290
+ const startBtn = document.createElement("button");
1291
+ startBtn.className = "tw-primary-btn";
1292
+ startBtn.type = "button";
1293
+ startBtn.textContent = this.config.startCallText;
1294
+ startBtn.addEventListener("click", () => {
1295
+ void this.beginCall();
1296
+ });
1297
+ controls.appendChild(startBtn);
1298
+ return controls;
1299
+ }
1300
+ if (this.resolvedMode() === "voice" && this.state === "live") {
1301
+ const micBtn = document.createElement("button");
1302
+ micBtn.className = `tw-mic-btn${this.micEnabled ? "" : " tw-muted"}`;
1303
+ micBtn.type = "button";
1304
+ micBtn.title = this.micEnabled ? "Mute microphone" : "Unmute microphone";
1305
+ micBtn.textContent = this.micEnabled ? "\u{1F399}" : "\u{1F507}";
1306
+ micBtn.addEventListener("click", () => {
1307
+ var _a;
1308
+ this.micEnabled = !this.micEnabled;
1309
+ (_a = this.agent) == null ? void 0 : _a.toggleMicrophone(this.micEnabled);
1310
+ this.render();
1311
+ });
1312
+ controls.appendChild(micBtn);
1313
+ }
1314
+ const endBtn = document.createElement("button");
1315
+ endBtn.className = "tw-primary-btn tw-danger";
1316
+ endBtn.type = "button";
1317
+ endBtn.textContent = this.config.endCallText;
1318
+ endBtn.disabled = this.state === "connecting";
1319
+ endBtn.addEventListener("click", () => this.endConversation());
1320
+ controls.appendChild(endBtn);
1321
+ return controls;
1322
+ }
1323
+ renderTextInput() {
1324
+ const row = document.createElement("div");
1325
+ row.className = "tw-text-input-row";
1326
+ const input = document.createElement("input");
1327
+ input.className = "tw-text-input";
1328
+ input.type = "text";
1329
+ input.placeholder = "Type a message\u2026";
1330
+ const send = () => {
1331
+ var _a;
1332
+ const text = input.value.trim();
1333
+ if (!text) return;
1334
+ void ((_a = this.agent) == null ? void 0 : _a.sendTextMessage(text));
1335
+ input.value = "";
1336
+ };
1337
+ input.addEventListener("keydown", (e) => {
1338
+ if (e.key === "Enter") send();
1339
+ });
1340
+ const sendBtn = document.createElement("button");
1341
+ sendBtn.className = "tw-send-btn";
1342
+ sendBtn.type = "button";
1343
+ sendBtn.textContent = "Send";
1344
+ sendBtn.addEventListener("click", send);
1345
+ row.appendChild(input);
1346
+ row.appendChild(sendBtn);
1347
+ return row;
1348
+ }
1349
+ /**
1350
+ * The chat thread for text mode. This is a fixed-height, internally scrolling
1351
+ * window (like a normal website chatbot): the container is rendered at its full
1352
+ * height as soon as the chat opens — empty until messages arrive — and messages
1353
+ * accumulate + scroll inside it, so the panel's overall height stays stable.
1354
+ * Auto-scrolls to the newest message after each render.
1355
+ */
1356
+ renderTranscript() {
1357
+ const wrap = document.createElement("div");
1358
+ wrap.className = "tw-transcript tw-chat";
1359
+ if (this.transcripts.length === 0) {
1360
+ const empty = document.createElement("div");
1361
+ empty.className = "tw-chat-empty";
1362
+ empty.textContent = this.state === "connecting" ? "" : "\u2026";
1363
+ wrap.appendChild(empty);
1364
+ } else {
1365
+ for (const t of this.transcripts) {
1366
+ const msg = document.createElement("div");
1367
+ msg.className = `tw-msg ${t.role === "user" ? "tw-user" : "tw-assistant"}`;
1368
+ msg.textContent = t.text;
1369
+ wrap.appendChild(msg);
1370
+ }
1371
+ }
1372
+ requestAnimationFrame(() => {
1373
+ wrap.scrollTop = wrap.scrollHeight;
1374
+ });
1375
+ return wrap;
1376
+ }
1377
+ };
1378
+
1379
+ // src/widget/register.ts
1380
+ var TRILLET_WIDGET_TAG = "trillet-widget";
1381
+ function registerTrilletWidget(tag = TRILLET_WIDGET_TAG) {
1382
+ if (typeof customElements === "undefined") return;
1383
+ if (customElements.get(tag)) return;
1384
+ customElements.define(tag, TrilletWidgetElement);
1385
+ }
1386
+
1387
+ // src/widget/react.tsx
1388
+ import * as React from "react";
1389
+ function setAttr(el, name, value) {
1390
+ if (value === void 0 || value === false || value === null) {
1391
+ el.removeAttribute(name);
1392
+ return;
1393
+ }
1394
+ if (value === true) {
1395
+ el.setAttribute(name, "");
1396
+ return;
1397
+ }
1398
+ el.setAttribute(name, String(value));
1399
+ }
1400
+ var TrilletWidget = (props) => {
1401
+ const ref = React.useRef(null);
1402
+ React.useEffect(() => {
1403
+ registerTrilletWidget();
1404
+ }, []);
1405
+ React.useEffect(() => {
1406
+ var _a, _b, _c, _d, _e;
1407
+ const el = ref.current;
1408
+ if (!el) return;
1409
+ setAttr(el, "agent-id", props.agentId);
1410
+ setAttr(el, "signed-url-endpoint", props.signedUrlEndpoint);
1411
+ setAttr(el, "workspace-id", props.workspaceId);
1412
+ setAttr(el, "agent-name", props.agentName);
1413
+ setAttr(el, "call-flow-name", props.callFlowName);
1414
+ setAttr(el, "workspace-name", props.workspaceName);
1415
+ setAttr(el, "avatar", (_a = props.avatar) != null ? _a : props.avatarImageUrl);
1416
+ setAttr(el, "orb-color", props.orbColor);
1417
+ setAttr(el, "avatar-orb-color-1", props.orbColor1);
1418
+ setAttr(el, "avatar-orb-color-2", props.orbColor2);
1419
+ setAttr(el, "variant", props.variant);
1420
+ setAttr(el, "placement", props.placement);
1421
+ setAttr(el, "dismissible", props.dismissible);
1422
+ setAttr(el, "action-text", props.actionText);
1423
+ setAttr(el, "start-call-text", props.startCallText);
1424
+ setAttr(el, "end-call-text", props.endCallText);
1425
+ setAttr(el, "message-text", props.messageText);
1426
+ setAttr(el, "switch-to-text-text", props.switchToTextText);
1427
+ setAttr(el, "switch-to-voice-text", props.switchToVoiceText);
1428
+ setAttr(el, "listening-text", props.listeningText);
1429
+ setAttr(el, "speaking-text", props.speakingText);
1430
+ setAttr(el, "expand-text", props.expandText);
1431
+ setAttr(el, "collapse-text", props.collapseText);
1432
+ setAttr(el, "mode", props.mode);
1433
+ const vars = (_b = props.variables) != null ? _b : props.dynamicVariables;
1434
+ setAttr(el, "variables", vars ? JSON.stringify(vars) : void 0);
1435
+ setAttr(el, "max-call-duration", props.maxCallDuration);
1436
+ setAttr(el, "recaptcha-site-key", props.recaptchaSiteKey);
1437
+ setAttr(el, "recaptcha-text", props.recaptchaText);
1438
+ setAttr(el, "disable-banner", props.disableBanner);
1439
+ setAttr(el, "brand-logo", (_c = props.brand) == null ? void 0 : _c.logo);
1440
+ setAttr(el, "brand-color", (_d = props.brand) == null ? void 0 : _d.primaryColor);
1441
+ setAttr(el, "brand-name", (_e = props.brand) == null ? void 0 : _e.name);
1442
+ });
1443
+ React.useEffect(() => {
1444
+ const el = ref.current;
1445
+ if (!el) return;
1446
+ el.getRoomDetails = props.getRoomDetails;
1447
+ el.roomDetails = props.roomDetails;
1448
+ }, [props.getRoomDetails, props.roomDetails]);
1449
+ React.useEffect(() => {
1450
+ const el = ref.current;
1451
+ if (!el) return;
1452
+ const onConvStart = () => {
1453
+ var _a;
1454
+ return (_a = props.onConversationStart) == null ? void 0 : _a.call(props);
1455
+ };
1456
+ const onConvEnd = (e) => {
1457
+ var _a;
1458
+ return (_a = props.onConversationEnd) == null ? void 0 : _a.call(props, e.detail);
1459
+ };
1460
+ const onStart = () => {
1461
+ var _a;
1462
+ return (_a = props.onCallStart) == null ? void 0 : _a.call(props);
1463
+ };
1464
+ const onEnd = (e) => {
1465
+ var _a;
1466
+ return (_a = props.onCallEnd) == null ? void 0 : _a.call(props, e.detail);
1467
+ };
1468
+ const onErr = (e) => {
1469
+ var _a;
1470
+ return (_a = props.onError) == null ? void 0 : _a.call(props, e.detail);
1471
+ };
1472
+ const onTr = (e) => {
1473
+ var _a;
1474
+ return (_a = props.onTranscript) == null ? void 0 : _a.call(props, e.detail);
1475
+ };
1476
+ el.addEventListener("conversationStarted", onConvStart);
1477
+ el.addEventListener("conversationEnded", onConvEnd);
1478
+ el.addEventListener("call-start", onStart);
1479
+ el.addEventListener("call-end", onEnd);
1480
+ el.addEventListener("error", onErr);
1481
+ el.addEventListener("transcript", onTr);
1482
+ return () => {
1483
+ el.removeEventListener("conversationStarted", onConvStart);
1484
+ el.removeEventListener("conversationEnded", onConvEnd);
1485
+ el.removeEventListener("call-start", onStart);
1486
+ el.removeEventListener("call-end", onEnd);
1487
+ el.removeEventListener("error", onErr);
1488
+ el.removeEventListener("transcript", onTr);
1489
+ };
1490
+ }, [
1491
+ props.onConversationStart,
1492
+ props.onConversationEnd,
1493
+ props.onCallStart,
1494
+ props.onCallEnd,
1495
+ props.onError,
1496
+ props.onTranscript
1497
+ ]);
1498
+ return React.createElement(TRILLET_WIDGET_TAG, {
1499
+ ref,
1500
+ class: props.className,
1501
+ style: props.style
1502
+ });
1503
+ };
1504
+
1505
+ // src/widget/index.ts
1506
+ registerTrilletWidget();
1507
+ export {
1508
+ TRILLET_WIDGET_TAG,
1509
+ TrilletWidget,
1510
+ TrilletWidgetElement,
1511
+ registerTrilletWidget
1512
+ };
1513
+ //# sourceMappingURL=index.js.map