@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,294 @@
1
+ import { i as isPlainObject } from "./dom.js";
2
+ //#region src/live-chat/adaptive-card.ts
3
+ const INPUT_TYPES = /* @__PURE__ */ new Set([
4
+ "Input.Text",
5
+ "Input.ChoiceSet",
6
+ "Input.Toggle"
7
+ ]);
8
+ const TEXT_STYLES = /* @__PURE__ */ new Set([
9
+ "email",
10
+ "tel",
11
+ "url"
12
+ ]);
13
+ function text(value) {
14
+ return typeof value === "string" && value.trim() ? value.trim() : null;
15
+ }
16
+ function flatten(elements, into = []) {
17
+ if (!Array.isArray(elements)) return into;
18
+ for (const element of elements) {
19
+ if (!isPlainObject(element)) continue;
20
+ into.push(element);
21
+ flatten(element.items, into);
22
+ flatten(element.columns, into);
23
+ }
24
+ return into;
25
+ }
26
+ function inputs(card) {
27
+ if (!isPlainObject(card)) throw new Error("The pre-chat survey is not an Adaptive Card");
28
+ const elements = flatten(card.body);
29
+ for (const element of elements) {
30
+ const type = String(element.type ?? "");
31
+ if (type.startsWith("Input.") && !INPUT_TYPES.has(type)) throw new Error(`The pre-chat survey has an input the chat window cannot show: ${type}`);
32
+ if (INPUT_TYPES.has(type) && !text(element.id)) throw new Error(`The pre-chat survey has an ${type} without an id`);
33
+ }
34
+ return elements;
35
+ }
36
+ function question(id) {
37
+ try {
38
+ const parsed = JSON.parse(id);
39
+ if (isPlainObject(parsed)) return {
40
+ name: text(parsed.Name),
41
+ text: text(parsed.QuestionText),
42
+ required: parsed.IsRequired === true
43
+ };
44
+ } catch {}
45
+ return {
46
+ name: null,
47
+ text: null,
48
+ required: false
49
+ };
50
+ }
51
+ function decode(value) {
52
+ return value.replace(/&#(x[0-9a-f]+|\d+);/gi, (entity, code) => {
53
+ const point = code[0] === "x" || code[0] === "X" ? Number.parseInt(code.slice(1), 16) : Number(code);
54
+ return point > 0 && point <= 1114111 ? String.fromCodePoint(point) : entity;
55
+ });
56
+ }
57
+ function markdown(value) {
58
+ return decode(value).replace(/\]\(\s+/g, "](");
59
+ }
60
+ function label(value) {
61
+ return markdown(value).replace(/^\*\s+/, "");
62
+ }
63
+ function isPlaceholderChoice(title) {
64
+ return /^[-\u2013\u2014]+$/.test(title);
65
+ }
66
+ /**
67
+ * The pre-chat survey Omnichannel keeps as an Adaptive Card, as the field list the chat window
68
+ * draws. A question's label is its own, or the text block right above it as Omnichannel lays them
69
+ * out; any other text block is a note. Throws on an input type the window cannot show rather than
70
+ * leaving a question out.
71
+ */
72
+ function surveyFieldsFromAdaptiveCard(card) {
73
+ const fields = [];
74
+ let pending = null;
75
+ const flush = () => {
76
+ if (pending) fields.push({
77
+ kind: "note",
78
+ text: markdown(pending)
79
+ });
80
+ pending = null;
81
+ };
82
+ for (const element of inputs(card)) {
83
+ const type = element.type;
84
+ if (type === "TextBlock") {
85
+ flush();
86
+ pending = text(element.text);
87
+ continue;
88
+ }
89
+ if (typeof type !== "string" || !INPUT_TYPES.has(type)) continue;
90
+ const id = String(element.id);
91
+ const asked = question(id);
92
+ const own = text(element.label) ?? (type === "Input.Toggle" ? text(element.title) : null);
93
+ if (own) flush();
94
+ const base = {
95
+ id,
96
+ name: asked.name ?? id,
97
+ label: label(own ?? pending ?? asked.text ?? id),
98
+ required: element.isRequired === true || asked.required
99
+ };
100
+ pending = null;
101
+ if (type === "Input.Text") {
102
+ const style = String(element.style ?? "");
103
+ fields.push({
104
+ ...base,
105
+ kind: "text",
106
+ inputType: TEXT_STYLES.has(style) ? style : "text",
107
+ multiline: element.isMultiline === true,
108
+ maxLength: typeof element.maxLength === "number" && element.maxLength > 0 ? element.maxLength : null,
109
+ placeholder: text(element.placeholder)
110
+ });
111
+ } else if (type === "Input.ChoiceSet") {
112
+ const choices = Array.isArray(element.choices) ? element.choices.filter(isPlainObject) : [];
113
+ fields.push({
114
+ ...base,
115
+ kind: "choice",
116
+ multiple: element.isMultiSelect === true,
117
+ choices: choices.filter((choice) => {
118
+ const title = text(choice.title);
119
+ return title !== null && !isPlaceholderChoice(title) && typeof choice.value === "string";
120
+ }).map((choice) => ({
121
+ label: decode(String(choice.title).trim()),
122
+ value: String(choice.value)
123
+ }))
124
+ });
125
+ } else fields.push({
126
+ ...base,
127
+ kind: "toggle"
128
+ });
129
+ }
130
+ flush();
131
+ return fields;
132
+ }
133
+ /**
134
+ * The answers as the card's submit action would send them, which is what Omnichannel takes as
135
+ * `preChatResponse`: the action's data with every input's value under its id, and a toggle as its
136
+ * `valueOn` or `valueOff`.
137
+ */
138
+ function preChatResponseFromAnswers(card, answers) {
139
+ const response = {};
140
+ const submit = isPlainObject(card) && Array.isArray(card.actions) ? card.actions.find((action) => isPlainObject(action) && action.type === "Action.Submit") : null;
141
+ if (isPlainObject(submit) && isPlainObject(submit.data)) for (const [key, value] of Object.entries(submit.data)) response[key] = String(value);
142
+ for (const element of inputs(card)) {
143
+ if (typeof element.type !== "string" || !INPUT_TYPES.has(element.type)) continue;
144
+ const id = String(element.id);
145
+ const answer = answers[id];
146
+ if (element.type === "Input.Toggle") response[id] = answer === true ? String(element.valueOn ?? "true") : String(element.valueOff ?? "false");
147
+ else response[id] = typeof answer === "string" ? answer : "";
148
+ }
149
+ return response;
150
+ }
151
+ //#endregion
152
+ //#region src/live-chat/omnichannel.ts
153
+ const PLACEHOLDER_NAMES = /* @__PURE__ */ new Set(["__agent__", "__system__"]);
154
+ function messageText(content, contentType) {
155
+ if (contentType !== "html") return content;
156
+ const template = document.createElement("template");
157
+ template.innerHTML = content;
158
+ return template.content.textContent ?? "";
159
+ }
160
+ /**
161
+ * A live chat provider over Dynamics 365 Omnichannel, through `@microsoft/omnichannel-chat-sdk`.
162
+ * The SDK is imported the first time the provider is asked anything, so a page pays for it only
163
+ * when a visitor asks for a person. Each chat gets its own SDK instance, dropped when it ends.
164
+ */
165
+ function createOmnichannelProvider(config) {
166
+ const messageListeners = /* @__PURE__ */ new Set();
167
+ const typingListeners = /* @__PURE__ */ new Set();
168
+ const endedListeners = /* @__PURE__ */ new Set();
169
+ let chat = null;
170
+ let survey = null;
171
+ function load() {
172
+ if (chat) return chat;
173
+ const pending = (async () => {
174
+ const module = await import("@microsoft/omnichannel-chat-sdk");
175
+ const sdk = new module.OmnichannelChatSDK({
176
+ orgId: config.orgId,
177
+ orgUrl: config.orgUrl,
178
+ widgetId: config.widgetId
179
+ });
180
+ await sdk.initialize();
181
+ return {
182
+ module,
183
+ sdk
184
+ };
185
+ })();
186
+ pending.catch(() => {
187
+ if (chat === pending) chat = null;
188
+ });
189
+ chat = pending;
190
+ return pending;
191
+ }
192
+ function drop() {
193
+ chat = null;
194
+ survey = null;
195
+ }
196
+ function receive(module, message) {
197
+ const customEvent = message.customEvent;
198
+ if (module.isCustomerMessage(message) || customEvent?.isCustomEvent || typeof message.content !== "string") return;
199
+ const text = messageText(message.content, message.contentType).trim();
200
+ if (!text) return;
201
+ const name = message.sender?.displayName?.trim();
202
+ const item = {
203
+ id: String(message.id),
204
+ text,
205
+ sender: module.isSystemMessage(message) ? "system" : "agent",
206
+ name: name && !PLACEHOLDER_NAMES.has(name) ? name : null
207
+ };
208
+ for (const listener of messageListeners) listener(item);
209
+ }
210
+ return {
211
+ async availability() {
212
+ const { sdk } = await load();
213
+ const settings = await sdk.getLiveChatConfig();
214
+ return String(settings.LiveWSAndLiveChatEngJoin?.OutOfOperatingHours ?? "").toLowerCase() === "true" ? {
215
+ status: "closed",
216
+ reason: "out-of-hours"
217
+ } : { status: "open" };
218
+ },
219
+ async survey() {
220
+ const { sdk } = await load();
221
+ survey = await sdk.getPreChatSurvey(true) ?? null;
222
+ return survey ? surveyFieldsFromAdaptiveCard(survey) : null;
223
+ },
224
+ async start(options) {
225
+ const { module, sdk } = await load();
226
+ if (options.resume) await sdk.startChat({ liveChatContext: JSON.parse(options.resume) });
227
+ else {
228
+ const customContext = Object.fromEntries(Object.entries(options.context ?? {}).map(([key, value]) => [key, {
229
+ value,
230
+ isDisplayable: true
231
+ }]));
232
+ await sdk.startChat({
233
+ preChatResponse: survey ? preChatResponseFromAnswers(survey, options.answers ?? {}) : void 0,
234
+ customContext
235
+ });
236
+ }
237
+ await sdk.onNewMessage((message) => receive(module, message), { rehydrate: Boolean(options.resume) });
238
+ await sdk.onTypingEvent(() => {
239
+ for (const listener of typingListeners) listener();
240
+ });
241
+ await sdk.onAgentEndSession(() => {
242
+ drop();
243
+ sdk.endChat({ isSessionEnded: true }).catch(() => void 0);
244
+ for (const listener of endedListeners) listener();
245
+ });
246
+ if (options.openingMessage) await sdk.sendMessage({ content: options.openingMessage });
247
+ },
248
+ async send(text) {
249
+ const { sdk } = await load();
250
+ await sdk.sendMessage({ content: text });
251
+ },
252
+ async typing() {
253
+ const { sdk } = await load();
254
+ await sdk.sendTypingEvent();
255
+ },
256
+ async end() {
257
+ if (!chat) return;
258
+ const { sdk } = await chat;
259
+ drop();
260
+ await sdk.endChat();
261
+ },
262
+ onMessage(listener) {
263
+ messageListeners.add(listener);
264
+ return () => messageListeners.delete(listener);
265
+ },
266
+ onTyping(listener) {
267
+ typingListeners.add(listener);
268
+ return () => typingListeners.delete(listener);
269
+ },
270
+ onEnded(listener) {
271
+ endedListeners.add(listener);
272
+ return () => endedListeners.delete(listener);
273
+ },
274
+ async resumeToken() {
275
+ if (!chat) return null;
276
+ const { sdk } = await chat;
277
+ const context = await sdk.getCurrentLiveChatContext();
278
+ return Object.keys(context ?? {}).length ? JSON.stringify(context) : null;
279
+ },
280
+ async emailTranscript({ email, message }) {
281
+ const { sdk } = await load();
282
+ await sdk.emailLiveChatTranscript({
283
+ emailAddress: email,
284
+ attachmentMessage: message ?? ""
285
+ });
286
+ },
287
+ async upload(file) {
288
+ const { sdk } = await load();
289
+ await sdk.uploadFileAttachment(file);
290
+ }
291
+ };
292
+ }
293
+ //#endregion
294
+ export { createOmnichannelProvider as t };