@xpert-ai/chatkit-ui5 0.0.1 → 0.1.0

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