@vettvangur/ai-sdk 0.8.1 → 0.10.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.
@@ -0,0 +1,534 @@
1
+ //#region src/live-chat/moments.ts
2
+ const FINGERPRINT = "@@livechat/postmessenger";
3
+ const FOUR_WAY_HANDSHAKE = "@@livechat/4way";
4
+ const HANDSHAKE_INTERVAL_MS = 500;
5
+ const HANDSHAKE_TRIES = 10;
6
+ const ECHO_REQUEST = 0;
7
+ const SUPPORTED_METHODS = ["sendMessage", "close"];
8
+ function isEnvelope(value, owner) {
9
+ return typeof value === "object" && value !== null && value[FINGERPRINT] === true && value.owner === owner && value.instance === 0;
10
+ }
11
+ function call(data) {
12
+ if (typeof data !== "object" || data === null) return null;
13
+ const { method, args } = data;
14
+ return typeof method === "string" ? {
15
+ method,
16
+ args: Array.isArray(args) ? args : []
17
+ } : null;
18
+ }
19
+ function messageText(arg) {
20
+ const text = typeof arg === "object" && arg !== null ? arg.text : null;
21
+ return typeof text === "string" ? text.trim() : "";
22
+ }
23
+ /**
24
+ * Hosts a LiveChat Moments app in `frame`: its `sendMessage` goes into the chat as the visitor's
25
+ * message and its `close` closes the sheet. A page that is not a Moments app never answers the
26
+ * handshake and is left alone. Each load of the frame is a new handshake. Returns a disconnect.
27
+ */
28
+ function hostMoments(frame, host) {
29
+ const view = frame.ownerDocument.defaultView;
30
+ if (!view) return () => {};
31
+ const owner = crypto.randomUUID();
32
+ const origin = new URL(frame.src, frame.ownerDocument.baseURI).origin;
33
+ let state = "handshake";
34
+ let timer = null;
35
+ function post(message) {
36
+ frame.contentWindow?.postMessage(message, origin);
37
+ }
38
+ function envelope(type, data, request) {
39
+ return {
40
+ [FINGERPRINT]: true,
41
+ owner,
42
+ instance: 0,
43
+ type,
44
+ data,
45
+ request
46
+ };
47
+ }
48
+ function stopHandshake() {
49
+ if (timer) clearInterval(timer);
50
+ timer = null;
51
+ }
52
+ function handshake() {
53
+ stopHandshake();
54
+ state = "handshake";
55
+ let tries = 0;
56
+ const send = () => {
57
+ tries += 1;
58
+ if (state !== "handshake" || tries > HANDSHAKE_TRIES) {
59
+ stopHandshake();
60
+ return;
61
+ }
62
+ post(envelope("handshake", { supportedMethods: SUPPORTED_METHODS }, null));
63
+ };
64
+ send();
65
+ timer = setInterval(send, HANDSHAKE_INTERVAL_MS);
66
+ }
67
+ async function run(method, args) {
68
+ switch (method) {
69
+ case "sendMessage": {
70
+ const text = messageText(args[0]);
71
+ if (text) await host.send(text);
72
+ return null;
73
+ }
74
+ case "close":
75
+ host.close();
76
+ return null;
77
+ default: throw new Error(`The chat window does not support ${method}`);
78
+ }
79
+ }
80
+ function receive(event) {
81
+ if (event.source !== frame.contentWindow || event.origin !== origin || !isEnvelope(event.data, owner)) return;
82
+ const message = event.data;
83
+ if (message.type === "response" && state === "handshake" && message.request === null) {
84
+ stopHandshake();
85
+ const result = message.data?.result;
86
+ if (typeof result === "object" && result !== null && FOUR_WAY_HANDSHAKE in result) {
87
+ state = "echo";
88
+ post(envelope("handshake_echo", void 0, ECHO_REQUEST));
89
+ } else state = "connected";
90
+ return;
91
+ }
92
+ if (message.type === "response" && state === "echo" && message.request === ECHO_REQUEST) {
93
+ state = "connected";
94
+ return;
95
+ }
96
+ const request = message.type === "call" && state === "connected" ? call(message.data) : null;
97
+ if (!request) return;
98
+ run(request.method, request.args).then((result) => {
99
+ post(envelope("response", {
100
+ error: false,
101
+ result
102
+ }, message.request ?? null));
103
+ }, (caught) => {
104
+ post(envelope("response", {
105
+ error: true,
106
+ result: {
107
+ real: true,
108
+ error: { message: caught instanceof Error ? caught.message : String(caught) }
109
+ }
110
+ }, message.request ?? null));
111
+ });
112
+ }
113
+ view.addEventListener("message", receive);
114
+ frame.addEventListener("load", handshake);
115
+ return () => {
116
+ stopHandshake();
117
+ view.removeEventListener("message", receive);
118
+ frame.removeEventListener("load", handshake);
119
+ };
120
+ }
121
+ //#endregion
122
+ //#region src/live-chat/livechat.ts
123
+ function on(sdk, method, type, handler) {
124
+ sdk[method](type, handler);
125
+ }
126
+ function chosenOptions(options, answer) {
127
+ if (typeof answer !== "string" || !answer) return [];
128
+ const ids = answer.split(",");
129
+ return options.filter((option) => ids.includes(option.id));
130
+ }
131
+ function surveyField(field) {
132
+ switch (field.type) {
133
+ case "header": return field.label.trim() ? {
134
+ kind: "note",
135
+ text: field.label
136
+ } : null;
137
+ case "name":
138
+ case "email": return {
139
+ kind: "text",
140
+ id: field.id,
141
+ name: field.type,
142
+ label: field.label,
143
+ required: field.required,
144
+ inputType: field.type === "email" ? "email" : "text",
145
+ multiline: false,
146
+ maxLength: null,
147
+ placeholder: null
148
+ };
149
+ case "question":
150
+ case "subject":
151
+ case "textarea": return {
152
+ kind: "text",
153
+ id: field.id,
154
+ name: field.id,
155
+ label: field.label,
156
+ required: field.required,
157
+ inputType: "text",
158
+ multiline: field.type === "textarea",
159
+ maxLength: null,
160
+ placeholder: null
161
+ };
162
+ case "radio":
163
+ case "select":
164
+ case "checkbox":
165
+ case "group_chooser": return {
166
+ kind: "choice",
167
+ id: field.id,
168
+ name: field.id,
169
+ label: field.label,
170
+ required: field.required,
171
+ multiple: field.type === "checkbox",
172
+ choices: field.options.map((option) => ({
173
+ label: option.label,
174
+ value: option.id
175
+ }))
176
+ };
177
+ case "checkbox_for_email": return {
178
+ kind: "toggle",
179
+ id: field.id,
180
+ name: field.id,
181
+ label: field.label,
182
+ required: field.required
183
+ };
184
+ default: throw new Error(`LiveChat pre-chat form has a ${field.type} field the window cannot ask`);
185
+ }
186
+ }
187
+ /** The pre-chat form's fields as the window asks them; a header becomes a note. */
188
+ function surveyFieldsFromForm(form) {
189
+ return form.fields.map(surveyField).filter((field) => field !== null);
190
+ }
191
+ /** The answers as the `filled_form` event LiveChat shows the agent at the top of the chat. */
192
+ function filledFormFields(form, answers) {
193
+ const filled = [];
194
+ for (const field of form.fields) {
195
+ const answer = answers[field.id];
196
+ switch (field.type) {
197
+ case "name":
198
+ case "email":
199
+ case "question":
200
+ case "subject":
201
+ case "textarea":
202
+ if (typeof answer === "string" && answer.trim()) filled.push({
203
+ type: field.type,
204
+ id: field.id,
205
+ label: field.label,
206
+ answer: answer.trim()
207
+ });
208
+ break;
209
+ case "radio":
210
+ case "select": {
211
+ const [option] = chosenOptions(field.options, answer);
212
+ if (option) filled.push({
213
+ type: field.type,
214
+ id: field.id,
215
+ label: field.label,
216
+ answer: {
217
+ id: option.id,
218
+ label: option.label
219
+ }
220
+ });
221
+ break;
222
+ }
223
+ case "checkbox": {
224
+ const options = chosenOptions(field.options, answer);
225
+ if (options.length) filled.push({
226
+ type: "checkbox",
227
+ id: field.id,
228
+ label: field.label,
229
+ answers: options.map((option) => ({
230
+ id: option.id,
231
+ label: option.label
232
+ }))
233
+ });
234
+ break;
235
+ }
236
+ case "group_chooser": {
237
+ const [option] = chosenOptions(field.options, answer);
238
+ if (option) filled.push({
239
+ type: "group_chooser",
240
+ id: field.id,
241
+ label: field.label,
242
+ answer: {
243
+ id: option.id,
244
+ label: option.label,
245
+ groupId: option.groupId
246
+ }
247
+ });
248
+ break;
249
+ }
250
+ case "checkbox_for_email": filled.push({
251
+ type: "checkbox_for_email",
252
+ id: field.id,
253
+ label: field.label,
254
+ answer: answer === true
255
+ });
256
+ }
257
+ }
258
+ return filled;
259
+ }
260
+ /**
261
+ * A rich message as an agent message: each card's title and subtitle as its text, and its link
262
+ * buttons as its buttons. A webview button, such as an agent app's sign-in, opens in a sheet over
263
+ * the thread, as LiveChat's own widget does; buttons that post back to the agent are left out.
264
+ */
265
+ function richMessage(event) {
266
+ const parts = [];
267
+ const actions = [];
268
+ for (const element of event.elements) {
269
+ if (element.title?.trim()) parts.push(`**${element.title.trim()}**`);
270
+ if (element.subtitle?.trim()) parts.push(element.subtitle.trim());
271
+ for (const button of element.buttons ?? []) if ((button.type === "url" || button.type === "open_external" || button.type === "webview") && button.text.trim()) actions.push({
272
+ label: button.text.trim(),
273
+ url: button.value,
274
+ sheet: button.type === "webview"
275
+ });
276
+ }
277
+ return {
278
+ text: parts.join("\n\n"),
279
+ actions
280
+ };
281
+ }
282
+ function errorCode(caught) {
283
+ return caught && typeof caught === "object" && "code" in caught ? String(caught.code) : null;
284
+ }
285
+ /**
286
+ * A live chat provider over LiveChat (livechat.com), through `@livechat/customer-sdk`. The SDK is
287
+ * imported and connected the first time the provider is asked anything, so a page pays for it only
288
+ * when a visitor asks for a person. LiveChat keeps the visitor's identity in the browser and allows
289
+ * them one chat, which a later handover starts a new thread in.
290
+ */
291
+ function createLiveChatProvider(config) {
292
+ const messageListeners = /* @__PURE__ */ new Set();
293
+ const typingListeners = /* @__PURE__ */ new Set();
294
+ const endedListeners = /* @__PURE__ */ new Set();
295
+ const agentListeners = /* @__PURE__ */ new Set();
296
+ const agentNames = /* @__PURE__ */ new Map();
297
+ let connection = null;
298
+ let customerId = null;
299
+ let online = false;
300
+ let form = null;
301
+ let current = null;
302
+ function agentJoined(user) {
303
+ if (user.type !== "agent") return;
304
+ agentNames.set(user.id, user.name);
305
+ for (const listener of agentListeners) listener({ name: user.name.trim() || null });
306
+ }
307
+ function receive(event) {
308
+ if (!event || event.authorId === customerId) return;
309
+ if (event.type !== "message" && event.type !== "system_message" && event.type !== "rich_message") return;
310
+ const { text, actions } = event.type === "rich_message" ? richMessage(event) : {
311
+ text: event.text.trim(),
312
+ actions: []
313
+ };
314
+ if (!text && !actions.length) return;
315
+ const system = event.type === "system_message";
316
+ const item = {
317
+ id: event.id,
318
+ text,
319
+ sender: system ? "system" : "agent",
320
+ name: system ? null : agentNames.get(event.authorId)?.trim() || null,
321
+ ...actions.length ? { actions } : {}
322
+ };
323
+ for (const listener of messageListeners) listener(item);
324
+ }
325
+ function listen(sdk) {
326
+ on(sdk, "on", "availability_updated", ({ availability }) => {
327
+ online = availability === "online";
328
+ });
329
+ on(sdk, "on", "incoming_event", ({ chatId, event }) => {
330
+ if (chatId === current?.chatId) receive(event);
331
+ });
332
+ on(sdk, "on", "incoming_typing_indicator", ({ chatId, typingIndicator }) => {
333
+ if (chatId !== current?.chatId || !typingIndicator.isTyping || typingIndicator.authorId === customerId) return;
334
+ for (const listener of typingListeners) listener();
335
+ });
336
+ on(sdk, "on", "user_added_to_chat", ({ chatId, user }) => {
337
+ if (chatId === current?.chatId) agentJoined(user);
338
+ });
339
+ on(sdk, "on", "chat_deactivated", ({ chatId }) => {
340
+ if (chatId !== current?.chatId) return;
341
+ current = null;
342
+ for (const listener of endedListeners) listener();
343
+ });
344
+ }
345
+ function load() {
346
+ if (connection) return connection;
347
+ const pending = (async () => {
348
+ const sdk = (await import("@livechat/customer-sdk")).init({
349
+ organizationId: config.organizationId,
350
+ clientId: config.clientId,
351
+ ...config.groupId === void 0 ? {} : { groupId: config.groupId }
352
+ });
353
+ try {
354
+ await new Promise((resolve, reject) => {
355
+ on(sdk, "once", "connected", ({ customer, availability }) => {
356
+ customerId = customer.id;
357
+ online = availability === "online";
358
+ resolve();
359
+ });
360
+ on(sdk, "once", "disconnected", ({ reason }) => {
361
+ reject(/* @__PURE__ */ new Error(`LiveChat could not connect: ${reason}`));
362
+ });
363
+ });
364
+ } catch (caught) {
365
+ sdk.destroy();
366
+ throw caught;
367
+ }
368
+ listen(sdk);
369
+ return sdk;
370
+ })();
371
+ pending.catch(() => {
372
+ if (connection === pending) connection = null;
373
+ });
374
+ connection = pending;
375
+ return pending;
376
+ }
377
+ function adopt(chatId, thread, users, replay) {
378
+ current = {
379
+ chatId,
380
+ threadId: thread.id
381
+ };
382
+ for (const user of users) if (user.type === "agent" && user.present) agentJoined(user);
383
+ if (replay) for (const event of thread.events) receive(event);
384
+ }
385
+ return {
386
+ async availability() {
387
+ await load();
388
+ return online ? { status: "open" } : {
389
+ status: "closed",
390
+ reason: "no-agents"
391
+ };
392
+ },
393
+ async survey() {
394
+ const response = await (await load()).getForm({
395
+ groupId: config.groupId ?? 0,
396
+ type: "prechat"
397
+ });
398
+ form = response.enabled ? response.form : null;
399
+ return form ? surveyFieldsFromForm(form) : null;
400
+ },
401
+ async start(options) {
402
+ const sdk = await load();
403
+ if (options.resume) {
404
+ const chat = await sdk.getChat({ chatId: options.resume });
405
+ if (!chat.thread?.active) throw new Error("LiveChat chat has ended");
406
+ adopt(chat.id, chat.thread, chat.users, true);
407
+ return;
408
+ }
409
+ const answers = options.answers ?? {};
410
+ const filled = form ? filledFormFields(form, answers) : [];
411
+ const name = filled.find((field) => field.type === "name");
412
+ const email = filled.find((field) => field.type === "email");
413
+ const group = filled.find((field) => field.type === "group_chooser");
414
+ if (name?.answer || email?.answer) await sdk.updateCustomer({
415
+ ...name?.answer ? { name: name.answer } : {},
416
+ ...email?.answer ? { email: email.answer } : {}
417
+ });
418
+ if (options.context && Object.keys(options.context).length) await sdk.setCustomerSessionFields({ sessionFields: options.context });
419
+ const events = [];
420
+ if (form && filled.length) events.push({
421
+ type: "filled_form",
422
+ formId: form.id,
423
+ formType: "prechat",
424
+ properties: {},
425
+ fields: filled
426
+ });
427
+ if (options.openingMessage) events.push({
428
+ type: "message",
429
+ text: options.openingMessage,
430
+ properties: {}
431
+ });
432
+ const chat = {
433
+ ...group?.answer ? { access: { groupIds: [group.answer.groupId] } } : {},
434
+ thread: { events }
435
+ };
436
+ try {
437
+ const { chat: started } = await sdk.startChat({ chat });
438
+ adopt(started.id, started.thread, started.users, false);
439
+ } catch (caught) {
440
+ if (errorCode(caught) !== "CHAT_LIMIT_REACHED") throw caught;
441
+ const { chatsSummary } = await sdk.listChats({ limit: 1 });
442
+ const earlier = chatsSummary[0];
443
+ if (!earlier) throw caught;
444
+ if (earlier.active) {
445
+ const open = await sdk.getChat({ chatId: earlier.id });
446
+ if (open.thread?.active) {
447
+ adopt(open.id, open.thread, open.users, false);
448
+ return;
449
+ }
450
+ }
451
+ const { chat: resumed } = await sdk.resumeChat({ chat: {
452
+ id: earlier.id,
453
+ ...chat
454
+ } });
455
+ adopt(resumed.id, resumed.thread, resumed.users, false);
456
+ }
457
+ },
458
+ async send(text) {
459
+ const sdk = await load();
460
+ if (!current) throw new Error("LiveChat has no chat to send to");
461
+ await sdk.sendEvent({
462
+ chatId: current.chatId,
463
+ event: {
464
+ type: "message",
465
+ text,
466
+ properties: {}
467
+ }
468
+ });
469
+ },
470
+ async typing() {},
471
+ async draft(text) {
472
+ const sdk = await load();
473
+ if (current) sdk.setSneakPeek({
474
+ chatId: current.chatId,
475
+ sneakPeekText: text
476
+ });
477
+ },
478
+ async end() {
479
+ if (!connection || !current) return;
480
+ const sdk = await connection;
481
+ const { chatId } = current;
482
+ current = null;
483
+ await sdk.deactivateChat({ id: chatId });
484
+ },
485
+ onMessage(listener) {
486
+ messageListeners.add(listener);
487
+ return () => messageListeners.delete(listener);
488
+ },
489
+ onTyping(listener) {
490
+ typingListeners.add(listener);
491
+ return () => typingListeners.delete(listener);
492
+ },
493
+ onEnded(listener) {
494
+ endedListeners.add(listener);
495
+ return () => endedListeners.delete(listener);
496
+ },
497
+ onAgent(listener) {
498
+ agentListeners.add(listener);
499
+ return () => agentListeners.delete(listener);
500
+ },
501
+ async resumeToken() {
502
+ return current?.chatId ?? null;
503
+ },
504
+ async emailTranscript({ email }) {
505
+ const sdk = await load();
506
+ if (!current) throw new Error("LiveChat has no chat to send a transcript of");
507
+ await sdk.updateThreadProperties({
508
+ chatId: current.chatId,
509
+ threadId: current.threadId,
510
+ properties: { routing: { transcript_email: email } }
511
+ });
512
+ },
513
+ async upload(file) {
514
+ const sdk = await load();
515
+ if (!current) throw new Error("LiveChat has no chat to upload to");
516
+ const { chatId } = current;
517
+ const { url } = await sdk.uploadFile({ file }).promise;
518
+ await sdk.sendEvent({
519
+ chatId,
520
+ event: {
521
+ type: "file",
522
+ url,
523
+ alternativeText: file.name,
524
+ properties: {}
525
+ }
526
+ });
527
+ },
528
+ connectSheet(frame, host) {
529
+ return hostMoments(frame, host);
530
+ }
531
+ };
532
+ }
533
+ //#endregion
534
+ export { createLiveChatProvider as t };
@@ -0,0 +1,22 @@
1
+ import { o as AiLiveChatProvider } from "./provider.js";
2
+ import { M as AiLiveChatFactoryContext, d as AiChatBindings, u as AiChatBinding } from "./contracts.js";
3
+ //#region src/mount.d.ts
4
+ /**
5
+ * The provider a person answers through, chosen by the root's attributes: Omnichannel when
6
+ * `data-ai-chat-omnichannel-org-id`, `-org-url` and `-widget-id` are all set, LiveChat when
7
+ * `data-ai-chat-livechat-organization-id` and `-client-id` are (with `-group-id` if it is), and
8
+ * the AiChat Live desk from `data-ai-chat-live-endpoint` otherwise. The Omnichannel and LiveChat
9
+ * SDKs load the first time a visitor asks for a person.
10
+ */
11
+ declare function liveChatFromAttributes(context: AiLiveChatFactoryContext): AiLiveChatProvider | undefined;
12
+ /**
13
+ * Binds a server-rendered chat once, however many times it is asked for: the first
14
+ * `[data-ai-chat]` in the document when no root is given. A root that is also
15
+ * `vv-ai-chat--window` is the window over the page, bound to its openers anywhere in the
16
+ * document, with the document's `data-ai-launcher-teaser` shown as `bindLauncherTeaser` decides.
17
+ * A person answers through `liveChatFromAttributes` unless `options.liveChat` says otherwise.
18
+ * Returns the binding, or null when there is no root.
19
+ */
20
+ declare function mountAiChat(root?: HTMLElement | null, options?: AiChatBindings): AiChatBinding | null;
21
+ //#endregion
22
+ export { liveChatFromAttributes, mountAiChat };
package/dist/mount.js ADDED
@@ -0,0 +1,56 @@
1
+ import { i as bindChat, n as bindLauncherTeaser, t as bindChatWindow } from "./window.js";
2
+ import { t as createOmnichannelProvider } from "./omnichannel.js";
3
+ import { t as createLiveChatProvider } from "./livechat.js";
4
+ import { liveChatFromRoot } from "./live-chat/aichat.js";
5
+ //#region src/mount.ts
6
+ /**
7
+ * The provider a person answers through, chosen by the root's attributes: Omnichannel when
8
+ * `data-ai-chat-omnichannel-org-id`, `-org-url` and `-widget-id` are all set, LiveChat when
9
+ * `data-ai-chat-livechat-organization-id` and `-client-id` are (with `-group-id` if it is), and
10
+ * the AiChat Live desk from `data-ai-chat-live-endpoint` otherwise. The Omnichannel and LiveChat
11
+ * SDKs load the first time a visitor asks for a person.
12
+ */
13
+ function liveChatFromAttributes(context) {
14
+ const { aiChatOmnichannelOrgId: orgId, aiChatOmnichannelOrgUrl: orgUrl, aiChatOmnichannelWidgetId: widgetId, aiChatLivechatOrganizationId: organizationId, aiChatLivechatClientId: clientId, aiChatLivechatGroupId: groupId } = context.root.dataset;
15
+ if (orgId && orgUrl && widgetId) return createOmnichannelProvider({
16
+ orgId,
17
+ orgUrl,
18
+ widgetId
19
+ });
20
+ if (organizationId && clientId) {
21
+ const group = Number(groupId);
22
+ return createLiveChatProvider({
23
+ organizationId,
24
+ clientId,
25
+ ...groupId && Number.isInteger(group) ? { groupId: group } : {}
26
+ });
27
+ }
28
+ return liveChatFromRoot(context);
29
+ }
30
+ const mounted = /* @__PURE__ */ new WeakMap();
31
+ /**
32
+ * Binds a server-rendered chat once, however many times it is asked for: the first
33
+ * `[data-ai-chat]` in the document when no root is given. A root that is also
34
+ * `vv-ai-chat--window` is the window over the page, bound to its openers anywhere in the
35
+ * document, with the document's `data-ai-launcher-teaser` shown as `bindLauncherTeaser` decides.
36
+ * A person answers through `liveChatFromAttributes` unless `options.liveChat` says otherwise.
37
+ * Returns the binding, or null when there is no root.
38
+ */
39
+ function mountAiChat(root, options = {}) {
40
+ const target = root ?? document.querySelector("[data-ai-chat]");
41
+ if (!target) return null;
42
+ const existing = mounted.get(target);
43
+ if (existing) return existing;
44
+ const binding = bindChat(target, {
45
+ liveChat: liveChatFromAttributes,
46
+ ...options
47
+ });
48
+ mounted.set(target, binding);
49
+ if (target.classList.contains("vv-ai-chat--window")) {
50
+ bindChatWindow(binding);
51
+ bindLauncherTeaser(binding, target.ownerDocument);
52
+ }
53
+ return binding;
54
+ }
55
+ //#endregion
56
+ export { liveChatFromAttributes, mountAiChat };