@xpert-ai/chatkit-ui5 0.1.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,3073 @@
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, _chatMinimizedToPet, _framePetOptionsOverride, _petClosedByContextMenu, _shadow, _petOverlay, _resolveLoaded, _loaded, _messenger, _ChatKitElementBase_instances, emitAndThrow_fn, setOptionsDataAttributes_fn, getDisplayMode_fn, getConfiguredPetOptions_fn, mergeConfiguredPetPositionDefaults_fn, getOverlayPetOptions_fn, resolvePetAssetUrl_fn, resolveOverlayPetOptions_fn, getFrameOptions_fn, setLauncherOpen_fn, setChatMinimizedToPet_fn, syncPetOverlayOptions_fn, handlePetActivate_fn, handlePetClose_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_CONTEXT_MENU_MARGIN = 8;
899
+ const PET_SUMMARY_FONT_FAMILY = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
900
+ const PET_OVERLAY_COPY = {
901
+ "en-US": {
902
+ closePetMenuItem: "Close pet",
903
+ hideMessage: "Hide message",
904
+ expandMessage: "Expand message",
905
+ collapseMessage: "Collapse message",
906
+ restoreMessage: "Show message",
907
+ replyButton: "Reply",
908
+ replyPlaceholder: "Reply...",
909
+ sendButton: "Send",
910
+ sendingButton: "Sending...",
911
+ sendFailed: "Failed to send"
912
+ },
913
+ "zh-CN": {
914
+ closePetMenuItem: "关闭宠物",
915
+ hideMessage: "隐藏消息",
916
+ expandMessage: "展开消息",
917
+ collapseMessage: "收起消息",
918
+ restoreMessage: "显示消息",
919
+ replyButton: "回复",
920
+ replyPlaceholder: "输入回复...",
921
+ sendButton: "发送",
922
+ sendingButton: "发送中...",
923
+ sendFailed: "发送失败"
924
+ }
925
+ };
926
+ function stopEventPropagation(event) {
927
+ event.stopPropagation();
928
+ }
929
+ function getViewportSize() {
930
+ const visualViewport = window.visualViewport;
931
+ return {
932
+ width: (visualViewport == null ? void 0 : visualViewport.width) || window.innerWidth || 320,
933
+ height: (visualViewport == null ? void 0 : visualViewport.height) || window.innerHeight || 480
934
+ };
935
+ }
936
+ function readPersistedPosition(storageKey, persist) {
937
+ if (!persist) {
938
+ return null;
939
+ }
940
+ try {
941
+ const raw = window.localStorage.getItem(storageKey);
942
+ if (!raw) {
943
+ return null;
944
+ }
945
+ const parsed = JSON.parse(raw);
946
+ if (!parsed || typeof parsed !== "object" || typeof parsed.x !== "number" || typeof parsed.y !== "number") {
947
+ return null;
948
+ }
949
+ return { x: parsed.x, y: parsed.y };
950
+ } catch {
951
+ return null;
952
+ }
953
+ }
954
+ function writePersistedPosition(storageKey, persist, position) {
955
+ if (!persist) {
956
+ return;
957
+ }
958
+ try {
959
+ window.localStorage.setItem(storageKey, JSON.stringify(position));
960
+ } catch {
961
+ }
962
+ }
963
+ function escapeCssUrl(value) {
964
+ return value.replace(/["\\]/g, "\\$&");
965
+ }
966
+ function getRenderScale(scale) {
967
+ return Math.max(0.1, scale) * PET_BASE_RENDER_SCALE;
968
+ }
969
+ function clampNumber(value, min, max) {
970
+ return Math.min(max, Math.max(min, value));
971
+ }
972
+ function getDefaultLocale() {
973
+ if (typeof window !== "undefined") {
974
+ try {
975
+ const stored = window.localStorage.getItem("chatkit:locale");
976
+ if (stored) {
977
+ return stored;
978
+ }
979
+ } catch {
980
+ }
981
+ }
982
+ return typeof navigator !== "undefined" ? navigator.language : null;
983
+ }
984
+ function resolveCopyLocale(locale) {
985
+ const normalized = (locale ?? getDefaultLocale() ?? "").trim().toLowerCase();
986
+ if (normalized === "zh-cn" || normalized === "zh-hans" || normalized.startsWith("zh")) {
987
+ return "zh-CN";
988
+ }
989
+ return "en-US";
990
+ }
991
+ function getSummaryDensityMetrics(density) {
992
+ switch (density) {
993
+ case "compact":
994
+ return {
995
+ padding: "8px 10px",
996
+ gap: 6,
997
+ marginTop: 3,
998
+ toggleSize: 30,
999
+ actionSize: 22
1000
+ };
1001
+ case "spacious":
1002
+ return {
1003
+ padding: "14px 16px",
1004
+ gap: 10,
1005
+ marginTop: 6,
1006
+ toggleSize: 38,
1007
+ actionSize: 28
1008
+ };
1009
+ case "normal":
1010
+ default:
1011
+ return {
1012
+ padding: "12px 14px",
1013
+ gap: 8,
1014
+ marginTop: 4,
1015
+ toggleSize: 34,
1016
+ actionSize: 26
1017
+ };
1018
+ }
1019
+ }
1020
+ function getSummaryRadius(radius) {
1021
+ switch (radius) {
1022
+ case "pill":
1023
+ return 24;
1024
+ case "round":
1025
+ return 16;
1026
+ case "sharp":
1027
+ return 0;
1028
+ case "soft":
1029
+ default:
1030
+ return 12;
1031
+ }
1032
+ }
1033
+ function getSummaryThemeMetrics(theme) {
1034
+ var _a2, _b2;
1035
+ const themeObject = typeof theme === "string" ? null : theme;
1036
+ const baseSize = ((_a2 = themeObject == null ? void 0 : themeObject.typography) == null ? void 0 : _a2.baseSize) ?? 16;
1037
+ const density = (themeObject == null ? void 0 : themeObject.density) ?? "normal";
1038
+ const densityOffset = density === "compact" ? -1 : density === "spacious" ? 1 : 0;
1039
+ const bodySize = clampNumber(baseSize - 2 + densityOffset, 11, 17);
1040
+ const densityMetrics = getSummaryDensityMetrics(density);
1041
+ return {
1042
+ ...densityMetrics,
1043
+ bodySize,
1044
+ titleSize: bodySize + 1,
1045
+ iconSize: clampNumber(bodySize + 2, 13, 19),
1046
+ radius: getSummaryRadius(themeObject == null ? void 0 : themeObject.radius),
1047
+ fontFamily: ((_b2 = themeObject == null ? void 0 : themeObject.typography) == null ? void 0 : _b2.fontFamily) ?? PET_SUMMARY_FONT_FAMILY
1048
+ };
1049
+ }
1050
+ function isPetState(value) {
1051
+ return value === "idle" || value === "running-right" || value === "running-left" || value === "waving" || value === "jumping" || value === "failed" || value === "waiting" || value === "running" || value === "review";
1052
+ }
1053
+ function parsePetStateChangePayload(value) {
1054
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1055
+ return null;
1056
+ }
1057
+ const payload = value;
1058
+ return isPetState(payload.state) ? { state: payload.state } : null;
1059
+ }
1060
+ function parsePetOptionsChangePayload(value) {
1061
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1062
+ return null;
1063
+ }
1064
+ const payload = value;
1065
+ if (payload.pet === null || typeof payload.pet === "boolean") {
1066
+ return { pet: payload.pet };
1067
+ }
1068
+ if (payload.pet && typeof payload.pet === "object" && !Array.isArray(payload.pet)) {
1069
+ return { pet: payload.pet };
1070
+ }
1071
+ return null;
1072
+ }
1073
+ function isThreadSummaryStatus(value) {
1074
+ return value === "running" || value === "completed" || value === "failed";
1075
+ }
1076
+ function getThreadSummaryKey(summary) {
1077
+ if (!summary) {
1078
+ return null;
1079
+ }
1080
+ return [
1081
+ summary.threadId,
1082
+ summary.messageId || summary.updatedAt || summary.message
1083
+ ].join(":");
1084
+ }
1085
+ function getThreadSummaryInteractionKey(summary) {
1086
+ if (!summary) {
1087
+ return null;
1088
+ }
1089
+ return [summary.threadId, summary.messageId ?? ""].join(":");
1090
+ }
1091
+ function parseThreadSummaryPayload(value) {
1092
+ if (value === null) {
1093
+ return { summary: null };
1094
+ }
1095
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1096
+ return null;
1097
+ }
1098
+ const payload = value;
1099
+ 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)) {
1100
+ return null;
1101
+ }
1102
+ return {
1103
+ summary: {
1104
+ threadId: payload.threadId,
1105
+ title: payload.title,
1106
+ message: payload.message,
1107
+ status: payload.status,
1108
+ ...typeof payload.messageId === "string" && payload.messageId.trim() ? { messageId: payload.messageId } : {},
1109
+ ...typeof payload.updatedAt === "string" && payload.updatedAt.trim() ? { updatedAt: payload.updatedAt } : {}
1110
+ }
1111
+ };
1112
+ }
1113
+ function parseThreadSummaryLogPayload(value) {
1114
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1115
+ return null;
1116
+ }
1117
+ const payload = value;
1118
+ if (payload.name !== "thread.summary") {
1119
+ return null;
1120
+ }
1121
+ return parseThreadSummaryPayload(payload.data ?? null);
1122
+ }
1123
+ class PetOverlay {
1124
+ constructor(root, options) {
1125
+ this.overlayElement = null;
1126
+ this.petElement = null;
1127
+ this.contextMenuElement = null;
1128
+ this.summaryElement = null;
1129
+ this.summaryToggleElement = null;
1130
+ this.mediaElement = null;
1131
+ this.options = null;
1132
+ this.theme = null;
1133
+ this.resolved = null;
1134
+ this.summary = null;
1135
+ this.summaryRenderKey = null;
1136
+ this.dismissedSummaryKey = null;
1137
+ this.isSummaryCollapsed = false;
1138
+ this.isSummaryExpanded = false;
1139
+ this.isSummaryHovering = false;
1140
+ this.isReplyOpen = false;
1141
+ this.isReplySubmitting = false;
1142
+ this.replyError = null;
1143
+ this.replyDraft = "";
1144
+ this.replyInputElement = null;
1145
+ this.copyLocale = resolveCopyLocale();
1146
+ this.copy = PET_OVERLAY_COPY[this.copyLocale];
1147
+ this.currentState = "waiting";
1148
+ this.lastAutoState = "waiting";
1149
+ this.transient = null;
1150
+ this.position = null;
1151
+ this.dragPosition = null;
1152
+ this.dragOffset = { x: 0, y: 0 };
1153
+ this.lastDragPosition = null;
1154
+ this.lastDragClientX = null;
1155
+ this.dragAnimation = null;
1156
+ this.isDragging = false;
1157
+ this.isHovering = false;
1158
+ this.movedDuringDrag = false;
1159
+ this.prefersReducedMotion = false;
1160
+ this.frame = 0;
1161
+ this.completed = false;
1162
+ this.activeAnimationName = null;
1163
+ this.activeAnimationMode = null;
1164
+ this.frameTimer = null;
1165
+ this.restingDelayTimer = null;
1166
+ this.mediaQuery = null;
1167
+ this.connected = false;
1168
+ this.handleViewportChange = () => {
1169
+ this.closeContextMenu();
1170
+ this.render();
1171
+ };
1172
+ this.handleReducedMotionChange = () => {
1173
+ var _a2;
1174
+ this.prefersReducedMotion = Boolean((_a2 = this.mediaQuery) == null ? void 0 : _a2.matches);
1175
+ if (this.prefersReducedMotion) {
1176
+ this.transient = null;
1177
+ }
1178
+ this.render();
1179
+ };
1180
+ this.handlePointerEnter = () => {
1181
+ this.clearRestingDelayTimer();
1182
+ this.isHovering = true;
1183
+ this.rescheduleAnimation();
1184
+ };
1185
+ this.handlePointerLeave = () => {
1186
+ if (!this.isDragging) {
1187
+ this.enterRestingAfterDelay();
1188
+ }
1189
+ };
1190
+ this.handleContextMenu = (event) => {
1191
+ event.preventDefault();
1192
+ event.stopPropagation();
1193
+ this.openContextMenu({ x: event.clientX, y: event.clientY });
1194
+ };
1195
+ this.handleContextMenuEvent = (event) => {
1196
+ event.preventDefault();
1197
+ event.stopPropagation();
1198
+ };
1199
+ this.handleContextMenuOutsidePointerDown = (event) => {
1200
+ const menu = this.contextMenuElement;
1201
+ if (menu && event.composedPath().includes(menu)) {
1202
+ return;
1203
+ }
1204
+ this.closeContextMenu();
1205
+ };
1206
+ this.handleContextMenuKeyDown = (event) => {
1207
+ if (event.key !== "Escape") {
1208
+ return;
1209
+ }
1210
+ event.preventDefault();
1211
+ this.closeContextMenu();
1212
+ };
1213
+ this.handleClosePetMenuItemClick = (event) => {
1214
+ var _a2;
1215
+ event.preventDefault();
1216
+ event.stopPropagation();
1217
+ this.closeContextMenu();
1218
+ (_a2 = this.onClose) == null ? void 0 : _a2.call(this);
1219
+ };
1220
+ this.handleSummaryPointerEnter = () => {
1221
+ this.isSummaryHovering = true;
1222
+ this.render();
1223
+ };
1224
+ this.handleSummaryPointerLeave = () => {
1225
+ this.isSummaryHovering = false;
1226
+ if (!this.isReplyOpen) {
1227
+ this.render();
1228
+ }
1229
+ };
1230
+ this.handleSummaryClick = () => {
1231
+ var _a2, _b2;
1232
+ const threadId = (_a2 = this.summary) == null ? void 0 : _a2.threadId.trim();
1233
+ if (!threadId) {
1234
+ return;
1235
+ }
1236
+ (_b2 = this.onThreadSummaryActivate) == null ? void 0 : _b2.call(this, threadId);
1237
+ };
1238
+ this.handleSummaryDelete = () => {
1239
+ const summaryKey = getThreadSummaryKey(this.summary);
1240
+ if (summaryKey) {
1241
+ this.dismissedSummaryKey = summaryKey;
1242
+ }
1243
+ this.isSummaryCollapsed = false;
1244
+ this.isReplyOpen = false;
1245
+ this.replyDraft = "";
1246
+ this.replyError = null;
1247
+ this.removeSummaryElements();
1248
+ };
1249
+ this.handleSummaryCollapseToggle = () => {
1250
+ this.isSummaryCollapsed = !this.isSummaryCollapsed;
1251
+ this.isSummaryExpanded = false;
1252
+ this.isReplyOpen = false;
1253
+ this.replyError = null;
1254
+ this.render();
1255
+ };
1256
+ this.handleSummaryExpandToggle = () => {
1257
+ this.isSummaryExpanded = !this.isSummaryExpanded;
1258
+ this.render();
1259
+ };
1260
+ this.handleReplyOpen = () => {
1261
+ this.isReplyOpen = true;
1262
+ this.replyError = null;
1263
+ this.render();
1264
+ };
1265
+ this.handleReplyInput = (event) => {
1266
+ const target = event.currentTarget;
1267
+ if (target instanceof HTMLInputElement) {
1268
+ this.replyDraft = target.value;
1269
+ this.replyError = null;
1270
+ }
1271
+ };
1272
+ this.handleReplySubmit = (event) => {
1273
+ event.preventDefault();
1274
+ void this.submitReply();
1275
+ };
1276
+ this.handleReplyKeyDown = (event) => {
1277
+ if (event.key !== "Escape") {
1278
+ return;
1279
+ }
1280
+ event.preventDefault();
1281
+ this.isReplyOpen = false;
1282
+ this.replyError = null;
1283
+ this.render();
1284
+ };
1285
+ this.handlePointerDown = (event) => {
1286
+ var _a2, _b2;
1287
+ if (event.button !== 0 || event.ctrlKey) {
1288
+ return;
1289
+ }
1290
+ this.closeContextMenu();
1291
+ if (!((_a2 = this.options) == null ? void 0 : _a2.position.draggable)) {
1292
+ return;
1293
+ }
1294
+ event.preventDefault();
1295
+ const rect = (_b2 = this.petElement) == null ? void 0 : _b2.getBoundingClientRect();
1296
+ if (!rect) {
1297
+ return;
1298
+ }
1299
+ const nextPosition = {
1300
+ x: rect.left,
1301
+ y: rect.top
1302
+ };
1303
+ this.dragOffset = {
1304
+ x: event.clientX - rect.left,
1305
+ y: event.clientY - rect.top
1306
+ };
1307
+ this.lastDragPosition = nextPosition;
1308
+ this.lastDragClientX = event.clientX;
1309
+ this.dragAnimation = null;
1310
+ this.movedDuringDrag = false;
1311
+ this.dragPosition = nextPosition;
1312
+ this.isDragging = true;
1313
+ this.clearRestingDelayTimer();
1314
+ this.isHovering = true;
1315
+ this.installDragListeners();
1316
+ this.rescheduleAnimation();
1317
+ };
1318
+ this.handlePointerMove = (event) => {
1319
+ const nextPosition = this.getNextDragPosition(event);
1320
+ const last = this.lastDragPosition;
1321
+ if (last && (Math.abs(last.x - nextPosition.x) > DRAG_DIRECTION_THRESHOLD_PX || Math.abs(last.y - nextPosition.y) > DRAG_DIRECTION_THRESHOLD_PX)) {
1322
+ this.movedDuringDrag = true;
1323
+ }
1324
+ if (this.lastDragClientX !== null) {
1325
+ const deltaX = event.clientX - this.lastDragClientX;
1326
+ if (deltaX > DRAG_DIRECTION_THRESHOLD_PX) {
1327
+ this.dragAnimation = "running-right";
1328
+ } else if (deltaX < -DRAG_DIRECTION_THRESHOLD_PX) {
1329
+ this.dragAnimation = "running-left";
1330
+ }
1331
+ }
1332
+ this.lastDragClientX = event.clientX;
1333
+ this.lastDragPosition = nextPosition;
1334
+ this.dragPosition = nextPosition;
1335
+ this.render();
1336
+ };
1337
+ this.handlePointerUp = (event) => {
1338
+ const finalPosition = this.lastDragPosition ?? this.getNextDragPosition(event);
1339
+ this.isDragging = false;
1340
+ this.dragPosition = null;
1341
+ this.dragAnimation = null;
1342
+ this.lastDragClientX = null;
1343
+ this.removeDragListeners();
1344
+ this.persistPosition(finalPosition);
1345
+ if (event.pointerType === "mouse" && this.isPointerOverPet(event)) {
1346
+ this.isHovering = true;
1347
+ this.rescheduleAnimation();
1348
+ } else {
1349
+ this.enterRestingAfterDelay();
1350
+ this.rescheduleAnimation();
1351
+ }
1352
+ };
1353
+ this.handleClick = () => {
1354
+ var _a2;
1355
+ if (this.movedDuringDrag) {
1356
+ return;
1357
+ }
1358
+ (_a2 = this.onActivate) == null ? void 0 : _a2.call(this);
1359
+ if (this.prefersReducedMotion) {
1360
+ return;
1361
+ }
1362
+ this.transient = { name: "waving" };
1363
+ this.render();
1364
+ };
1365
+ this.root = root;
1366
+ this.onActivate = options == null ? void 0 : options.onActivate;
1367
+ this.onClose = options == null ? void 0 : options.onClose;
1368
+ this.onReply = options == null ? void 0 : options.onReply;
1369
+ this.onThreadSummaryActivate = options == null ? void 0 : options.onThreadSummaryActivate;
1370
+ this.connect();
1371
+ }
1372
+ connect() {
1373
+ if (this.connected) {
1374
+ return;
1375
+ }
1376
+ this.connected = true;
1377
+ this.installViewportListeners();
1378
+ this.installReducedMotionListener();
1379
+ this.render();
1380
+ }
1381
+ setOptions(pet, theme) {
1382
+ this.closeContextMenu();
1383
+ const nextOptions = chatkitTypes.normalizePetOptions(pet);
1384
+ this.options = nextOptions;
1385
+ this.theme = theme ?? null;
1386
+ if (!nextOptions) {
1387
+ this.isDragging = false;
1388
+ this.isHovering = false;
1389
+ this.position = null;
1390
+ this.dragPosition = null;
1391
+ this.dragAnimation = null;
1392
+ this.lastDragPosition = null;
1393
+ this.lastDragClientX = null;
1394
+ this.transient = null;
1395
+ this.resolved = null;
1396
+ this.clearRestingDelayTimer();
1397
+ this.removeDragListeners();
1398
+ this.removeOverlay();
1399
+ return;
1400
+ }
1401
+ this.position = readPersistedPosition(
1402
+ chatkitTypes.DEFAULT_PET_STORAGE_KEY,
1403
+ nextOptions.position.persist
1404
+ );
1405
+ if (nextOptions.behavior === "auto" && !this.prefersReducedMotion) {
1406
+ this.transient = { name: "waving" };
1407
+ }
1408
+ this.resolveCharacter();
1409
+ this.render();
1410
+ }
1411
+ setState(state) {
1412
+ var _a2;
1413
+ const previous = this.lastAutoState;
1414
+ this.lastAutoState = state;
1415
+ this.currentState = state;
1416
+ if (((_a2 = this.options) == null ? void 0 : _a2.behavior) === "auto" && !this.prefersReducedMotion && state === "idle" && (previous === "running" || previous === "review") && !this.transient) {
1417
+ this.transient = { name: "jumping" };
1418
+ } else if (state !== "idle") {
1419
+ this.transient = null;
1420
+ }
1421
+ this.render();
1422
+ }
1423
+ setLocale(locale) {
1424
+ const nextLocale = resolveCopyLocale(locale);
1425
+ if (nextLocale === this.copyLocale) {
1426
+ return;
1427
+ }
1428
+ this.copyLocale = nextLocale;
1429
+ this.copy = PET_OVERLAY_COPY[nextLocale];
1430
+ this.summaryRenderKey = null;
1431
+ this.closeContextMenu();
1432
+ this.render();
1433
+ }
1434
+ setThreadSummary(summary) {
1435
+ const previousKey = getThreadSummaryInteractionKey(this.summary);
1436
+ const nextKey = getThreadSummaryInteractionKey(summary);
1437
+ this.summary = summary;
1438
+ if (!summary) {
1439
+ this.isSummaryCollapsed = false;
1440
+ this.isSummaryExpanded = false;
1441
+ this.isSummaryHovering = false;
1442
+ this.isReplyOpen = false;
1443
+ this.isReplySubmitting = false;
1444
+ this.replyError = null;
1445
+ this.replyDraft = "";
1446
+ this.summaryRenderKey = null;
1447
+ this.removeSummaryElements();
1448
+ return;
1449
+ }
1450
+ if (previousKey !== nextKey) {
1451
+ this.isSummaryCollapsed = false;
1452
+ this.isSummaryExpanded = false;
1453
+ this.isSummaryHovering = false;
1454
+ this.isReplyOpen = false;
1455
+ this.isReplySubmitting = false;
1456
+ this.replyError = null;
1457
+ this.replyDraft = "";
1458
+ }
1459
+ this.render();
1460
+ }
1461
+ setThreadSummaryStatus(status) {
1462
+ if (!this.summary || this.summary.status === status) {
1463
+ return;
1464
+ }
1465
+ this.summary = { ...this.summary, status };
1466
+ this.render();
1467
+ }
1468
+ destroy() {
1469
+ var _a2, _b2, _c2, _d;
1470
+ if (!this.connected) {
1471
+ return;
1472
+ }
1473
+ this.connected = false;
1474
+ this.clearRestingDelayTimer();
1475
+ this.clearTimers();
1476
+ this.removeDragListeners();
1477
+ this.removeOverlay();
1478
+ window.removeEventListener("resize", this.handleViewportChange);
1479
+ (_a2 = window.visualViewport) == null ? void 0 : _a2.removeEventListener(
1480
+ "resize",
1481
+ this.handleViewportChange
1482
+ );
1483
+ (_b2 = window.visualViewport) == null ? void 0 : _b2.removeEventListener(
1484
+ "scroll",
1485
+ this.handleViewportChange
1486
+ );
1487
+ (_d = (_c2 = this.mediaQuery) == null ? void 0 : _c2.removeEventListener) == null ? void 0 : _d.call(
1488
+ _c2,
1489
+ "change",
1490
+ this.handleReducedMotionChange
1491
+ );
1492
+ this.mediaQuery = null;
1493
+ }
1494
+ installViewportListeners() {
1495
+ var _a2, _b2;
1496
+ window.addEventListener("resize", this.handleViewportChange);
1497
+ (_a2 = window.visualViewport) == null ? void 0 : _a2.addEventListener(
1498
+ "resize",
1499
+ this.handleViewportChange
1500
+ );
1501
+ (_b2 = window.visualViewport) == null ? void 0 : _b2.addEventListener(
1502
+ "scroll",
1503
+ this.handleViewportChange
1504
+ );
1505
+ }
1506
+ installReducedMotionListener() {
1507
+ var _a2, _b2;
1508
+ if (!window.matchMedia) {
1509
+ return;
1510
+ }
1511
+ this.mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
1512
+ this.prefersReducedMotion = this.mediaQuery.matches;
1513
+ (_b2 = (_a2 = this.mediaQuery).addEventListener) == null ? void 0 : _b2.call(
1514
+ _a2,
1515
+ "change",
1516
+ this.handleReducedMotionChange
1517
+ );
1518
+ }
1519
+ resolveCharacter() {
1520
+ if (!this.options) {
1521
+ this.resolved = null;
1522
+ return;
1523
+ }
1524
+ const character = this.options.character;
1525
+ this.resolved = chatkitTypes.resolvePetCharacter(character);
1526
+ }
1527
+ ensureOverlay() {
1528
+ if (this.overlayElement && this.petElement) {
1529
+ return;
1530
+ }
1531
+ const overlay = document.createElement("div");
1532
+ overlay.setAttribute("data-chatkit-host-pet-layer", "");
1533
+ overlay.style.position = "fixed";
1534
+ overlay.style.inset = "0";
1535
+ overlay.style.pointerEvents = "none";
1536
+ overlay.style.overflow = "visible";
1537
+ const style = document.createElement("style");
1538
+ style.textContent = `
1539
+ @keyframes chatkit-pet-summary-spin {
1540
+ to { transform: rotate(360deg); }
1541
+ }
1542
+ `;
1543
+ const pet = document.createElement("div");
1544
+ pet.setAttribute("data-chatkit-host-pet", "");
1545
+ pet.style.position = "absolute";
1546
+ pet.style.top = "0";
1547
+ pet.style.left = "0";
1548
+ pet.style.pointerEvents = "auto";
1549
+ pet.style.touchAction = "none";
1550
+ pet.style.userSelect = "none";
1551
+ pet.style.willChange = "transform";
1552
+ pet.addEventListener("pointerenter", this.handlePointerEnter);
1553
+ pet.addEventListener("pointerleave", this.handlePointerLeave);
1554
+ pet.addEventListener("pointerdown", this.handlePointerDown);
1555
+ pet.addEventListener("contextmenu", this.handleContextMenu);
1556
+ pet.addEventListener("click", this.handleClick);
1557
+ overlay.append(style, pet);
1558
+ this.root.append(overlay);
1559
+ this.overlayElement = overlay;
1560
+ this.petElement = pet;
1561
+ }
1562
+ removeOverlay() {
1563
+ var _a2;
1564
+ this.clearRestingDelayTimer();
1565
+ this.clearTimers();
1566
+ this.closeContextMenu();
1567
+ if (this.petElement) {
1568
+ this.petElement.removeEventListener(
1569
+ "pointerenter",
1570
+ this.handlePointerEnter
1571
+ );
1572
+ this.petElement.removeEventListener(
1573
+ "pointerleave",
1574
+ this.handlePointerLeave
1575
+ );
1576
+ this.petElement.removeEventListener(
1577
+ "pointerdown",
1578
+ this.handlePointerDown
1579
+ );
1580
+ this.petElement.removeEventListener(
1581
+ "contextmenu",
1582
+ this.handleContextMenu
1583
+ );
1584
+ this.petElement.removeEventListener("click", this.handleClick);
1585
+ }
1586
+ this.isHovering = false;
1587
+ this.removeSummaryElements();
1588
+ (_a2 = this.overlayElement) == null ? void 0 : _a2.remove();
1589
+ this.overlayElement = null;
1590
+ this.petElement = null;
1591
+ this.mediaElement = null;
1592
+ }
1593
+ removeSummaryElements() {
1594
+ var _a2, _b2;
1595
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1596
+ (_b2 = this.summaryToggleElement) == null ? void 0 : _b2.remove();
1597
+ this.summaryElement = null;
1598
+ this.summaryToggleElement = null;
1599
+ this.replyInputElement = null;
1600
+ this.summaryRenderKey = null;
1601
+ }
1602
+ getSize() {
1603
+ if (!this.options || !this.resolved) {
1604
+ return { width: 0, height: 0 };
1605
+ }
1606
+ const scale = getRenderScale(this.options.position.scale);
1607
+ const baseSize = {
1608
+ width: this.resolved.atlas.cellWidth,
1609
+ height: this.resolved.atlas.cellHeight
1610
+ };
1611
+ return {
1612
+ width: baseSize.width * scale,
1613
+ height: baseSize.height * scale
1614
+ };
1615
+ }
1616
+ getCurrentPosition(size) {
1617
+ const options = this.options;
1618
+ if (!options) {
1619
+ return { x: 0, y: 0 };
1620
+ }
1621
+ const viewport = getViewportSize();
1622
+ const padding = chatkitTypes.normalizeBoundsPadding(options.position.boundsPadding);
1623
+ const pin = options.position.pin === void 0 ? "bottom-right" : options.position.pin;
1624
+ const pinnedPosition = pin ? chatkitTypes.getPinnedPetPosition(pin, size, viewport, padding) : null;
1625
+ return chatkitTypes.clampPetPosition(
1626
+ this.dragPosition ?? this.position ?? pinnedPosition ?? { x: padding.left, y: padding.top },
1627
+ size,
1628
+ viewport,
1629
+ padding
1630
+ );
1631
+ }
1632
+ persistPosition(nextPosition) {
1633
+ if (!this.options) {
1634
+ return;
1635
+ }
1636
+ const size = this.getSize();
1637
+ const clamped = chatkitTypes.clampPetPosition(
1638
+ nextPosition,
1639
+ size,
1640
+ getViewportSize(),
1641
+ chatkitTypes.normalizeBoundsPadding(this.options.position.boundsPadding)
1642
+ );
1643
+ this.position = clamped;
1644
+ writePersistedPosition(
1645
+ chatkitTypes.DEFAULT_PET_STORAGE_KEY,
1646
+ this.options.position.persist,
1647
+ clamped
1648
+ );
1649
+ }
1650
+ getActiveAnimationName() {
1651
+ if (!this.options) {
1652
+ return "idle";
1653
+ }
1654
+ if (this.isDragging) {
1655
+ return this.dragAnimation ?? "running";
1656
+ }
1657
+ if (this.transient) {
1658
+ return this.transient.name;
1659
+ }
1660
+ if (this.options.behavior === "manual") {
1661
+ return "idle";
1662
+ }
1663
+ return this.currentState;
1664
+ }
1665
+ getActiveAnimationMode() {
1666
+ if (this.isDragging) {
1667
+ return "loop";
1668
+ }
1669
+ return this.transient ? "once" : "loop";
1670
+ }
1671
+ resetAnimationIfNeeded(name, mode) {
1672
+ if (this.activeAnimationName === name && this.activeAnimationMode === mode) {
1673
+ return;
1674
+ }
1675
+ this.clearTimers();
1676
+ this.activeAnimationName = name;
1677
+ this.activeAnimationMode = mode;
1678
+ this.frame = 0;
1679
+ this.completed = false;
1680
+ }
1681
+ render() {
1682
+ if (!this.options || !this.resolved) {
1683
+ this.clearTimers();
1684
+ if (this.petElement) {
1685
+ this.petElement.replaceChildren();
1686
+ }
1687
+ this.removeSummaryElements();
1688
+ this.mediaElement = null;
1689
+ this.activeAnimationName = null;
1690
+ this.activeAnimationMode = null;
1691
+ this.frame = 0;
1692
+ this.completed = false;
1693
+ return;
1694
+ }
1695
+ this.ensureOverlay();
1696
+ const overlay = this.overlayElement;
1697
+ const pet = this.petElement;
1698
+ if (!overlay || !pet) {
1699
+ return;
1700
+ }
1701
+ const size = this.getSize();
1702
+ const position = this.getCurrentPosition(size);
1703
+ const animationName = this.getActiveAnimationName();
1704
+ const animationMode = this.getActiveAnimationMode();
1705
+ this.resetAnimationIfNeeded(animationName, animationMode);
1706
+ overlay.style.zIndex = String(this.options.position.zIndex);
1707
+ pet.style.width = `${size.width}px`;
1708
+ pet.style.height = `${size.height}px`;
1709
+ pet.style.transform = `translate3d(${position.x}px, ${position.y}px, 0)`;
1710
+ pet.style.cursor = this.options.position.draggable ? this.isDragging ? "grabbing" : "grab" : "default";
1711
+ pet.dataset.petAnimation = animationName;
1712
+ pet.setAttribute("aria-label", this.options.ariaLabel);
1713
+ pet.setAttribute("role", "img");
1714
+ this.renderAtlas(animationName, animationMode);
1715
+ this.renderThreadSummary(position, size);
1716
+ this.scheduleNextFrame(animationName, animationMode);
1717
+ }
1718
+ renderThreadSummary(position, size) {
1719
+ var _a2, _b2, _c2;
1720
+ const summary = this.summary;
1721
+ const summaryKey = getThreadSummaryKey(summary);
1722
+ if (!summary || !summaryKey || this.dismissedSummaryKey === summaryKey) {
1723
+ this.removeSummaryElements();
1724
+ return;
1725
+ }
1726
+ if (this.isSummaryCollapsed) {
1727
+ this.renderCollapsedSummary(position, size);
1728
+ return;
1729
+ }
1730
+ const nextRenderKey = [
1731
+ this.copyLocale,
1732
+ this.isSummaryExpanded ? "expanded" : "compact",
1733
+ this.isSummaryHovering ? "hover" : "rest",
1734
+ this.isReplyOpen ? "reply" : "closed",
1735
+ this.isReplySubmitting ? "submitting" : "ready",
1736
+ this.replyError ?? ""
1737
+ ].join("|");
1738
+ if (!this.summaryElement || this.summaryRenderKey !== nextRenderKey) {
1739
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1740
+ (_b2 = this.summaryToggleElement) == null ? void 0 : _b2.remove();
1741
+ this.summaryElement = this.createSummaryBubble(summary);
1742
+ this.summaryToggleElement = this.createSummaryToggleButton("v");
1743
+ (_c2 = this.overlayElement) == null ? void 0 : _c2.append(
1744
+ this.summaryElement,
1745
+ this.summaryToggleElement
1746
+ );
1747
+ this.summaryRenderKey = nextRenderKey;
1748
+ if (this.isReplyOpen && !this.isReplySubmitting) {
1749
+ window.setTimeout(() => {
1750
+ var _a3;
1751
+ return (_a3 = this.replyInputElement) == null ? void 0 : _a3.focus();
1752
+ }, 0);
1753
+ }
1754
+ }
1755
+ this.updateSummaryBubbleContent(summary);
1756
+ this.positionSummaryBubble(position, size);
1757
+ }
1758
+ renderCollapsedSummary(position, size) {
1759
+ var _a2, _b2;
1760
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1761
+ this.summaryElement = null;
1762
+ this.summaryRenderKey = null;
1763
+ if (!this.summaryToggleElement) {
1764
+ this.summaryToggleElement = this.createSummaryToggleButton("1");
1765
+ (_b2 = this.overlayElement) == null ? void 0 : _b2.append(this.summaryToggleElement);
1766
+ }
1767
+ this.summaryToggleElement.textContent = "1";
1768
+ this.positionSummaryToggleBadge(position, size);
1769
+ }
1770
+ positionSummaryToggleBadge(position, size) {
1771
+ const badge = this.summaryToggleElement;
1772
+ if (!badge) {
1773
+ return;
1774
+ }
1775
+ const viewport = getViewportSize();
1776
+ const badgeSize = getSummaryThemeMetrics(this.theme).toggleSize;
1777
+ const x = clampNumber(
1778
+ position.x + size.width - badgeSize * 0.35,
1779
+ PET_SUMMARY_MARGIN,
1780
+ viewport.width - badgeSize - PET_SUMMARY_MARGIN
1781
+ );
1782
+ const y = clampNumber(
1783
+ position.y - badgeSize * 0.35,
1784
+ PET_SUMMARY_MARGIN,
1785
+ viewport.height - badgeSize - PET_SUMMARY_MARGIN
1786
+ );
1787
+ badge.style.width = `${badgeSize}px`;
1788
+ badge.style.height = `${badgeSize}px`;
1789
+ badge.style.transform = `translate3d(${x}px, ${y}px, 0)`;
1790
+ badge.style.borderRadius = "999px";
1791
+ }
1792
+ positionSummaryBubble(position, size) {
1793
+ const bubble = this.summaryElement;
1794
+ const toggle = this.summaryToggleElement;
1795
+ if (!bubble || !toggle) {
1796
+ return;
1797
+ }
1798
+ const viewport = getViewportSize();
1799
+ const width = Math.min(
1800
+ PET_SUMMARY_WIDTH,
1801
+ viewport.width - PET_SUMMARY_MARGIN * 2
1802
+ );
1803
+ bubble.style.width = `${width}px`;
1804
+ const bubbleHeight = bubble.offsetHeight || 96;
1805
+ const aboveY = position.y - bubbleHeight - PET_SUMMARY_GAP;
1806
+ const showAbove = aboveY >= PET_SUMMARY_MARGIN;
1807
+ const y = showAbove ? aboveY : clampNumber(
1808
+ position.y + size.height + PET_SUMMARY_GAP,
1809
+ PET_SUMMARY_MARGIN,
1810
+ viewport.height - bubbleHeight - PET_SUMMARY_MARGIN
1811
+ );
1812
+ const x = clampNumber(
1813
+ position.x + size.width / 2 - width / 2,
1814
+ PET_SUMMARY_MARGIN,
1815
+ viewport.width - width - PET_SUMMARY_MARGIN
1816
+ );
1817
+ bubble.style.transform = `translate3d(${x}px, ${y}px, 0)`;
1818
+ this.positionSummaryToggleBadge(position, size);
1819
+ }
1820
+ createSummaryBubble(summary) {
1821
+ const shouldShowReplyButton = this.isSummaryHovering && !this.isReplyOpen;
1822
+ const metrics = getSummaryThemeMetrics(this.theme);
1823
+ const bubble = document.createElement("div");
1824
+ bubble.setAttribute("data-chatkit-pet-summary", "");
1825
+ bubble.addEventListener("pointerenter", this.handleSummaryPointerEnter);
1826
+ bubble.addEventListener("pointerleave", this.handleSummaryPointerLeave);
1827
+ bubble.addEventListener("click", this.handleSummaryClick);
1828
+ bubble.style.position = "absolute";
1829
+ bubble.style.top = "0";
1830
+ bubble.style.left = "0";
1831
+ bubble.style.boxSizing = "border-box";
1832
+ bubble.style.pointerEvents = "auto";
1833
+ bubble.style.padding = metrics.padding;
1834
+ bubble.style.border = "1px solid rgba(148, 163, 184, 0.22)";
1835
+ bubble.style.borderRadius = `${metrics.radius}px`;
1836
+ bubble.style.background = "rgba(255, 255, 255, 0.94)";
1837
+ bubble.style.color = "#1f2937";
1838
+ bubble.style.boxShadow = "0 8px 24px rgba(15, 23, 42, 0.1)";
1839
+ bubble.style.font = `500 ${metrics.bodySize}px/1.35 ${metrics.fontFamily}`;
1840
+ bubble.style.backdropFilter = "blur(10px)";
1841
+ const header = document.createElement("div");
1842
+ header.style.display = "flex";
1843
+ header.style.alignItems = "center";
1844
+ header.style.gap = `${metrics.gap}px`;
1845
+ if (this.isSummaryHovering || this.isReplyOpen) {
1846
+ header.append(
1847
+ this.createSummaryActionButton(
1848
+ "x",
1849
+ this.copy.hideMessage,
1850
+ this.handleSummaryDelete
1851
+ )
1852
+ );
1853
+ }
1854
+ const title = document.createElement("div");
1855
+ title.textContent = summary.title;
1856
+ title.style.minWidth = "0";
1857
+ title.style.flex = "1";
1858
+ title.style.overflow = "hidden";
1859
+ title.style.textOverflow = "ellipsis";
1860
+ title.style.whiteSpace = "nowrap";
1861
+ title.style.fontWeight = "700";
1862
+ title.style.fontSize = `${metrics.titleSize}px`;
1863
+ title.dataset.chatkitPetSummaryTitle = "";
1864
+ header.append(title);
1865
+ if (this.isSummaryHovering || this.isReplyOpen) {
1866
+ header.append(
1867
+ this.createSummaryActionButton(
1868
+ this.isSummaryExpanded ? "-" : ">",
1869
+ this.isSummaryExpanded ? this.copy.collapseMessage : this.copy.expandMessage,
1870
+ this.handleSummaryExpandToggle
1871
+ )
1872
+ );
1873
+ } else {
1874
+ header.append(this.createStatusIcon(summary.status));
1875
+ }
1876
+ const message = document.createElement("div");
1877
+ message.textContent = summary.message;
1878
+ message.style.marginTop = `${metrics.marginTop}px`;
1879
+ message.style.fontWeight = "400";
1880
+ message.style.color = "#374151";
1881
+ message.style.overflow = "hidden";
1882
+ if (this.isSummaryExpanded) {
1883
+ message.style.maxHeight = "7em";
1884
+ message.style.overflowY = "auto";
1885
+ } else {
1886
+ message.style.display = "-webkit-box";
1887
+ message.style.setProperty("-webkit-line-clamp", "2");
1888
+ message.style.setProperty("-webkit-box-orient", "vertical");
1889
+ }
1890
+ message.dataset.chatkitPetSummaryMessage = "";
1891
+ bubble.append(header, message);
1892
+ if (shouldShowReplyButton) {
1893
+ const reply = this.createTextButton(
1894
+ this.copy.replyButton,
1895
+ this.handleReplyOpen
1896
+ );
1897
+ reply.style.position = "absolute";
1898
+ reply.style.right = "14px";
1899
+ reply.style.bottom = "10px";
1900
+ bubble.append(reply);
1901
+ }
1902
+ if (this.isReplyOpen) {
1903
+ bubble.append(this.createReplyForm());
1904
+ }
1905
+ return bubble;
1906
+ }
1907
+ updateSummaryBubbleContent(summary) {
1908
+ var _a2, _b2, _c2;
1909
+ const title = (_a2 = this.summaryElement) == null ? void 0 : _a2.querySelector(
1910
+ "[data-chatkit-pet-summary-title]"
1911
+ );
1912
+ if (title && title.textContent !== summary.title) {
1913
+ title.textContent = summary.title;
1914
+ }
1915
+ const message = (_b2 = this.summaryElement) == null ? void 0 : _b2.querySelector(
1916
+ "[data-chatkit-pet-summary-message]"
1917
+ );
1918
+ if (message && message.textContent !== summary.message) {
1919
+ message.textContent = summary.message;
1920
+ }
1921
+ const statusIcon = (_c2 = this.summaryElement) == null ? void 0 : _c2.querySelector(
1922
+ "[data-chatkit-pet-summary-status]"
1923
+ );
1924
+ if (statusIcon && statusIcon.dataset.chatkitPetSummaryStatus !== summary.status) {
1925
+ const nextIcon = this.createStatusIcon(summary.status);
1926
+ statusIcon.replaceWith(nextIcon);
1927
+ }
1928
+ }
1929
+ createSummaryToggleButton(label) {
1930
+ const metrics = getSummaryThemeMetrics(this.theme);
1931
+ const button = document.createElement("button");
1932
+ button.type = "button";
1933
+ button.textContent = label;
1934
+ button.title = label === "1" ? this.copy.restoreMessage : this.copy.collapseMessage;
1935
+ button.addEventListener("click", stopEventPropagation);
1936
+ button.addEventListener("click", this.handleSummaryCollapseToggle);
1937
+ button.style.position = "absolute";
1938
+ button.style.top = "0";
1939
+ button.style.left = "0";
1940
+ button.style.pointerEvents = "auto";
1941
+ button.style.border = "1px solid rgba(148, 163, 184, 0.28)";
1942
+ button.style.background = "rgba(248, 250, 252, 0.94)";
1943
+ button.style.color = "#475569";
1944
+ button.style.boxShadow = "0 6px 18px rgba(15, 23, 42, 0.1)";
1945
+ button.style.cursor = "pointer";
1946
+ button.style.font = `600 ${metrics.titleSize}px/1 ${metrics.fontFamily}`;
1947
+ button.style.display = "flex";
1948
+ button.style.alignItems = "center";
1949
+ button.style.justifyContent = "center";
1950
+ return button;
1951
+ }
1952
+ createStatusIcon(status) {
1953
+ const metrics = getSummaryThemeMetrics(this.theme);
1954
+ const iconSize = metrics.iconSize;
1955
+ const icon = document.createElement("span");
1956
+ icon.setAttribute("aria-hidden", "true");
1957
+ icon.dataset.chatkitPetSummaryStatus = status;
1958
+ icon.style.display = "inline-flex";
1959
+ icon.style.width = `${iconSize}px`;
1960
+ icon.style.height = `${iconSize}px`;
1961
+ icon.style.alignItems = "center";
1962
+ icon.style.justifyContent = "center";
1963
+ icon.style.flex = "0 0 auto";
1964
+ if (status === "running") {
1965
+ icon.style.border = "2px solid rgba(71, 85, 105, 0.32)";
1966
+ icon.style.borderTopColor = "#64748b";
1967
+ icon.style.borderRadius = "999px";
1968
+ icon.style.animation = "chatkit-pet-summary-spin 900ms linear infinite";
1969
+ return icon;
1970
+ }
1971
+ icon.style.borderRadius = "999px";
1972
+ icon.style.fontSize = `${Math.max(10, iconSize - 4)}px`;
1973
+ icon.style.fontWeight = "700";
1974
+ if (status === "failed") {
1975
+ icon.textContent = "!";
1976
+ icon.style.background = "#fee2e2";
1977
+ icon.style.color = "#b91c1c";
1978
+ return icon;
1979
+ }
1980
+ icon.textContent = "";
1981
+ icon.style.border = "2px solid #22c55e";
1982
+ icon.style.position = "relative";
1983
+ const check = document.createElement("span");
1984
+ check.style.width = `${Math.round(iconSize * 0.44)}px`;
1985
+ check.style.height = `${Math.round(iconSize * 0.25)}px`;
1986
+ check.style.borderLeft = "2px solid #22c55e";
1987
+ check.style.borderBottom = "2px solid #22c55e";
1988
+ check.style.transform = "rotate(-45deg) translate(1px, -1px)";
1989
+ icon.append(check);
1990
+ return icon;
1991
+ }
1992
+ createSummaryActionButton(label, title, onClick) {
1993
+ const metrics = getSummaryThemeMetrics(this.theme);
1994
+ const button = document.createElement("button");
1995
+ button.type = "button";
1996
+ button.textContent = label;
1997
+ button.title = title;
1998
+ button.addEventListener("click", (event) => {
1999
+ event.preventDefault();
2000
+ event.stopPropagation();
2001
+ onClick();
2002
+ });
2003
+ button.style.width = `${metrics.actionSize}px`;
2004
+ button.style.height = `${metrics.actionSize}px`;
2005
+ button.style.border = "0";
2006
+ button.style.borderRadius = "999px";
2007
+ button.style.background = "rgba(241, 245, 249, 0.96)";
2008
+ button.style.color = "#475569";
2009
+ button.style.cursor = "pointer";
2010
+ button.style.font = `600 ${metrics.titleSize}px/1 ${metrics.fontFamily}`;
2011
+ return button;
2012
+ }
2013
+ createTextButton(label, onClick) {
2014
+ const button = document.createElement("button");
2015
+ button.type = "button";
2016
+ button.textContent = label;
2017
+ button.addEventListener("click", (event) => {
2018
+ event.preventDefault();
2019
+ event.stopPropagation();
2020
+ onClick();
2021
+ });
2022
+ button.style.border = "1px solid rgba(148, 163, 184, 0.28)";
2023
+ button.style.borderRadius = "999px";
2024
+ button.style.background = "rgba(248, 250, 252, 0.95)";
2025
+ button.style.color = "#334155";
2026
+ button.style.cursor = "pointer";
2027
+ button.style.padding = "3px 10px";
2028
+ button.style.font = '600 12px/1.4 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2029
+ return button;
2030
+ }
2031
+ createReplyForm() {
2032
+ const form = document.createElement("form");
2033
+ form.addEventListener("click", stopEventPropagation);
2034
+ form.addEventListener("submit", this.handleReplySubmit);
2035
+ form.addEventListener("keydown", this.handleReplyKeyDown);
2036
+ form.style.display = "flex";
2037
+ form.style.gap = "6px";
2038
+ form.style.alignItems = "center";
2039
+ form.style.marginTop = "8px";
2040
+ const input = document.createElement("input");
2041
+ input.type = "text";
2042
+ input.value = this.replyDraft;
2043
+ input.disabled = this.isReplySubmitting;
2044
+ input.placeholder = this.copy.replyPlaceholder;
2045
+ input.addEventListener("input", this.handleReplyInput);
2046
+ input.style.minWidth = "0";
2047
+ input.style.flex = "1";
2048
+ input.style.border = "1px solid rgba(148, 163, 184, 0.35)";
2049
+ input.style.borderRadius = "999px";
2050
+ input.style.padding = "6px 10px";
2051
+ input.style.font = '400 13px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2052
+ this.replyInputElement = input;
2053
+ const send = document.createElement("button");
2054
+ send.type = "submit";
2055
+ send.textContent = this.isReplySubmitting ? this.copy.sendingButton : this.copy.sendButton;
2056
+ send.disabled = this.isReplySubmitting;
2057
+ send.style.border = "0";
2058
+ send.style.borderRadius = "999px";
2059
+ send.style.background = "#22c55e";
2060
+ send.style.color = "#052e16";
2061
+ send.style.cursor = this.isReplySubmitting ? "default" : "pointer";
2062
+ send.style.padding = "6px 10px";
2063
+ send.style.font = '700 12px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2064
+ form.append(input, send);
2065
+ if (this.replyError) {
2066
+ const error = document.createElement("div");
2067
+ error.textContent = this.copy.sendFailed;
2068
+ error.style.flexBasis = "100%";
2069
+ error.style.color = "#b91c1c";
2070
+ error.style.fontSize = "12px";
2071
+ form.style.flexWrap = "wrap";
2072
+ form.append(error);
2073
+ }
2074
+ return form;
2075
+ }
2076
+ createContextMenu() {
2077
+ const menu = document.createElement("div");
2078
+ menu.setAttribute("data-chatkit-pet-context-menu", "");
2079
+ menu.setAttribute("role", "menu");
2080
+ menu.addEventListener("contextmenu", this.handleContextMenuEvent);
2081
+ menu.addEventListener("pointerdown", stopEventPropagation);
2082
+ menu.addEventListener("click", stopEventPropagation);
2083
+ menu.style.position = "absolute";
2084
+ menu.style.top = "0";
2085
+ menu.style.left = "0";
2086
+ menu.style.boxSizing = "border-box";
2087
+ menu.style.minWidth = "132px";
2088
+ menu.style.padding = "4px";
2089
+ menu.style.pointerEvents = "auto";
2090
+ menu.style.border = "1px solid rgba(148, 163, 184, 0.28)";
2091
+ menu.style.borderRadius = "10px";
2092
+ menu.style.background = "rgba(255, 255, 255, 0.96)";
2093
+ menu.style.color = "#1f2937";
2094
+ menu.style.boxShadow = "0 12px 28px rgba(15, 23, 42, 0.16)";
2095
+ menu.style.font = '500 13px/1.3 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2096
+ menu.style.backdropFilter = "blur(10px)";
2097
+ const closeItem = document.createElement("button");
2098
+ closeItem.type = "button";
2099
+ closeItem.textContent = this.copy.closePetMenuItem;
2100
+ closeItem.setAttribute("role", "menuitem");
2101
+ closeItem.addEventListener("click", this.handleClosePetMenuItemClick);
2102
+ closeItem.style.display = "block";
2103
+ closeItem.style.width = "100%";
2104
+ closeItem.style.border = "0";
2105
+ closeItem.style.borderRadius = "7px";
2106
+ closeItem.style.background = "transparent";
2107
+ closeItem.style.color = "inherit";
2108
+ closeItem.style.cursor = "pointer";
2109
+ closeItem.style.padding = "7px 10px";
2110
+ closeItem.style.textAlign = "left";
2111
+ closeItem.style.font = "inherit";
2112
+ menu.append(closeItem);
2113
+ return menu;
2114
+ }
2115
+ openContextMenu(position) {
2116
+ var _a2;
2117
+ const overlay = this.overlayElement;
2118
+ if (!overlay) {
2119
+ return;
2120
+ }
2121
+ this.closeContextMenu();
2122
+ const menu = this.createContextMenu();
2123
+ overlay.append(menu);
2124
+ this.contextMenuElement = menu;
2125
+ this.positionContextMenu(position);
2126
+ (_a2 = menu.querySelector("button")) == null ? void 0 : _a2.focus({ preventScroll: true });
2127
+ window.addEventListener(
2128
+ "pointerdown",
2129
+ this.handleContextMenuOutsidePointerDown,
2130
+ true
2131
+ );
2132
+ window.addEventListener("keydown", this.handleContextMenuKeyDown);
2133
+ }
2134
+ closeContextMenu() {
2135
+ var _a2;
2136
+ (_a2 = this.contextMenuElement) == null ? void 0 : _a2.remove();
2137
+ this.contextMenuElement = null;
2138
+ window.removeEventListener(
2139
+ "pointerdown",
2140
+ this.handleContextMenuOutsidePointerDown,
2141
+ true
2142
+ );
2143
+ window.removeEventListener("keydown", this.handleContextMenuKeyDown);
2144
+ }
2145
+ positionContextMenu(position) {
2146
+ const menu = this.contextMenuElement;
2147
+ if (!menu) {
2148
+ return;
2149
+ }
2150
+ const viewport = getViewportSize();
2151
+ const width = menu.offsetWidth || 132;
2152
+ const height = menu.offsetHeight || 40;
2153
+ const maxX = Math.max(
2154
+ PET_CONTEXT_MENU_MARGIN,
2155
+ viewport.width - width - PET_CONTEXT_MENU_MARGIN
2156
+ );
2157
+ const maxY = Math.max(
2158
+ PET_CONTEXT_MENU_MARGIN,
2159
+ viewport.height - height - PET_CONTEXT_MENU_MARGIN
2160
+ );
2161
+ const x = clampNumber(position.x, PET_CONTEXT_MENU_MARGIN, maxX);
2162
+ const y = clampNumber(position.y, PET_CONTEXT_MENU_MARGIN, maxY);
2163
+ menu.style.transform = `translate3d(${x}px, ${y}px, 0)`;
2164
+ }
2165
+ renderAtlas(animationName, animationMode) {
2166
+ var _a2;
2167
+ if (!this.petElement || ((_a2 = this.resolved) == null ? void 0 : _a2.kind) !== "atlas" || !this.options) {
2168
+ return;
2169
+ }
2170
+ if (!(this.mediaElement instanceof HTMLDivElement)) {
2171
+ const frame = document.createElement("div");
2172
+ frame.setAttribute("aria-hidden", "true");
2173
+ this.petElement.replaceChildren(frame);
2174
+ this.mediaElement = frame;
2175
+ }
2176
+ const frameElement = this.mediaElement;
2177
+ const atlas = this.resolved.atlas;
2178
+ const definition = atlas.animations[animationName] ?? atlas.animations.idle;
2179
+ const safeFrame = animationMode === "once" && this.completed ? Math.max(0, definition.frames - 1) : Math.min(this.frame, Math.max(0, definition.frames - 1));
2180
+ const scale = getRenderScale(this.options.position.scale);
2181
+ const sourceWidth = atlas.cellWidth;
2182
+ const sourceHeight = atlas.cellHeight;
2183
+ const backgroundWidth = atlas.columns * sourceWidth;
2184
+ const backgroundHeight = atlas.rows * sourceHeight;
2185
+ frameElement.style.width = `${sourceWidth}px`;
2186
+ frameElement.style.height = `${sourceHeight}px`;
2187
+ frameElement.style.overflow = "hidden";
2188
+ frameElement.style.transform = `scale(${scale})`;
2189
+ frameElement.style.transformOrigin = "top left";
2190
+ frameElement.style.pointerEvents = "none";
2191
+ frameElement.style.backgroundImage = `url("${escapeCssUrl(
2192
+ this.resolved.src
2193
+ )}")`;
2194
+ frameElement.style.backgroundRepeat = "no-repeat";
2195
+ frameElement.style.backgroundSize = `${backgroundWidth}px ${backgroundHeight}px`;
2196
+ frameElement.style.backgroundPosition = `${-safeFrame * sourceWidth}px ${-definition.row * sourceHeight}px`;
2197
+ frameElement.style.imageRendering = this.options.imageRendering;
2198
+ frameElement.dataset.petFrame = String(safeFrame);
2199
+ }
2200
+ scheduleNextFrame(animationName, animationMode) {
2201
+ if (this.prefersReducedMotion || this.completed || !this.resolved) {
2202
+ this.clearTimers();
2203
+ return;
2204
+ }
2205
+ if (this.frameTimer !== null) {
2206
+ return;
2207
+ }
2208
+ const atlas = this.resolved.atlas;
2209
+ const definition = atlas.animations[animationName] ?? atlas.animations.idle;
2210
+ const duration = definition.frameDurations[this.frame] ?? definition.frameDurations[definition.frameDurations.length - 1] ?? 150;
2211
+ const baseDuration = duration * PET_FRAME_DURATION_MULTIPLIER;
2212
+ const effectiveDuration = this.isHovering || this.isDragging ? baseDuration : baseDuration * PET_RESTING_FRAME_DURATION_MULTIPLIER;
2213
+ this.frameTimer = window.setTimeout(() => {
2214
+ this.frameTimer = null;
2215
+ const nextFrame = this.frame + 1;
2216
+ if (nextFrame >= definition.frames) {
2217
+ if (animationMode === "once") {
2218
+ this.completed = true;
2219
+ this.frame = Math.max(0, definition.frames - 1);
2220
+ this.finishTransient();
2221
+ return;
2222
+ }
2223
+ this.frame = 0;
2224
+ this.render();
2225
+ return;
2226
+ }
2227
+ this.frame = nextFrame;
2228
+ this.render();
2229
+ }, effectiveDuration);
2230
+ }
2231
+ clearTimers() {
2232
+ if (this.frameTimer !== null) {
2233
+ window.clearTimeout(this.frameTimer);
2234
+ this.frameTimer = null;
2235
+ }
2236
+ }
2237
+ clearRestingDelayTimer() {
2238
+ if (this.restingDelayTimer !== null) {
2239
+ window.clearTimeout(this.restingDelayTimer);
2240
+ this.restingDelayTimer = null;
2241
+ }
2242
+ }
2243
+ finishTransient() {
2244
+ this.transient = null;
2245
+ this.activeAnimationName = null;
2246
+ this.activeAnimationMode = null;
2247
+ this.render();
2248
+ }
2249
+ rescheduleAnimation() {
2250
+ this.clearTimers();
2251
+ this.render();
2252
+ }
2253
+ enterRestingAfterDelay() {
2254
+ this.clearRestingDelayTimer();
2255
+ this.isHovering = true;
2256
+ this.restingDelayTimer = window.setTimeout(() => {
2257
+ this.restingDelayTimer = null;
2258
+ if (this.isDragging) {
2259
+ return;
2260
+ }
2261
+ this.isHovering = false;
2262
+ this.rescheduleAnimation();
2263
+ }, PET_RESTING_DELAY_MS);
2264
+ }
2265
+ isPointOverPet(clientX, clientY) {
2266
+ var _a2;
2267
+ const rect = (_a2 = this.petElement) == null ? void 0 : _a2.getBoundingClientRect();
2268
+ if (!rect) {
2269
+ return false;
2270
+ }
2271
+ return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
2272
+ }
2273
+ isPointerOverPet(event) {
2274
+ return this.isPointOverPet(event.clientX, event.clientY);
2275
+ }
2276
+ async submitReply() {
2277
+ var _a2;
2278
+ const text = this.replyDraft.trim();
2279
+ if (!text || this.isReplySubmitting) {
2280
+ return;
2281
+ }
2282
+ this.isReplySubmitting = true;
2283
+ this.replyError = null;
2284
+ this.render();
2285
+ try {
2286
+ await ((_a2 = this.onReply) == null ? void 0 : _a2.call(this, text));
2287
+ this.replyDraft = "";
2288
+ this.isReplyOpen = false;
2289
+ this.isSummaryHovering = false;
2290
+ } catch {
2291
+ this.replyError = "Failed to send";
2292
+ } finally {
2293
+ this.isReplySubmitting = false;
2294
+ this.render();
2295
+ }
2296
+ }
2297
+ getNextDragPosition(event) {
2298
+ if (!this.options) {
2299
+ return { x: 0, y: 0 };
2300
+ }
2301
+ return chatkitTypes.clampPetPosition(
2302
+ {
2303
+ x: event.clientX - this.dragOffset.x,
2304
+ y: event.clientY - this.dragOffset.y
2305
+ },
2306
+ this.getSize(),
2307
+ getViewportSize(),
2308
+ chatkitTypes.normalizeBoundsPadding(this.options.position.boundsPadding)
2309
+ );
2310
+ }
2311
+ installDragListeners() {
2312
+ window.addEventListener("pointermove", this.handlePointerMove);
2313
+ window.addEventListener("pointerup", this.handlePointerUp, { once: true });
2314
+ window.addEventListener("pointercancel", this.handlePointerUp, {
2315
+ once: true
2316
+ });
2317
+ }
2318
+ removeDragListeners() {
2319
+ window.removeEventListener("pointermove", this.handlePointerMove);
2320
+ window.removeEventListener("pointerup", this.handlePointerUp);
2321
+ window.removeEventListener("pointercancel", this.handlePointerUp);
2322
+ }
2323
+ }
2324
+ function getInnerOptions(options) {
2325
+ return removeMethods(options);
2326
+ }
2327
+ function requireCommandCapability(value, context) {
2328
+ const command = String(context.name);
2329
+ return function(...args) {
2330
+ if (!this.capabilities.commands.has(command)) {
2331
+ throw new IntegrationError(
2332
+ `ChatKit command "${String(command)}" is not available for the "${this.profile}" profile.`
2333
+ );
2334
+ }
2335
+ return value.apply(this, args);
2336
+ };
2337
+ }
2338
+ 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) {
2339
+ constructor({ profile }) {
2340
+ super();
2341
+ __runInitializers(_init, 5, this);
2342
+ __privateAdd(this, _ChatKitElementBase_instances);
2343
+ __privateAdd(this, _opts);
2344
+ __privateAdd(this, _frameUrl);
2345
+ __privateAdd(this, _frame);
2346
+ __privateAdd(this, _wrapper);
2347
+ __privateAdd(this, _launcherCloseButton);
2348
+ __privateAdd(this, _launcherOpen, false);
2349
+ __privateAdd(this, _chatMinimizedToPet, false);
2350
+ __privateAdd(this, _framePetOptionsOverride);
2351
+ __privateAdd(this, _petClosedByContextMenu, false);
2352
+ __privateAdd(this, _shadow, this.attachShadow({ mode: "open" }));
2353
+ __privateAdd(this, _petOverlay, new PetOverlay(__privateGet(this, _shadow), {
2354
+ onActivate: () => __privateMethod(this, _ChatKitElementBase_instances, handlePetActivate_fn).call(this),
2355
+ onClose: () => __privateMethod(this, _ChatKitElementBase_instances, handlePetClose_fn).call(this),
2356
+ onReply: (text) => __privateMethod(this, _ChatKitElementBase_instances, handlePetReply_fn).call(this, text),
2357
+ onThreadSummaryActivate: (threadId) => void __privateMethod(this, _ChatKitElementBase_instances, handlePetThreadSummaryActivate_fn).call(this, threadId)
2358
+ }));
2359
+ __privateAdd(this, _resolveLoaded);
2360
+ __privateAdd(this, _loaded, new Promise((resolve) => {
2361
+ __privateSet(this, _resolveLoaded, resolve);
2362
+ }));
2363
+ __privateAdd(this, _messenger, new ChatFrameMessenger({
2364
+ fetch: (...args) => {
2365
+ var _a2;
2366
+ const customFetch = ((_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.api) && "fetch" in __privateGet(this, _opts).api && __privateGet(this, _opts).api.fetch;
2367
+ return customFetch ? customFetch(...args) : fetch(...args);
2368
+ },
2369
+ target: () => {
2370
+ var _a2;
2371
+ return ((_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.contentWindow) ?? null;
2372
+ },
2373
+ targetOrigin: window.location.origin,
2374
+ handlers: {
2375
+ onFileInputClick: ({
2376
+ inputAttributes
2377
+ }) => {
2378
+ return new Promise((resolve) => {
2379
+ const input = document.createElement("input");
2380
+ for (const [key, value] of Object.entries(inputAttributes)) {
2381
+ input.setAttribute(key, String(value));
2382
+ }
2383
+ const respond = () => {
2384
+ resolve(Array.from(input.files || []));
2385
+ if (__privateGet(this, _shadow).contains(input)) {
2386
+ __privateGet(this, _shadow).removeChild(input);
2387
+ }
2388
+ };
2389
+ input.addEventListener("cancel", respond);
2390
+ input.addEventListener("change", respond);
2391
+ __privateGet(this, _shadow).appendChild(input);
2392
+ input.click();
2393
+ });
2394
+ },
2395
+ onClientToolCall: async ({
2396
+ name,
2397
+ params,
2398
+ id,
2399
+ tool_call_id
2400
+ }) => {
2401
+ var _a2;
2402
+ const onClientTool = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.onClientTool;
2403
+ if (!onClientTool) {
2404
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError(
2405
+ `No handler for client tool calls. You'll need to add onClientTool to your ChatKit options.`
2406
+ ));
2407
+ }
2408
+ return onClientTool({ name, params, id, tool_call_id });
2409
+ },
2410
+ onWidgetAction: async ({
2411
+ action,
2412
+ widgetItem
2413
+ }) => {
2414
+ var _a2, _b2;
2415
+ const onAction = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.widgets) == null ? void 0 : _b2.onAction;
2416
+ if (!onAction) {
2417
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError(
2418
+ `No handler for widget actions. You'll need to add widgets.onAction to your ChatKit options.`
2419
+ ));
2420
+ }
2421
+ return onAction(action, widgetItem);
2422
+ },
2423
+ onEntitySearch: async ({ query }) => {
2424
+ var _a2, _b2, _c2;
2425
+ return ((_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onTagSearch) == null ? void 0 : _c2.call(_b2, query)) ?? [];
2426
+ },
2427
+ onEntityClick: async ({ entity }) => {
2428
+ var _a2, _b2, _c2;
2429
+ return (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onClick) == null ? void 0 : _c2.call(_b2, entity);
2430
+ },
2431
+ onEntityPreview: async ({ entity }) => {
2432
+ var _a2, _b2, _c2;
2433
+ 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 };
2434
+ },
2435
+ onGetClientSecret: async (currentClientSecret) => {
2436
+ if (!__privateGet(this, _opts) || !("getClientSecret" in __privateGet(this, _opts).api) || !__privateGet(this, _opts).api.getClientSecret) {
2437
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError(
2438
+ "Could not refresh the session because ChatKitOptions.api.getClientSecret is not configured."
2439
+ ));
2440
+ }
2441
+ return __privateGet(this, _opts).api.getClientSecret(currentClientSecret ?? null);
2442
+ },
2443
+ onAddMetadataToRequest: ({
2444
+ op,
2445
+ params
2446
+ }) => {
2447
+ throw new IntegrationError(
2448
+ "ChatKit: onAddMetadataToRequest is unimplemented."
2449
+ );
2450
+ }
2451
+ }
2452
+ }));
2453
+ __privateAdd(this, _handleLauncherClose, () => {
2454
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2455
+ });
2456
+ __privateAdd(this, _handleFrameLoad, () => {
2457
+ var _a2;
2458
+ this.dataset.loaded = "true";
2459
+ this.dispatchEvent(
2460
+ new CustomEvent("chatkit.ready", { bubbles: true, composed: true })
2461
+ );
2462
+ (_a2 = __privateGet(this, _resolveLoaded)) == null ? void 0 : _a2.call(this);
2463
+ });
2464
+ __privateAdd(this, _initialized, false);
2465
+ this.profile = profile;
2466
+ this.capabilities = getCapabilities(profile);
2467
+ }
2468
+ setProfile(profile) {
2469
+ this.profile = profile;
2470
+ this.capabilities = getCapabilities(profile);
2471
+ }
2472
+ connectedCallback() {
2473
+ __privateGet(this, _petOverlay).connect();
2474
+ const style = document.createElement("style");
2475
+ style.textContent = `
2476
+ :host {
2477
+ display: block;
2478
+ position: relative;
2479
+ height: 100%;
2480
+ width: 100%;
2481
+ overflow: visible;
2482
+ }
2483
+ :host([data-display-mode="pet"]) {
2484
+ display: contents;
2485
+ }
2486
+ :host([data-chat-minimized-to-pet="true"]) {
2487
+ display: contents;
2488
+ }
2489
+ .ck-iframe {
2490
+ border: none;
2491
+ position: absolute;
2492
+ inset: 0;
2493
+ width: 100%;
2494
+ height: 100%;
2495
+ overflow: hidden;
2496
+ color-scheme: light only;
2497
+ }
2498
+ .ck-wrapper {
2499
+ position: absolute;
2500
+ inset: 0;
2501
+ width: 100%;
2502
+ height: 100%;
2503
+ overflow: hidden;
2504
+ opacity: 0;
2505
+ }
2506
+ .ck-launcher-close {
2507
+ display: none;
2508
+ }
2509
+ :host([data-display-mode="pet"]) .ck-wrapper {
2510
+ position: fixed;
2511
+ inset: auto 16px 16px auto;
2512
+ width: min(420px, calc(100vw - 32px));
2513
+ height: min(720px, calc(100vh - 32px));
2514
+ max-height: calc(100vh - 32px);
2515
+ overflow: visible;
2516
+ border: 1px solid rgba(148, 163, 184, 0.35);
2517
+ border-radius: 18px;
2518
+ background: Canvas;
2519
+ box-shadow:
2520
+ 0 24px 80px rgba(15, 23, 42, 0.22),
2521
+ 0 0 0 1px rgba(15, 23, 42, 0.04);
2522
+ opacity: 0;
2523
+ pointer-events: none;
2524
+ transform: translateY(12px) scale(0.98);
2525
+ transition:
2526
+ opacity 160ms ease,
2527
+ transform 160ms ease;
2528
+ z-index: 39;
2529
+ }
2530
+ :host([data-display-mode="pet"][data-chat-open="true"]) .ck-wrapper {
2531
+ opacity: 1;
2532
+ pointer-events: auto;
2533
+ transform: translateY(0) scale(1);
2534
+ }
2535
+ :host([data-display-mode="pet"]) .ck-iframe {
2536
+ border-radius: inherit;
2537
+ }
2538
+ :host([data-display-mode="pet"]) .ck-launcher-close {
2539
+ display: inline-flex;
2540
+ position: absolute;
2541
+ top: -10px;
2542
+ right: -10px;
2543
+ z-index: 2;
2544
+ width: 28px;
2545
+ height: 28px;
2546
+ align-items: center;
2547
+ justify-content: center;
2548
+ border: 1px solid rgba(148, 163, 184, 0.45);
2549
+ border-radius: 999px;
2550
+ background: rgba(255, 255, 255, 0.96);
2551
+ color: #475569;
2552
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18);
2553
+ cursor: pointer;
2554
+ font: inherit;
2555
+ font-size: 0;
2556
+ line-height: 1;
2557
+ }
2558
+ :host([data-display-mode="pet"]) .ck-launcher-close::before,
2559
+ :host([data-display-mode="pet"]) .ck-launcher-close::after {
2560
+ content: '';
2561
+ position: absolute;
2562
+ top: 50%;
2563
+ left: 50%;
2564
+ width: 14px;
2565
+ height: 2px;
2566
+ border-radius: 999px;
2567
+ background: currentColor;
2568
+ transform: translate(-50%, -50%) rotate(45deg);
2569
+ }
2570
+ :host([data-display-mode="pet"]) .ck-launcher-close::after {
2571
+ transform: translate(-50%, -50%) rotate(-45deg);
2572
+ }
2573
+ :host([data-display-mode="pet"]) .ck-launcher-close:hover {
2574
+ background: #fff;
2575
+ color: #0f172a;
2576
+ }
2577
+ :host([data-color-scheme="dark"]) .ck-iframe {
2578
+ color-scheme: dark only;
2579
+ }
2580
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-wrapper {
2581
+ border-color: rgba(148, 163, 184, 0.28);
2582
+ background: #020617;
2583
+ box-shadow:
2584
+ 0 24px 80px rgba(0, 0, 0, 0.5),
2585
+ 0 0 0 1px rgba(255, 255, 255, 0.06);
2586
+ }
2587
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-launcher-close {
2588
+ background: rgba(15, 23, 42, 0.88);
2589
+ border-color: rgba(148, 163, 184, 0.32);
2590
+ color: #cbd5e1;
2591
+ }
2592
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-launcher-close:hover {
2593
+ background: #1e293b;
2594
+ color: #f8fafc;
2595
+ }
2596
+ :host([data-loaded="true"]) .ck-wrapper {
2597
+ opacity: 1;
2598
+ }
2599
+ :host([data-chat-minimized-to-pet="true"]) .ck-wrapper {
2600
+ opacity: 0;
2601
+ pointer-events: none;
2602
+ visibility: hidden;
2603
+ }
2604
+ :host([data-display-mode="pet"]:not([data-chat-open="true"])) .ck-wrapper {
2605
+ opacity: 0;
2606
+ }
2607
+ @media (max-width: 520px) {
2608
+ :host([data-display-mode="pet"]) .ck-wrapper {
2609
+ inset: auto 8px 8px 8px;
2610
+ width: auto;
2611
+ height: min(680px, calc(100vh - 16px));
2612
+ max-height: calc(100vh - 16px);
2613
+ border-radius: 16px;
2614
+ }
2615
+ :host([data-display-mode="pet"]) .ck-launcher-close {
2616
+ top: -8px;
2617
+ right: 8px;
2618
+ }
2619
+ }
2620
+ `;
2621
+ const frame = document.createElement("iframe");
2622
+ frame.className = "ck-iframe";
2623
+ frame.name = "chatkit";
2624
+ frame.role = "presentation";
2625
+ frame.tabIndex = 0;
2626
+ frame.setAttribute("allowtransparency", "true");
2627
+ frame.setAttribute("frameborder", "0");
2628
+ frame.setAttribute("scrolling", "no");
2629
+ frame.setAttribute("allow", "clipboard-read; clipboard-write");
2630
+ __privateSet(this, _frame, frame);
2631
+ const wrapper = document.createElement("div");
2632
+ wrapper.className = "ck-wrapper";
2633
+ wrapper.appendChild(frame);
2634
+ __privateSet(this, _wrapper, wrapper);
2635
+ const closeButton = document.createElement("button");
2636
+ closeButton.className = "ck-launcher-close";
2637
+ closeButton.type = "button";
2638
+ closeButton.setAttribute("aria-label", "Close chat");
2639
+ closeButton.addEventListener("click", __privateGet(this, _handleLauncherClose));
2640
+ wrapper.appendChild(closeButton);
2641
+ __privateSet(this, _launcherCloseButton, closeButton);
2642
+ __privateGet(this, _shadow).append(style);
2643
+ __privateGet(this, _messenger).on("left_header_icon_click", () => {
2644
+ var _a2, _b2, _c2;
2645
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.leftAction) == null ? void 0 : _c2.onClick();
2646
+ });
2647
+ __privateGet(this, _messenger).on("right_header_icon_click", () => {
2648
+ var _a2, _b2, _c2;
2649
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.rightAction) == null ? void 0 : _c2.onClick();
2650
+ });
2651
+ __privateGet(this, _messenger).on("public_event", ([event, data]) => {
2652
+ if (event === "log") {
2653
+ const payload = parseThreadSummaryLogPayload(data);
2654
+ if (payload) {
2655
+ __privateGet(this, _petOverlay).setThreadSummary(payload.summary);
2656
+ }
2657
+ } else if (event === "response.start") {
2658
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("running");
2659
+ } else if (event === "response.end") {
2660
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("completed");
2661
+ } else if (event === "response.stop") {
2662
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("completed");
2663
+ }
2664
+ if (!this.capabilities.events.has(event)) return;
2665
+ if (event === "error" && "error" in data) {
2666
+ const error = fromPossibleFrameSafeError(data.error);
2667
+ this.dispatchEvent(
2668
+ new CustomEvent("chatkit.error", { detail: { error } })
2669
+ );
2670
+ if (error instanceof IntegrationError) {
2671
+ throw error;
2672
+ }
2673
+ return;
2674
+ }
2675
+ this.dispatchEvent(new CustomEvent(`chatkit.${event}`, { detail: data }));
2676
+ });
2677
+ __privateGet(this, _messenger).on("pet_state_change", (data) => {
2678
+ const payload = parsePetStateChangePayload(data);
2679
+ if (payload) {
2680
+ __privateGet(this, _petOverlay).setState(payload.state);
2681
+ }
2682
+ });
2683
+ __privateGet(this, _messenger).on("pet_options_change", (data) => {
2684
+ const payload = parsePetOptionsChangePayload(data);
2685
+ if (payload) {
2686
+ if (!__privateGet(this, _petClosedByContextMenu) || payload.pet === null) {
2687
+ __privateSet(this, _petClosedByContextMenu, false);
2688
+ }
2689
+ __privateSet(this, _framePetOptionsOverride, payload.pet);
2690
+ __privateMethod(this, _ChatKitElementBase_instances, syncPetOverlayOptions_fn).call(this);
2691
+ }
2692
+ });
2693
+ __privateGet(this, _messenger).on("chat_minimize_change", (data) => {
2694
+ const minimized = typeof data === "object" && data !== null && "minimized" in data && data.minimized === true;
2695
+ if (minimized && !__privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this)) {
2696
+ return;
2697
+ }
2698
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, minimized);
2699
+ if (minimized) {
2700
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2701
+ }
2702
+ });
2703
+ __privateGet(this, _messenger).on("unmount", () => {
2704
+ if (__privateGet(this, _wrapper) && __privateGet(this, _shadow).contains(__privateGet(this, _wrapper))) {
2705
+ __privateGet(this, _shadow).removeChild(__privateGet(this, _wrapper));
2706
+ __privateSet(this, _wrapper, void 0);
2707
+ __privateSet(this, _frame, void 0);
2708
+ }
2709
+ });
2710
+ __privateGet(this, _messenger).on(
2711
+ "capabilities_profile_change",
2712
+ ({ profile }) => {
2713
+ this.setProfile(profile);
2714
+ }
2715
+ );
2716
+ frame.addEventListener("load", __privateGet(this, _handleFrameLoad), { once: true });
2717
+ try {
2718
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
2719
+ } catch (error) {
2720
+ console.error(error);
2721
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError("Failed to initialize ChatKit"));
2722
+ }
2723
+ }
2724
+ disconnectedCallback() {
2725
+ var _a2, _b2;
2726
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.removeEventListener("load", __privateGet(this, _handleFrameLoad));
2727
+ (_b2 = __privateGet(this, _launcherCloseButton)) == null ? void 0 : _b2.removeEventListener(
2728
+ "click",
2729
+ __privateGet(this, _handleLauncherClose)
2730
+ );
2731
+ __privateGet(this, _messenger).disconnect();
2732
+ __privateGet(this, _petOverlay).destroy();
2733
+ }
2734
+ applySanitizedOptions(newOptions) {
2735
+ __privateSet(this, _opts, newOptions);
2736
+ __privateSet(this, _petClosedByContextMenu, false);
2737
+ __privateGet(this, _petOverlay).setLocale(newOptions.locale);
2738
+ __privateMethod(this, _ChatKitElementBase_instances, syncPetOverlayOptions_fn).call(this);
2739
+ if (__privateGet(this, _initialized)) {
2740
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
2741
+ __privateGet(this, _loaded).then(() => {
2742
+ __privateGet(this, _messenger).commands.setOptions(
2743
+ getInnerOptions(__privateMethod(this, _ChatKitElementBase_instances, getFrameOptions_fn).call(this, newOptions))
2744
+ );
2745
+ });
2746
+ } else {
2747
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
2748
+ }
2749
+ }
2750
+ setOptions(newOptions) {
2751
+ try {
2752
+ const sanitized = this.sanitizeOptions(newOptions);
2753
+ __privateMethod(this, _ChatKitElementBase_instances, consumeFrameUrl_fn).call(this, sanitized);
2754
+ this.applySanitizedOptions(sanitized);
2755
+ } catch (error) {
2756
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError("Failed to parse options"));
2757
+ }
2758
+ }
2759
+ async focusComposer() {
2760
+ var _a2, _b2;
2761
+ await __privateGet(this, _loaded);
2762
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.focus();
2763
+ await ((_b2 = __privateGet(this, _messenger)) == null ? void 0 : _b2.commands.focusComposer());
2764
+ }
2765
+ async fetchUpdates() {
2766
+ var _a2;
2767
+ await __privateGet(this, _loaded);
2768
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.fetchUpdates());
2769
+ }
2770
+ async sendUserMessage(params) {
2771
+ var _a2;
2772
+ await __privateGet(this, _loaded);
2773
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendUserMessage(params));
2774
+ }
2775
+ async setComposerValue(params) {
2776
+ var _a2;
2777
+ await __privateGet(this, _loaded);
2778
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setComposerValue(params));
2779
+ }
2780
+ async setThreadId(threadId) {
2781
+ var _a2;
2782
+ await __privateGet(this, _loaded);
2783
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setThreadId({ threadId }));
2784
+ }
2785
+ async shareThread() {
2786
+ var _a2;
2787
+ await __privateGet(this, _loaded);
2788
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.shareThread();
2789
+ }
2790
+ async sendCustomAction(action, itemId) {
2791
+ var _a2;
2792
+ await __privateGet(this, _loaded);
2793
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendCustomAction({ action, itemId });
2794
+ }
2795
+ async showHistory() {
2796
+ var _a2;
2797
+ await __privateGet(this, _loaded);
2798
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.showHistory();
2799
+ }
2800
+ async hideHistory() {
2801
+ var _a2;
2802
+ await __privateGet(this, _loaded);
2803
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.hideHistory();
2804
+ }
2805
+ async setTrainingOptOut(value) {
2806
+ var _a2;
2807
+ await __privateGet(this, _loaded);
2808
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setTrainingOptOut({ value });
2809
+ }
2810
+ }
2811
+ _init = __decoratorStart(_c);
2812
+ _opts = new WeakMap();
2813
+ _frameUrl = new WeakMap();
2814
+ _frame = new WeakMap();
2815
+ _wrapper = new WeakMap();
2816
+ _launcherCloseButton = new WeakMap();
2817
+ _launcherOpen = new WeakMap();
2818
+ _chatMinimizedToPet = new WeakMap();
2819
+ _framePetOptionsOverride = new WeakMap();
2820
+ _petClosedByContextMenu = new WeakMap();
2821
+ _shadow = new WeakMap();
2822
+ _petOverlay = new WeakMap();
2823
+ _resolveLoaded = new WeakMap();
2824
+ _loaded = new WeakMap();
2825
+ _messenger = new WeakMap();
2826
+ _ChatKitElementBase_instances = new WeakSet();
2827
+ emitAndThrow_fn = function(error) {
2828
+ this.dispatchEvent(new CustomEvent("chatkit.error", { detail: { error } }));
2829
+ throw error;
2830
+ };
2831
+ setOptionsDataAttributes_fn = function(options) {
2832
+ var _a2;
2833
+ this.dataset.colorScheme = typeof options.theme === "string" ? options.theme : ((_a2 = options.theme) == null ? void 0 : _a2.colorScheme) ?? "light";
2834
+ this.dataset.displayMode = __privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options);
2835
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options) !== "pet") {
2836
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2837
+ }
2838
+ };
2839
+ getDisplayMode_fn = function(options = __privateGet(this, _opts)) {
2840
+ return (options == null ? void 0 : options.displayMode) === "pet" ? "pet" : "chat";
2841
+ };
2842
+ getConfiguredPetOptions_fn = function(options = __privateGet(this, _opts)) {
2843
+ if (!options) {
2844
+ return null;
2845
+ }
2846
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options) === "pet" && !chatkitTypes.normalizePetOptions(options.pet ?? null)) {
2847
+ return true;
2848
+ }
2849
+ return options.pet ?? null;
2850
+ };
2851
+ mergeConfiguredPetPositionDefaults_fn = function(pet) {
2852
+ if (!pet) {
2853
+ return pet;
2854
+ }
2855
+ const configured = chatkitTypes.normalizePetOptions(
2856
+ __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this) ?? null
2857
+ );
2858
+ if (!configured) {
2859
+ return pet;
2860
+ }
2861
+ if (pet === true) {
2862
+ return { position: configured.position };
2863
+ }
2864
+ if (!pet.position) {
2865
+ return { ...pet, position: configured.position };
2866
+ }
2867
+ return {
2868
+ ...pet,
2869
+ position: {
2870
+ ...configured.position,
2871
+ ...pet.position,
2872
+ boundsPadding: pet.position.boundsPadding ?? configured.position.boundsPadding,
2873
+ pin: "pin" in pet.position ? pet.position.pin : configured.position.pin
2874
+ }
2875
+ };
2876
+ };
2877
+ getOverlayPetOptions_fn = function() {
2878
+ if (__privateGet(this, _petClosedByContextMenu)) {
2879
+ return null;
2880
+ }
2881
+ let pet;
2882
+ if (__privateGet(this, _framePetOptionsOverride) !== void 0) {
2883
+ pet = __privateMethod(this, _ChatKitElementBase_instances, mergeConfiguredPetPositionDefaults_fn).call(this, __privateGet(this, _framePetOptionsOverride));
2884
+ } else {
2885
+ pet = __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this);
2886
+ }
2887
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet" && !chatkitTypes.normalizePetOptions(pet ?? null)) {
2888
+ pet = true;
2889
+ }
2890
+ return __privateMethod(this, _ChatKitElementBase_instances, resolveOverlayPetOptions_fn).call(this, pet);
2891
+ };
2892
+ resolvePetAssetUrl_fn = function(src) {
2893
+ try {
2894
+ const base = new URL(
2895
+ __privateGet(this, _frameUrl) ?? window.location.href,
2896
+ window.location.origin
2897
+ );
2898
+ return new URL(src, base).toString();
2899
+ } catch {
2900
+ return src;
2901
+ }
2902
+ };
2903
+ resolveOverlayPetOptions_fn = function(pet) {
2904
+ const normalized = chatkitTypes.normalizePetOptions(pet ?? null);
2905
+ if (!normalized) {
2906
+ return null;
2907
+ }
2908
+ return {
2909
+ character: {
2910
+ ...normalized.character,
2911
+ src: __privateMethod(this, _ChatKitElementBase_instances, resolvePetAssetUrl_fn).call(this, normalized.character.src)
2912
+ },
2913
+ position: normalized.position,
2914
+ behavior: normalized.behavior,
2915
+ ariaLabel: normalized.ariaLabel,
2916
+ imageRendering: normalized.imageRendering
2917
+ };
2918
+ };
2919
+ getFrameOptions_fn = function(options) {
2920
+ const pet = __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this, options);
2921
+ if (pet === (options.pet ?? null)) {
2922
+ return options;
2923
+ }
2924
+ const nextOptions = { ...options };
2925
+ if (pet === null) {
2926
+ delete nextOptions.pet;
2927
+ } else {
2928
+ nextOptions.pet = pet;
2929
+ }
2930
+ return nextOptions;
2931
+ };
2932
+ setLauncherOpen_fn = function(open) {
2933
+ __privateSet(this, _launcherOpen, open);
2934
+ if (open) {
2935
+ this.dataset.chatOpen = "true";
2936
+ } else {
2937
+ delete this.dataset.chatOpen;
2938
+ }
2939
+ };
2940
+ setChatMinimizedToPet_fn = function(minimized) {
2941
+ const next = minimized && Boolean(__privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this));
2942
+ __privateSet(this, _chatMinimizedToPet, next);
2943
+ if (next) {
2944
+ this.dataset.chatMinimizedToPet = "true";
2945
+ } else {
2946
+ delete this.dataset.chatMinimizedToPet;
2947
+ }
2948
+ };
2949
+ syncPetOverlayOptions_fn = function() {
2950
+ var _a2;
2951
+ const overlayPetOptions = __privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this);
2952
+ __privateGet(this, _petOverlay).setOptions(overlayPetOptions, (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.theme);
2953
+ if (!overlayPetOptions) {
2954
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, false);
2955
+ }
2956
+ };
2957
+ handlePetActivate_fn = function() {
2958
+ if (__privateGet(this, _chatMinimizedToPet)) {
2959
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, false);
2960
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet") {
2961
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2962
+ }
2963
+ __privateGet(this, _loaded).then(() => this.focusComposer()).catch(() => void 0);
2964
+ return;
2965
+ }
2966
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) !== "pet") {
2967
+ return;
2968
+ }
2969
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2970
+ __privateGet(this, _loaded).then(() => this.focusComposer()).catch(() => void 0);
2971
+ };
2972
+ handlePetClose_fn = function() {
2973
+ __privateSet(this, _petClosedByContextMenu, true);
2974
+ __privateSet(this, _framePetOptionsOverride, null);
2975
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, false);
2976
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2977
+ __privateGet(this, _petOverlay).setOptions(null);
2978
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet") {
2979
+ return;
2980
+ }
2981
+ __privateGet(this, _loaded).then(() => __privateGet(this, _messenger).commands.setPetEnabled({ enabled: false })).catch(() => void 0);
2982
+ };
2983
+ handlePetReply_fn = async function(text) {
2984
+ await this.sendUserMessage({ text });
2985
+ };
2986
+ handlePetThreadSummaryActivate_fn = async function(threadId) {
2987
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet") {
2988
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2989
+ }
2990
+ await this.setThreadId(threadId);
2991
+ await this.focusComposer();
2992
+ };
2993
+ _handleLauncherClose = new WeakMap();
2994
+ getFrameUrl_fn = function() {
2995
+ if (!__privateGet(this, _frameUrl)) {
2996
+ throw new IntegrationError(
2997
+ "ChatKit frameUrl is not configured. Provide it via setOptions({ frameUrl }) before mounting."
2998
+ );
2999
+ }
3000
+ return __privateGet(this, _frameUrl);
3001
+ };
3002
+ setFrameUrl_fn = function(frameUrl) {
3003
+ if (__privateGet(this, _initialized) && __privateGet(this, _frameUrl) && __privateGet(this, _frameUrl) !== frameUrl) {
3004
+ throw new IntegrationError(
3005
+ "ChatKit frameUrl cannot be changed after initialization. Create a new element to use a different URL."
3006
+ );
3007
+ }
3008
+ __privateSet(this, _frameUrl, frameUrl);
3009
+ };
3010
+ consumeFrameUrl_fn = function(options) {
3011
+ if (!("frameUrl" in options)) return;
3012
+ const frameUrl = options.frameUrl;
3013
+ delete options.frameUrl;
3014
+ if (frameUrl == null) return;
3015
+ if (typeof frameUrl !== "string" || frameUrl.trim() === "") {
3016
+ throw new IntegrationError(
3017
+ "ChatKit frameUrl must be a non-empty string."
3018
+ );
3019
+ }
3020
+ __privateMethod(this, _ChatKitElementBase_instances, setFrameUrl_fn).call(this, frameUrl);
3021
+ };
3022
+ _handleFrameLoad = new WeakMap();
3023
+ _initialized = new WeakMap();
3024
+ maybeInit_fn = function() {
3025
+ if (__privateGet(this, _initialized) || !__privateGet(this, _frame) || !__privateGet(this, _opts)) {
3026
+ return;
3027
+ }
3028
+ __privateSet(this, _initialized, true);
3029
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
3030
+ const frameURL = new URL(__privateMethod(this, _ChatKitElementBase_instances, getFrameUrl_fn).call(this), window.location.origin);
3031
+ __privateGet(this, _messenger).setTargetOrigin(frameURL.origin);
3032
+ frameURL.hash = encodeBase64({
3033
+ options: getInnerOptions(__privateMethod(this, _ChatKitElementBase_instances, getFrameOptions_fn).call(this, __privateGet(this, _opts))),
3034
+ referrer: window.location.origin,
3035
+ profile: this.profile
3036
+ });
3037
+ __privateGet(this, _messenger).connect();
3038
+ __privateGet(this, _frame).src = frameURL.toString();
3039
+ if (__privateGet(this, _wrapper)) {
3040
+ __privateGet(this, _shadow).append(__privateGet(this, _wrapper));
3041
+ }
3042
+ };
3043
+ __decorateElement(_init, 1, "focusComposer", _focusComposer_dec, ChatKitElementBase);
3044
+ __decorateElement(_init, 1, "fetchUpdates", _fetchUpdates_dec, ChatKitElementBase);
3045
+ __decorateElement(_init, 1, "sendUserMessage", _sendUserMessage_dec, ChatKitElementBase);
3046
+ __decorateElement(_init, 1, "setComposerValue", _setComposerValue_dec, ChatKitElementBase);
3047
+ __decorateElement(_init, 1, "setThreadId", _setThreadId_dec, ChatKitElementBase);
3048
+ __decorateElement(_init, 1, "shareThread", _shareThread_dec, ChatKitElementBase);
3049
+ __decorateElement(_init, 1, "sendCustomAction", _sendCustomAction_dec, ChatKitElementBase);
3050
+ __decorateElement(_init, 1, "showHistory", _showHistory_dec, ChatKitElementBase);
3051
+ __decorateElement(_init, 1, "hideHistory", _hideHistory_dec, ChatKitElementBase);
3052
+ __decorateElement(_init, 1, "setTrainingOptOut", _setTrainingOptOut_dec, ChatKitElementBase);
3053
+ __decoratorMetadata(_init, ChatKitElementBase);
3054
+ class ChatKitElement extends ChatKitElementBase {
3055
+ constructor() {
3056
+ super({ profile: "chatkit" });
3057
+ }
3058
+ sanitizeOptions(options) {
3059
+ var _a2;
3060
+ (_a2 = options.threadItemActions) == null ? true : delete _a2.share;
3061
+ return options;
3062
+ }
3063
+ }
3064
+ function registerChatKitElement(tag = "xpertai-chatkit") {
3065
+ if (!("customElements" in globalThis)) return;
3066
+ if (!customElements.get(tag)) {
3067
+ customElements.define(tag, ChatKitElement);
3068
+ }
3069
+ }
3070
+ registerChatKitElement();
5
3071
  const EXCLUDED_HANDLER_KEYS = /* @__PURE__ */ new Set(["onClientTool"]);
6
3072
  const EVENT_HANDLER_MAP = {
7
3073
  "chatkit.error": "onError",
@@ -66,8 +3132,8 @@
66
3132
  };
67
3133
  }
68
3134
  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) {
3135
+ var _a2, _b2;
3136
+ if ((_b2 = (_a2 = sap == null ? void 0 : sap.ui) == null ? void 0 : _a2.core) == null ? void 0 : _b2.Control) {
71
3137
  return sap.ui.core.Control;
72
3138
  }
73
3139
  throw new Error("sap.ui.core.Control is required for @xpert-ai/chatkit-ui5");
@@ -163,10 +3229,10 @@
163
3229
  el.addEventListener(
164
3230
  eventName,
165
3231
  (e) => {
166
- var _a;
3232
+ var _a2;
167
3233
  const detail = e.detail;
168
3234
  const handlerName = EVENT_HANDLER_MAP[eventName];
169
- const handler = (_a = this._handlers) == null ? void 0 : _a[handlerName];
3235
+ const handler = (_a2 = this._handlers) == null ? void 0 : _a2[handlerName];
170
3236
  if (typeof handler === "function") {
171
3237
  handler(detail);
172
3238
  }