@xpert-ai/chatkit-react 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,53 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
11
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
12
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
13
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
14
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
15
+ var __runInitializers = (array, flags, self, value) => {
16
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
17
+ return value;
18
+ };
19
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
20
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
21
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
22
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
23
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
24
+ return __privateGet(this, extra);
25
+ }, set [name](x) {
26
+ return __privateSet(this, extra, x);
27
+ } }, name));
28
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
29
+ for (var i = decorators.length - 1; i >= 0; i--) {
30
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
31
+ if (k) {
32
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
33
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
34
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
35
+ }
36
+ 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;
37
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
38
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
39
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
40
+ }
41
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
42
+ };
43
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
44
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
45
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
46
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
47
+ 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);
48
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
49
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
50
+ 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, _shadow, _resolveLoaded, _loaded, _messenger, _ChatKitElementBase_instances, emitAndThrow_fn, setOptionsDataAttributes_fn, getFrameUrl_fn, setFrameUrl_fn, consumeFrameUrl_fn, _handleFrameLoad, _initialized, maybeInit_fn, _init;
1
51
  import * as React from "react";
2
52
  import React__default from "react";
3
53
  import { jsx } from "react/jsx-runtime";
@@ -139,6 +189,1238 @@ function useChatKit(options) {
139
189
  [methods, control]
140
190
  );
141
191
  }
