@aikaara/chat-sdk 0.3.0 → 0.3.3

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/headless.mjs CHANGED
@@ -1,37 +1,37 @@
1
- import { E as y } from "./AikaaraChatClient-Cqbcd1jb.mjs";
2
- import { A as v, a as F, b as I, C as _, c as E, d as b, M as w, T as U, e as C, i as k, f as j, p as A } from "./AikaaraChatClient-Cqbcd1jb.mjs";
3
- class m extends y {
1
+ import { E as I } from "./ui-BMGa0gZH.mjs";
2
+ import { A as $, b as q, k as N, C as M, l as P, m as D, M as z, T as B, n as H, o as O, p as V, q as W } from "./ui-BMGa0gZH.mjs";
3
+ class F extends I {
4
4
  registration = null;
5
5
  pendingEdits = [];
6
- constructor(t) {
7
- super(), this.setupListeners(t);
6
+ constructor(e) {
7
+ super(), this.setupListeners(e);
8
8
  }
9
9
  /**
10
10
  * Register a form to receive AI-driven edits.
11
11
  * Only one form can be registered at a time (the active page).
12
12
  */
13
- registerForm(t) {
14
- this.registration = t;
15
- const e = this.pendingEdits.filter(
16
- (i) => i.entity_type === t.entityType && String(i.entity_id) === String(t.entityId)
13
+ registerForm(e) {
14
+ this.registration = e;
15
+ const r = this.pendingEdits.filter(
16
+ (i) => i.entity_type === e.entityType && String(i.entity_id) === String(e.entityId)
17
17
  );
18
- if (e.length > 0) {
19
- for (const i of e)
20
- t.onFieldUpdate(i.fields), this.emit("edit:applied", {
18
+ if (r.length > 0) {
19
+ for (const i of r)
20
+ e.onFieldUpdate(i.fields), this.emit("edit:applied", {
21
21
  entityType: i.entity_type,
22
22
  entityId: i.entity_id,
23
23
  fields: i.fields
24
24
  });
25
25
  this.pendingEdits = this.pendingEdits.filter(
26
- (i) => !(i.entity_type === t.entityType && String(i.entity_id) === String(t.entityId))
26
+ (i) => !(i.entity_type === e.entityType && String(i.entity_id) === String(e.entityId))
27
27
  );
28
28
  }
29
29
  }
30
30
  /**
31
31
  * Unregister the form (call on unmount).
32
32
  */
33
- unregisterForm(t, e) {
34
- this.registration?.entityType === t && String(this.registration?.entityId) === String(e) && (this.registration = null);
33
+ unregisterForm(e, r) {
34
+ this.registration?.entityType === e && String(this.registration?.entityId) === String(r) && (this.registration = null);
35
35
  }
36
36
  /**
37
37
  * Get the current form registration (if any).
@@ -42,13 +42,13 @@ class m extends y {
42
42
  /**
43
43
  * Manually push field updates (for custom tool handling).
44
44
  */
45
- pushFieldUpdates(t, e, i) {
46
- this.registration && this.registration.entityType === t && String(this.registration.entityId) === String(e) ? (this.registration.onFieldUpdate(i), this.emit("edit:applied", { entityType: t, entityId: e, fields: i })) : (this.pendingEdits.push({
45
+ pushFieldUpdates(e, r, i) {
46
+ this.registration && this.registration.entityType === e && String(this.registration.entityId) === String(r) ? (this.registration.onFieldUpdate(i), this.emit("edit:applied", { entityType: e, entityId: r, fields: i })) : (this.pendingEdits.push({
47
47
  action: "edit_entity",
48
- entity_type: t,
49
- entity_id: e,
48
+ entity_type: e,
49
+ entity_id: r,
50
50
  fields: i
51
- }), this.emit("edit:pending", { entityType: t, entityId: e, fields: i }));
51
+ }), this.emit("edit:pending", { entityType: e, entityId: r, fields: i }));
52
52
  }
53
53
  /**
54
54
  * Request the current form to save.
@@ -61,61 +61,61 @@ class m extends y {
61
61
  entityType: this.registration.entityType,
62
62
  entityId: this.registration.entityId
63
63
  }), { success: !0 };
64
- } catch (t) {
65
- const e = t instanceof Error ? t.message : "Save failed";
64
+ } catch (e) {
65
+ const r = e instanceof Error ? e.message : "Save failed";
66
66
  return this.emit("save:error", {
67
67
  entityType: this.registration.entityType,
68
68
  entityId: this.registration.entityId,
69
- error: e
70
- }), { success: !1, error: e };
69
+ error: r
70
+ }), { success: !1, error: r };
71
71
  }
72
72
  }
73
73
  /**
74
74
  * Request the current form to run a test.
75
75
  */
76
- async requestTest(t) {
76
+ async requestTest(e) {
77
77
  if (!this.registration?.onTest)
78
78
  return { success: !1, error: "Current form does not support testing" };
79
79
  try {
80
- return await this.registration.onTest(t), { success: !0 };
81
- } catch (e) {
82
- return { success: !1, error: e instanceof Error ? e.message : "Test failed" };
80
+ return await this.registration.onTest(e), { success: !0 };
81
+ } catch (r) {
82
+ return { success: !1, error: r instanceof Error ? r.message : "Test failed" };
83
83
  }
84
84
  }
85
- setupListeners(t) {
86
- t.on("action:edit_entity", (e) => {
87
- this.pushFieldUpdates(e.entity_type, e.entity_id, e.fields);
88
- }), t.on("action:save_entity", (e) => {
85
+ setupListeners(e) {
86
+ e.on("action:edit_entity", (r) => {
87
+ this.pushFieldUpdates(r.entity_type, r.entity_id, r.fields);
88
+ }), e.on("action:save_entity", (r) => {
89
89
  this.requestSave();
90
- }), t.on("action:test_tool", (e) => {
91
- this.emit("test:triggered", { toolId: e.tool_id, parameters: e.parameters }), this.requestTest(e.parameters);
90
+ }), e.on("action:test_tool", (r) => {
91
+ this.emit("test:triggered", { toolId: r.tool_id, parameters: r.parameters }), this.requestTest(r.parameters);
92
92
  });
93
93
  }
94
94
  }
95
- function g(r) {
95
+ function T(t) {
96
96
  return {
97
- async upload(t, e) {
98
- const i = new FormData(), p = r.fieldName ?? "file";
99
- i.append(p, t, t.name);
100
- const a = typeof r.extraFields == "function" ? r.extraFields(e) : r.extraFields;
101
- if (a)
102
- for (const [c, u] of Object.entries(a)) i.append(c, u);
103
- i.append("conversationId", e.conversationId), i.append("userId", e.userId), e.projectId && i.append("projectId", e.projectId);
104
- const l = typeof r.headers == "function" ? await r.headers() : r.headers ?? {}, n = await fetch(r.endpoint, {
105
- method: r.method ?? "POST",
97
+ async upload(e, r) {
98
+ const i = new FormData(), a = t.fieldName ?? "file";
99
+ i.append(a, e, e.name);
100
+ const n = typeof t.extraFields == "function" ? t.extraFields(r) : t.extraFields;
101
+ if (n)
102
+ for (const [y, h] of Object.entries(n)) i.append(y, h);
103
+ i.append("conversationId", r.conversationId), i.append("userId", r.userId), r.projectId && i.append("projectId", r.projectId);
104
+ const o = typeof t.headers == "function" ? await t.headers() : t.headers ?? {}, p = await fetch(t.endpoint, {
105
+ method: t.method ?? "POST",
106
106
  body: i,
107
- headers: l,
108
- credentials: r.credentials
107
+ headers: o,
108
+ credentials: t.credentials
109
109
  });
110
- if (!n.ok)
111
- throw new Error(`Upload failed: ${n.status} ${n.statusText}`);
112
- const o = await n.json().catch(() => ({}));
113
- if (r.parseResponse) return r.parseResponse(o, e);
114
- const s = o, d = s.url ?? s.fileUrl ?? s.publicUrl, h = s.fileName ?? s.name ?? t.name;
115
- if (!d) throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');
110
+ if (!p.ok)
111
+ throw new Error(`Upload failed: ${p.status} ${p.statusText}`);
112
+ const d = await p.json().catch(() => ({}));
113
+ if (t.parseResponse) return t.parseResponse(d, r);
114
+ const s = d, c = s.url ?? s.fileUrl ?? s.publicUrl, m = s.fileName ?? s.name ?? e.name;
115
+ if (!c) throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');
116
116
  return {
117
- url: d,
118
- fileName: h,
117
+ url: c,
118
+ fileName: m,
119
119
  cloudFileId: typeof s.cloudFileId == "string" ? s.cloudFileId : void 0,
120
120
  relativePath: typeof s.path == "string" ? s.path : void 0,
121
121
  contentType: typeof s.contentType == "string" ? s.contentType : void 0,
@@ -125,20 +125,190 @@ function g(r) {
125
125
  }
126
126
  };
127
127
  }
128
+ const x = "/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";
129
+ function v(t) {
130
+ const e = t.apiBase.replace(/\/$/, ""), r = t.pageSize ?? 200, i = t.pathTemplate ?? x;
131
+ return {
132
+ async fetchMessages(a, n) {
133
+ const o = i.replace("{userId}", encodeURIComponent(n.userId)).replace("{conversationId}", encodeURIComponent(a)).replace("{appId}", encodeURIComponent(n.appId ?? "tilechat")).replace("{projectId}", encodeURIComponent(n.projectId ?? "")).replace("{pageSize}", String(r)), p = o.startsWith("http") ? o : `${e}${o.startsWith("/") ? o : `/${o}`}`, d = {
134
+ accept: "application/json",
135
+ // Some Spring/chat21 backends reject GETs without an explicit
136
+ // Content-Type — match bandhan's chatapi which sends it on GETs.
137
+ "content-type": "application/json",
138
+ ...t.extraHeaders ?? {}
139
+ };
140
+ if (t.getToken) {
141
+ const y = await t.getToken();
142
+ y && (d.authorization = y);
143
+ }
144
+ const s = await fetch(p, { method: "GET", headers: d, credentials: "include" }), c = await s.json().catch(() => null);
145
+ if (t.parseResponse && c) return t.parseResponse(c);
146
+ const m = c;
147
+ if (m && Array.isArray(m.result))
148
+ return m.result;
149
+ if (!s.ok) throw new Error(`History fetch failed: ${s.status} ${s.statusText}`);
150
+ return [];
151
+ }
152
+ };
153
+ }
154
+ function w() {
155
+ const t = typeof crypto < "u" ? crypto : null;
156
+ if (t?.randomUUID) return t.randomUUID();
157
+ if (t?.getRandomValues) {
158
+ const e = new Uint8Array(16);
159
+ t.getRandomValues(e), e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
160
+ const r = [...e].map((i) => i.toString(16).padStart(2, "0")).join("");
161
+ return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
162
+ }
163
+ return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, (e) => {
164
+ const r = Math.random() * 16 | 0;
165
+ return (e === "x" ? r : r & 3 | 8).toString(16);
166
+ });
167
+ }
168
+ const S = "aikaara_chat:requestId";
169
+ function f(t, e) {
170
+ return `${S}:${t}:${e}`;
171
+ }
172
+ function b(t, e) {
173
+ try {
174
+ return localStorage.getItem(f(t, e));
175
+ } catch {
176
+ return null;
177
+ }
178
+ }
179
+ function k(t, e, r) {
180
+ try {
181
+ localStorage.setItem(f(t, e), r);
182
+ } catch {
183
+ }
184
+ }
185
+ function C(t, e) {
186
+ try {
187
+ localStorage.removeItem(f(t, e));
188
+ } catch {
189
+ }
190
+ }
191
+ async function E(t, e) {
192
+ const r = await fetch(t, {
193
+ method: "GET",
194
+ headers: { accept: "application/json", ...e ?? {} }
195
+ });
196
+ if (!r.ok) {
197
+ const a = await r.text().catch(() => "");
198
+ throw new Error(`Widget config fetch failed: ${r.status} ${r.statusText} ${a.slice(0, 200)}`);
199
+ }
200
+ const i = await r.json();
201
+ if (i && typeof i == "object") {
202
+ if ("config" in i) return i.config;
203
+ if ("data" in i) return i.data;
204
+ }
205
+ return i;
206
+ }
207
+ function A(t, e) {
208
+ return t.replace("{projectId}", e).replace("{uuid}", w().replace(/-/g, ""));
209
+ }
210
+ async function j(t) {
211
+ const e = {
212
+ ...t.config ?? (t.configUrl ? await E(t.configUrl, t.configHeaders) : {}),
213
+ ...t.overrides ?? {}
214
+ }, r = e.transport ?? "tiledesk", i = e.tiledesk;
215
+ if ((r === "tiledesk" || r === "dual") && !i)
216
+ throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");
217
+ const a = i?.projectId ?? "", n = t.identity.userId, o = t.forceNewConversation ? null : b(n, a), p = i?.requestIdTemplate ?? "support-group-{projectId}-{uuid}", d = t.conversationId ?? o ?? A(p, a);
218
+ (!o || t.forceNewConversation) && a && k(n, a, d);
219
+ const s = await t.tokenProvider(), c = t.tokenProvider, m = t.historyTokenProvider ?? c, y = i ? {
220
+ mqttEndpoint: i.mqttEndpoint,
221
+ jwtToken: s,
222
+ userId: n,
223
+ userName: t.identity.userName,
224
+ projectId: i.projectId,
225
+ appId: i.appId,
226
+ mqttUsername: i.mqttUsername,
227
+ protocolId: i.protocolId,
228
+ protocolVersion: i.protocolVersion,
229
+ keepAliveSec: i.keepAliveSec,
230
+ connectTimeoutMs: i.connectTimeoutMs,
231
+ maxReconnectAttempts: i.maxReconnectAttempts,
232
+ reconnectMaxDelayMs: i.reconnectMaxDelayMs,
233
+ wildcardSubscribe: i.wildcardSubscribe,
234
+ enablePresence: i.enablePresence,
235
+ autoInitiateOnEmpty: i.autoInitiateOnEmpty,
236
+ chatInitiatedAttributes: i.chatInitiatedAttributes,
237
+ messageDefaults: {
238
+ ...i.messageDefaults,
239
+ ...t.identity.departmentId ? { departmentId: t.identity.departmentId } : i.messageDefaults?.departmentId ? { departmentId: i.messageDefaults.departmentId } : {}
240
+ },
241
+ fileTemplate: i.fileTemplate,
242
+ topicTemplates: i.topicTemplates,
243
+ debug: i.debug,
244
+ senderFullname: t.identity.senderFullname ?? t.identity.userName,
245
+ tokenProvider: c
246
+ } : void 0, h = t.uploadAdapter ?? (e.uploadEndpoint ? T({
247
+ endpoint: e.uploadEndpoint,
248
+ fieldName: e.uploadFieldName,
249
+ extraFields: e.uploadExtraFields
250
+ }) : void 0), g = t.historyAdapter ?? (e.historyApiBase ? v({
251
+ apiBase: e.historyApiBase,
252
+ pageSize: e.historyPageSize ?? 200,
253
+ pathTemplate: e.historyPathTemplate,
254
+ getToken: m
255
+ }) : void 0), l = {
256
+ transport: r,
257
+ baseUrl: "",
258
+ userToken: n,
259
+ conversationId: d,
260
+ display: e.display ?? "embed",
261
+ position: e.position,
262
+ primaryColor: e.primaryColor,
263
+ title: e.title,
264
+ subtitle: e.subtitle,
265
+ avatarUrl: e.avatarUrl,
266
+ width: e.width,
267
+ height: e.height,
268
+ borderRadius: e.borderRadius,
269
+ fontFamily: e.fontFamily,
270
+ welcomeMessage: e.welcomeMessage,
271
+ placeholder: e.placeholder,
272
+ showTimestamps: e.showTimestamps,
273
+ persistConversation: e.persistConversation,
274
+ tiledesk: y,
275
+ tiledeskIdentity: {
276
+ userId: n,
277
+ userName: t.identity.userName,
278
+ departmentId: t.identity.departmentId,
279
+ senderFullname: t.identity.senderFullname ?? t.identity.userName
280
+ },
281
+ templateActionAttributes: e.templateActionAttributes,
282
+ uploadAdapter: h,
283
+ historyAdapter: g,
284
+ onError: t.onError
285
+ }, u = document.createElement("aikaara-chat-widget");
286
+ return u.configure(l), l.title && u.setAttribute("title", l.title), l.primaryColor && u.setAttribute("primary-color", l.primaryColor), l.display && u.setAttribute("display", l.display), l.display === "embed" && (u.style.cssText = "display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"), t.container.appendChild(u), {
287
+ widget: u,
288
+ requestId: d,
289
+ config: l,
290
+ destroy() {
291
+ u.remove();
292
+ }
293
+ };
294
+ }
128
295
  export {
129
- v as ActionCableClient,
130
- F as AikaaraChatClient,
131
- I as ApiClient,
132
- _ as ChannelSubscription,
133
- E as ConnectionManager,
134
- b as ConversationManager,
135
- y as EventEmitter,
136
- m as FormBridge,
137
- w as MessageStore,
138
- U as TiledeskTransport,
139
- g as createFetchUploadAdapter,
140
- C as extractTiledeskFileEnvelope,
141
- k as inferTiledeskRole,
142
- j as isTiledeskSelfEcho,
143
- A as parseTiledeskTemplate
296
+ $ as ActionCableClient,
297
+ q as AikaaraChatClient,
298
+ N as ApiClient,
299
+ M as ChannelSubscription,
300
+ P as ConnectionManager,
301
+ D as ConversationManager,
302
+ I as EventEmitter,
303
+ F as FormBridge,
304
+ z as MessageStore,
305
+ B as TiledeskTransport,
306
+ C as clearPersistedConversationId,
307
+ T as createFetchUploadAdapter,
308
+ v as createTiledeskHistoryAdapter,
309
+ H as extractTiledeskFileEnvelope,
310
+ O as inferTiledeskRole,
311
+ V as isTiledeskSelfEcho,
312
+ j as mountTenantWidget,
313
+ W as parseTiledeskTemplate
144
314
  };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./AikaaraChatClient-kAu65hX-.cjs"),n=require("./headless.cjs"),a=require("./ui.cjs");function c(t){a.registerComponents();const r=document.createElement("aikaara-chat-widget"),o={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[s,l]of Object.entries(o)){const i=t[s];i!=null&&r.setAttribute(l,String(i))}return r.configure(t),document.body.appendChild(r),r}function d(){const t=document.querySelector("aikaara-chat-widget");t&&t.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.TiledeskTransport=e.TiledeskTransport;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.FormBridge=n.FormBridge;exports.createFetchUploadAdapter=n.createFetchUploadAdapter;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;exports.mount=c;exports.unmount=d;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./ui-B0-Np9Dn.cjs"),t=require("./headless.cjs");function l(a){e.registerComponents();const r=document.createElement("aikaara-chat-widget"),n={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,s]of Object.entries(n)){const i=a[o];i!=null&&r.setAttribute(s,String(i))}return r.configure(a),document.body.appendChild(r),r}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.TiledeskTransport=e.TiledeskTransport;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.FormBridge=t.FormBridge;exports.clearPersistedConversationId=t.clearPersistedConversationId;exports.createFetchUploadAdapter=t.createFetchUploadAdapter;exports.createTiledeskHistoryAdapter=t.createTiledeskHistoryAdapter;exports.mountTenantWidget=t.mountTenantWidget;exports.mount=l;exports.unmount=d;