@xpert-ai/chatkit-ui5 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,2727 @@
1
1
  (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof sap.ui.define === "function" && sap.ui.define.amd ? sap.ui.define("xpertai/chatkit/ui5", ["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.XpertChatkitUI5 = {}));
3
- })(this, function(exports2) {
4
- "use strict";
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@xpert-ai/chatkit-types")) : typeof sap.ui.define === "function" && sap.ui.define.amd ? sap.ui.define("xpertai/chatkit/ui5", ["exports", "@xpert-ai/chatkit-types"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.XpertChatkitUI5 = {}, global.chatkitTypes));
3
+ })(this, function(exports2, chatkitTypes) {
4
+ "use strict";var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
14
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
15
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
16
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
17
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
18
+ var __runInitializers = (array, flags, self2, value) => {
19
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self2) : value = fns[i].call(self2, value);
20
+ return value;
21
+ };
22
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
23
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
24
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
25
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
26
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
27
+ return __privateGet(this, extra);
28
+ }, set [name](x) {
29
+ return __privateSet(this, extra, x);
30
+ } }, name));
31
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
32
+ for (var i = decorators.length - 1; i >= 0; i--) {
33
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
34
+ if (k) {
35
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
36
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
37
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
38
+ }
39
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
40
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
41
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
42
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
43
+ }
44
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
45
+ };
46
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
47
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
48
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
49
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
50
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
51
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
52
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
53
+
54
+ var _a, _b, _setTrainingOptOut_dec, _hideHistory_dec, _showHistory_dec, _sendCustomAction_dec, _shareThread_dec, _setThreadId_dec, _setComposerValue_dec, _sendUserMessage_dec, _fetchUpdates_dec, _focusComposer_dec, _c, _opts, _frameUrl, _frame, _wrapper, _launcherCloseButton, _launcherOpen, _framePetOptionsOverride, _shadow, _petOverlay, _resolveLoaded, _loaded, _messenger, _ChatKitElementBase_instances, emitAndThrow_fn, setOptionsDataAttributes_fn, getDisplayMode_fn, getConfiguredPetOptions_fn, getOverlayPetOptions_fn, resolvePetAssetUrl_fn, resolveOverlayPetOptions_fn, getFrameOptions_fn, setLauncherOpen_fn, handlePetActivate_fn, handlePetReply_fn, handlePetThreadSummaryActivate_fn, _handleLauncherClose, getFrameUrl_fn, setFrameUrl_fn, consumeFrameUrl_fn, _handleFrameLoad, _initialized, maybeInit_fn, _init;
55
+ class EventEmitter {
56
+ constructor() {
57
+ __publicField(this, "callbacks", /* @__PURE__ */ new Map());
58
+ }
59
+ on(event, callback) {
60
+ if (!this.callbacks.has(event)) {
61
+ this.callbacks.set(event, /* @__PURE__ */ new Set());
62
+ }
63
+ this.callbacks.get(event).add(callback);
64
+ }
65
+ emit(event, ...args) {
66
+ var _a2;
67
+ const data = args[0];
68
+ (_a2 = this.callbacks.get(event)) == null ? void 0 : _a2.forEach((callback) => callback(data));
69
+ }
70
+ off(event, callback) {
71
+ var _a2;
72
+ if (!callback) {
73
+ this.callbacks.delete(event);
74
+ } else {
75
+ (_a2 = this.callbacks.get(event)) == null ? void 0 : _a2.delete(callback);
76
+ }
77
+ }
78
+ allOff() {
79
+ this.callbacks.clear();
80
+ }
81
+ }
82
+ async function getBytes(stream, onChunk) {
83
+ const reader = stream.getReader();
84
+ let result;
85
+ while (!(result = await reader.read()).done) {
86
+ onChunk(result.value);
87
+ }
88
+ }
89
+ function getLines(onLine) {
90
+ let buffer;
91
+ let position;
92
+ let fieldLength;
93
+ let discardTrailingNewline = false;
94
+ return function onChunk(arr) {
95
+ if (buffer === void 0) {
96
+ buffer = arr;
97
+ position = 0;
98
+ fieldLength = -1;
99
+ } else {
100
+ buffer = concat(buffer, arr);
101
+ }
102
+ const bufLength = buffer.length;
103
+ let lineStart = 0;
104
+ while (position < bufLength) {
105
+ if (discardTrailingNewline) {
106
+ if (buffer[position] === 10) {
107
+ lineStart = ++position;
108
+ }
109
+ discardTrailingNewline = false;
110
+ }
111
+ let lineEnd = -1;
112
+ for (; position < bufLength && lineEnd === -1; ++position) {
113
+ switch (buffer[position]) {
114
+ case 58:
115
+ if (fieldLength === -1) {
116
+ fieldLength = position - lineStart;
117
+ }
118
+ break;
119
+ case 13:
120
+ discardTrailingNewline = true;
121
+ case 10:
122
+ lineEnd = position;
123
+ break;
124
+ }
125
+ }
126
+ if (lineEnd === -1) {
127
+ break;
128
+ }
129
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
130
+ lineStart = position;
131
+ fieldLength = -1;
132
+ }
133
+ if (lineStart === bufLength) {
134
+ buffer = void 0;
135
+ } else if (lineStart !== 0) {
136
+ buffer = buffer.subarray(lineStart);
137
+ position -= lineStart;
138
+ }
139
+ };
140
+ }
141
+ function getMessages(onId, onRetry, onMessage) {
142
+ let message = newMessage();
143
+ const decoder = new TextDecoder();
144
+ return function onLine(line, fieldLength) {
145
+ if (line.length === 0) {
146
+ onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
147
+ message = newMessage();
148
+ } else if (fieldLength > 0) {
149
+ const field = decoder.decode(line.subarray(0, fieldLength));
150
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
151
+ const value = decoder.decode(line.subarray(valueOffset));
152
+ switch (field) {
153
+ case "data":
154
+ message.data = message.data ? message.data + "\n" + value : value;
155
+ break;
156
+ case "event":
157
+ message.event = value;
158
+ break;
159
+ case "id":
160
+ onId(message.id = value);
161
+ break;
162
+ case "retry":
163
+ const retry = parseInt(value, 10);
164
+ if (!isNaN(retry)) {
165
+ onRetry(message.retry = retry);
166
+ }
167
+ break;
168
+ }
169
+ }
170
+ };
171
+ }
172
+ function concat(a, b) {
173
+ const res = new Uint8Array(a.length + b.length);
174
+ res.set(a);
175
+ res.set(b, a.length);
176
+ return res;
177
+ }
178
+ function newMessage() {
179
+ return {
180
+ data: "",
181
+ event: "",
182
+ id: "",
183
+ retry: void 0
184
+ };
185
+ }
186
+ var __rest = function(s, e) {
187
+ var t = {};
188
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
189
+ t[p] = s[p];
190
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
191
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
192
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
193
+ t[p[i]] = s[p[i]];
194
+ }
195
+ return t;
196
+ };
197
+ const EventStreamContentType = "text/event-stream";
198
+ const DefaultRetryInterval = 1e3;
199
+ const LastEventId = "last-event-id";
200
+ function fetchEventSource(input, _a2) {
201
+ var { signal: inputSignal, headers: inputHeaders, onopen: inputOnOpen, onmessage, onclose, onerror, openWhenHidden, fetch: inputFetch } = _a2, rest = __rest(_a2, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]);
202
+ return new Promise((resolve, reject) => {
203
+ const headers = Object.assign({}, inputHeaders);
204
+ if (!headers.accept) {
205
+ headers.accept = EventStreamContentType;
206
+ }
207
+ let curRequestController;
208
+ function onVisibilityChange() {
209
+ curRequestController.abort();
210
+ if (!document.hidden) {
211
+ create();
212
+ }
213
+ }
214
+ if (!openWhenHidden) {
215
+ document.addEventListener("visibilitychange", onVisibilityChange);
216
+ }
217
+ let retryInterval = DefaultRetryInterval;
218
+ let retryTimer = 0;
219
+ function dispose() {
220
+ document.removeEventListener("visibilitychange", onVisibilityChange);
221
+ window.clearTimeout(retryTimer);
222
+ curRequestController.abort();
223
+ }
224
+ inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener("abort", () => {
225
+ dispose();
226
+ resolve();
227
+ });
228
+ const fetch2 = inputFetch !== null && inputFetch !== void 0 ? inputFetch : window.fetch;
229
+ const onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen;
230
+ async function create() {
231
+ var _a3;
232
+ curRequestController = new AbortController();
233
+ try {
234
+ const response = await fetch2(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
235
+ await onopen(response);
236
+ await getBytes(response.body, getLines(getMessages((id) => {
237
+ if (id) {
238
+ headers[LastEventId] = id;
239
+ } else {
240
+ delete headers[LastEventId];
241
+ }
242
+ }, (retry) => {
243
+ retryInterval = retry;
244
+ }, onmessage)));
245
+ onclose === null || onclose === void 0 ? void 0 : onclose();
246
+ dispose();
247
+ resolve();
248
+ } catch (err) {
249
+ if (!curRequestController.signal.aborted) {
250
+ try {
251
+ const interval = (_a3 = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a3 !== void 0 ? _a3 : retryInterval;
252
+ window.clearTimeout(retryTimer);
253
+ retryTimer = window.setTimeout(create, interval);
254
+ } catch (innerErr) {
255
+ dispose();
256
+ reject(innerErr);
257
+ }
258
+ }
259
+ }
260
+ }
261
+ create();
262
+ });
263
+ }
264
+ function defaultOnOpen(response) {
265
+ const contentType = response.headers.get("content-type");
266
+ if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(EventStreamContentType))) {
267
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
268
+ }
269
+ }
270
+ const FRAME_SAFE_ERROR_KEY = "__chatkit_error__";
271
+ class HttpError extends Error {
272
+ constructor(message, res, metadata) {
273
+ super(message);
274
+ __publicField(this, "status");
275
+ __publicField(this, "statusText");
276
+ __publicField(this, "metadata");
277
+ this.name = "HttpError";
278
+ this.statusText = res.statusText;
279
+ this.status = res.status;
280
+ this.metadata = metadata;
281
+ }
282
+ static fromPossibleFrameSafeError(error) {
283
+ if (error instanceof HttpError) {
284
+ return error;
285
+ }
286
+ if (error && typeof error === "object" && FRAME_SAFE_ERROR_KEY in error && error[FRAME_SAFE_ERROR_KEY] === "HttpError") {
287
+ const safeError = error;
288
+ const parsedError = new HttpError(
289
+ safeError.message,
290
+ {
291
+ status: safeError.status,
292
+ statusText: safeError.statusText
293
+ },
294
+ safeError.metadata
295
+ );
296
+ parsedError.stack = safeError.stack;
297
+ return parsedError;
298
+ }
299
+ return null;
300
+ }
301
+ }
302
+ _a = FRAME_SAFE_ERROR_KEY;
303
+ const _FrameSafeHttpError = class _FrameSafeHttpError {
304
+ constructor(message, res, metadata) {
305
+ __publicField(this, _a, "HttpError");
306
+ __publicField(this, "message");
307
+ __publicField(this, "stack");
308
+ __publicField(this, "status");
309
+ __publicField(this, "statusText");
310
+ __publicField(this, "metadata");
311
+ this.message = message;
312
+ this.stack = new Error(message).stack;
313
+ this.status = res.status;
314
+ this.statusText = res.statusText;
315
+ this.metadata = metadata;
316
+ }
317
+ static fromHttpError(error) {
318
+ return new _FrameSafeHttpError(
319
+ error.message,
320
+ {
321
+ status: error.status,
322
+ statusText: error.statusText
323
+ },
324
+ error.metadata
325
+ );
326
+ }
327
+ };
328
+ let FrameSafeHttpError = _FrameSafeHttpError;
329
+ const BASE_RETRY_DELAY_MS = 1e3;
330
+ const MAX_RETRY_DELAY_MS = 1e4;
331
+ const MAX_RETRY_ATTEMPTS = 5;
332
+ const nextDelay = (attempt, maxRetryDelay = MAX_RETRY_DELAY_MS, baseDelayMs = BASE_RETRY_DELAY_MS) => {
333
+ const max = Math.min(maxRetryDelay, baseDelayMs * 2 ** attempt);
334
+ return Math.floor(max * (0.5 + Math.random() * 0.5));
335
+ };
336
+ class RetryableError extends Error {
337
+ constructor(cause) {
338
+ super();
339
+ this.cause = cause;
340
+ }
341
+ }
342
+ const fetchEventSourceWithRetry = async (url, params) => {
343
+ let retryAttempt = 0;
344
+ const { onopen, ...restParams } = params;
345
+ await fetchEventSource(url, {
346
+ ...restParams,
347
+ onopen: async (res) => {
348
+ var _a2;
349
+ onopen == null ? void 0 : onopen(res);
350
+ if (res.ok && ((_a2 = res.headers.get("content-type")) == null ? void 0 : _a2.startsWith("text/event-stream"))) {
351
+ retryAttempt = 0;
352
+ return;
353
+ }
354
+ const httpError = new FrameSafeHttpError(`Streaming failed: ${res.statusText}`, res);
355
+ if (res.status >= 400 && res.status < 500) {
356
+ throw httpError;
357
+ } else {
358
+ throw new RetryableError(httpError);
359
+ }
360
+ },
361
+ onerror: (error) => {
362
+ if (error instanceof RetryableError) {
363
+ if (retryAttempt >= MAX_RETRY_ATTEMPTS) {
364
+ throw error.cause;
365
+ }
366
+ retryAttempt += 1;
367
+ return nextDelay(retryAttempt);
368
+ }
369
+ throw error;
370
+ }
371
+ });
372
+ };
373
+ function safeRandomUUID() {
374
+ const cryptoRef = globalThis.crypto;
375
+ if (typeof (cryptoRef == null ? void 0 : cryptoRef.randomUUID) === "function") {
376
+ return cryptoRef.randomUUID();
377
+ }
378
+ if (typeof (cryptoRef == null ? void 0 : cryptoRef.getRandomValues) === "function") {
379
+ const bytes = new Uint8Array(16);
380
+ cryptoRef.getRandomValues(bytes);
381
+ bytes[6] = bytes[6] & 15 | 64;
382
+ bytes[8] = bytes[8] & 63 | 128;
383
+ return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
384
+ }
385
+ return `ck_${Date.now()}_${Math.random().toString(16).slice(2)}`;
386
+ }
387
+ let IntegrationError$1 = class IntegrationError2 extends Error {
388
+ constructor(message) {
389
+ super(message);
390
+ __publicField(this, "_name");
391
+ this.name = "IntegrationError";
392
+ this._name = this.name;
393
+ }
394
+ static fromPossibleFrameSafeError(error) {
395
+ if (error && typeof error === "object" && FRAME_SAFE_ERROR_KEY in error && error[FRAME_SAFE_ERROR_KEY] === "IntegrationError") {
396
+ const safeError = error;
397
+ const parsedError = new IntegrationError2(safeError.message);
398
+ parsedError.stack = safeError.stack;
399
+ return parsedError;
400
+ }
401
+ return null;
402
+ }
403
+ };
404
+ _b = FRAME_SAFE_ERROR_KEY;
405
+ class FrameSafeIntegrationError {
406
+ constructor(message) {
407
+ __publicField(this, _b, "IntegrationError");
408
+ __publicField(this, "message");
409
+ __publicField(this, "stack");
410
+ this.message = message;
411
+ this.stack = new Error(message).stack;
412
+ }
413
+ }
414
+ class BaseMessenger {
415
+ constructor({
416
+ handlers,
417
+ target,
418
+ targetOrigin,
419
+ fetch: fetch2 = window.fetch
420
+ }) {
421
+ __publicField(this, "targetOrigin");
422
+ __publicField(this, "target");
423
+ __publicField(this, "commandHandlers");
424
+ __publicField(this, "_fetch");
425
+ __publicField(this, "emitter", new EventEmitter());
426
+ __publicField(this, "handlers", /* @__PURE__ */ new Map());
427
+ __publicField(this, "fetchEventSourceHandlers", /* @__PURE__ */ new Map());
428
+ __publicField(this, "abortControllers", /* @__PURE__ */ new Map());
429
+ __publicField(this, "commands", new Proxy(
430
+ {},
431
+ {
432
+ get: (_, command) => {
433
+ return (data, transfer) => {
434
+ return new Promise((resolve, reject) => {
435
+ const nonce = safeRandomUUID();
436
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
437
+ this.sendMessage(
438
+ {
439
+ type: "command",
440
+ nonce,
441
+ command: `on${command.charAt(0).toUpperCase()}${command.slice(1)}`,
442
+ data
443
+ },
444
+ transfer
445
+ );
446
+ });
447
+ };
448
+ }
449
+ }
450
+ ));
451
+ __publicField(this, "handleMessage", async (event) => {
452
+ var _a2, _b2, _c2, _d;
453
+ if (!event.data || event.data.__xpaiChatKit !== true || event.origin !== this.targetOrigin || event.source !== this.target()) {
454
+ return;
455
+ }
456
+ const data = event.data;
457
+ switch (data.type) {
458
+ case "event": {
459
+ this.emitter.emit(data.event, data.data);
460
+ break;
461
+ }
462
+ case "fetch": {
463
+ try {
464
+ if (data.formData) {
465
+ const formData = new FormData();
466
+ for (const [key, value] of Object.entries(data.formData)) {
467
+ formData.append(key, value);
468
+ }
469
+ data.params.body = formData;
470
+ }
471
+ const controller = new AbortController();
472
+ this.abortControllers.set(data.nonce, controller);
473
+ data.params.signal = controller.signal;
474
+ const res = await this._fetch(data.url, data.params);
475
+ if (!res.ok) {
476
+ const message = await res.json().then((json2) => json2.message || res.statusText).catch(() => res.statusText);
477
+ throw new FrameSafeHttpError(message, res);
478
+ }
479
+ const json = await res.json().catch(() => ({}));
480
+ this.sendMessage({
481
+ type: "response",
482
+ response: json,
483
+ nonce: data.nonce
484
+ });
485
+ } catch (error) {
486
+ this.sendMessage({
487
+ type: "response",
488
+ error,
489
+ nonce: data.nonce
490
+ });
491
+ }
492
+ break;
493
+ }
494
+ case "fetchEventSource": {
495
+ try {
496
+ const controller = new AbortController();
497
+ this.abortControllers.set(data.nonce, controller);
498
+ await fetchEventSourceWithRetry(data.url, {
499
+ ...data.params,
500
+ signal: controller.signal,
501
+ fetch: this._fetch,
502
+ onmessage: (message) => {
503
+ this.sendMessage({
504
+ type: "fetchEventSourceMessage",
505
+ message,
506
+ nonce: data.nonce
507
+ });
508
+ }
509
+ });
510
+ this.sendMessage({
511
+ type: "response",
512
+ response: void 0,
513
+ nonce: data.nonce
514
+ });
515
+ } catch (error) {
516
+ this.sendMessage({
517
+ type: "response",
518
+ error,
519
+ nonce: data.nonce
520
+ });
521
+ }
522
+ break;
523
+ }
524
+ case "command": {
525
+ if (!this.canReceiveCommand(data.command)) {
526
+ this.sendMessage({
527
+ type: "response",
528
+ error: new FrameSafeIntegrationError(`Command ${data.command} not supported`),
529
+ nonce: data.nonce
530
+ });
531
+ return;
532
+ }
533
+ try {
534
+ const response = await ((_b2 = (_a2 = this.commandHandlers)[data.command]) == null ? void 0 : _b2.call(_a2, data.data));
535
+ this.sendMessage({
536
+ type: "response",
537
+ response,
538
+ nonce: data.nonce
539
+ });
540
+ } catch (error) {
541
+ this.sendMessage({
542
+ type: "response",
543
+ error,
544
+ nonce: data.nonce
545
+ });
546
+ }
547
+ break;
548
+ }
549
+ case "response": {
550
+ const handler = this.handlers.get(data.nonce);
551
+ if (!handler) {
552
+ console.error("No handler found for nonce", data.nonce);
553
+ return;
554
+ }
555
+ if (data.error) {
556
+ const integrationError = IntegrationError$1.fromPossibleFrameSafeError(data.error);
557
+ const httpError = HttpError.fromPossibleFrameSafeError(data.error);
558
+ if (integrationError) {
559
+ integrationError.stack = handler.stack;
560
+ handler.reject(integrationError);
561
+ } else if (httpError) {
562
+ handler.reject(httpError);
563
+ } else {
564
+ handler.reject(data.error);
565
+ }
566
+ } else {
567
+ handler.resolve(data.response);
568
+ }
569
+ this.handlers.delete(data.nonce);
570
+ break;
571
+ }
572
+ case "fetchEventSourceMessage": {
573
+ const handler = this.fetchEventSourceHandlers.get(data.nonce);
574
+ if (!handler) {
575
+ console.error("No handler found for nonce", data.nonce);
576
+ return;
577
+ }
578
+ (_d = (_c2 = this.fetchEventSourceHandlers.get(data.nonce)) == null ? void 0 : _c2.onmessage) == null ? void 0 : _d.call(_c2, data.message);
579
+ break;
580
+ }
581
+ case "abortSignal": {
582
+ const controller = this.abortControllers.get(data.nonce);
583
+ if (controller) {
584
+ controller.abort(data.reason);
585
+ this.abortControllers.delete(data.nonce);
586
+ }
587
+ break;
588
+ }
589
+ }
590
+ });
591
+ this.commandHandlers = handlers;
592
+ this.target = target;
593
+ this.targetOrigin = targetOrigin;
594
+ this._fetch = (...args) => fetch2(...args);
595
+ }
596
+ setTargetOrigin(targetOrigin) {
597
+ this.targetOrigin = targetOrigin;
598
+ }
599
+ sendMessage(data, transfer) {
600
+ var _a2;
601
+ const message = {
602
+ __xpaiChatKit: true,
603
+ ...data
604
+ };
605
+ (_a2 = this.target()) == null ? void 0 : _a2.postMessage(message, this.targetOrigin, transfer);
606
+ }
607
+ connect() {
608
+ window.addEventListener("message", this.handleMessage);
609
+ }
610
+ disconnect() {
611
+ window.removeEventListener("message", this.handleMessage);
612
+ }
613
+ fetch(url, params) {
614
+ return new Promise((resolve, reject) => {
615
+ const nonce = safeRandomUUID();
616
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
617
+ let formData;
618
+ if (params.body instanceof FormData) {
619
+ formData = {};
620
+ for (const [key, value] of params.body.entries()) {
621
+ formData[key] = value;
622
+ }
623
+ params.body = void 0;
624
+ }
625
+ if (params.signal) {
626
+ params.signal.addEventListener("abort", () => {
627
+ var _a2;
628
+ this.sendMessage({
629
+ type: "abortSignal",
630
+ nonce,
631
+ reason: (_a2 = params.signal) == null ? void 0 : _a2.reason
632
+ });
633
+ });
634
+ params.signal = void 0;
635
+ }
636
+ this.sendMessage({ type: "fetch", nonce, params, formData, url });
637
+ });
638
+ }
639
+ // Supporting onopen would require a good way for us to serialize the Response object
640
+ // across the iframe boundary, which is not trivial and also not really necessary.
641
+ fetchEventSource(url, params) {
642
+ return new Promise((resolve, reject) => {
643
+ const { onmessage, signal, ...rest } = params;
644
+ const nonce = safeRandomUUID();
645
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
646
+ this.fetchEventSourceHandlers.set(nonce, {
647
+ onmessage
648
+ });
649
+ if (signal) {
650
+ signal.addEventListener("abort", () => {
651
+ this.sendMessage({
652
+ type: "abortSignal",
653
+ nonce,
654
+ reason: signal.reason
655
+ });
656
+ });
657
+ }
658
+ this.sendMessage({ type: "fetchEventSource", nonce, params: rest, url });
659
+ });
660
+ }
661
+ emit(...[event, data, transfer]) {
662
+ this.sendMessage(
663
+ {
664
+ type: "event",
665
+ event,
666
+ data
667
+ },
668
+ transfer
669
+ );
670
+ }
671
+ on(...[event, callback]) {
672
+ this.emitter.on(event, callback);
673
+ }
674
+ destroy() {
675
+ window.removeEventListener("message", this.handleMessage);
676
+ this.emitter.allOff();
677
+ this.handlers.clear();
678
+ }
679
+ }
680
+ const toUrlBase64 = (bin) => btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
681
+ const encodeBase64 = (value) => {
682
+ if (value === void 0) {
683
+ throw new TypeError(
684
+ "encodeBase64: `undefined` cannot be encoded to valid JSON. Pass null instead."
685
+ );
686
+ }
687
+ const json = JSON.stringify(value);
688
+ const bytes = new TextEncoder().encode(json);
689
+ let bin = "";
690
+ for (const b of bytes) bin += String.fromCharCode(b);
691
+ return toUrlBase64(bin);
692
+ };
693
+ class IntegrationError extends Error {
694
+ }
695
+ function fromPossibleFrameSafeError(err) {
696
+ return err.message;
697
+ }
698
+ const BASE_CAPABILITY_ALLOWLIST = [
699
+ // commands
700
+ "command.setOptions",
701
+ "command.sendUserMessage",
702
+ "command.setComposerValue",
703
+ "command.setThreadId",
704
+ "command.focusComposer",
705
+ "command.fetchUpdates",
706
+ "command.sendCustomAction",
707
+ "command.showHistory",
708
+ "command.hideHistory",
709
+ // events
710
+ "event.ready",
711
+ "event.error",
712
+ "event.log",
713
+ "event.response.start",
714
+ "event.response.end",
715
+ "event.response.stop",
716
+ "event.thread.change",
717
+ "event.tool.change",
718
+ "event.thread.load.start",
719
+ "event.thread.load.end",
720
+ "event.deeplink",
721
+ "event.effect",
722
+ // errors
723
+ "error.StreamError",
724
+ "error.StreamEventParsingError",
725
+ "error.WidgetItemError",
726
+ "error.InitialThreadLoadError",
727
+ "error.FileAttachmentError",
728
+ "error.HistoryViewError",
729
+ "error.FatalAppError",
730
+ "error.IntegrationError",
731
+ "error.EntitySearchError",
732
+ "error.DomainVerificationRequestError",
733
+ // backend
734
+ "backend.threads.get_by_id",
735
+ "backend.threads.list",
736
+ "backend.threads.update",
737
+ "backend.threads.delete",
738
+ "backend.threads.create",
739
+ "backend.threads.add_user_message",
740
+ "backend.threads.add_client_tool_output",
741
+ "backend.threads.retry_after_item",
742
+ "backend.threads.custom_action",
743
+ "backend.attachments.create",
744
+ "backend.attachments.get_preview",
745
+ "backend.attachments.delete",
746
+ "backend.items.list",
747
+ "backend.items.feedback",
748
+ // thread item types
749
+ "thread.item.generated_image",
750
+ "thread.item.user_message",
751
+ "thread.item.assistant_message",
752
+ "thread.item.client_tool_call",
753
+ "thread.item.widget",
754
+ "thread.item.task",
755
+ "thread.item.workflow",
756
+ "thread.item.end_of_turn",
757
+ "thread.item.image_generation",
758
+ // widgets
759
+ "widget.Basic",
760
+ "widget.Card",
761
+ "widget.ListView",
762
+ "widget.ListViewItem",
763
+ "widget.Badge",
764
+ "widget.Box",
765
+ "widget.Row",
766
+ "widget.Col",
767
+ "widget.Button",
768
+ "widget.Caption",
769
+ "widget.Chart",
770
+ "widget.Checkbox",
771
+ "widget.DatePicker",
772
+ "widget.Divider",
773
+ "widget.Form",
774
+ "widget.Icon",
775
+ "widget.Image",
776
+ "widget.Input",
777
+ "widget.Label",
778
+ "widget.Markdown",
779
+ "widget.RadioGroup",
780
+ "widget.Select",
781
+ "widget.Spacer",
782
+ "widget.Text",
783
+ "widget.Textarea",
784
+ "widget.Title",
785
+ "widget.Transition"
786
+ ];
787
+ const BASE_CAPABILITY_DENYLIST = [
788
+ // --- commands
789
+ "command.shareThread",
790
+ "command.setTrainingOptOut",
791
+ // --- events
792
+ "event.thread.restore",
793
+ "event.message.share",
794
+ "event.image.download",
795
+ "event.history.open",
796
+ "event.history.close",
797
+ "event.log.chatgpt",
798
+ // --- errors
799
+ // These errors considered internal and are not exposed to the user by default.
800
+ "error.HttpError",
801
+ "error.NetworkError",
802
+ "error.UnhandledError",
803
+ "error.UnhandledPromiseRejectionError",
804
+ "error.StreamEventHandlingError",
805
+ "error.StreamStopError",
806
+ "error.ThreadRenderingError",
807
+ "error.IntlError",
808
+ "error.AppError",
809
+ // --- backend
810
+ "backend.threads.stop",
811
+ "backend.threads.share",
812
+ "backend.threads.create_from_shared",
813
+ "backend.threads.init",
814
+ "backend.attachments.process",
815
+ // widgets
816
+ "widget.CardCarousel",
817
+ "widget.Favicon",
818
+ "widget.CardLinkItem",
819
+ "widget.Map"
820
+ ];
821
+ const PROFILE_TO_RULES = {
822
+ "chatkit": {
823
+ allow: [...BASE_CAPABILITY_ALLOWLIST, "thread.item.image_generation"],
824
+ deny: BASE_CAPABILITY_DENYLIST
825
+ }
826
+ };
827
+ const getCapabilities = (profile) => {
828
+ const rules = PROFILE_TO_RULES[profile];
829
+ const effective = new Set(rules.allow);
830
+ for (const capability of rules.deny ?? []) {
831
+ effective.delete(capability);
832
+ }
833
+ const commands = /* @__PURE__ */ new Set();
834
+ const events = /* @__PURE__ */ new Set();
835
+ const backend = /* @__PURE__ */ new Set();
836
+ const threadItems = /* @__PURE__ */ new Set();
837
+ const errors = /* @__PURE__ */ new Set();
838
+ const widgets = /* @__PURE__ */ new Set();
839
+ for (const capability of effective) {
840
+ if (capability.startsWith("command.")) {
841
+ commands.add(capability.slice("command.".length));
842
+ continue;
843
+ }
844
+ if (capability.startsWith("event.")) {
845
+ events.add(capability.slice("event.".length));
846
+ continue;
847
+ }
848
+ if (capability.startsWith("backend.")) {
849
+ backend.add(capability.slice("backend.".length));
850
+ continue;
851
+ }
852
+ if (capability.startsWith("thread.item.")) {
853
+ threadItems.add(capability.slice("thread.item.".length));
854
+ }
855
+ if (capability.startsWith("error.")) {
856
+ errors.add(capability.slice("error.".length));
857
+ continue;
858
+ }
859
+ if (capability.startsWith("widget.")) {
860
+ widgets.add(capability.slice("widget.".length));
861
+ continue;
862
+ }
863
+ }
864
+ return { commands, events, backend, threadItems, errors, widgets };
865
+ };
866
+ class ChatFrameMessenger extends BaseMessenger {
867
+ // Messenger running in outer can always handle commands coming from inner
868
+ canReceiveCommand(_) {
869
+ return true;
870
+ }
871
+ }
872
+ const removeMethods = (obj, seen = /* @__PURE__ */ new WeakSet()) => {
873
+ if (typeof obj === "function") return "[ChatKitMethod]";
874
+ if (typeof obj !== "object" || obj === null) return obj;
875
+ if (seen.has(obj)) return obj;
876
+ seen.add(obj);
877
+ if (Array.isArray(obj)) {
878
+ return obj.map((c) => removeMethods(c, seen));
879
+ }
880
+ const result = {};
881
+ for (const [key, value] of Object.entries(obj)) {
882
+ if (typeof value !== "function") {
883
+ result[key] = removeMethods(value, seen);
884
+ } else {
885
+ result[key] = "[ChatKitMethod]";
886
+ }
887
+ }
888
+ return result;
889
+ };
890
+ const DRAG_DIRECTION_THRESHOLD_PX = 2;
891
+ const PET_BASE_RENDER_SCALE = 0.5;
892
+ const PET_FRAME_DURATION_MULTIPLIER = 1.5;
893
+ const PET_RESTING_FRAME_DURATION_MULTIPLIER = 3;
894
+ const PET_RESTING_DELAY_MS = 2e3;
895
+ const PET_SUMMARY_GAP = 12;
896
+ const PET_SUMMARY_WIDTH = 320;
897
+ const PET_SUMMARY_MARGIN = 12;
898
+ const PET_OVERLAY_COPY = {
899
+ "en-US": {
900
+ hideMessage: "Hide message",
901
+ expandMessage: "Expand message",
902
+ collapseMessage: "Collapse message",
903
+ restoreMessage: "Show message",
904
+ replyButton: "Reply",
905
+ replyPlaceholder: "Reply...",
906
+ sendButton: "Send",
907
+ sendingButton: "Sending...",
908
+ sendFailed: "Failed to send"
909
+ },
910
+ "zh-CN": {
911
+ hideMessage: "隐藏消息",
912
+ expandMessage: "展开消息",
913
+ collapseMessage: "收起消息",
914
+ restoreMessage: "显示消息",
915
+ replyButton: "回复",
916
+ replyPlaceholder: "输入回复...",
917
+ sendButton: "发送",
918
+ sendingButton: "发送中...",
919
+ sendFailed: "发送失败"
920
+ }
921
+ };
922
+ function stopEventPropagation(event) {
923
+ event.stopPropagation();
924
+ }
925
+ function getViewportSize() {
926
+ const visualViewport = window.visualViewport;
927
+ return {
928
+ width: (visualViewport == null ? void 0 : visualViewport.width) || window.innerWidth || 320,
929
+ height: (visualViewport == null ? void 0 : visualViewport.height) || window.innerHeight || 480
930
+ };
931
+ }
932
+ function readPersistedPosition(storageKey, persist) {
933
+ if (!persist) {
934
+ return null;
935
+ }
936
+ try {
937
+ const raw = window.localStorage.getItem(storageKey);
938
+ if (!raw) {
939
+ return null;
940
+ }
941
+ const parsed = JSON.parse(raw);
942
+ if (!parsed || typeof parsed !== "object" || typeof parsed.x !== "number" || typeof parsed.y !== "number") {
943
+ return null;
944
+ }
945
+ return { x: parsed.x, y: parsed.y };
946
+ } catch {
947
+ return null;
948
+ }
949
+ }
950
+ function writePersistedPosition(storageKey, persist, position) {
951
+ if (!persist) {
952
+ return;
953
+ }
954
+ try {
955
+ window.localStorage.setItem(storageKey, JSON.stringify(position));
956
+ } catch {
957
+ }
958
+ }
959
+ function escapeCssUrl(value) {
960
+ return value.replace(/["\\]/g, "\\$&");
961
+ }
962
+ function getRenderScale(scale) {
963
+ return Math.max(0.1, scale) * PET_BASE_RENDER_SCALE;
964
+ }
965
+ function clampNumber(value, min, max) {
966
+ return Math.min(max, Math.max(min, value));
967
+ }
968
+ function getDefaultLocale() {
969
+ if (typeof window !== "undefined") {
970
+ try {
971
+ const stored = window.localStorage.getItem("chatkit:locale");
972
+ if (stored) {
973
+ return stored;
974
+ }
975
+ } catch {
976
+ }
977
+ }
978
+ return typeof navigator !== "undefined" ? navigator.language : null;
979
+ }
980
+ function resolveCopyLocale(locale) {
981
+ const normalized = (locale ?? getDefaultLocale() ?? "").trim().toLowerCase();
982
+ if (normalized === "zh-cn" || normalized === "zh-hans" || normalized.startsWith("zh")) {
983
+ return "zh-CN";
984
+ }
985
+ return "en-US";
986
+ }
987
+ function isPetState(value) {
988
+ return value === "idle" || value === "running-right" || value === "running-left" || value === "waving" || value === "jumping" || value === "failed" || value === "waiting" || value === "running" || value === "review";
989
+ }
990
+ function parsePetStateChangePayload(value) {
991
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
992
+ return null;
993
+ }
994
+ const payload = value;
995
+ return isPetState(payload.state) ? { state: payload.state } : null;
996
+ }
997
+ function parsePetOptionsChangePayload(value) {
998
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
999
+ return null;
1000
+ }
1001
+ const payload = value;
1002
+ if (payload.pet === null || typeof payload.pet === "boolean") {
1003
+ return { pet: payload.pet };
1004
+ }
1005
+ if (payload.pet && typeof payload.pet === "object" && !Array.isArray(payload.pet)) {
1006
+ return { pet: payload.pet };
1007
+ }
1008
+ return null;
1009
+ }
1010
+ function isThreadSummaryStatus(value) {
1011
+ return value === "running" || value === "completed" || value === "failed";
1012
+ }
1013
+ function getThreadSummaryKey(summary) {
1014
+ if (!summary) {
1015
+ return null;
1016
+ }
1017
+ return [
1018
+ summary.threadId,
1019
+ summary.messageId || summary.updatedAt || summary.message
1020
+ ].join(":");
1021
+ }
1022
+ function parseThreadSummaryPayload(value) {
1023
+ if (value === null) {
1024
+ return { summary: null };
1025
+ }
1026
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1027
+ return null;
1028
+ }
1029
+ const payload = value;
1030
+ if (typeof payload.threadId !== "string" || !payload.threadId.trim() || typeof payload.title !== "string" || !payload.title.trim() || typeof payload.message !== "string" || !payload.message.trim() || !isThreadSummaryStatus(payload.status)) {
1031
+ return null;
1032
+ }
1033
+ return {
1034
+ summary: {
1035
+ threadId: payload.threadId,
1036
+ title: payload.title,
1037
+ message: payload.message,
1038
+ status: payload.status,
1039
+ ...typeof payload.messageId === "string" && payload.messageId.trim() ? { messageId: payload.messageId } : {},
1040
+ ...typeof payload.updatedAt === "string" && payload.updatedAt.trim() ? { updatedAt: payload.updatedAt } : {}
1041
+ }
1042
+ };
1043
+ }
1044
+ function parseThreadSummaryLogPayload(value) {
1045
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1046
+ return null;
1047
+ }
1048
+ const payload = value;
1049
+ if (payload.name !== "thread.summary") {
1050
+ return null;
1051
+ }
1052
+ return parseThreadSummaryPayload(payload.data ?? null);
1053
+ }
1054
+ class PetOverlay {
1055
+ constructor(root, options) {
1056
+ this.overlayElement = null;
1057
+ this.petElement = null;
1058
+ this.summaryElement = null;
1059
+ this.summaryToggleElement = null;
1060
+ this.mediaElement = null;
1061
+ this.options = null;
1062
+ this.resolved = null;
1063
+ this.summary = null;
1064
+ this.summaryRenderKey = null;
1065
+ this.dismissedSummaryKey = null;
1066
+ this.isSummaryCollapsed = false;
1067
+ this.isSummaryExpanded = false;
1068
+ this.isSummaryHovering = false;
1069
+ this.isReplyOpen = false;
1070
+ this.isReplySubmitting = false;
1071
+ this.replyError = null;
1072
+ this.replyDraft = "";
1073
+ this.replyInputElement = null;
1074
+ this.copyLocale = resolveCopyLocale();
1075
+ this.copy = PET_OVERLAY_COPY[this.copyLocale];
1076
+ this.currentState = "waiting";
1077
+ this.lastAutoState = "waiting";
1078
+ this.transient = null;
1079
+ this.position = null;
1080
+ this.dragPosition = null;
1081
+ this.dragOffset = { x: 0, y: 0 };
1082
+ this.lastDragPosition = null;
1083
+ this.lastDragClientX = null;
1084
+ this.dragAnimation = null;
1085
+ this.isDragging = false;
1086
+ this.isHovering = false;
1087
+ this.movedDuringDrag = false;
1088
+ this.prefersReducedMotion = false;
1089
+ this.frame = 0;
1090
+ this.completed = false;
1091
+ this.activeAnimationName = null;
1092
+ this.activeAnimationMode = null;
1093
+ this.frameTimer = null;
1094
+ this.restingDelayTimer = null;
1095
+ this.mediaQuery = null;
1096
+ this.connected = false;
1097
+ this.handleViewportChange = () => {
1098
+ this.render();
1099
+ };
1100
+ this.handleReducedMotionChange = () => {
1101
+ var _a2;
1102
+ this.prefersReducedMotion = Boolean((_a2 = this.mediaQuery) == null ? void 0 : _a2.matches);
1103
+ if (this.prefersReducedMotion) {
1104
+ this.transient = null;
1105
+ }
1106
+ this.render();
1107
+ };
1108
+ this.handlePointerEnter = () => {
1109
+ this.clearRestingDelayTimer();
1110
+ this.isHovering = true;
1111
+ this.rescheduleAnimation();
1112
+ };
1113
+ this.handlePointerLeave = () => {
1114
+ if (!this.isDragging) {
1115
+ this.enterRestingAfterDelay();
1116
+ }
1117
+ };
1118
+ this.handleSummaryPointerEnter = () => {
1119
+ this.isSummaryHovering = true;
1120
+ this.render();
1121
+ };
1122
+ this.handleSummaryPointerLeave = () => {
1123
+ this.isSummaryHovering = false;
1124
+ if (!this.isReplyOpen) {
1125
+ this.render();
1126
+ }
1127
+ };
1128
+ this.handleSummaryClick = () => {
1129
+ var _a2, _b2;
1130
+ const threadId = (_a2 = this.summary) == null ? void 0 : _a2.threadId.trim();
1131
+ if (!threadId) {
1132
+ return;
1133
+ }
1134
+ (_b2 = this.onThreadSummaryActivate) == null ? void 0 : _b2.call(this, threadId);
1135
+ };
1136
+ this.handleSummaryDelete = () => {
1137
+ const summaryKey = getThreadSummaryKey(this.summary);
1138
+ if (summaryKey) {
1139
+ this.dismissedSummaryKey = summaryKey;
1140
+ }
1141
+ this.isSummaryCollapsed = false;
1142
+ this.isReplyOpen = false;
1143
+ this.replyDraft = "";
1144
+ this.replyError = null;
1145
+ this.removeSummaryElements();
1146
+ };
1147
+ this.handleSummaryCollapseToggle = () => {
1148
+ this.isSummaryCollapsed = !this.isSummaryCollapsed;
1149
+ this.isSummaryExpanded = false;
1150
+ this.isReplyOpen = false;
1151
+ this.replyError = null;
1152
+ this.render();
1153
+ };
1154
+ this.handleSummaryExpandToggle = () => {
1155
+ this.isSummaryExpanded = !this.isSummaryExpanded;
1156
+ this.render();
1157
+ };
1158
+ this.handleReplyOpen = () => {
1159
+ this.isReplyOpen = true;
1160
+ this.replyError = null;
1161
+ this.render();
1162
+ };
1163
+ this.handleReplyInput = (event) => {
1164
+ const target = event.currentTarget;
1165
+ if (target instanceof HTMLInputElement) {
1166
+ this.replyDraft = target.value;
1167
+ this.replyError = null;
1168
+ }
1169
+ };
1170
+ this.handleReplySubmit = (event) => {
1171
+ event.preventDefault();
1172
+ void this.submitReply();
1173
+ };
1174
+ this.handleReplyKeyDown = (event) => {
1175
+ if (event.key !== "Escape") {
1176
+ return;
1177
+ }
1178
+ event.preventDefault();
1179
+ this.isReplyOpen = false;
1180
+ this.replyError = null;
1181
+ this.render();
1182
+ };
1183
+ this.handlePointerDown = (event) => {
1184
+ var _a2, _b2;
1185
+ if (!((_a2 = this.options) == null ? void 0 : _a2.position.draggable) || event.button !== 0) {
1186
+ return;
1187
+ }
1188
+ event.preventDefault();
1189
+ const rect = (_b2 = this.petElement) == null ? void 0 : _b2.getBoundingClientRect();
1190
+ if (!rect) {
1191
+ return;
1192
+ }
1193
+ const nextPosition = {
1194
+ x: rect.left,
1195
+ y: rect.top
1196
+ };
1197
+ this.dragOffset = {
1198
+ x: event.clientX - rect.left,
1199
+ y: event.clientY - rect.top
1200
+ };
1201
+ this.lastDragPosition = nextPosition;
1202
+ this.lastDragClientX = event.clientX;
1203
+ this.dragAnimation = null;
1204
+ this.movedDuringDrag = false;
1205
+ this.dragPosition = nextPosition;
1206
+ this.isDragging = true;
1207
+ this.clearRestingDelayTimer();
1208
+ this.isHovering = true;
1209
+ this.installDragListeners();
1210
+ this.rescheduleAnimation();
1211
+ };
1212
+ this.handlePointerMove = (event) => {
1213
+ const nextPosition = this.getNextDragPosition(event);
1214
+ const last = this.lastDragPosition;
1215
+ if (last && (Math.abs(last.x - nextPosition.x) > DRAG_DIRECTION_THRESHOLD_PX || Math.abs(last.y - nextPosition.y) > DRAG_DIRECTION_THRESHOLD_PX)) {
1216
+ this.movedDuringDrag = true;
1217
+ }
1218
+ if (this.lastDragClientX !== null) {
1219
+ const deltaX = event.clientX - this.lastDragClientX;
1220
+ if (deltaX > DRAG_DIRECTION_THRESHOLD_PX) {
1221
+ this.dragAnimation = "running-right";
1222
+ } else if (deltaX < -DRAG_DIRECTION_THRESHOLD_PX) {
1223
+ this.dragAnimation = "running-left";
1224
+ }
1225
+ }
1226
+ this.lastDragClientX = event.clientX;
1227
+ this.lastDragPosition = nextPosition;
1228
+ this.dragPosition = nextPosition;
1229
+ this.render();
1230
+ };
1231
+ this.handlePointerUp = (event) => {
1232
+ const finalPosition = this.lastDragPosition ?? this.getNextDragPosition(event);
1233
+ this.isDragging = false;
1234
+ this.dragPosition = null;
1235
+ this.dragAnimation = null;
1236
+ this.lastDragClientX = null;
1237
+ this.removeDragListeners();
1238
+ this.persistPosition(finalPosition);
1239
+ if (event.pointerType === "mouse" && this.isPointerOverPet(event)) {
1240
+ this.isHovering = true;
1241
+ this.rescheduleAnimation();
1242
+ } else {
1243
+ this.enterRestingAfterDelay();
1244
+ this.rescheduleAnimation();
1245
+ }
1246
+ };
1247
+ this.handleClick = () => {
1248
+ var _a2;
1249
+ if (this.movedDuringDrag) {
1250
+ return;
1251
+ }
1252
+ (_a2 = this.onActivate) == null ? void 0 : _a2.call(this);
1253
+ if (this.prefersReducedMotion) {
1254
+ return;
1255
+ }
1256
+ this.transient = { name: "waving" };
1257
+ this.render();
1258
+ };
1259
+ this.root = root;
1260
+ this.onActivate = options == null ? void 0 : options.onActivate;
1261
+ this.onReply = options == null ? void 0 : options.onReply;
1262
+ this.onThreadSummaryActivate = options == null ? void 0 : options.onThreadSummaryActivate;
1263
+ this.connect();
1264
+ }
1265
+ connect() {
1266
+ if (this.connected) {
1267
+ return;
1268
+ }
1269
+ this.connected = true;
1270
+ this.installViewportListeners();
1271
+ this.installReducedMotionListener();
1272
+ this.render();
1273
+ }
1274
+ setOptions(pet) {
1275
+ const nextOptions = chatkitTypes.normalizePetOptions(pet);
1276
+ this.options = nextOptions;
1277
+ if (!nextOptions) {
1278
+ this.isDragging = false;
1279
+ this.isHovering = false;
1280
+ this.position = null;
1281
+ this.dragPosition = null;
1282
+ this.dragAnimation = null;
1283
+ this.lastDragPosition = null;
1284
+ this.lastDragClientX = null;
1285
+ this.transient = null;
1286
+ this.resolved = null;
1287
+ this.clearRestingDelayTimer();
1288
+ this.removeDragListeners();
1289
+ this.removeOverlay();
1290
+ return;
1291
+ }
1292
+ this.position = readPersistedPosition(
1293
+ chatkitTypes.DEFAULT_PET_STORAGE_KEY,
1294
+ nextOptions.position.persist
1295
+ );
1296
+ if (nextOptions.behavior === "auto" && !this.prefersReducedMotion) {
1297
+ this.transient = { name: "waving" };
1298
+ }
1299
+ this.resolveCharacter();
1300
+ this.render();
1301
+ }
1302
+ setState(state) {
1303
+ var _a2;
1304
+ const previous = this.lastAutoState;
1305
+ this.lastAutoState = state;
1306
+ this.currentState = state;
1307
+ if (((_a2 = this.options) == null ? void 0 : _a2.behavior) === "auto" && !this.prefersReducedMotion && state === "idle" && (previous === "running" || previous === "review") && !this.transient) {
1308
+ this.transient = { name: "jumping" };
1309
+ } else if (state !== "idle") {
1310
+ this.transient = null;
1311
+ }
1312
+ this.render();
1313
+ }
1314
+ setLocale(locale) {
1315
+ const nextLocale = resolveCopyLocale(locale);
1316
+ if (nextLocale === this.copyLocale) {
1317
+ return;
1318
+ }
1319
+ this.copyLocale = nextLocale;
1320
+ this.copy = PET_OVERLAY_COPY[nextLocale];
1321
+ this.summaryRenderKey = null;
1322
+ this.render();
1323
+ }
1324
+ setThreadSummary(summary) {
1325
+ const previousKey = getThreadSummaryKey(this.summary);
1326
+ const nextKey = getThreadSummaryKey(summary);
1327
+ this.summary = summary;
1328
+ if (!summary) {
1329
+ this.isSummaryCollapsed = false;
1330
+ this.isSummaryExpanded = false;
1331
+ this.isSummaryHovering = false;
1332
+ this.isReplyOpen = false;
1333
+ this.isReplySubmitting = false;
1334
+ this.replyError = null;
1335
+ this.replyDraft = "";
1336
+ this.summaryRenderKey = null;
1337
+ this.removeSummaryElements();
1338
+ return;
1339
+ }
1340
+ if (previousKey !== nextKey) {
1341
+ this.isSummaryCollapsed = false;
1342
+ this.isSummaryExpanded = false;
1343
+ this.isSummaryHovering = false;
1344
+ this.isReplyOpen = false;
1345
+ this.isReplySubmitting = false;
1346
+ this.replyError = null;
1347
+ this.replyDraft = "";
1348
+ }
1349
+ this.render();
1350
+ }
1351
+ setThreadSummaryStatus(status) {
1352
+ if (!this.summary || this.summary.status === status) {
1353
+ return;
1354
+ }
1355
+ this.summary = { ...this.summary, status };
1356
+ this.render();
1357
+ }
1358
+ destroy() {
1359
+ var _a2, _b2, _c2, _d;
1360
+ if (!this.connected) {
1361
+ return;
1362
+ }
1363
+ this.connected = false;
1364
+ this.clearRestingDelayTimer();
1365
+ this.clearTimers();
1366
+ this.removeDragListeners();
1367
+ this.removeOverlay();
1368
+ window.removeEventListener("resize", this.handleViewportChange);
1369
+ (_a2 = window.visualViewport) == null ? void 0 : _a2.removeEventListener(
1370
+ "resize",
1371
+ this.handleViewportChange
1372
+ );
1373
+ (_b2 = window.visualViewport) == null ? void 0 : _b2.removeEventListener(
1374
+ "scroll",
1375
+ this.handleViewportChange
1376
+ );
1377
+ (_d = (_c2 = this.mediaQuery) == null ? void 0 : _c2.removeEventListener) == null ? void 0 : _d.call(
1378
+ _c2,
1379
+ "change",
1380
+ this.handleReducedMotionChange
1381
+ );
1382
+ this.mediaQuery = null;
1383
+ }
1384
+ installViewportListeners() {
1385
+ var _a2, _b2;
1386
+ window.addEventListener("resize", this.handleViewportChange);
1387
+ (_a2 = window.visualViewport) == null ? void 0 : _a2.addEventListener("resize", this.handleViewportChange);
1388
+ (_b2 = window.visualViewport) == null ? void 0 : _b2.addEventListener("scroll", this.handleViewportChange);
1389
+ }
1390
+ installReducedMotionListener() {
1391
+ var _a2, _b2;
1392
+ if (!window.matchMedia) {
1393
+ return;
1394
+ }
1395
+ this.mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
1396
+ this.prefersReducedMotion = this.mediaQuery.matches;
1397
+ (_b2 = (_a2 = this.mediaQuery).addEventListener) == null ? void 0 : _b2.call(
1398
+ _a2,
1399
+ "change",
1400
+ this.handleReducedMotionChange
1401
+ );
1402
+ }
1403
+ resolveCharacter() {
1404
+ if (!this.options) {
1405
+ this.resolved = null;
1406
+ return;
1407
+ }
1408
+ const character = this.options.character;
1409
+ this.resolved = chatkitTypes.resolvePetCharacter(character);
1410
+ }
1411
+ ensureOverlay() {
1412
+ if (this.overlayElement && this.petElement) {
1413
+ return;
1414
+ }
1415
+ const overlay = document.createElement("div");
1416
+ overlay.setAttribute("data-chatkit-host-pet-layer", "");
1417
+ overlay.style.position = "fixed";
1418
+ overlay.style.inset = "0";
1419
+ overlay.style.pointerEvents = "none";
1420
+ overlay.style.overflow = "visible";
1421
+ const style = document.createElement("style");
1422
+ style.textContent = `
1423
+ @keyframes chatkit-pet-summary-spin {
1424
+ to { transform: rotate(360deg); }
1425
+ }
1426
+ `;
1427
+ const pet = document.createElement("div");
1428
+ pet.setAttribute("data-chatkit-host-pet", "");
1429
+ pet.style.position = "absolute";
1430
+ pet.style.top = "0";
1431
+ pet.style.left = "0";
1432
+ pet.style.pointerEvents = "auto";
1433
+ pet.style.touchAction = "none";
1434
+ pet.style.userSelect = "none";
1435
+ pet.style.willChange = "transform";
1436
+ pet.addEventListener("pointerenter", this.handlePointerEnter);
1437
+ pet.addEventListener("pointerleave", this.handlePointerLeave);
1438
+ pet.addEventListener("pointerdown", this.handlePointerDown);
1439
+ pet.addEventListener("click", this.handleClick);
1440
+ overlay.append(style, pet);
1441
+ this.root.append(overlay);
1442
+ this.overlayElement = overlay;
1443
+ this.petElement = pet;
1444
+ }
1445
+ removeOverlay() {
1446
+ var _a2;
1447
+ this.clearRestingDelayTimer();
1448
+ this.clearTimers();
1449
+ if (this.petElement) {
1450
+ this.petElement.removeEventListener(
1451
+ "pointerenter",
1452
+ this.handlePointerEnter
1453
+ );
1454
+ this.petElement.removeEventListener(
1455
+ "pointerleave",
1456
+ this.handlePointerLeave
1457
+ );
1458
+ this.petElement.removeEventListener("pointerdown", this.handlePointerDown);
1459
+ this.petElement.removeEventListener("click", this.handleClick);
1460
+ }
1461
+ this.isHovering = false;
1462
+ this.removeSummaryElements();
1463
+ (_a2 = this.overlayElement) == null ? void 0 : _a2.remove();
1464
+ this.overlayElement = null;
1465
+ this.petElement = null;
1466
+ this.mediaElement = null;
1467
+ }
1468
+ removeSummaryElements() {
1469
+ var _a2, _b2;
1470
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1471
+ (_b2 = this.summaryToggleElement) == null ? void 0 : _b2.remove();
1472
+ this.summaryElement = null;
1473
+ this.summaryToggleElement = null;
1474
+ this.replyInputElement = null;
1475
+ this.summaryRenderKey = null;
1476
+ }
1477
+ getSize() {
1478
+ if (!this.options || !this.resolved) {
1479
+ return { width: 0, height: 0 };
1480
+ }
1481
+ const scale = getRenderScale(this.options.position.scale);
1482
+ const baseSize = {
1483
+ width: this.resolved.atlas.cellWidth,
1484
+ height: this.resolved.atlas.cellHeight
1485
+ };
1486
+ return {
1487
+ width: baseSize.width * scale,
1488
+ height: baseSize.height * scale
1489
+ };
1490
+ }
1491
+ getCurrentPosition(size) {
1492
+ const options = this.options;
1493
+ if (!options) {
1494
+ return { x: 0, y: 0 };
1495
+ }
1496
+ const viewport = getViewportSize();
1497
+ const padding = chatkitTypes.normalizeBoundsPadding(options.position.boundsPadding);
1498
+ const pin = options.position.pin === void 0 ? "bottom-right" : options.position.pin;
1499
+ const pinnedPosition = pin ? chatkitTypes.getPinnedPetPosition(pin, size, viewport, padding) : null;
1500
+ return chatkitTypes.clampPetPosition(
1501
+ this.dragPosition ?? this.position ?? pinnedPosition ?? { x: padding.left, y: padding.top },
1502
+ size,
1503
+ viewport,
1504
+ padding
1505
+ );
1506
+ }
1507
+ persistPosition(nextPosition) {
1508
+ if (!this.options) {
1509
+ return;
1510
+ }
1511
+ const size = this.getSize();
1512
+ const clamped = chatkitTypes.clampPetPosition(
1513
+ nextPosition,
1514
+ size,
1515
+ getViewportSize(),
1516
+ chatkitTypes.normalizeBoundsPadding(this.options.position.boundsPadding)
1517
+ );
1518
+ this.position = clamped;
1519
+ writePersistedPosition(
1520
+ chatkitTypes.DEFAULT_PET_STORAGE_KEY,
1521
+ this.options.position.persist,
1522
+ clamped
1523
+ );
1524
+ }
1525
+ getActiveAnimationName() {
1526
+ if (!this.options) {
1527
+ return "idle";
1528
+ }
1529
+ if (this.isDragging) {
1530
+ return this.dragAnimation ?? "running";
1531
+ }
1532
+ if (this.transient) {
1533
+ return this.transient.name;
1534
+ }
1535
+ if (this.options.behavior === "manual") {
1536
+ return "idle";
1537
+ }
1538
+ return this.currentState;
1539
+ }
1540
+ getActiveAnimationMode() {
1541
+ if (this.isDragging) {
1542
+ return "loop";
1543
+ }
1544
+ return this.transient ? "once" : "loop";
1545
+ }
1546
+ resetAnimationIfNeeded(name, mode) {
1547
+ if (this.activeAnimationName === name && this.activeAnimationMode === mode) {
1548
+ return;
1549
+ }
1550
+ this.clearTimers();
1551
+ this.activeAnimationName = name;
1552
+ this.activeAnimationMode = mode;
1553
+ this.frame = 0;
1554
+ this.completed = false;
1555
+ }
1556
+ render() {
1557
+ if (!this.options || !this.resolved) {
1558
+ this.clearTimers();
1559
+ if (this.petElement) {
1560
+ this.petElement.replaceChildren();
1561
+ }
1562
+ this.removeSummaryElements();
1563
+ this.mediaElement = null;
1564
+ this.activeAnimationName = null;
1565
+ this.activeAnimationMode = null;
1566
+ this.frame = 0;
1567
+ this.completed = false;
1568
+ return;
1569
+ }
1570
+ this.ensureOverlay();
1571
+ const overlay = this.overlayElement;
1572
+ const pet = this.petElement;
1573
+ if (!overlay || !pet) {
1574
+ return;
1575
+ }
1576
+ const size = this.getSize();
1577
+ const position = this.getCurrentPosition(size);
1578
+ const animationName = this.getActiveAnimationName();
1579
+ const animationMode = this.getActiveAnimationMode();
1580
+ this.resetAnimationIfNeeded(animationName, animationMode);
1581
+ overlay.style.zIndex = String(this.options.position.zIndex);
1582
+ pet.style.width = `${size.width}px`;
1583
+ pet.style.height = `${size.height}px`;
1584
+ pet.style.transform = `translate3d(${position.x}px, ${position.y}px, 0)`;
1585
+ pet.style.cursor = this.options.position.draggable ? this.isDragging ? "grabbing" : "grab" : "default";
1586
+ pet.dataset.petAnimation = animationName;
1587
+ pet.setAttribute("aria-label", this.options.ariaLabel);
1588
+ pet.setAttribute("role", "img");
1589
+ this.renderAtlas(animationName, animationMode);
1590
+ this.renderThreadSummary(position, size);
1591
+ this.scheduleNextFrame(animationName, animationMode);
1592
+ }
1593
+ renderThreadSummary(position, size) {
1594
+ var _a2, _b2, _c2;
1595
+ const summary = this.summary;
1596
+ const summaryKey = getThreadSummaryKey(summary);
1597
+ if (!summary || !summaryKey || this.dismissedSummaryKey === summaryKey) {
1598
+ this.removeSummaryElements();
1599
+ return;
1600
+ }
1601
+ if (this.isSummaryCollapsed) {
1602
+ this.renderCollapsedSummary(position, size);
1603
+ return;
1604
+ }
1605
+ const nextRenderKey = [
1606
+ summaryKey,
1607
+ summary.title,
1608
+ summary.message,
1609
+ summary.status,
1610
+ this.copyLocale,
1611
+ this.isSummaryExpanded ? "expanded" : "compact",
1612
+ this.isSummaryHovering ? "hover" : "rest",
1613
+ this.isReplyOpen ? "reply" : "closed",
1614
+ this.isReplySubmitting ? "submitting" : "ready",
1615
+ this.replyError ?? ""
1616
+ ].join("|");
1617
+ if (!this.summaryElement || this.summaryRenderKey !== nextRenderKey) {
1618
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1619
+ (_b2 = this.summaryToggleElement) == null ? void 0 : _b2.remove();
1620
+ this.summaryElement = this.createSummaryBubble(summary);
1621
+ this.summaryToggleElement = this.createSummaryToggleButton("v");
1622
+ (_c2 = this.overlayElement) == null ? void 0 : _c2.append(this.summaryElement, this.summaryToggleElement);
1623
+ this.summaryRenderKey = nextRenderKey;
1624
+ if (this.isReplyOpen && !this.isReplySubmitting) {
1625
+ window.setTimeout(() => {
1626
+ var _a3;
1627
+ return (_a3 = this.replyInputElement) == null ? void 0 : _a3.focus();
1628
+ }, 0);
1629
+ }
1630
+ }
1631
+ this.positionSummaryBubble(position, size);
1632
+ }
1633
+ renderCollapsedSummary(position, size) {
1634
+ var _a2, _b2;
1635
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1636
+ this.summaryElement = null;
1637
+ this.summaryRenderKey = null;
1638
+ if (!this.summaryToggleElement) {
1639
+ this.summaryToggleElement = this.createSummaryToggleButton("1");
1640
+ (_b2 = this.overlayElement) == null ? void 0 : _b2.append(this.summaryToggleElement);
1641
+ }
1642
+ this.summaryToggleElement.textContent = "1";
1643
+ this.positionSummaryToggleBadge(position, size);
1644
+ }
1645
+ positionSummaryToggleBadge(position, size) {
1646
+ const badge = this.summaryToggleElement;
1647
+ if (!badge) {
1648
+ return;
1649
+ }
1650
+ const viewport = getViewportSize();
1651
+ const badgeSize = 34;
1652
+ const x = clampNumber(
1653
+ position.x + size.width - badgeSize * 0.35,
1654
+ PET_SUMMARY_MARGIN,
1655
+ viewport.width - badgeSize - PET_SUMMARY_MARGIN
1656
+ );
1657
+ const y = clampNumber(
1658
+ position.y - badgeSize * 0.35,
1659
+ PET_SUMMARY_MARGIN,
1660
+ viewport.height - badgeSize - PET_SUMMARY_MARGIN
1661
+ );
1662
+ badge.style.width = `${badgeSize}px`;
1663
+ badge.style.height = `${badgeSize}px`;
1664
+ badge.style.transform = `translate3d(${x}px, ${y}px, 0)`;
1665
+ badge.style.borderRadius = "999px";
1666
+ }
1667
+ positionSummaryBubble(position, size) {
1668
+ const bubble = this.summaryElement;
1669
+ const toggle = this.summaryToggleElement;
1670
+ if (!bubble || !toggle) {
1671
+ return;
1672
+ }
1673
+ const viewport = getViewportSize();
1674
+ const width = Math.min(PET_SUMMARY_WIDTH, viewport.width - PET_SUMMARY_MARGIN * 2);
1675
+ bubble.style.width = `${width}px`;
1676
+ const bubbleHeight = bubble.offsetHeight || 96;
1677
+ const aboveY = position.y - bubbleHeight - PET_SUMMARY_GAP;
1678
+ const showAbove = aboveY >= PET_SUMMARY_MARGIN;
1679
+ const y = showAbove ? aboveY : clampNumber(
1680
+ position.y + size.height + PET_SUMMARY_GAP,
1681
+ PET_SUMMARY_MARGIN,
1682
+ viewport.height - bubbleHeight - PET_SUMMARY_MARGIN
1683
+ );
1684
+ const x = clampNumber(
1685
+ position.x + size.width / 2 - width / 2,
1686
+ PET_SUMMARY_MARGIN,
1687
+ viewport.width - width - PET_SUMMARY_MARGIN
1688
+ );
1689
+ bubble.style.transform = `translate3d(${x}px, ${y}px, 0)`;
1690
+ this.positionSummaryToggleBadge(position, size);
1691
+ }
1692
+ createSummaryBubble(summary) {
1693
+ const shouldShowReplyButton = this.isSummaryHovering && !this.isReplyOpen;
1694
+ const bubble = document.createElement("div");
1695
+ bubble.setAttribute("data-chatkit-pet-summary", "");
1696
+ bubble.addEventListener("pointerenter", this.handleSummaryPointerEnter);
1697
+ bubble.addEventListener("pointerleave", this.handleSummaryPointerLeave);
1698
+ bubble.addEventListener("click", this.handleSummaryClick);
1699
+ bubble.style.position = "absolute";
1700
+ bubble.style.top = "0";
1701
+ bubble.style.left = "0";
1702
+ bubble.style.boxSizing = "border-box";
1703
+ bubble.style.pointerEvents = "auto";
1704
+ bubble.style.padding = "12px 14px";
1705
+ bubble.style.paddingBottom = "12px";
1706
+ bubble.style.border = "1px solid rgba(148, 163, 184, 0.22)";
1707
+ bubble.style.borderRadius = "22px";
1708
+ bubble.style.background = "rgba(255, 255, 255, 0.94)";
1709
+ bubble.style.color = "#1f2937";
1710
+ bubble.style.boxShadow = "0 8px 24px rgba(15, 23, 42, 0.1)";
1711
+ bubble.style.font = '500 14px/1.35 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
1712
+ bubble.style.backdropFilter = "blur(10px)";
1713
+ const header = document.createElement("div");
1714
+ header.style.display = "flex";
1715
+ header.style.alignItems = "center";
1716
+ header.style.gap = "8px";
1717
+ if (this.isSummaryHovering || this.isReplyOpen) {
1718
+ header.append(
1719
+ this.createSummaryActionButton(
1720
+ "x",
1721
+ this.copy.hideMessage,
1722
+ this.handleSummaryDelete
1723
+ )
1724
+ );
1725
+ }
1726
+ const title = document.createElement("div");
1727
+ title.textContent = summary.title;
1728
+ title.style.minWidth = "0";
1729
+ title.style.flex = "1";
1730
+ title.style.overflow = "hidden";
1731
+ title.style.textOverflow = "ellipsis";
1732
+ title.style.whiteSpace = "nowrap";
1733
+ title.style.fontWeight = "700";
1734
+ title.style.fontSize = "15px";
1735
+ header.append(title);
1736
+ if (this.isSummaryHovering || this.isReplyOpen) {
1737
+ header.append(
1738
+ this.createSummaryActionButton(
1739
+ this.isSummaryExpanded ? "-" : ">",
1740
+ this.isSummaryExpanded ? this.copy.collapseMessage : this.copy.expandMessage,
1741
+ this.handleSummaryExpandToggle
1742
+ )
1743
+ );
1744
+ } else {
1745
+ header.append(this.createStatusIcon(summary.status));
1746
+ }
1747
+ const message = document.createElement("div");
1748
+ message.textContent = summary.message;
1749
+ message.style.marginTop = "4px";
1750
+ message.style.fontWeight = "400";
1751
+ message.style.color = "#374151";
1752
+ message.style.overflow = "hidden";
1753
+ if (this.isSummaryExpanded) {
1754
+ message.style.maxHeight = "7em";
1755
+ message.style.overflowY = "auto";
1756
+ } else {
1757
+ message.style.display = "-webkit-box";
1758
+ message.style.setProperty("-webkit-line-clamp", "2");
1759
+ message.style.setProperty("-webkit-box-orient", "vertical");
1760
+ }
1761
+ bubble.append(header, message);
1762
+ if (shouldShowReplyButton) {
1763
+ const reply = this.createTextButton(
1764
+ this.copy.replyButton,
1765
+ this.handleReplyOpen
1766
+ );
1767
+ reply.style.position = "absolute";
1768
+ reply.style.right = "14px";
1769
+ reply.style.bottom = "10px";
1770
+ bubble.append(reply);
1771
+ }
1772
+ if (this.isReplyOpen) {
1773
+ bubble.append(this.createReplyForm());
1774
+ }
1775
+ return bubble;
1776
+ }
1777
+ createSummaryToggleButton(label) {
1778
+ const button = document.createElement("button");
1779
+ button.type = "button";
1780
+ button.textContent = label;
1781
+ button.title = label === "1" ? this.copy.restoreMessage : this.copy.collapseMessage;
1782
+ button.addEventListener("click", stopEventPropagation);
1783
+ button.addEventListener("click", this.handleSummaryCollapseToggle);
1784
+ button.style.position = "absolute";
1785
+ button.style.top = "0";
1786
+ button.style.left = "0";
1787
+ button.style.pointerEvents = "auto";
1788
+ button.style.border = "1px solid rgba(148, 163, 184, 0.28)";
1789
+ button.style.background = "rgba(248, 250, 252, 0.94)";
1790
+ button.style.color = "#475569";
1791
+ button.style.boxShadow = "0 6px 18px rgba(15, 23, 42, 0.1)";
1792
+ button.style.cursor = "pointer";
1793
+ button.style.font = '600 15px/1 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
1794
+ button.style.display = "flex";
1795
+ button.style.alignItems = "center";
1796
+ button.style.justifyContent = "center";
1797
+ return button;
1798
+ }
1799
+ createStatusIcon(status) {
1800
+ const icon = document.createElement("span");
1801
+ icon.setAttribute("aria-hidden", "true");
1802
+ icon.style.display = "inline-flex";
1803
+ icon.style.width = "16px";
1804
+ icon.style.height = "16px";
1805
+ icon.style.alignItems = "center";
1806
+ icon.style.justifyContent = "center";
1807
+ icon.style.flex = "0 0 auto";
1808
+ if (status === "running") {
1809
+ icon.style.border = "2px solid rgba(71, 85, 105, 0.32)";
1810
+ icon.style.borderTopColor = "#64748b";
1811
+ icon.style.borderRadius = "999px";
1812
+ icon.style.animation = "chatkit-pet-summary-spin 900ms linear infinite";
1813
+ return icon;
1814
+ }
1815
+ icon.style.borderRadius = "999px";
1816
+ icon.style.fontSize = "12px";
1817
+ icon.style.fontWeight = "700";
1818
+ if (status === "failed") {
1819
+ icon.textContent = "!";
1820
+ icon.style.background = "#fee2e2";
1821
+ icon.style.color = "#b91c1c";
1822
+ return icon;
1823
+ }
1824
+ icon.textContent = "";
1825
+ icon.style.border = "2px solid #22c55e";
1826
+ icon.style.position = "relative";
1827
+ const check = document.createElement("span");
1828
+ check.style.width = "7px";
1829
+ check.style.height = "4px";
1830
+ check.style.borderLeft = "2px solid #22c55e";
1831
+ check.style.borderBottom = "2px solid #22c55e";
1832
+ check.style.transform = "rotate(-45deg) translate(1px, -1px)";
1833
+ icon.append(check);
1834
+ return icon;
1835
+ }
1836
+ createSummaryActionButton(label, title, onClick) {
1837
+ const button = document.createElement("button");
1838
+ button.type = "button";
1839
+ button.textContent = label;
1840
+ button.title = title;
1841
+ button.addEventListener("click", (event) => {
1842
+ event.preventDefault();
1843
+ event.stopPropagation();
1844
+ onClick();
1845
+ });
1846
+ button.style.width = "26px";
1847
+ button.style.height = "26px";
1848
+ button.style.border = "0";
1849
+ button.style.borderRadius = "999px";
1850
+ button.style.background = "rgba(241, 245, 249, 0.96)";
1851
+ button.style.color = "#475569";
1852
+ button.style.cursor = "pointer";
1853
+ button.style.font = '600 15px/1 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
1854
+ return button;
1855
+ }
1856
+ createTextButton(label, onClick) {
1857
+ const button = document.createElement("button");
1858
+ button.type = "button";
1859
+ button.textContent = label;
1860
+ button.addEventListener("click", (event) => {
1861
+ event.preventDefault();
1862
+ event.stopPropagation();
1863
+ onClick();
1864
+ });
1865
+ button.style.border = "1px solid rgba(148, 163, 184, 0.28)";
1866
+ button.style.borderRadius = "999px";
1867
+ button.style.background = "rgba(248, 250, 252, 0.95)";
1868
+ button.style.color = "#334155";
1869
+ button.style.cursor = "pointer";
1870
+ button.style.padding = "3px 10px";
1871
+ button.style.font = '600 12px/1.4 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
1872
+ return button;
1873
+ }
1874
+ createReplyForm() {
1875
+ const form = document.createElement("form");
1876
+ form.addEventListener("click", stopEventPropagation);
1877
+ form.addEventListener("submit", this.handleReplySubmit);
1878
+ form.addEventListener("keydown", this.handleReplyKeyDown);
1879
+ form.style.display = "flex";
1880
+ form.style.gap = "6px";
1881
+ form.style.alignItems = "center";
1882
+ form.style.marginTop = "8px";
1883
+ const input = document.createElement("input");
1884
+ input.type = "text";
1885
+ input.value = this.replyDraft;
1886
+ input.disabled = this.isReplySubmitting;
1887
+ input.placeholder = this.copy.replyPlaceholder;
1888
+ input.addEventListener("input", this.handleReplyInput);
1889
+ input.style.minWidth = "0";
1890
+ input.style.flex = "1";
1891
+ input.style.border = "1px solid rgba(148, 163, 184, 0.35)";
1892
+ input.style.borderRadius = "999px";
1893
+ input.style.padding = "6px 10px";
1894
+ input.style.font = '400 13px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
1895
+ this.replyInputElement = input;
1896
+ const send = document.createElement("button");
1897
+ send.type = "submit";
1898
+ send.textContent = this.isReplySubmitting ? this.copy.sendingButton : this.copy.sendButton;
1899
+ send.disabled = this.isReplySubmitting;
1900
+ send.style.border = "0";
1901
+ send.style.borderRadius = "999px";
1902
+ send.style.background = "#22c55e";
1903
+ send.style.color = "#052e16";
1904
+ send.style.cursor = this.isReplySubmitting ? "default" : "pointer";
1905
+ send.style.padding = "6px 10px";
1906
+ send.style.font = '700 12px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
1907
+ form.append(input, send);
1908
+ if (this.replyError) {
1909
+ const error = document.createElement("div");
1910
+ error.textContent = this.copy.sendFailed;
1911
+ error.style.flexBasis = "100%";
1912
+ error.style.color = "#b91c1c";
1913
+ error.style.fontSize = "12px";
1914
+ form.style.flexWrap = "wrap";
1915
+ form.append(error);
1916
+ }
1917
+ return form;
1918
+ }
1919
+ renderAtlas(animationName, animationMode) {
1920
+ var _a2;
1921
+ if (!this.petElement || ((_a2 = this.resolved) == null ? void 0 : _a2.kind) !== "atlas" || !this.options) {
1922
+ return;
1923
+ }
1924
+ if (!(this.mediaElement instanceof HTMLDivElement)) {
1925
+ const frame = document.createElement("div");
1926
+ frame.setAttribute("aria-hidden", "true");
1927
+ this.petElement.replaceChildren(frame);
1928
+ this.mediaElement = frame;
1929
+ }
1930
+ const frameElement = this.mediaElement;
1931
+ const atlas = this.resolved.atlas;
1932
+ const definition = atlas.animations[animationName] ?? atlas.animations.idle;
1933
+ const safeFrame = animationMode === "once" && this.completed ? Math.max(0, definition.frames - 1) : Math.min(this.frame, Math.max(0, definition.frames - 1));
1934
+ const scale = getRenderScale(this.options.position.scale);
1935
+ const sourceWidth = atlas.cellWidth;
1936
+ const sourceHeight = atlas.cellHeight;
1937
+ const backgroundWidth = atlas.columns * sourceWidth;
1938
+ const backgroundHeight = atlas.rows * sourceHeight;
1939
+ frameElement.style.width = `${sourceWidth}px`;
1940
+ frameElement.style.height = `${sourceHeight}px`;
1941
+ frameElement.style.overflow = "hidden";
1942
+ frameElement.style.transform = `scale(${scale})`;
1943
+ frameElement.style.transformOrigin = "top left";
1944
+ frameElement.style.pointerEvents = "none";
1945
+ frameElement.style.backgroundImage = `url("${escapeCssUrl(
1946
+ this.resolved.src
1947
+ )}")`;
1948
+ frameElement.style.backgroundRepeat = "no-repeat";
1949
+ frameElement.style.backgroundSize = `${backgroundWidth}px ${backgroundHeight}px`;
1950
+ frameElement.style.backgroundPosition = `${-safeFrame * sourceWidth}px ${-definition.row * sourceHeight}px`;
1951
+ frameElement.style.imageRendering = this.options.imageRendering;
1952
+ frameElement.dataset.petFrame = String(safeFrame);
1953
+ }
1954
+ scheduleNextFrame(animationName, animationMode) {
1955
+ if (this.prefersReducedMotion || this.completed || !this.resolved) {
1956
+ this.clearTimers();
1957
+ return;
1958
+ }
1959
+ if (this.frameTimer !== null) {
1960
+ return;
1961
+ }
1962
+ const atlas = this.resolved.atlas;
1963
+ const definition = atlas.animations[animationName] ?? atlas.animations.idle;
1964
+ const duration = definition.frameDurations[this.frame] ?? definition.frameDurations[definition.frameDurations.length - 1] ?? 150;
1965
+ const baseDuration = duration * PET_FRAME_DURATION_MULTIPLIER;
1966
+ const effectiveDuration = this.isHovering || this.isDragging ? baseDuration : baseDuration * PET_RESTING_FRAME_DURATION_MULTIPLIER;
1967
+ this.frameTimer = window.setTimeout(() => {
1968
+ this.frameTimer = null;
1969
+ const nextFrame = this.frame + 1;
1970
+ if (nextFrame >= definition.frames) {
1971
+ if (animationMode === "once") {
1972
+ this.completed = true;
1973
+ this.frame = Math.max(0, definition.frames - 1);
1974
+ this.finishTransient();
1975
+ return;
1976
+ }
1977
+ this.frame = 0;
1978
+ this.render();
1979
+ return;
1980
+ }
1981
+ this.frame = nextFrame;
1982
+ this.render();
1983
+ }, effectiveDuration);
1984
+ }
1985
+ clearTimers() {
1986
+ if (this.frameTimer !== null) {
1987
+ window.clearTimeout(this.frameTimer);
1988
+ this.frameTimer = null;
1989
+ }
1990
+ }
1991
+ clearRestingDelayTimer() {
1992
+ if (this.restingDelayTimer !== null) {
1993
+ window.clearTimeout(this.restingDelayTimer);
1994
+ this.restingDelayTimer = null;
1995
+ }
1996
+ }
1997
+ finishTransient() {
1998
+ this.transient = null;
1999
+ this.activeAnimationName = null;
2000
+ this.activeAnimationMode = null;
2001
+ this.render();
2002
+ }
2003
+ rescheduleAnimation() {
2004
+ this.clearTimers();
2005
+ this.render();
2006
+ }
2007
+ enterRestingAfterDelay() {
2008
+ this.clearRestingDelayTimer();
2009
+ this.isHovering = true;
2010
+ this.restingDelayTimer = window.setTimeout(() => {
2011
+ this.restingDelayTimer = null;
2012
+ if (this.isDragging) {
2013
+ return;
2014
+ }
2015
+ this.isHovering = false;
2016
+ this.rescheduleAnimation();
2017
+ }, PET_RESTING_DELAY_MS);
2018
+ }
2019
+ isPointerOverPet(event) {
2020
+ var _a2;
2021
+ const rect = (_a2 = this.petElement) == null ? void 0 : _a2.getBoundingClientRect();
2022
+ if (!rect) {
2023
+ return false;
2024
+ }
2025
+ return event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
2026
+ }
2027
+ async submitReply() {
2028
+ var _a2;
2029
+ const text = this.replyDraft.trim();
2030
+ if (!text || this.isReplySubmitting) {
2031
+ return;
2032
+ }
2033
+ this.isReplySubmitting = true;
2034
+ this.replyError = null;
2035
+ this.render();
2036
+ try {
2037
+ await ((_a2 = this.onReply) == null ? void 0 : _a2.call(this, text));
2038
+ this.replyDraft = "";
2039
+ this.isReplyOpen = false;
2040
+ this.isSummaryHovering = false;
2041
+ } catch {
2042
+ this.replyError = "Failed to send";
2043
+ } finally {
2044
+ this.isReplySubmitting = false;
2045
+ this.render();
2046
+ }
2047
+ }
2048
+ getNextDragPosition(event) {
2049
+ if (!this.options) {
2050
+ return { x: 0, y: 0 };
2051
+ }
2052
+ return chatkitTypes.clampPetPosition(
2053
+ {
2054
+ x: event.clientX - this.dragOffset.x,
2055
+ y: event.clientY - this.dragOffset.y
2056
+ },
2057
+ this.getSize(),
2058
+ getViewportSize(),
2059
+ chatkitTypes.normalizeBoundsPadding(this.options.position.boundsPadding)
2060
+ );
2061
+ }
2062
+ installDragListeners() {
2063
+ window.addEventListener("pointermove", this.handlePointerMove);
2064
+ window.addEventListener("pointerup", this.handlePointerUp, { once: true });
2065
+ window.addEventListener("pointercancel", this.handlePointerUp, {
2066
+ once: true
2067
+ });
2068
+ }
2069
+ removeDragListeners() {
2070
+ window.removeEventListener("pointermove", this.handlePointerMove);
2071
+ window.removeEventListener("pointerup", this.handlePointerUp);
2072
+ window.removeEventListener("pointercancel", this.handlePointerUp);
2073
+ }
2074
+ }
2075
+ function getInnerOptions(options) {
2076
+ return removeMethods(options);
2077
+ }
2078
+ function requireCommandCapability(value, context) {
2079
+ const command = String(context.name);
2080
+ return function(...args) {
2081
+ if (!this.capabilities.commands.has(command)) {
2082
+ throw new IntegrationError(
2083
+ `ChatKit command "${String(command)}" is not available for the "${this.profile}" profile.`
2084
+ );
2085
+ }
2086
+ return value.apply(this, args);
2087
+ };
2088
+ }
2089
+ class ChatKitElementBase extends (_c = HTMLElement, _focusComposer_dec = [requireCommandCapability], _fetchUpdates_dec = [requireCommandCapability], _sendUserMessage_dec = [requireCommandCapability], _setComposerValue_dec = [requireCommandCapability], _setThreadId_dec = [requireCommandCapability], _shareThread_dec = [requireCommandCapability], _sendCustomAction_dec = [requireCommandCapability], _showHistory_dec = [requireCommandCapability], _hideHistory_dec = [requireCommandCapability], _setTrainingOptOut_dec = [requireCommandCapability], _c) {
2090
+ constructor({ profile }) {
2091
+ super();
2092
+ __runInitializers(_init, 5, this);
2093
+ __privateAdd(this, _ChatKitElementBase_instances);
2094
+ __privateAdd(this, _opts);
2095
+ __privateAdd(this, _frameUrl);
2096
+ __privateAdd(this, _frame);
2097
+ __privateAdd(this, _wrapper);
2098
+ __privateAdd(this, _launcherCloseButton);
2099
+ __privateAdd(this, _launcherOpen, false);
2100
+ __privateAdd(this, _framePetOptionsOverride);
2101
+ __privateAdd(this, _shadow, this.attachShadow({ mode: "open" }));
2102
+ __privateAdd(this, _petOverlay, new PetOverlay(__privateGet(this, _shadow), {
2103
+ onActivate: () => __privateMethod(this, _ChatKitElementBase_instances, handlePetActivate_fn).call(this),
2104
+ onReply: (text) => __privateMethod(this, _ChatKitElementBase_instances, handlePetReply_fn).call(this, text),
2105
+ onThreadSummaryActivate: (threadId) => void __privateMethod(this, _ChatKitElementBase_instances, handlePetThreadSummaryActivate_fn).call(this, threadId)
2106
+ }));
2107
+ __privateAdd(this, _resolveLoaded);
2108
+ __privateAdd(this, _loaded, new Promise((resolve) => {
2109
+ __privateSet(this, _resolveLoaded, resolve);
2110
+ }));
2111
+ __privateAdd(this, _messenger, new ChatFrameMessenger({
2112
+ fetch: (...args) => {
2113
+ var _a2;
2114
+ const customFetch = ((_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.api) && "fetch" in __privateGet(this, _opts).api && __privateGet(this, _opts).api.fetch;
2115
+ return customFetch ? customFetch(...args) : fetch(...args);
2116
+ },
2117
+ target: () => {
2118
+ var _a2;
2119
+ return ((_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.contentWindow) ?? null;
2120
+ },
2121
+ targetOrigin: window.location.origin,
2122
+ handlers: {
2123
+ onFileInputClick: ({
2124
+ inputAttributes
2125
+ }) => {
2126
+ return new Promise((resolve) => {
2127
+ const input = document.createElement("input");
2128
+ for (const [key, value] of Object.entries(inputAttributes)) {
2129
+ input.setAttribute(key, String(value));
2130
+ }
2131
+ const respond = () => {
2132
+ resolve(Array.from(input.files || []));
2133
+ if (__privateGet(this, _shadow).contains(input)) {
2134
+ __privateGet(this, _shadow).removeChild(input);
2135
+ }
2136
+ };
2137
+ input.addEventListener("cancel", respond);
2138
+ input.addEventListener("change", respond);
2139
+ __privateGet(this, _shadow).appendChild(input);
2140
+ input.click();
2141
+ });
2142
+ },
2143
+ onClientToolCall: async ({
2144
+ name,
2145
+ params,
2146
+ id,
2147
+ tool_call_id
2148
+ }) => {
2149
+ var _a2;
2150
+ const onClientTool = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.onClientTool;
2151
+ if (!onClientTool) {
2152
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError(
2153
+ `No handler for client tool calls. You'll need to add onClientTool to your ChatKit options.`
2154
+ ));
2155
+ }
2156
+ return onClientTool({ name, params, id, tool_call_id });
2157
+ },
2158
+ onWidgetAction: async ({
2159
+ action,
2160
+ widgetItem
2161
+ }) => {
2162
+ var _a2, _b2;
2163
+ const onAction = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.widgets) == null ? void 0 : _b2.onAction;
2164
+ if (!onAction) {
2165
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError(
2166
+ `No handler for widget actions. You'll need to add widgets.onAction to your ChatKit options.`
2167
+ ));
2168
+ }
2169
+ return onAction(action, widgetItem);
2170
+ },
2171
+ onEntitySearch: async ({ query }) => {
2172
+ var _a2, _b2, _c2;
2173
+ return ((_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onTagSearch) == null ? void 0 : _c2.call(_b2, query)) ?? [];
2174
+ },
2175
+ onEntityClick: async ({ entity }) => {
2176
+ var _a2, _b2, _c2;
2177
+ return (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onClick) == null ? void 0 : _c2.call(_b2, entity);
2178
+ },
2179
+ onEntityPreview: async ({ entity }) => {
2180
+ var _a2, _b2, _c2;
2181
+ return ((_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onRequestPreview) == null ? void 0 : _c2.call(_b2, entity)) ?? { preview: null };
2182
+ },
2183
+ onGetClientSecret: async (currentClientSecret) => {
2184
+ if (!__privateGet(this, _opts) || !("getClientSecret" in __privateGet(this, _opts).api) || !__privateGet(this, _opts).api.getClientSecret) {
2185
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError(
2186
+ "Could not refresh the session because ChatKitOptions.api.getClientSecret is not configured."
2187
+ ));
2188
+ }
2189
+ return __privateGet(this, _opts).api.getClientSecret(currentClientSecret ?? null);
2190
+ },
2191
+ onAddMetadataToRequest: ({
2192
+ op,
2193
+ params
2194
+ }) => {
2195
+ throw new IntegrationError(
2196
+ "ChatKit: onAddMetadataToRequest is unimplemented."
2197
+ );
2198
+ }
2199
+ }
2200
+ }));
2201
+ __privateAdd(this, _handleLauncherClose, () => {
2202
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2203
+ });
2204
+ __privateAdd(this, _handleFrameLoad, () => {
2205
+ var _a2;
2206
+ this.dataset.loaded = "true";
2207
+ this.dispatchEvent(
2208
+ new CustomEvent("chatkit.ready", { bubbles: true, composed: true })
2209
+ );
2210
+ (_a2 = __privateGet(this, _resolveLoaded)) == null ? void 0 : _a2.call(this);
2211
+ });
2212
+ __privateAdd(this, _initialized, false);
2213
+ this.profile = profile;
2214
+ this.capabilities = getCapabilities(profile);
2215
+ }
2216
+ setProfile(profile) {
2217
+ this.profile = profile;
2218
+ this.capabilities = getCapabilities(profile);
2219
+ }
2220
+ connectedCallback() {
2221
+ __privateGet(this, _petOverlay).connect();
2222
+ const style = document.createElement("style");
2223
+ style.textContent = `
2224
+ :host {
2225
+ display: block;
2226
+ position: relative;
2227
+ height: 100%;
2228
+ width: 100%;
2229
+ overflow: visible;
2230
+ }
2231
+ :host([data-display-mode="pet"]) {
2232
+ display: contents;
2233
+ }
2234
+ .ck-iframe {
2235
+ border: none;
2236
+ position: absolute;
2237
+ inset: 0;
2238
+ width: 100%;
2239
+ height: 100%;
2240
+ overflow: hidden;
2241
+ color-scheme: light only;
2242
+ }
2243
+ .ck-wrapper {
2244
+ position: absolute;
2245
+ inset: 0;
2246
+ width: 100%;
2247
+ height: 100%;
2248
+ overflow: hidden;
2249
+ opacity: 0;
2250
+ }
2251
+ .ck-launcher-close {
2252
+ display: none;
2253
+ }
2254
+ :host([data-display-mode="pet"]) .ck-wrapper {
2255
+ position: fixed;
2256
+ inset: auto 16px 16px auto;
2257
+ width: min(420px, calc(100vw - 32px));
2258
+ height: min(720px, calc(100vh - 32px));
2259
+ max-height: calc(100vh - 32px);
2260
+ overflow: visible;
2261
+ border: 1px solid rgba(148, 163, 184, 0.35);
2262
+ border-radius: 18px;
2263
+ background: Canvas;
2264
+ box-shadow:
2265
+ 0 24px 80px rgba(15, 23, 42, 0.22),
2266
+ 0 0 0 1px rgba(15, 23, 42, 0.04);
2267
+ opacity: 0;
2268
+ pointer-events: none;
2269
+ transform: translateY(12px) scale(0.98);
2270
+ transition:
2271
+ opacity 160ms ease,
2272
+ transform 160ms ease;
2273
+ z-index: 39;
2274
+ }
2275
+ :host([data-display-mode="pet"][data-chat-open="true"]) .ck-wrapper {
2276
+ opacity: 1;
2277
+ pointer-events: auto;
2278
+ transform: translateY(0) scale(1);
2279
+ }
2280
+ :host([data-display-mode="pet"]) .ck-iframe {
2281
+ border-radius: inherit;
2282
+ }
2283
+ :host([data-display-mode="pet"]) .ck-launcher-close {
2284
+ display: inline-flex;
2285
+ position: absolute;
2286
+ top: -10px;
2287
+ right: -10px;
2288
+ z-index: 2;
2289
+ width: 28px;
2290
+ height: 28px;
2291
+ align-items: center;
2292
+ justify-content: center;
2293
+ border: 1px solid rgba(148, 163, 184, 0.45);
2294
+ border-radius: 999px;
2295
+ background: rgba(255, 255, 255, 0.96);
2296
+ color: #475569;
2297
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18);
2298
+ cursor: pointer;
2299
+ font: inherit;
2300
+ font-size: 0;
2301
+ line-height: 1;
2302
+ }
2303
+ :host([data-display-mode="pet"]) .ck-launcher-close::before,
2304
+ :host([data-display-mode="pet"]) .ck-launcher-close::after {
2305
+ content: '';
2306
+ position: absolute;
2307
+ top: 50%;
2308
+ left: 50%;
2309
+ width: 14px;
2310
+ height: 2px;
2311
+ border-radius: 999px;
2312
+ background: currentColor;
2313
+ transform: translate(-50%, -50%) rotate(45deg);
2314
+ }
2315
+ :host([data-display-mode="pet"]) .ck-launcher-close::after {
2316
+ transform: translate(-50%, -50%) rotate(-45deg);
2317
+ }
2318
+ :host([data-display-mode="pet"]) .ck-launcher-close:hover {
2319
+ background: #fff;
2320
+ color: #0f172a;
2321
+ }
2322
+ :host([data-color-scheme="dark"]) .ck-iframe {
2323
+ color-scheme: dark only;
2324
+ }
2325
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-wrapper {
2326
+ border-color: rgba(148, 163, 184, 0.28);
2327
+ background: #020617;
2328
+ box-shadow:
2329
+ 0 24px 80px rgba(0, 0, 0, 0.5),
2330
+ 0 0 0 1px rgba(255, 255, 255, 0.06);
2331
+ }
2332
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-launcher-close {
2333
+ background: rgba(15, 23, 42, 0.88);
2334
+ border-color: rgba(148, 163, 184, 0.32);
2335
+ color: #cbd5e1;
2336
+ }
2337
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-launcher-close:hover {
2338
+ background: #1e293b;
2339
+ color: #f8fafc;
2340
+ }
2341
+ :host([data-loaded="true"]) .ck-wrapper {
2342
+ opacity: 1;
2343
+ }
2344
+ :host([data-display-mode="pet"]:not([data-chat-open="true"])) .ck-wrapper {
2345
+ opacity: 0;
2346
+ }
2347
+ @media (max-width: 520px) {
2348
+ :host([data-display-mode="pet"]) .ck-wrapper {
2349
+ inset: auto 8px 8px 8px;
2350
+ width: auto;
2351
+ height: min(680px, calc(100vh - 16px));
2352
+ max-height: calc(100vh - 16px);
2353
+ border-radius: 16px;
2354
+ }
2355
+ :host([data-display-mode="pet"]) .ck-launcher-close {
2356
+ top: -8px;
2357
+ right: 8px;
2358
+ }
2359
+ }
2360
+ `;
2361
+ const frame = document.createElement("iframe");
2362
+ frame.className = "ck-iframe";
2363
+ frame.name = "chatkit";
2364
+ frame.role = "presentation";
2365
+ frame.tabIndex = 0;
2366
+ frame.setAttribute("allowtransparency", "true");
2367
+ frame.setAttribute("frameborder", "0");
2368
+ frame.setAttribute("scrolling", "no");
2369
+ frame.setAttribute("allow", "clipboard-read; clipboard-write");
2370
+ __privateSet(this, _frame, frame);
2371
+ const wrapper = document.createElement("div");
2372
+ wrapper.className = "ck-wrapper";
2373
+ wrapper.appendChild(frame);
2374
+ __privateSet(this, _wrapper, wrapper);
2375
+ const closeButton = document.createElement("button");
2376
+ closeButton.className = "ck-launcher-close";
2377
+ closeButton.type = "button";
2378
+ closeButton.setAttribute("aria-label", "Close chat");
2379
+ closeButton.addEventListener("click", __privateGet(this, _handleLauncherClose));
2380
+ wrapper.appendChild(closeButton);
2381
+ __privateSet(this, _launcherCloseButton, closeButton);
2382
+ __privateGet(this, _shadow).append(style);
2383
+ __privateGet(this, _messenger).on("left_header_icon_click", () => {
2384
+ var _a2, _b2, _c2;
2385
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.leftAction) == null ? void 0 : _c2.onClick();
2386
+ });
2387
+ __privateGet(this, _messenger).on("right_header_icon_click", () => {
2388
+ var _a2, _b2, _c2;
2389
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.rightAction) == null ? void 0 : _c2.onClick();
2390
+ });
2391
+ __privateGet(this, _messenger).on("public_event", ([event, data]) => {
2392
+ if (event === "log") {
2393
+ const payload = parseThreadSummaryLogPayload(data);
2394
+ if (payload) {
2395
+ __privateGet(this, _petOverlay).setThreadSummary(payload.summary);
2396
+ }
2397
+ } else if (event === "response.start") {
2398
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("running");
2399
+ } else if (event === "response.end") {
2400
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("completed");
2401
+ } else if (event === "response.stop") {
2402
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("completed");
2403
+ }
2404
+ if (!this.capabilities.events.has(event)) return;
2405
+ if (event === "error" && "error" in data) {
2406
+ const error = fromPossibleFrameSafeError(data.error);
2407
+ this.dispatchEvent(
2408
+ new CustomEvent("chatkit.error", { detail: { error } })
2409
+ );
2410
+ if (error instanceof IntegrationError) {
2411
+ throw error;
2412
+ }
2413
+ return;
2414
+ }
2415
+ this.dispatchEvent(new CustomEvent(`chatkit.${event}`, { detail: data }));
2416
+ });
2417
+ __privateGet(this, _messenger).on("pet_state_change", (data) => {
2418
+ const payload = parsePetStateChangePayload(data);
2419
+ if (payload) {
2420
+ __privateGet(this, _petOverlay).setState(payload.state);
2421
+ }
2422
+ });
2423
+ __privateGet(this, _messenger).on("pet_options_change", (data) => {
2424
+ const payload = parsePetOptionsChangePayload(data);
2425
+ if (payload) {
2426
+ __privateSet(this, _framePetOptionsOverride, payload.pet);
2427
+ __privateGet(this, _petOverlay).setOptions(__privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this));
2428
+ }
2429
+ });
2430
+ __privateGet(this, _messenger).on("unmount", () => {
2431
+ if (__privateGet(this, _wrapper) && __privateGet(this, _shadow).contains(__privateGet(this, _wrapper))) {
2432
+ __privateGet(this, _shadow).removeChild(__privateGet(this, _wrapper));
2433
+ __privateSet(this, _wrapper, void 0);
2434
+ __privateSet(this, _frame, void 0);
2435
+ }
2436
+ });
2437
+ __privateGet(this, _messenger).on(
2438
+ "capabilities_profile_change",
2439
+ ({ profile }) => {
2440
+ this.setProfile(profile);
2441
+ }
2442
+ );
2443
+ frame.addEventListener("load", __privateGet(this, _handleFrameLoad), { once: true });
2444
+ try {
2445
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
2446
+ } catch (error) {
2447
+ console.error(error);
2448
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError("Failed to initialize ChatKit"));
2449
+ }
2450
+ }
2451
+ disconnectedCallback() {
2452
+ var _a2, _b2;
2453
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.removeEventListener("load", __privateGet(this, _handleFrameLoad));
2454
+ (_b2 = __privateGet(this, _launcherCloseButton)) == null ? void 0 : _b2.removeEventListener(
2455
+ "click",
2456
+ __privateGet(this, _handleLauncherClose)
2457
+ );
2458
+ __privateGet(this, _messenger).disconnect();
2459
+ __privateGet(this, _petOverlay).destroy();
2460
+ }
2461
+ applySanitizedOptions(newOptions) {
2462
+ __privateSet(this, _opts, newOptions);
2463
+ __privateGet(this, _petOverlay).setLocale(newOptions.locale);
2464
+ __privateGet(this, _petOverlay).setOptions(__privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this));
2465
+ if (__privateGet(this, _initialized)) {
2466
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
2467
+ __privateGet(this, _loaded).then(() => {
2468
+ __privateGet(this, _messenger).commands.setOptions(
2469
+ getInnerOptions(__privateMethod(this, _ChatKitElementBase_instances, getFrameOptions_fn).call(this, newOptions))
2470
+ );
2471
+ });
2472
+ } else {
2473
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
2474
+ }
2475
+ }
2476
+ setOptions(newOptions) {
2477
+ try {
2478
+ const sanitized = this.sanitizeOptions(newOptions);
2479
+ __privateMethod(this, _ChatKitElementBase_instances, consumeFrameUrl_fn).call(this, sanitized);
2480
+ this.applySanitizedOptions(sanitized);
2481
+ } catch (error) {
2482
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError("Failed to parse options"));
2483
+ }
2484
+ }
2485
+ async focusComposer() {
2486
+ var _a2, _b2;
2487
+ await __privateGet(this, _loaded);
2488
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.focus();
2489
+ await ((_b2 = __privateGet(this, _messenger)) == null ? void 0 : _b2.commands.focusComposer());
2490
+ }
2491
+ async fetchUpdates() {
2492
+ var _a2;
2493
+ await __privateGet(this, _loaded);
2494
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.fetchUpdates());
2495
+ }
2496
+ async sendUserMessage(params) {
2497
+ var _a2;
2498
+ await __privateGet(this, _loaded);
2499
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendUserMessage(params));
2500
+ }
2501
+ async setComposerValue(params) {
2502
+ var _a2;
2503
+ await __privateGet(this, _loaded);
2504
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setComposerValue(params));
2505
+ }
2506
+ async setThreadId(threadId) {
2507
+ var _a2;
2508
+ await __privateGet(this, _loaded);
2509
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setThreadId({ threadId }));
2510
+ }
2511
+ async shareThread() {
2512
+ var _a2;
2513
+ await __privateGet(this, _loaded);
2514
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.shareThread();
2515
+ }
2516
+ async sendCustomAction(action, itemId) {
2517
+ var _a2;
2518
+ await __privateGet(this, _loaded);
2519
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendCustomAction({ action, itemId });
2520
+ }
2521
+ async showHistory() {
2522
+ var _a2;
2523
+ await __privateGet(this, _loaded);
2524
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.showHistory();
2525
+ }
2526
+ async hideHistory() {
2527
+ var _a2;
2528
+ await __privateGet(this, _loaded);
2529
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.hideHistory();
2530
+ }
2531
+ async setTrainingOptOut(value) {
2532
+ var _a2;
2533
+ await __privateGet(this, _loaded);
2534
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setTrainingOptOut({ value });
2535
+ }
2536
+ }
2537
+ _init = __decoratorStart(_c);
2538
+ _opts = new WeakMap();
2539
+ _frameUrl = new WeakMap();
2540
+ _frame = new WeakMap();
2541
+ _wrapper = new WeakMap();
2542
+ _launcherCloseButton = new WeakMap();
2543
+ _launcherOpen = new WeakMap();
2544
+ _framePetOptionsOverride = new WeakMap();
2545
+ _shadow = new WeakMap();
2546
+ _petOverlay = new WeakMap();
2547
+ _resolveLoaded = new WeakMap();
2548
+ _loaded = new WeakMap();
2549
+ _messenger = new WeakMap();
2550
+ _ChatKitElementBase_instances = new WeakSet();
2551
+ emitAndThrow_fn = function(error) {
2552
+ this.dispatchEvent(new CustomEvent("chatkit.error", { detail: { error } }));
2553
+ throw error;
2554
+ };
2555
+ setOptionsDataAttributes_fn = function(options) {
2556
+ var _a2;
2557
+ this.dataset.colorScheme = typeof options.theme === "string" ? options.theme : ((_a2 = options.theme) == null ? void 0 : _a2.colorScheme) ?? "light";
2558
+ this.dataset.displayMode = __privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options);
2559
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options) !== "pet") {
2560
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2561
+ }
2562
+ };
2563
+ getDisplayMode_fn = function(options = __privateGet(this, _opts)) {
2564
+ return (options == null ? void 0 : options.displayMode) === "pet" ? "pet" : "chat";
2565
+ };
2566
+ getConfiguredPetOptions_fn = function(options = __privateGet(this, _opts)) {
2567
+ if (!options) {
2568
+ return null;
2569
+ }
2570
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options) === "pet" && !chatkitTypes.normalizePetOptions(options.pet ?? null)) {
2571
+ return true;
2572
+ }
2573
+ return options.pet ?? null;
2574
+ };
2575
+ getOverlayPetOptions_fn = function() {
2576
+ let pet = __privateGet(this, _framePetOptionsOverride) !== void 0 ? __privateGet(this, _framePetOptionsOverride) : __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this);
2577
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet" && !chatkitTypes.normalizePetOptions(pet ?? null)) {
2578
+ pet = true;
2579
+ }
2580
+ return __privateMethod(this, _ChatKitElementBase_instances, resolveOverlayPetOptions_fn).call(this, pet);
2581
+ };
2582
+ resolvePetAssetUrl_fn = function(src) {
2583
+ try {
2584
+ const base = new URL(
2585
+ __privateGet(this, _frameUrl) ?? window.location.href,
2586
+ window.location.origin
2587
+ );
2588
+ return new URL(src, base).toString();
2589
+ } catch {
2590
+ return src;
2591
+ }
2592
+ };
2593
+ resolveOverlayPetOptions_fn = function(pet) {
2594
+ const normalized = chatkitTypes.normalizePetOptions(pet ?? null);
2595
+ if (!normalized) {
2596
+ return null;
2597
+ }
2598
+ return {
2599
+ character: {
2600
+ ...normalized.character,
2601
+ src: __privateMethod(this, _ChatKitElementBase_instances, resolvePetAssetUrl_fn).call(this, normalized.character.src)
2602
+ },
2603
+ position: normalized.position,
2604
+ behavior: normalized.behavior,
2605
+ ariaLabel: normalized.ariaLabel,
2606
+ imageRendering: normalized.imageRendering
2607
+ };
2608
+ };
2609
+ getFrameOptions_fn = function(options) {
2610
+ const pet = __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this, options);
2611
+ if (pet === (options.pet ?? null)) {
2612
+ return options;
2613
+ }
2614
+ const nextOptions = { ...options };
2615
+ if (pet === null) {
2616
+ delete nextOptions.pet;
2617
+ } else {
2618
+ nextOptions.pet = pet;
2619
+ }
2620
+ return nextOptions;
2621
+ };
2622
+ setLauncherOpen_fn = function(open) {
2623
+ __privateSet(this, _launcherOpen, open);
2624
+ if (open) {
2625
+ this.dataset.chatOpen = "true";
2626
+ } else {
2627
+ delete this.dataset.chatOpen;
2628
+ }
2629
+ };
2630
+ handlePetActivate_fn = function() {
2631
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) !== "pet") {
2632
+ return;
2633
+ }
2634
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2635
+ __privateGet(this, _loaded).then(() => this.focusComposer()).catch(() => void 0);
2636
+ };
2637
+ handlePetReply_fn = async function(text) {
2638
+ await this.sendUserMessage({ text });
2639
+ };
2640
+ handlePetThreadSummaryActivate_fn = async function(threadId) {
2641
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet") {
2642
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2643
+ }
2644
+ await this.setThreadId(threadId);
2645
+ await this.focusComposer();
2646
+ };
2647
+ _handleLauncherClose = new WeakMap();
2648
+ getFrameUrl_fn = function() {
2649
+ if (!__privateGet(this, _frameUrl)) {
2650
+ throw new IntegrationError(
2651
+ "ChatKit frameUrl is not configured. Provide it via setOptions({ frameUrl }) before mounting."
2652
+ );
2653
+ }
2654
+ return __privateGet(this, _frameUrl);
2655
+ };
2656
+ setFrameUrl_fn = function(frameUrl) {
2657
+ if (__privateGet(this, _initialized) && __privateGet(this, _frameUrl) && __privateGet(this, _frameUrl) !== frameUrl) {
2658
+ throw new IntegrationError(
2659
+ "ChatKit frameUrl cannot be changed after initialization. Create a new element to use a different URL."
2660
+ );
2661
+ }
2662
+ __privateSet(this, _frameUrl, frameUrl);
2663
+ };
2664
+ consumeFrameUrl_fn = function(options) {
2665
+ if (!("frameUrl" in options)) return;
2666
+ const frameUrl = options.frameUrl;
2667
+ delete options.frameUrl;
2668
+ if (frameUrl == null) return;
2669
+ if (typeof frameUrl !== "string" || frameUrl.trim() === "") {
2670
+ throw new IntegrationError(
2671
+ "ChatKit frameUrl must be a non-empty string."
2672
+ );
2673
+ }
2674
+ __privateMethod(this, _ChatKitElementBase_instances, setFrameUrl_fn).call(this, frameUrl);
2675
+ };
2676
+ _handleFrameLoad = new WeakMap();
2677
+ _initialized = new WeakMap();
2678
+ maybeInit_fn = function() {
2679
+ if (__privateGet(this, _initialized) || !__privateGet(this, _frame) || !__privateGet(this, _opts)) {
2680
+ return;
2681
+ }
2682
+ __privateSet(this, _initialized, true);
2683
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
2684
+ const frameURL = new URL(__privateMethod(this, _ChatKitElementBase_instances, getFrameUrl_fn).call(this), window.location.origin);
2685
+ __privateGet(this, _messenger).setTargetOrigin(frameURL.origin);
2686
+ frameURL.hash = encodeBase64({
2687
+ options: getInnerOptions(__privateMethod(this, _ChatKitElementBase_instances, getFrameOptions_fn).call(this, __privateGet(this, _opts))),
2688
+ referrer: window.location.origin,
2689
+ profile: this.profile
2690
+ });
2691
+ __privateGet(this, _messenger).connect();
2692
+ __privateGet(this, _frame).src = frameURL.toString();
2693
+ if (__privateGet(this, _wrapper)) {
2694
+ __privateGet(this, _shadow).append(__privateGet(this, _wrapper));
2695
+ }
2696
+ };
2697
+ __decorateElement(_init, 1, "focusComposer", _focusComposer_dec, ChatKitElementBase);
2698
+ __decorateElement(_init, 1, "fetchUpdates", _fetchUpdates_dec, ChatKitElementBase);
2699
+ __decorateElement(_init, 1, "sendUserMessage", _sendUserMessage_dec, ChatKitElementBase);
2700
+ __decorateElement(_init, 1, "setComposerValue", _setComposerValue_dec, ChatKitElementBase);
2701
+ __decorateElement(_init, 1, "setThreadId", _setThreadId_dec, ChatKitElementBase);
2702
+ __decorateElement(_init, 1, "shareThread", _shareThread_dec, ChatKitElementBase);
2703
+ __decorateElement(_init, 1, "sendCustomAction", _sendCustomAction_dec, ChatKitElementBase);
2704
+ __decorateElement(_init, 1, "showHistory", _showHistory_dec, ChatKitElementBase);
2705
+ __decorateElement(_init, 1, "hideHistory", _hideHistory_dec, ChatKitElementBase);
2706
+ __decorateElement(_init, 1, "setTrainingOptOut", _setTrainingOptOut_dec, ChatKitElementBase);
2707
+ __decoratorMetadata(_init, ChatKitElementBase);
2708
+ class ChatKitElement extends ChatKitElementBase {
2709
+ constructor() {
2710
+ super({ profile: "chatkit" });
2711
+ }
2712
+ sanitizeOptions(options) {
2713
+ var _a2;
2714
+ (_a2 = options.threadItemActions) == null ? true : delete _a2.share;
2715
+ return options;
2716
+ }
2717
+ }
2718
+ function registerChatKitElement(tag = "xpertai-chatkit") {
2719
+ if (!("customElements" in globalThis)) return;
2720
+ if (!customElements.get(tag)) {
2721
+ customElements.define(tag, ChatKitElement);
2722
+ }
2723
+ }
2724
+ registerChatKitElement();
5
2725
  const EXCLUDED_HANDLER_KEYS = /* @__PURE__ */ new Set(["onClientTool"]);
