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