192
+ class EventEmitter {
193
+ constructor() {
194
+ __publicField(this, "callbacks", /* @__PURE__ */ new Map());
195
+ }
196
+ on(event, callback) {
197
+ if (!this.callbacks.has(event)) {
198
+ this.callbacks.set(event, /* @__PURE__ */ new Set());
199
+ }
200
+ this.callbacks.get(event).add(callback);
201
+ }
202
+ emit(event, ...args) {
203
+ var _a2;
204
+ const data = args[0];
205
+ (_a2 = this.callbacks.get(event)) == null ? void 0 : _a2.forEach((callback) => callback(data));
206
+ }
207
+ off(event, callback) {
208
+ var _a2;
209
+ if (!callback) {
210
+ this.callbacks.delete(event);
211
+ } else {
212
+ (_a2 = this.callbacks.get(event)) == null ? void 0 : _a2.delete(callback);
213
+ }
214
+ }
215
+ allOff() {
216
+ this.callbacks.clear();
217
+ }
218
+ }
219
+ async function getBytes(stream, onChunk) {
220
+ const reader = stream.getReader();
221
+ let result;
222
+ while (!(result = await reader.read()).done) {
223
+ onChunk(result.value);
224
+ }
225
+ }
226
+ function getLines(onLine) {
227
+ let buffer;
228
+ let position;
229
+ let fieldLength;
230
+ let discardTrailingNewline = false;
231
+ return function onChunk(arr) {
232
+ if (buffer === void 0) {
233
+ buffer = arr;
234
+ position = 0;
235
+ fieldLength = -1;
236
+ } else {
237
+ buffer = concat(buffer, arr);
238
+ }
239
+ const bufLength = buffer.length;
240
+ let lineStart = 0;
241
+ while (position < bufLength) {
242
+ if (discardTrailingNewline) {
243
+ if (buffer[position] === 10) {
244
+ lineStart = ++position;
245
+ }
246
+ discardTrailingNewline = false;
247
+ }
248
+ let lineEnd = -1;
249
+ for (; position < bufLength && lineEnd === -1; ++position) {
250
+ switch (buffer[position]) {
251
+ case 58:
252
+ if (fieldLength === -1) {
253
+ fieldLength = position - lineStart;
254
+ }
255
+ break;
256
+ case 13:
257
+ discardTrailingNewline = true;
258
+ case 10:
259
+ lineEnd = position;
260
+ break;
261
+ }
262
+ }
263
+ if (lineEnd === -1) {
264
+ break;
265
+ }
266
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
267
+ lineStart = position;
268
+ fieldLength = -1;
269
+ }
270
+ if (lineStart === bufLength) {
271
+ buffer = void 0;
272
+ } else if (lineStart !== 0) {
273
+ buffer = buffer.subarray(lineStart);
274
+ position -= lineStart;
275
+ }
276
+ };
277
+ }
278
+ function getMessages(onId, onRetry, onMessage) {
279
+ let message = newMessage();
280
+ const decoder = new TextDecoder();
281
+ return function onLine(line, fieldLength) {
282
+ if (line.length === 0) {
283
+ onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
284
+ message = newMessage();
285
+ } else if (fieldLength > 0) {
286
+ const field = decoder.decode(line.subarray(0, fieldLength));
287
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
288
+ const value = decoder.decode(line.subarray(valueOffset));
289
+ switch (field) {
290
+ case "data":
291
+ message.data = message.data ? message.data + "\n" + value : value;
292
+ break;
293
+ case "event":
294
+ message.event = value;
295
+ break;
296
+ case "id":
297
+ onId(message.id = value);
298
+ break;
299
+ case "retry":
300
+ const retry = parseInt(value, 10);
301
+ if (!isNaN(retry)) {
302
+ onRetry(message.retry = retry);
303
+ }
304
+ break;
305
+ }
306
+ }
307
+ };
308
+ }
309
+ function concat(a, b) {
310
+ const res = new Uint8Array(a.length + b.length);
311
+ res.set(a);
312
+ res.set(b, a.length);
313
+ return res;
314
+ }
315
+ function newMessage() {
316
+ return {
317
+ data: "",
318
+ event: "",
319
+ id: "",
320
+ retry: void 0
321
+ };
322
+ }
323
+ var __rest = function(s, e) {
324
+ var t = {};
325
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
326
+ t[p] = s[p];
327
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
328
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
329
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
330
+ t[p[i]] = s[p[i]];
331
+ }
332
+ return t;
333
+ };
334
+ const EventStreamContentType = "text/event-stream";
335
+ const DefaultRetryInterval = 1e3;
336
+ const LastEventId = "last-event-id";
337
+ function fetchEventSource(input, _a2) {
338
+ 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"]);
339
+ return new Promise((resolve, reject) => {
340
+ const headers = Object.assign({}, inputHeaders);
341
+ if (!headers.accept) {
342
+ headers.accept = EventStreamContentType;
343
+ }
344
+ let curRequestController;
345
+ function onVisibilityChange() {
346
+ curRequestController.abort();
347
+ if (!document.hidden) {
348
+ create();
349
+ }
350
+ }
351
+ if (!openWhenHidden) {
352
+ document.addEventListener("visibilitychange", onVisibilityChange);
353
+ }
354
+ let retryInterval = DefaultRetryInterval;
355
+ let retryTimer = 0;
356
+ function dispose() {
357
+ document.removeEventListener("visibilitychange", onVisibilityChange);
358
+ window.clearTimeout(retryTimer);
359
+ curRequestController.abort();
360
+ }
361
+ inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener("abort", () => {
362
+ dispose();
363
+ resolve();
364
+ });
365
+ const fetch2 = inputFetch !== null && inputFetch !== void 0 ? inputFetch : window.fetch;
366
+ const onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen;
367
+ async function create() {
368
+ var _a3;
369
+ curRequestController = new AbortController();
370
+ try {
371
+ const response = await fetch2(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
372
+ await onopen(response);
373
+ await getBytes(response.body, getLines(getMessages((id) => {
374
+ if (id) {
375
+ headers[LastEventId] = id;
376
+ } else {
377
+ delete headers[LastEventId];
378
+ }
379
+ }, (retry) => {
380
+ retryInterval = retry;
381
+ }, onmessage)));
382
+ onclose === null || onclose === void 0 ? void 0 : onclose();
383
+ dispose();
384
+ resolve();
385
+ } catch (err) {
386
+ if (!curRequestController.signal.aborted) {
387
+ try {
388
+ const interval = (_a3 = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a3 !== void 0 ? _a3 : retryInterval;
389
+ window.clearTimeout(retryTimer);
390
+ retryTimer = window.setTimeout(create, interval);
391
+ } catch (innerErr) {
392
+ dispose();
393
+ reject(innerErr);
394
+ }
395
+ }
396
+ }
397
+ }
398
+ create();
399
+ });
400
+ }
401
+ function defaultOnOpen(response) {
402
+ const contentType = response.headers.get("content-type");
403
+ if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(EventStreamContentType))) {
404
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
405
+ }
406
+ }
407
+ const FRAME_SAFE_ERROR_KEY = "__chatkit_error__";
408
+ class HttpError extends Error {
409
+ constructor(message, res, metadata) {
410
+ super(message);
411
+ __publicField(this, "status");
412
+ __publicField(this, "statusText");
413
+ __publicField(this, "metadata");
414
+ this.name = "HttpError";
415
+ this.statusText = res.statusText;
416
+ this.status = res.status;
417
+ this.metadata = metadata;
418
+ }
419
+ static fromPossibleFrameSafeError(error) {
420
+ if (error instanceof HttpError) {
421
+ return error;
422
+ }
423
+ if (error && typeof error === "object" && FRAME_SAFE_ERROR_KEY in error && error[FRAME_SAFE_ERROR_KEY] === "HttpError") {
424
+ const safeError = error;
425
+ const parsedError = new HttpError(
426
+ safeError.message,
427
+ {
428
+ status: safeError.status,
429
+ statusText: safeError.statusText
430
+ },
431
+ safeError.metadata
432
+ );
433
+ parsedError.stack = safeError.stack;
434
+ return parsedError;
435
+ }
436
+ return null;
437
+ }
438
+ }
439
+ _a = FRAME_SAFE_ERROR_KEY;
440
+ const _FrameSafeHttpError = class _FrameSafeHttpError {
441
+ constructor(message, res, metadata) {
442
+ __publicField(this, _a, "HttpError");
443
+ __publicField(this, "message");
444
+ __publicField(this, "stack");
445
+ __publicField(this, "status");
446
+ __publicField(this, "statusText");
447
+ __publicField(this, "metadata");
448
+ this.message = message;
449
+ this.stack = new Error(message).stack;
450
+ this.status = res.status;
451
+ this.statusText = res.statusText;
452
+ this.metadata = metadata;
453
+ }
454
+ static fromHttpError(error) {
455
+ return new _FrameSafeHttpError(
456
+ error.message,
457
+ {
458
+ status: error.status,
459
+ statusText: error.statusText
460
+ },
461
+ error.metadata
462
+ );
463
+ }
464
+ };
465
+ let FrameSafeHttpError = _FrameSafeHttpError;
466
+ const BASE_RETRY_DELAY_MS = 1e3;
467
+ const MAX_RETRY_DELAY_MS = 1e4;
468
+ const MAX_RETRY_ATTEMPTS = 5;
469
+ const nextDelay = (attempt, maxRetryDelay = MAX_RETRY_DELAY_MS, baseDelayMs = BASE_RETRY_DELAY_MS) => {
470
+ const max = Math.min(maxRetryDelay, baseDelayMs * 2 ** attempt);
471
+ return Math.floor(max * (0.5 + Math.random() * 0.5));
472
+ };
473
+ class RetryableError extends Error {
474
+ constructor(cause) {
475
+ super();
476
+ this.cause = cause;
477
+ }
478
+ }
479
+ const fetchEventSourceWithRetry = async (url, params) => {
480
+ let retryAttempt = 0;
481
+ const { onopen, ...restParams } = params;
482
+ await fetchEventSource(url, {
483
+ ...restParams,
484
+ onopen: async (res) => {
485
+ var _a2;
486
+ onopen == null ? void 0 : onopen(res);
487
+ if (res.ok && ((_a2 = res.headers.get("content-type")) == null ? void 0 : _a2.startsWith("text/event-stream"))) {
488
+ retryAttempt = 0;
489
+ return;
490
+ }
491
+ const httpError = new FrameSafeHttpError(`Streaming failed: ${res.statusText}`, res);
492
+ if (res.status >= 400 && res.status < 500) {
493
+ throw httpError;
494
+ } else {
495
+ throw new RetryableError(httpError);
496
+ }
497
+ },
498
+ onerror: (error) => {
499
+ if (error instanceof RetryableError) {
500
+ if (retryAttempt >= MAX_RETRY_ATTEMPTS) {
501
+ throw error.cause;
502
+ }
503
+ retryAttempt += 1;
504
+ return nextDelay(retryAttempt);
505
+ }
506
+ throw error;
507
+ }
508
+ });
509
+ };
510
+ function safeRandomUUID() {
511
+ const cryptoRef = globalThis.crypto;
512
+ if (typeof (cryptoRef == null ? void 0 : cryptoRef.randomUUID) === "function") {
513
+ return cryptoRef.randomUUID();
514
+ }
515
+ if (typeof (cryptoRef == null ? void 0 : cryptoRef.getRandomValues) === "function") {
516
+ const bytes = new Uint8Array(16);
517
+ cryptoRef.getRandomValues(bytes);
518
+ bytes[6] = bytes[6] & 15 | 64;
519
+ bytes[8] = bytes[8] & 63 | 128;
520
+ return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
521
+ }
522
+ return `ck_${Date.now()}_${Math.random().toString(16).slice(2)}`;
523
+ }
524
+ let IntegrationError$1 = class IntegrationError extends Error {
525
+ constructor(message) {
526
+ super(message);
527
+ __publicField(this, "_name");
528
+ this.name = "IntegrationError";
529
+ this._name = this.name;
530
+ }
531
+ static fromPossibleFrameSafeError(error) {
532
+ if (error && typeof error === "object" && FRAME_SAFE_ERROR_KEY in error && error[FRAME_SAFE_ERROR_KEY] === "IntegrationError") {
533
+ const safeError = error;
534
+ const parsedError = new IntegrationError(safeError.message);
535
+ parsedError.stack = safeError.stack;
536
+ return parsedError;
537
+ }
538
+ return null;
539
+ }
540
+ };
541
+ _b = FRAME_SAFE_ERROR_KEY;
542
+ class FrameSafeIntegrationError {
543
+ constructor(message) {
544
+ __publicField(this, _b, "IntegrationError");
545
+ __publicField(this, "message");
546
+ __publicField(this, "stack");
547
+ this.message = message;
548
+ this.stack = new Error(message).stack;
549
+ }
550
+ }
551
+ class BaseMessenger {
552
+ constructor({
553
+ handlers,
554
+ target,
555
+ targetOrigin,
556
+ fetch: fetch2 = window.fetch
557
+ }) {
558
+ __publicField(this, "targetOrigin");
559
+ __publicField(this, "target");
560
+ __publicField(this, "commandHandlers");
561
+ __publicField(this, "_fetch");
562
+ __publicField(this, "emitter", new EventEmitter());
563
+ __publicField(this, "handlers", /* @__PURE__ */ new Map());
564
+ __publicField(this, "fetchEventSourceHandlers", /* @__PURE__ */ new Map());
565
+ __publicField(this, "abortControllers", /* @__PURE__ */ new Map());
566
+ __publicField(this, "commands", new Proxy(
567
+ {},
568
+ {
569
+ get: (_, command) => {
570
+ return (data, transfer) => {
571
+ return new Promise((resolve, reject) => {
572
+ const nonce = safeRandomUUID();
573
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
574
+ this.sendMessage(
575
+ {
576
+ type: "command",
577
+ nonce,
578
+ command: `on${command.charAt(0).toUpperCase()}${command.slice(1)}`,
579
+ data
580
+ },
581
+ transfer
582
+ );
583
+ });
584
+ };
585
+ }
586
+ }
587
+ ));
588
+ __publicField(this, "handleMessage", async (event) => {
589
+ var _a2, _b2, _c2, _d;
590
+ if (!event.data || event.data.__xpaiChatKit !== true || event.origin !== this.targetOrigin || event.source !== this.target()) {
591
+ return;
592
+ }
593
+ const data = event.data;
594
+ switch (data.type) {
595
+ case "event": {
596
+ this.emitter.emit(data.event, data.data);
597
+ break;
598
+ }
599
+ case "fetch": {
600
+ try {
601
+ if (data.formData) {
602
+ const formData = new FormData();
603
+ for (const [key, value] of Object.entries(data.formData)) {
604
+ formData.append(key, value);
605
+ }
606
+ data.params.body = formData;
607
+ }
608
+ const controller = new AbortController();
609
+ this.abortControllers.set(data.nonce, controller);
610
+ data.params.signal = controller.signal;
611
+ const res = await this._fetch(data.url, data.params);
612
+ if (!res.ok) {
613
+ const message = await res.json().then((json2) => json2.message || res.statusText).catch(() => res.statusText);
614
+ throw new FrameSafeHttpError(message, res);
615
+ }
616
+ const json = await res.json().catch(() => ({}));
617
+ this.sendMessage({
618
+ type: "response",
619
+ response: json,
620
+ nonce: data.nonce
621
+ });
622
+ } catch (error) {
623
+ this.sendMessage({
624
+ type: "response",
625
+ error,
626
+ nonce: data.nonce
627
+ });
628
+ }
629
+ break;
630
+ }
631
+ case "fetchEventSource": {
632
+ try {
633
+ const controller = new AbortController();
634
+ this.abortControllers.set(data.nonce, controller);
635
+ await fetchEventSourceWithRetry(data.url, {
636
+ ...data.params,
637
+ signal: controller.signal,
638
+ fetch: this._fetch,
639
+ onmessage: (message) => {
640
+ this.sendMessage({
641
+ type: "fetchEventSourceMessage",
642
+ message,
643
+ nonce: data.nonce
644
+ });
645
+ }
646
+ });
647
+ this.sendMessage({
648
+ type: "response",
649
+ response: void 0,
650
+ nonce: data.nonce
651
+ });
652
+ } catch (error) {
653
+ this.sendMessage({
654
+ type: "response",
655
+ error,
656
+ nonce: data.nonce
657
+ });
658
+ }
659
+ break;
660
+ }
661
+ case "command": {
662
+ if (!this.canReceiveCommand(data.command)) {
663
+ this.sendMessage({
664
+ type: "response",
665
+ error: new FrameSafeIntegrationError(`Command ${data.command} not supported`),
666
+ nonce: data.nonce
667
+ });
668
+ return;
669
+ }
670
+ try {
671
+ const response = await ((_b2 = (_a2 = this.commandHandlers)[data.command]) == null ? void 0 : _b2.call(_a2, data.data));
672
+ this.sendMessage({
673
+ type: "response",
674
+ response,
675
+ nonce: data.nonce
676
+ });
677
+ } catch (error) {
678
+ this.sendMessage({
679
+ type: "response",
680
+ error,
681
+ nonce: data.nonce
682
+ });
683
+ }
684
+ break;
685
+ }
686
+ case "response": {
687
+ const handler = this.handlers.get(data.nonce);
688
+ if (!handler) {
689
+ console.error("No handler found for nonce", data.nonce);
690
+ return;
691
+ }
692
+ if (data.error) {
693
+ const integrationError = IntegrationError$1.fromPossibleFrameSafeError(data.error);
694
+ const httpError = HttpError.fromPossibleFrameSafeError(data.error);
695
+ if (integrationError) {
696
+ integrationError.stack = handler.stack;
697
+ handler.reject(integrationError);
698
+ } else if (httpError) {
699
+ handler.reject(httpError);
700
+ } else {
701
+ handler.reject(data.error);
702
+ }
703
+ } else {
704
+ handler.resolve(data.response);
705
+ }
706
+ this.handlers.delete(data.nonce);
707
+ break;
708
+ }
709
+ case "fetchEventSourceMessage": {
710
+ const handler = this.fetchEventSourceHandlers.get(data.nonce);
711
+ if (!handler) {
712
+ console.error("No handler found for nonce", data.nonce);
713
+ return;
714
+ }
715
+ (_d = (_c2 = this.fetchEventSourceHandlers.get(data.nonce)) == null ? void 0 : _c2.onmessage) == null ? void 0 : _d.call(_c2, data.message);
716
+ break;
717
+ }
718
+ case "abortSignal": {
719
+ const controller = this.abortControllers.get(data.nonce);
720
+ if (controller) {
721
+ controller.abort(data.reason);
722
+ this.abortControllers.delete(data.nonce);
723
+ }
724
+ break;
725
+ }
726
+ }
727
+ });
728
+ this.commandHandlers = handlers;
729
+ this.target = target;
730
+ this.targetOrigin = targetOrigin;
731
+ this._fetch = (...args) => fetch2(...args);
732
+ }
733
+ setTargetOrigin(targetOrigin) {
734
+ this.targetOrigin = targetOrigin;
735
+ }
736
+ sendMessage(data, transfer) {
737
+ var _a2;
738
+ const message = {
739
+ __xpaiChatKit: true,
740
+ ...data
741
+ };
742
+ (_a2 = this.target()) == null ? void 0 : _a2.postMessage(message, this.targetOrigin, transfer);
743
+ }
744
+ connect() {
745
+ window.addEventListener("message", this.handleMessage);
746
+ }
747
+ disconnect() {
748
+ window.removeEventListener("message", this.handleMessage);
749
+ }
750
+ fetch(url, params) {
751
+ return new Promise((resolve, reject) => {
752
+ const nonce = safeRandomUUID();
753
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
754
+ let formData;
755
+ if (params.body instanceof FormData) {
756
+ formData = {};
757
+ for (const [key, value] of params.body.entries()) {
758
+ formData[key] = value;
759
+ }
760
+ params.body = void 0;
761
+ }
762
+ if (params.signal) {
763
+ params.signal.addEventListener("abort", () => {
764
+ var _a2;
765
+ this.sendMessage({
766
+ type: "abortSignal",
767
+ nonce,
768
+ reason: (_a2 = params.signal) == null ? void 0 : _a2.reason
769
+ });
770
+ });
771
+ params.signal = void 0;
772
+ }
773
+ this.sendMessage({ type: "fetch", nonce, params, formData, url });
774
+ });
775
+ }
776
+ // Supporting onopen would require a good way for us to serialize the Response object
777
+ // across the iframe boundary, which is not trivial and also not really necessary.
778
+ fetchEventSource(url, params) {
779
+ return new Promise((resolve, reject) => {
780
+ const { onmessage, signal, ...rest } = params;
781
+ const nonce = safeRandomUUID();
782
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
783
+ this.fetchEventSourceHandlers.set(nonce, {
784
+ onmessage
785
+ });
786
+ if (signal) {
787
+ signal.addEventListener("abort", () => {
788
+ this.sendMessage({
789
+ type: "abortSignal",
790
+ nonce,
791
+ reason: signal.reason
792
+ });
793
+ });
794
+ }
795
+ this.sendMessage({ type: "fetchEventSource", nonce, params: rest, url });
796
+ });
797
+ }
798
+ emit(...[event, data, transfer]) {
799
+ this.sendMessage(
800
+ {
801
+ type: "event",
802
+ event,
803
+ data
804
+ },
805
+ transfer
806
+ );
807
+ }
808
+ on(...[event, callback]) {
809
+ this.emitter.on(event, callback);
810
+ }
811
+ destroy() {
812
+ window.removeEventListener("message", this.handleMessage);
813
+ this.emitter.allOff();
814
+ this.handlers.clear();
815
+ }
816
+ }
817
+ const toUrlBase64 = (bin) => btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
818
+ const encodeBase64 = (value) => {
819
+ if (value === void 0) {
820
+ throw new TypeError(
821
+ "encodeBase64: `undefined` cannot be encoded to valid JSON. Pass null instead."
822
+ );
823
+ }
824
+ const json = JSON.stringify(value);
825
+ const bytes = new TextEncoder().encode(json);
826
+ let bin = "";
827
+ for (const b of bytes) bin += String.fromCharCode(b);
828
+ return toUrlBase64(bin);
829
+ };
830
+ class IntegrationError2 extends Error {
831
+ }
832
+ function fromPossibleFrameSafeError(err) {
833
+ return err.message;
834
+ }
835
+ const BASE_CAPABILITY_ALLOWLIST = [
836
+ // commands
837
+ "command.setOptions",
838
+ "command.sendUserMessage",
839
+ "command.setComposerValue",
840
+ "command.setThreadId",
841
+ "command.focusComposer",
842
+ "command.fetchUpdates",
843
+ "command.sendCustomAction",
844
+ "command.showHistory",
845
+ "command.hideHistory",
846
+ // events
847
+ "event.ready",
848
+ "event.error",
849
+ "event.log",
850
+ "event.response.start",
851
+ "event.response.end",
852
+ "event.response.stop",
853
+ "event.thread.change",
854
+ "event.tool.change",
855
+ "event.thread.load.start",
856
+ "event.thread.load.end",
857
+ "event.deeplink",
858
+ "event.effect",
859
+ // errors
860
+ "error.StreamError",
861
+ "error.StreamEventParsingError",
862
+ "error.WidgetItemError",
863
+ "error.InitialThreadLoadError",
864
+ "error.FileAttachmentError",
865
+ "error.HistoryViewError",
866
+ "error.FatalAppError",
867
+ "error.IntegrationError",
868
+ "error.EntitySearchError",
869
+ "error.DomainVerificationRequestError",
870
+ // backend
871
+ "backend.threads.get_by_id",
872
+ "backend.threads.list",
873
+ "backend.threads.update",
874
+ "backend.threads.delete",
875
+ "backend.threads.create",
876
+ "backend.threads.add_user_message",
877
+ "backend.threads.add_client_tool_output",
878
+ "backend.threads.retry_after_item",
879
+ "backend.threads.custom_action",
880
+ "backend.attachments.create",
881
+ "backend.attachments.get_preview",
882
+ "backend.attachments.delete",
883
+ "backend.items.list",
884
+ "backend.items.feedback",
885
+ // thread item types
886
+ "thread.item.generated_image",
887
+ "thread.item.user_message",
888
+ "thread.item.assistant_message",
889
+ "thread.item.client_tool_call",
890
+ "thread.item.widget",
891
+ "thread.item.task",
892
+ "thread.item.workflow",
893
+ "thread.item.end_of_turn",
894
+ "thread.item.image_generation",
895
+ // widgets
896
+ "widget.Basic",
897
+ "widget.Card",
898
+ "widget.ListView",
899
+ "widget.ListViewItem",
900
+ "widget.Badge",
901
+ "widget.Box",
902
+ "widget.Row",
903
+ "widget.Col",
904
+ "widget.Button",
905
+ "widget.Caption",
906
+ "widget.Chart",
907
+ "widget.Checkbox",
908
+ "widget.DatePicker",
909
+ "widget.Divider",
910
+ "widget.Form",
911
+ "widget.Icon",
912
+ "widget.Image",
913
+ "widget.Input",
914
+ "widget.Label",
915
+ "widget.Markdown",
916
+ "widget.RadioGroup",
917
+ "widget.Select",
918
+ "widget.Spacer",
919
+ "widget.Text",
920
+ "widget.Textarea",
921
+ "widget.Title",
922
+ "widget.Transition"
923
+ ];
924
+ const BASE_CAPABILITY_DENYLIST = [
925
+ // --- commands
926
+ "command.shareThread",
927
+ "command.setTrainingOptOut",
928
+ // --- events
929
+ "event.thread.restore",
930
+ "event.message.share",
931
+ "event.image.download",
932
+ "event.history.open",
933
+ "event.history.close",
934
+ "event.log.chatgpt",
935
+ // --- errors
936
+ // These errors considered internal and are not exposed to the user by default.
937
+ "error.HttpError",
938
+ "error.NetworkError",
939
+ "error.UnhandledError",
940
+ "error.UnhandledPromiseRejectionError",
941
+ "error.StreamEventHandlingError",
942
+ "error.StreamStopError",
943
+ "error.ThreadRenderingError",
944
+ "error.IntlError",
945
+ "error.AppError",
946
+ // --- backend
947
+ "backend.threads.stop",
948
+ "backend.threads.share",
949
+ "backend.threads.create_from_shared",
950
+ "backend.threads.init",
951
+ "backend.attachments.process",
952
+ // widgets
953
+ "widget.CardCarousel",
954
+ "widget.Favicon",
955
+ "widget.CardLinkItem",
956
+ "widget.Map"
957
+ ];
958
+ const PROFILE_TO_RULES = {
959
+ "chatkit": {
960
+ allow: [...BASE_CAPABILITY_ALLOWLIST, "thread.item.image_generation"],
961
+ deny: BASE_CAPABILITY_DENYLIST
962
+ }
963
+ };
964
+ const getCapabilities = (profile) => {
965
+ const rules = PROFILE_TO_RULES[profile];
966
+ const effective = new Set(rules.allow);
967
+ for (const capability of rules.deny ?? []) {
968
+ effective.delete(capability);
969
+ }
970
+ const commands = /* @__PURE__ */ new Set();
971
+ const events = /* @__PURE__ */ new Set();
972
+ const backend = /* @__PURE__ */ new Set();
973
+ const threadItems = /* @__PURE__ */ new Set();
974
+ const errors = /* @__PURE__ */ new Set();
975
+ const widgets = /* @__PURE__ */ new Set();
976
+ for (const capability of effective) {
977
+ if (capability.startsWith("command.")) {
978
+ commands.add(capability.slice("command.".length));
979
+ continue;
980
+ }
981
+ if (capability.startsWith("event.")) {
982
+ events.add(capability.slice("event.".length));
983
+ continue;
984
+ }
985
+ if (capability.startsWith("backend.")) {
986
+ backend.add(capability.slice("backend.".length));
987
+ continue;
988
+ }
989
+ if (capability.startsWith("thread.item.")) {
990
+ threadItems.add(capability.slice("thread.item.".length));
991
+ }
992
+ if (capability.startsWith("error.")) {
993
+ errors.add(capability.slice("error.".length));
994
+ continue;
995
+ }
996
+ if (capability.startsWith("widget.")) {
997
+ widgets.add(capability.slice("widget.".length));
998
+ continue;
999
+ }
1000
+ }
1001
+ return { commands, events, backend, threadItems, errors, widgets };
1002
+ };
1003
+ class ChatFrameMessenger extends BaseMessenger {
1004
+ // Messenger running in outer can always handle commands coming from inner
1005
+ canReceiveCommand(_) {
1006
+ return true;
1007
+ }
1008
+ }
1009
+ const removeMethods = (obj, seen = /* @__PURE__ */ new WeakSet()) => {
1010
+ if (typeof obj === "function") return "[ChatKitMethod]";
1011
+ if (typeof obj !== "object" || obj === null) return obj;
1012
+ if (seen.has(obj)) return obj;
1013
+ seen.add(obj);
1014
+ if (Array.isArray(obj)) {
1015
+ return obj.map((c) => removeMethods(c, seen));
1016
+ }
1017
+ const result = {};
1018
+ for (const [key, value] of Object.entries(obj)) {
1019
+ if (typeof value !== "function") {
1020
+ result[key] = removeMethods(value, seen);
1021
+ } else {
1022
+ result[key] = "[ChatKitMethod]";
1023
+ }
1024
+ }
1025
+ return result;
1026
+ };
1027
+ function getInnerOptions(options) {
1028
+ return removeMethods(options);
1029
+ }
1030
+ function requireCommandCapability(value, context) {
1031
+ const command = String(context.name);
1032
+ return function(...args) {
1033
+ if (!this.capabilities.commands.has(command)) {
1034
+ throw new IntegrationError2(
1035
+ `ChatKit command "${String(command)}" is not available for the "${this.profile}" profile.`
1036
+ );
1037
+ }
1038
+ return value.apply(this, args);
1039
+ };
1040
+ }
1041
+ 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) {
1042
+ constructor({ profile }) {
1043
+ super();
1044
+ __runInitializers(_init, 5, this);
1045
+ __privateAdd(this, _ChatKitElementBase_instances);
1046
+ __privateAdd(this, _opts);
1047
+ __privateAdd(this, _frameUrl);
1048
+ __privateAdd(this, _frame);
1049
+ __privateAdd(this, _wrapper);
1050
+ __privateAdd(this, _shadow, this.attachShadow({ mode: "open" }));
1051
+ __privateAdd(this, _resolveLoaded);
1052
+ __privateAdd(this, _loaded, new Promise((resolve) => {
1053
+ __privateSet(this, _resolveLoaded, resolve);
1054
+ }));
1055
+ __privateAdd(this, _messenger, new ChatFrameMessenger({
1056
+ fetch: (...args) => {
1057
+ var _a2;
1058
+ const customFetch = ((_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.api) && "fetch" in __privateGet(this, _opts).api && __privateGet(this, _opts).api.fetch;
1059
+ return customFetch ? customFetch(...args) : fetch(...args);
1060
+ },
1061
+ target: () => {
1062
+ var _a2;
1063
+ return ((_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.contentWindow) ?? null;
1064
+ },
1065
+ targetOrigin: window.location.origin,
1066
+ handlers: {
1067
+ onFileInputClick: ({
1068
+ inputAttributes
1069
+ }) => {
1070
+ return new Promise((resolve) => {
1071
+ const input = document.createElement("input");
1072
+ for (const [key, value] of Object.entries(inputAttributes)) {
1073
+ input.setAttribute(key, String(value));
1074
+ }
1075
+ const respond = () => {
1076
+ resolve(Array.from(input.files || []));
1077
+ if (__privateGet(this, _shadow).contains(input)) {
1078
+ __privateGet(this, _shadow).removeChild(input);
1079
+ }
1080
+ };
1081
+ input.addEventListener("cancel", respond);
1082
+ input.addEventListener("change", respond);
1083
+ __privateGet(this, _shadow).appendChild(input);
1084
+ input.click();
1085
+ });
1086
+ },
1087
+ onClientToolCall: async ({
1088
+ name,
1089
+ params,
1090
+ id,
1091
+ tool_call_id
1092
+ }) => {
1093
+ var _a2;
1094
+ const onClientTool = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.onClientTool;
1095
+ if (!onClientTool) {
1096
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError2(
1097
+ `No handler for client tool calls. You'll need to add onClientTool to your ChatKit options.`
1098
+ ));
1099
+ }
1100
+ return onClientTool({ name, params, id, tool_call_id });
1101
+ },
1102
+ onWidgetAction: async ({
1103
+ action,
1104
+ widgetItem
1105
+ }) => {
1106
+ var _a2, _b2;
1107
+ const onAction = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.widgets) == null ? void 0 : _b2.onAction;
1108
+ if (!onAction) {
1109
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError2(
1110
+ `No handler for widget actions. You'll need to add widgets.onAction to your ChatKit options.`
1111
+ ));
1112
+ }
1113
+ return onAction(action, widgetItem);
1114
+ },
1115
+ onEntitySearch: async ({ query }) => {
1116
+ var _a2, _b2, _c2;
1117
+ return ((_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onTagSearch) == null ? void 0 : _c2.call(_b2, query)) ?? [];
1118
+ },
1119
+ onEntityClick: async ({ entity }) => {
1120
+ var _a2, _b2, _c2;
1121
+ return (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onClick) == null ? void 0 : _c2.call(_b2, entity);
1122
+ },
1123
+ onEntityPreview: async ({ entity }) => {
1124
+ var _a2, _b2, _c2;
1125
+ 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 };
1126
+ },
1127
+ onGetClientSecret: async (currentClientSecret) => {
1128
+ if (!__privateGet(this, _opts) || !("getClientSecret" in __privateGet(this, _opts).api) || !__privateGet(this, _opts).api.getClientSecret) {
1129
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError2(
1130
+ "Could not refresh the session because ChatKitOptions.api.getClientSecret is not configured."
1131
+ ));
1132
+ }
1133
+ return __privateGet(this, _opts).api.getClientSecret(currentClientSecret ?? null);
1134
+ },
1135
+ onAddMetadataToRequest: ({
1136
+ op,
1137
+ params
1138
+ }) => {
1139
+ throw new IntegrationError2(
1140
+ "ChatKit: onAddMetadataToRequest is unimplemented."
1141
+ );
1142
+ }
1143
+ }
1144
+ }));
1145
+ __privateAdd(this, _handleFrameLoad, () => {
1146
+ var _a2;
1147
+ this.dataset.loaded = "true";
1148
+ this.dispatchEvent(
1149
+ new CustomEvent("chatkit.ready", { bubbles: true, composed: true })
1150
+ );
1151
+ (_a2 = __privateGet(this, _resolveLoaded)) == null ? void 0 : _a2.call(this);
1152
+ });
1153
+ __privateAdd(this, _initialized, false);
1154
+ this.profile = profile;
1155
+ this.capabilities = getCapabilities(profile);
1156
+ }
1157
+ setProfile(profile) {
1158
+ this.profile = profile;
1159
+ this.capabilities = getCapabilities(profile);
1160
+ }
1161
+ connectedCallback() {
1162
+ const style = document.createElement("style");
1163
+ style.textContent = `
1164
+ :host {
1165
+ display: block;
1166
+ position: relative;
1167
+ height: 100%;
1168
+ width: 100%;
1169
+ }
1170
+ .ck-iframe {
1171
+ border: none;
1172
+ position: absolute;
1173
+ inset: 0;
1174
+ width: 100%;
1175
+ height: 100%;
1176
+ overflow: hidden;
1177
+ color-scheme: light only;
1178
+ }
1179
+ .ck-wrapper {
1180
+ position: absolute;
1181
+ inset: 0;
1182
+ width: 100%;
1183
+ height: 100%;
1184
+ overflow: hidden;
1185
+ opacity: 0;
1186
+ }
1187
+ :host([data-color-scheme="dark"]) .ck-iframe {
1188
+ color-scheme: dark only;
1189
+ }
1190
+ :host([data-loaded="true"]) .ck-wrapper {
1191
+ opacity: 1;
1192
+ }
1193
+ `;
1194
+ const frame = document.createElement("iframe");
1195
+ frame.className = "ck-iframe";
1196
+ frame.name = "chatkit";
1197
+ frame.role = "presentation";
1198
+ frame.tabIndex = 0;
1199
+ frame.setAttribute("allowtransparency", "true");
1200
+ frame.setAttribute("frameborder", "0");
1201
+ frame.setAttribute("scrolling", "no");
1202
+ frame.setAttribute("allow", "clipboard-read; clipboard-write");
1203
+ __privateSet(this, _frame, frame);
1204
+ const wrapper = document.createElement("div");
1205
+ wrapper.className = "ck-wrapper";
1206
+ wrapper.appendChild(frame);
1207
+ __privateSet(this, _wrapper, wrapper);
1208
+ __privateGet(this, _shadow).append(style);
1209
+ __privateGet(this, _messenger).on("left_header_icon_click", () => {
1210
+ var _a2, _b2, _c2;
1211
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.leftAction) == null ? void 0 : _c2.onClick();
1212
+ });
1213
+ __privateGet(this, _messenger).on("right_header_icon_click", () => {
1214
+ var _a2, _b2, _c2;
1215
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.rightAction) == null ? void 0 : _c2.onClick();
1216
+ });
1217
+ __privateGet(this, _messenger).on("public_event", ([event, data]) => {
1218
+ if (!this.capabilities.events.has(event)) return;
1219
+ if (event === "error" && "error" in data) {
1220
+ const error = fromPossibleFrameSafeError(data.error);
1221
+ this.dispatchEvent(
1222
+ new CustomEvent("chatkit.error", { detail: { error } })
1223
+ );
1224
+ if (error instanceof IntegrationError2) {
1225
+ throw error;
1226
+ }
1227
+ return;
1228
+ }
1229
+ this.dispatchEvent(new CustomEvent(`chatkit.${event}`, { detail: data }));
1230
+ });
1231
+ __privateGet(this, _messenger).on("unmount", () => {
1232
+ if (__privateGet(this, _wrapper) && __privateGet(this, _shadow).contains(__privateGet(this, _wrapper))) {
1233
+ __privateGet(this, _shadow).removeChild(__privateGet(this, _wrapper));
1234
+ __privateSet(this, _wrapper, void 0);
1235
+ __privateSet(this, _frame, void 0);
1236
+ }
1237
+ });
1238
+ __privateGet(this, _messenger).on(
1239
+ "capabilities_profile_change",
1240
+ ({ profile }) => {
1241
+ this.setProfile(profile);
1242
+ }
1243
+ );
1244
+ frame.addEventListener("load", __privateGet(this, _handleFrameLoad), { once: true });
1245
+ try {
1246
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
1247
+ } catch (error) {
1248
+ console.error(error);
1249
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError2("Failed to initialize ChatKit"));
1250
+ }
1251
+ }
1252
+ disconnectedCallback() {
1253
+ var _a2;
1254
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.removeEventListener("load", __privateGet(this, _handleFrameLoad));
1255
+ __privateGet(this, _messenger).disconnect();
1256
+ }
1257
+ applySanitizedOptions(newOptions) {
1258
+ __privateSet(this, _opts, newOptions);
1259
+ if (__privateGet(this, _initialized)) {
1260
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
1261
+ __privateGet(this, _loaded).then(() => {
1262
+ __privateGet(this, _messenger).commands.setOptions(getInnerOptions(newOptions));
1263
+ });
1264
+ } else {
1265
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
1266
+ }
1267
+ }
1268
+ setOptions(newOptions) {
1269
+ try {
1270
+ const sanitized = this.sanitizeOptions(newOptions);
1271
+ __privateMethod(this, _ChatKitElementBase_instances, consumeFrameUrl_fn).call(this, sanitized);
1272
+ this.applySanitizedOptions(sanitized);
1273
+ } catch (error) {
1274
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError2("Failed to parse options"));
1275
+ }
1276
+ }
1277
+ async focusComposer() {
1278
+ var _a2, _b2;
1279
+ await __privateGet(this, _loaded);
1280
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.focus();
1281
+ await ((_b2 = __privateGet(this, _messenger)) == null ? void 0 : _b2.commands.focusComposer());
1282
+ }
1283
+ async fetchUpdates() {
1284
+ var _a2;
1285
+ await __privateGet(this, _loaded);
1286
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.fetchUpdates());
1287
+ }
1288
+ async sendUserMessage(params) {
1289
+ var _a2;
1290
+ await __privateGet(this, _loaded);
1291
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendUserMessage(params));
1292
+ }
1293
+ async setComposerValue(params) {
1294
+ var _a2;
1295
+ await __privateGet(this, _loaded);
1296
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setComposerValue(params));
1297
+ }
1298
+ async setThreadId(threadId) {
1299
+ var _a2;
1300
+ await __privateGet(this, _loaded);
1301
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setThreadId({ threadId }));
1302
+ }
1303
+ async shareThread() {
1304
+ var _a2;
1305
+ await __privateGet(this, _loaded);
1306
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.shareThread();
1307
+ }
1308
+ async sendCustomAction(action, itemId) {
1309
+ var _a2;
1310
+ await __privateGet(this, _loaded);
1311
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendCustomAction({ action, itemId });
1312
+ }
1313
+ async showHistory() {
1314
+ var _a2;
1315
+ await __privateGet(this, _loaded);
1316
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.showHistory();
1317
+ }
1318
+ async hideHistory() {
1319
+ var _a2;
1320
+ await __privateGet(this, _loaded);
1321
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.hideHistory();
1322
+ }
1323
+ async setTrainingOptOut(value) {
1324
+ var _a2;
1325
+ await __privateGet(this, _loaded);
1326
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setTrainingOptOut({ value });
1327
+ }
1328
+ }
1329
+ _init = __decoratorStart(_c);
1330
+ _opts = new WeakMap();
1331
+ _frameUrl = new WeakMap();
1332
+ _frame = new WeakMap();
1333
+ _wrapper = new WeakMap();
1334
+ _shadow = new WeakMap();
1335
+ _resolveLoaded = new WeakMap();
1336
+ _loaded = new WeakMap();
1337
+ _messenger = new WeakMap();
1338
+ _ChatKitElementBase_instances = new WeakSet();
1339
+ emitAndThrow_fn = function(error) {
1340
+ this.dispatchEvent(new CustomEvent("chatkit.error", { detail: { error } }));
1341
+ throw error;
1342
+ };
1343
+ setOptionsDataAttributes_fn = function(options) {
1344
+ var _a2;
1345
+ this.dataset.colorScheme = typeof options.theme === "string" ? options.theme : ((_a2 = options.theme) == null ? void 0 : _a2.colorScheme) ?? "light";
1346
+ };
1347
+ getFrameUrl_fn = function() {
1348
+ if (!__privateGet(this, _frameUrl)) {
1349
+ throw new IntegrationError2(
1350
+ "ChatKit frameUrl is not configured. Provide it via setOptions({ frameUrl }) before mounting."
1351
+ );
1352
+ }
1353
+ return __privateGet(this, _frameUrl);
1354
+ };
1355
+ setFrameUrl_fn = function(frameUrl) {
1356
+ if (__privateGet(this, _initialized) && __privateGet(this, _frameUrl) && __privateGet(this, _frameUrl) !== frameUrl) {
1357
+ throw new IntegrationError2(
1358
+ "ChatKit frameUrl cannot be changed after initialization. Create a new element to use a different URL."
1359
+ );
1360
+ }
1361
+ __privateSet(this, _frameUrl, frameUrl);
1362
+ };
1363
+ consumeFrameUrl_fn = function(options) {
1364
+ if (!("frameUrl" in options)) return;
1365
+ const frameUrl = options.frameUrl;
1366
+ delete options.frameUrl;
1367
+ if (frameUrl == null) return;
1368
+ if (typeof frameUrl !== "string" || frameUrl.trim() === "") {
1369
+ throw new IntegrationError2(
1370
+ "ChatKit frameUrl must be a non-empty string."
1371
+ );
1372
+ }
1373
+ __privateMethod(this, _ChatKitElementBase_instances, setFrameUrl_fn).call(this, frameUrl);
1374
+ };
1375
+ _handleFrameLoad = new WeakMap();
1376
+ _initialized = new WeakMap();
1377
+ maybeInit_fn = function() {
1378
+ if (__privateGet(this, _initialized) || !__privateGet(this, _frame) || !__privateGet(this, _opts)) {
1379
+ return;
1380
+ }
1381
+ __privateSet(this, _initialized, true);
1382
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
1383
+ const frameURL = new URL(__privateMethod(this, _ChatKitElementBase_instances, getFrameUrl_fn).call(this), window.location.origin);
1384
+ __privateGet(this, _messenger).setTargetOrigin(frameURL.origin);
1385
+ frameURL.hash = encodeBase64({
1386
+ options: getInnerOptions(__privateGet(this, _opts)),
1387
+ referrer: window.location.origin,
1388
+ profile: this.profile
1389
+ });
1390
+ __privateGet(this, _messenger).connect();
1391
+ __privateGet(this, _frame).src = frameURL.toString();
1392
+ if (__privateGet(this, _wrapper)) {
1393
+ __privateGet(this, _shadow).append(__privateGet(this, _wrapper));
1394
+ }
1395
+ };
1396
+ __decorateElement(_init, 1, "focusComposer", _focusComposer_dec, ChatKitElementBase);
1397
+ __decorateElement(_init, 1, "fetchUpdates", _fetchUpdates_dec, ChatKitElementBase);
1398
+ __decorateElement(_init, 1, "sendUserMessage", _sendUserMessage_dec, ChatKitElementBase);
1399
+ __decorateElement(_init, 1, "setComposerValue", _setComposerValue_dec, ChatKitElementBase);
1400
+ __decorateElement(_init, 1, "setThreadId", _setThreadId_dec, ChatKitElementBase);
1401
+ __decorateElement(_init, 1, "shareThread", _shareThread_dec, ChatKitElementBase);
1402
+ __decorateElement(_init, 1, "sendCustomAction", _sendCustomAction_dec, ChatKitElementBase);
1403
+ __decorateElement(_init, 1, "showHistory", _showHistory_dec, ChatKitElementBase);
1404
+ __decorateElement(_init, 1, "hideHistory", _hideHistory_dec, ChatKitElementBase);
1405
+ __decorateElement(_init, 1, "setTrainingOptOut", _setTrainingOptOut_dec, ChatKitElementBase);
1406
+ __decoratorMetadata(_init, ChatKitElementBase);
1407
+ class ChatKitElement extends ChatKitElementBase {
1408
+ constructor() {
1409
+ super({ profile: "chatkit" });
1410
+ }
1411
+ sanitizeOptions(options) {
1412
+ var _a2;
1413
+ (_a2 = options.threadItemActions) == null ? true : delete _a2.share;
1414
+ return options;
1415
+ }
1416
+ }
1417
+ function registerChatKitElement(tag = "xpertai-chatkit") {
1418
+ if (!("customElements" in globalThis)) return;
1419
+ if (!customElements.get(tag)) {
1420
+ customElements.define(tag, ChatKitElement);
1421
+ }
1422
+ }
1423
+ registerChatKitElement();
142
1424
  const EVENT_HANDLER_MAP = {
143
1425
  "chatkit.error": "onError",
144
1426
  "chatkit.response.end": "onResponseEnd",