6
2726
  const EVENT_HANDLER_MAP = {
7
2727
  "chatkit.error": "onError",
@@ -66,8 +2786,8 @@
66
2786
  };
67
2787
  }
68
2788
  function getControlBase() {
69
- var _a, _b;
70
- if ((_b = (_a = sap == null ? void 0 : sap.ui) == null ? void 0 : _a.core) == null ? void 0 : _b.Control) {
2789
+ var _a2, _b2;
2790
+ if ((_b2 = (_a2 = sap == null ? void 0 : sap.ui) == null ? void 0 : _a2.core) == null ? void 0 : _b2.Control) {
71
2791
  return sap.ui.core.Control;
72
2792
  }
73
2793
  throw new Error("sap.ui.core.Control is required for @xpert-ai/chatkit-ui5");
@@ -163,10 +2883,10 @@
163
2883
  el.addEventListener(
164
2884
  eventName,
165
2885
  (e) => {
166
- var _a;
2886
+ var _a2;
167
2887
  const detail = e.detail;
168
2888
  const handlerName = EVENT_HANDLER_MAP[eventName];
169
- const handler = (_a = this._handlers) == null ? void 0 : _a[handlerName];
2889
+ const handler = (_a2 = this._handlers) == null ? void 0 : _a2[handlerName];
170
2890
  if (typeof handler === "function") {
171
2891
  handler(detail);
172
2892
  }