@vettvangur/ai-sdk 0.5.2 → 0.5.4
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/README.md +79 -0
- package/dist/dom.js +62 -0
- package/dist/index.d.ts +77 -1
- package/dist/index.js +614 -312
- package/dist/live-chat/aichat.d.ts +26 -0
- package/dist/live-chat/aichat.js +231 -0
- package/dist/live-chat/omnichannel.d.ts +15 -0
- package/dist/live-chat/omnichannel.js +278 -0
- package/dist/live-chat.d.ts +36 -0
- package/dist/live-chat.js +2 -0
- package/dist/provider.d.ts +102 -0
- package/dist/survey.js +393 -0
- package/package.json +22 -1
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { a as AiLiveChatProvider, s as AiLiveChatSurveyField } from "../provider.js";
|
|
2
|
+
//#region src/live-chat/aichat.d.ts
|
|
3
|
+
type AiChatLiveConfig = {
|
|
4
|
+
/** The prefix the site maps the chat under with `MapAiChat`, such as `/webapi/aichat`. */
|
|
5
|
+
endpoint: string;
|
|
6
|
+
/** Sent with every request, such as the antiforgery header the chat stream sends. */
|
|
7
|
+
headers?: Record<string, string>;
|
|
8
|
+
/**
|
|
9
|
+
* Asked before the chat starts. The answers reach the agent by field name, with a choice as its
|
|
10
|
+
* label and a toggle as `true` or `false`.
|
|
11
|
+
*/
|
|
12
|
+
survey?: AiLiveChatSurveyField[];
|
|
13
|
+
/** What a toggle's answer reads as for the agent; `true` and `false` when not given. */
|
|
14
|
+
yes?: string;
|
|
15
|
+
no?: string;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A live chat provider over the Vettvangur.AiChat package's own Live desk: agents answer from the
|
|
19
|
+
* Live view of its backoffice section. The visitor's chat is a token from `start`, which is also
|
|
20
|
+
* the resume token, and its news comes over a server-sent event stream that reconnects when it
|
|
21
|
+
* drops. The stream names the agent once they have taken the chat, and again after each
|
|
22
|
+
* reconnect. `availability()` is `no-agents` while nobody has the Live view open.
|
|
23
|
+
*/
|
|
24
|
+
declare function createAiChatLiveProvider(config: AiChatLiveConfig): AiLiveChatProvider;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { AiChatLiveConfig, createAiChatLiveProvider };
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
//#region src/live-chat/aichat.ts
|
|
2
|
+
/** The header that carries the visitor's chat token after `start`. */
|
|
3
|
+
const TOKEN_HEADER = "X-AiChat-Live";
|
|
4
|
+
const RETRY_MS = 1e3;
|
|
5
|
+
const RETRY_LIMIT_MS = 15e3;
|
|
6
|
+
function details(config, answers) {
|
|
7
|
+
const result = {};
|
|
8
|
+
for (const field of config.survey ?? []) {
|
|
9
|
+
if (field.kind === "note" || !answers || !(field.id in answers)) continue;
|
|
10
|
+
const answer = answers[field.id];
|
|
11
|
+
if (typeof answer === "boolean") result[field.name] = answer ? config.yes ?? "true" : config.no ?? "false";
|
|
12
|
+
else if (field.kind === "choice") {
|
|
13
|
+
const values = (answer ?? "").split(",").filter(Boolean);
|
|
14
|
+
result[field.name] = values.map((value) => field.choices.find((choice) => choice.value === value)?.label ?? value).join(", ");
|
|
15
|
+
} else if (answer) result[field.name] = answer;
|
|
16
|
+
}
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
19
|
+
function parseRecord(record) {
|
|
20
|
+
let name = "";
|
|
21
|
+
const data = [];
|
|
22
|
+
for (const line of record.split(/\r?\n/)) if (line.startsWith("event:")) name = line.slice(6).trim();
|
|
23
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
|
|
24
|
+
if (!name || !data.length) return null;
|
|
25
|
+
try {
|
|
26
|
+
const parsed = JSON.parse(data.join("\n"));
|
|
27
|
+
return parsed && typeof parsed === "object" ? {
|
|
28
|
+
name,
|
|
29
|
+
data: parsed
|
|
30
|
+
} : null;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function* readEvents(body) {
|
|
36
|
+
const reader = body.getReader();
|
|
37
|
+
const decoder = new TextDecoder();
|
|
38
|
+
let buffer = "";
|
|
39
|
+
try {
|
|
40
|
+
while (true) {
|
|
41
|
+
const { done, value } = await reader.read();
|
|
42
|
+
if (done) return;
|
|
43
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
|
|
44
|
+
let boundary = buffer.indexOf("\n\n");
|
|
45
|
+
while (boundary !== -1) {
|
|
46
|
+
const event = parseRecord(buffer.slice(0, boundary));
|
|
47
|
+
buffer = buffer.slice(boundary + 2);
|
|
48
|
+
if (event) yield event;
|
|
49
|
+
boundary = buffer.indexOf("\n\n");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
} finally {
|
|
53
|
+
reader.cancel().catch(() => void 0);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* A live chat provider over the Vettvangur.AiChat package's own Live desk: agents answer from the
|
|
58
|
+
* Live view of its backoffice section. The visitor's chat is a token from `start`, which is also
|
|
59
|
+
* the resume token, and its news comes over a server-sent event stream that reconnects when it
|
|
60
|
+
* drops. The stream names the agent once they have taken the chat, and again after each
|
|
61
|
+
* reconnect. `availability()` is `no-agents` while nobody has the Live view open.
|
|
62
|
+
*/
|
|
63
|
+
function createAiChatLiveProvider(config) {
|
|
64
|
+
const base = `${config.endpoint.replace(/\/+$/, "")}/live`;
|
|
65
|
+
const messageListeners = /* @__PURE__ */ new Set();
|
|
66
|
+
const typingListeners = /* @__PURE__ */ new Set();
|
|
67
|
+
const endedListeners = /* @__PURE__ */ new Set();
|
|
68
|
+
const agentListeners = /* @__PURE__ */ new Set();
|
|
69
|
+
let token = null;
|
|
70
|
+
let stream = null;
|
|
71
|
+
function headers(extra = {}) {
|
|
72
|
+
return {
|
|
73
|
+
...config.headers,
|
|
74
|
+
...token ? { [TOKEN_HEADER]: token } : {},
|
|
75
|
+
...extra
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
async function request(path, init = {}) {
|
|
79
|
+
const response = await fetch(`${base}/${path}`, {
|
|
80
|
+
credentials: "same-origin",
|
|
81
|
+
...init,
|
|
82
|
+
headers: headers(init.headers)
|
|
83
|
+
});
|
|
84
|
+
if (!response.ok) throw new Error(`AI chat live request ${path} failed with ${response.status}`);
|
|
85
|
+
return response;
|
|
86
|
+
}
|
|
87
|
+
function post(path, body) {
|
|
88
|
+
return request(path, {
|
|
89
|
+
method: "POST",
|
|
90
|
+
headers: body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
91
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
function stop() {
|
|
95
|
+
stream?.abort();
|
|
96
|
+
stream = null;
|
|
97
|
+
token = null;
|
|
98
|
+
}
|
|
99
|
+
function ended() {
|
|
100
|
+
stop();
|
|
101
|
+
for (const listener of endedListeners) listener();
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Follows the chat until it ends or `end()` is called. Resolves once the first connection is
|
|
105
|
+
* open, so `start` fails when the chat cannot be reached at all; later drops reconnect from the
|
|
106
|
+
* last message seen.
|
|
107
|
+
*/
|
|
108
|
+
async function follow() {
|
|
109
|
+
const controller = new AbortController();
|
|
110
|
+
stream = controller;
|
|
111
|
+
let after = "0";
|
|
112
|
+
let retry = RETRY_MS;
|
|
113
|
+
const connect = async () => {
|
|
114
|
+
const response = await fetch(`${base}/events?after=${encodeURIComponent(after)}`, {
|
|
115
|
+
credentials: "same-origin",
|
|
116
|
+
headers: headers({ Accept: "text/event-stream" }),
|
|
117
|
+
signal: controller.signal
|
|
118
|
+
});
|
|
119
|
+
if (response.status === 404) throw Object.assign(/* @__PURE__ */ new Error("AI chat live chat no longer exists"), { gone: true });
|
|
120
|
+
if (!response.ok || !response.body) throw new Error(`AI chat live events failed with ${response.status}`);
|
|
121
|
+
return response.body;
|
|
122
|
+
};
|
|
123
|
+
const isGone = (caught) => Boolean(caught?.gone);
|
|
124
|
+
const read = async (body) => {
|
|
125
|
+
try {
|
|
126
|
+
for await (const event of readEvents(body)) {
|
|
127
|
+
retry = RETRY_MS;
|
|
128
|
+
if (event.name === "message" && typeof event.data.id === "string" && typeof event.data.text === "string") {
|
|
129
|
+
after = event.data.id;
|
|
130
|
+
const message = {
|
|
131
|
+
id: event.data.id,
|
|
132
|
+
text: event.data.text,
|
|
133
|
+
sender: event.data.sender === "system" ? "system" : "agent",
|
|
134
|
+
name: typeof event.data.name === "string" && event.data.name.trim() ? event.data.name.trim() : null
|
|
135
|
+
};
|
|
136
|
+
for (const listener of messageListeners) listener(message);
|
|
137
|
+
} else if (event.name === "agent") {
|
|
138
|
+
const name = typeof event.data.name === "string" && event.data.name.trim() ? event.data.name.trim() : null;
|
|
139
|
+
for (const listener of agentListeners) listener({ name });
|
|
140
|
+
} else if (event.name === "typing") for (const listener of typingListeners) listener();
|
|
141
|
+
else if (event.name === "ended") return "ended";
|
|
142
|
+
}
|
|
143
|
+
} catch {}
|
|
144
|
+
return "dropped";
|
|
145
|
+
};
|
|
146
|
+
const run = async (first) => {
|
|
147
|
+
let body = first;
|
|
148
|
+
while (!controller.signal.aborted) {
|
|
149
|
+
if (body && await read(body) === "ended") break;
|
|
150
|
+
body = null;
|
|
151
|
+
if (controller.signal.aborted) return;
|
|
152
|
+
await new Promise((resolve) => setTimeout(resolve, retry));
|
|
153
|
+
retry = Math.min(retry * 2, RETRY_LIMIT_MS);
|
|
154
|
+
try {
|
|
155
|
+
body = await connect();
|
|
156
|
+
} catch (caught) {
|
|
157
|
+
if (isGone(caught)) break;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (!controller.signal.aborted && stream === controller) ended();
|
|
161
|
+
};
|
|
162
|
+
run(await connect());
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
async availability() {
|
|
166
|
+
return (await (await request("availability", { cache: "no-store" })).json()).status === "open" ? { status: "open" } : {
|
|
167
|
+
status: "closed",
|
|
168
|
+
reason: "no-agents"
|
|
169
|
+
};
|
|
170
|
+
},
|
|
171
|
+
async survey() {
|
|
172
|
+
return config.survey?.length ? config.survey : null;
|
|
173
|
+
},
|
|
174
|
+
async start(options) {
|
|
175
|
+
stop();
|
|
176
|
+
if (options.resume) token = options.resume;
|
|
177
|
+
else {
|
|
178
|
+
const context = options.context ?? {};
|
|
179
|
+
token = (await (await post("start", {
|
|
180
|
+
conversationId: context.aiConversationId,
|
|
181
|
+
culture: context.aiLanguage ?? document.documentElement.lang,
|
|
182
|
+
context,
|
|
183
|
+
details: details(config, options.answers),
|
|
184
|
+
openingMessage: options.openingMessage
|
|
185
|
+
})).json()).token;
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
await follow();
|
|
189
|
+
} catch (caught) {
|
|
190
|
+
stop();
|
|
191
|
+
throw caught;
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
async send(text) {
|
|
195
|
+
await post("send", { text });
|
|
196
|
+
},
|
|
197
|
+
async typing() {
|
|
198
|
+
if (token) await post("typing");
|
|
199
|
+
},
|
|
200
|
+
async draft(text) {
|
|
201
|
+
if (token) await post("typing", { text });
|
|
202
|
+
},
|
|
203
|
+
async end() {
|
|
204
|
+
if (!token) return;
|
|
205
|
+
const pending = post("end");
|
|
206
|
+
stop();
|
|
207
|
+
await pending;
|
|
208
|
+
},
|
|
209
|
+
onMessage(listener) {
|
|
210
|
+
messageListeners.add(listener);
|
|
211
|
+
return () => messageListeners.delete(listener);
|
|
212
|
+
},
|
|
213
|
+
onTyping(listener) {
|
|
214
|
+
typingListeners.add(listener);
|
|
215
|
+
return () => typingListeners.delete(listener);
|
|
216
|
+
},
|
|
217
|
+
onEnded(listener) {
|
|
218
|
+
endedListeners.add(listener);
|
|
219
|
+
return () => endedListeners.delete(listener);
|
|
220
|
+
},
|
|
221
|
+
onAgent(listener) {
|
|
222
|
+
agentListeners.add(listener);
|
|
223
|
+
return () => agentListeners.delete(listener);
|
|
224
|
+
},
|
|
225
|
+
async resumeToken() {
|
|
226
|
+
return token;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
//#endregion
|
|
231
|
+
export { createAiChatLiveProvider };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { a as AiLiveChatProvider } from "../provider.js";
|
|
2
|
+
//#region src/live-chat/omnichannel.d.ts
|
|
3
|
+
type AiOmnichannelConfig = {
|
|
4
|
+
orgId: string;
|
|
5
|
+
orgUrl: string;
|
|
6
|
+
widgetId: string;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* A live chat provider over Dynamics 365 Omnichannel, through `@microsoft/omnichannel-chat-sdk`.
|
|
10
|
+
* The SDK is imported the first time the provider is asked anything, so a page pays for it only
|
|
11
|
+
* when a visitor asks for a person. Each chat gets its own SDK instance, dropped when it ends.
|
|
12
|
+
*/
|
|
13
|
+
declare function createOmnichannelProvider(config: AiOmnichannelConfig): AiLiveChatProvider;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { AiOmnichannelConfig, createOmnichannelProvider };
|
|
@@ -0,0 +1,278 @@
|
|
|
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
|
+
};
|
|
43
|
+
} catch {}
|
|
44
|
+
return {
|
|
45
|
+
name: null,
|
|
46
|
+
text: null
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function markdown(value) {
|
|
50
|
+
return value.replace(/\]\(\s+/g, "](");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The pre-chat survey Omnichannel keeps as an Adaptive Card, as the field list the chat window
|
|
54
|
+
* draws. A question's label is its own, or the text block right above it as Omnichannel lays them
|
|
55
|
+
* out; any other text block is a note. Throws on an input type the window cannot show rather than
|
|
56
|
+
* leaving a question out.
|
|
57
|
+
*/
|
|
58
|
+
function surveyFieldsFromAdaptiveCard(card) {
|
|
59
|
+
const fields = [];
|
|
60
|
+
let pending = null;
|
|
61
|
+
const flush = () => {
|
|
62
|
+
if (pending) fields.push({
|
|
63
|
+
kind: "note",
|
|
64
|
+
text: markdown(pending)
|
|
65
|
+
});
|
|
66
|
+
pending = null;
|
|
67
|
+
};
|
|
68
|
+
for (const element of inputs(card)) {
|
|
69
|
+
const type = element.type;
|
|
70
|
+
if (type === "TextBlock") {
|
|
71
|
+
flush();
|
|
72
|
+
pending = text(element.text);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (typeof type !== "string" || !INPUT_TYPES.has(type)) continue;
|
|
76
|
+
const id = String(element.id);
|
|
77
|
+
const asked = question(id);
|
|
78
|
+
const own = text(element.label) ?? (type === "Input.Toggle" ? text(element.title) : null);
|
|
79
|
+
if (own) flush();
|
|
80
|
+
const label = markdown(own ?? pending ?? asked.text ?? id);
|
|
81
|
+
pending = null;
|
|
82
|
+
const base = {
|
|
83
|
+
id,
|
|
84
|
+
name: asked.name ?? id,
|
|
85
|
+
label,
|
|
86
|
+
required: element.isRequired === true
|
|
87
|
+
};
|
|
88
|
+
if (type === "Input.Text") {
|
|
89
|
+
const style = String(element.style ?? "");
|
|
90
|
+
fields.push({
|
|
91
|
+
...base,
|
|
92
|
+
kind: "text",
|
|
93
|
+
inputType: TEXT_STYLES.has(style) ? style : "text",
|
|
94
|
+
multiline: element.isMultiline === true,
|
|
95
|
+
maxLength: typeof element.maxLength === "number" && element.maxLength > 0 ? element.maxLength : null,
|
|
96
|
+
placeholder: text(element.placeholder)
|
|
97
|
+
});
|
|
98
|
+
} else if (type === "Input.ChoiceSet") {
|
|
99
|
+
const choices = Array.isArray(element.choices) ? element.choices.filter(isPlainObject) : [];
|
|
100
|
+
fields.push({
|
|
101
|
+
...base,
|
|
102
|
+
kind: "choice",
|
|
103
|
+
multiple: element.isMultiSelect === true,
|
|
104
|
+
choices: choices.filter((choice) => text(choice.title) && typeof choice.value === "string").map((choice) => ({
|
|
105
|
+
label: String(choice.title).trim(),
|
|
106
|
+
value: String(choice.value)
|
|
107
|
+
}))
|
|
108
|
+
});
|
|
109
|
+
} else fields.push({
|
|
110
|
+
...base,
|
|
111
|
+
kind: "toggle"
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
flush();
|
|
115
|
+
return fields;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The answers as the card's submit action would send them, which is what Omnichannel takes as
|
|
119
|
+
* `preChatResponse`: the action's data with every input's value under its id, and a toggle as its
|
|
120
|
+
* `valueOn` or `valueOff`.
|
|
121
|
+
*/
|
|
122
|
+
function preChatResponseFromAnswers(card, answers) {
|
|
123
|
+
const response = {};
|
|
124
|
+
const submit = isPlainObject(card) && Array.isArray(card.actions) ? card.actions.find((action) => isPlainObject(action) && action.type === "Action.Submit") : null;
|
|
125
|
+
if (isPlainObject(submit) && isPlainObject(submit.data)) for (const [key, value] of Object.entries(submit.data)) response[key] = String(value);
|
|
126
|
+
for (const element of inputs(card)) {
|
|
127
|
+
if (typeof element.type !== "string" || !INPUT_TYPES.has(element.type)) continue;
|
|
128
|
+
const id = String(element.id);
|
|
129
|
+
const answer = answers[id];
|
|
130
|
+
if (element.type === "Input.Toggle") response[id] = answer === true ? String(element.valueOn ?? "true") : String(element.valueOff ?? "false");
|
|
131
|
+
else response[id] = typeof answer === "string" ? answer : "";
|
|
132
|
+
}
|
|
133
|
+
return response;
|
|
134
|
+
}
|
|
135
|
+
//#endregion
|
|
136
|
+
//#region src/live-chat/omnichannel.ts
|
|
137
|
+
const PLACEHOLDER_NAMES = /* @__PURE__ */ new Set(["__agent__", "__system__"]);
|
|
138
|
+
function messageText(content, contentType) {
|
|
139
|
+
if (contentType !== "html") return content;
|
|
140
|
+
const template = document.createElement("template");
|
|
141
|
+
template.innerHTML = content;
|
|
142
|
+
return template.content.textContent ?? "";
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* A live chat provider over Dynamics 365 Omnichannel, through `@microsoft/omnichannel-chat-sdk`.
|
|
146
|
+
* The SDK is imported the first time the provider is asked anything, so a page pays for it only
|
|
147
|
+
* when a visitor asks for a person. Each chat gets its own SDK instance, dropped when it ends.
|
|
148
|
+
*/
|
|
149
|
+
function createOmnichannelProvider(config) {
|
|
150
|
+
const messageListeners = /* @__PURE__ */ new Set();
|
|
151
|
+
const typingListeners = /* @__PURE__ */ new Set();
|
|
152
|
+
const endedListeners = /* @__PURE__ */ new Set();
|
|
153
|
+
let chat = null;
|
|
154
|
+
let survey = null;
|
|
155
|
+
function load() {
|
|
156
|
+
if (chat) return chat;
|
|
157
|
+
const pending = (async () => {
|
|
158
|
+
const module = await import("@microsoft/omnichannel-chat-sdk");
|
|
159
|
+
const sdk = new module.OmnichannelChatSDK({
|
|
160
|
+
orgId: config.orgId,
|
|
161
|
+
orgUrl: config.orgUrl,
|
|
162
|
+
widgetId: config.widgetId
|
|
163
|
+
});
|
|
164
|
+
await sdk.initialize();
|
|
165
|
+
return {
|
|
166
|
+
module,
|
|
167
|
+
sdk
|
|
168
|
+
};
|
|
169
|
+
})();
|
|
170
|
+
pending.catch(() => {
|
|
171
|
+
if (chat === pending) chat = null;
|
|
172
|
+
});
|
|
173
|
+
chat = pending;
|
|
174
|
+
return pending;
|
|
175
|
+
}
|
|
176
|
+
function drop() {
|
|
177
|
+
chat = null;
|
|
178
|
+
survey = null;
|
|
179
|
+
}
|
|
180
|
+
function receive(module, message) {
|
|
181
|
+
const customEvent = message.customEvent;
|
|
182
|
+
if (module.isCustomerMessage(message) || customEvent?.isCustomEvent || typeof message.content !== "string") return;
|
|
183
|
+
const text = messageText(message.content, message.contentType).trim();
|
|
184
|
+
if (!text) return;
|
|
185
|
+
const name = message.sender?.displayName?.trim();
|
|
186
|
+
const item = {
|
|
187
|
+
id: String(message.id),
|
|
188
|
+
text,
|
|
189
|
+
sender: module.isSystemMessage(message) ? "system" : "agent",
|
|
190
|
+
name: name && !PLACEHOLDER_NAMES.has(name) ? name : null
|
|
191
|
+
};
|
|
192
|
+
for (const listener of messageListeners) listener(item);
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
async availability() {
|
|
196
|
+
const { sdk } = await load();
|
|
197
|
+
const settings = await sdk.getLiveChatConfig();
|
|
198
|
+
return String(settings.LiveWSAndLiveChatEngJoin?.OutOfOperatingHours ?? "").toLowerCase() === "true" ? {
|
|
199
|
+
status: "closed",
|
|
200
|
+
reason: "out-of-hours"
|
|
201
|
+
} : { status: "open" };
|
|
202
|
+
},
|
|
203
|
+
async survey() {
|
|
204
|
+
const { sdk } = await load();
|
|
205
|
+
survey = await sdk.getPreChatSurvey(true) ?? null;
|
|
206
|
+
return survey ? surveyFieldsFromAdaptiveCard(survey) : null;
|
|
207
|
+
},
|
|
208
|
+
async start(options) {
|
|
209
|
+
const { module, sdk } = await load();
|
|
210
|
+
if (options.resume) await sdk.startChat({ liveChatContext: JSON.parse(options.resume) });
|
|
211
|
+
else {
|
|
212
|
+
const customContext = Object.fromEntries(Object.entries(options.context ?? {}).map(([key, value]) => [key, {
|
|
213
|
+
value,
|
|
214
|
+
isDisplayable: true
|
|
215
|
+
}]));
|
|
216
|
+
await sdk.startChat({
|
|
217
|
+
preChatResponse: survey ? preChatResponseFromAnswers(survey, options.answers ?? {}) : void 0,
|
|
218
|
+
customContext
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
await sdk.onNewMessage((message) => receive(module, message), { rehydrate: Boolean(options.resume) });
|
|
222
|
+
await sdk.onTypingEvent(() => {
|
|
223
|
+
for (const listener of typingListeners) listener();
|
|
224
|
+
});
|
|
225
|
+
await sdk.onAgentEndSession(() => {
|
|
226
|
+
drop();
|
|
227
|
+
sdk.endChat({ isSessionEnded: true }).catch(() => void 0);
|
|
228
|
+
for (const listener of endedListeners) listener();
|
|
229
|
+
});
|
|
230
|
+
if (options.openingMessage) await sdk.sendMessage({ content: options.openingMessage });
|
|
231
|
+
},
|
|
232
|
+
async send(text) {
|
|
233
|
+
const { sdk } = await load();
|
|
234
|
+
await sdk.sendMessage({ content: text });
|
|
235
|
+
},
|
|
236
|
+
async typing() {
|
|
237
|
+
const { sdk } = await load();
|
|
238
|
+
await sdk.sendTypingEvent();
|
|
239
|
+
},
|
|
240
|
+
async end() {
|
|
241
|
+
if (!chat) return;
|
|
242
|
+
const { sdk } = await chat;
|
|
243
|
+
drop();
|
|
244
|
+
await sdk.endChat();
|
|
245
|
+
},
|
|
246
|
+
onMessage(listener) {
|
|
247
|
+
messageListeners.add(listener);
|
|
248
|
+
return () => messageListeners.delete(listener);
|
|
249
|
+
},
|
|
250
|
+
onTyping(listener) {
|
|
251
|
+
typingListeners.add(listener);
|
|
252
|
+
return () => typingListeners.delete(listener);
|
|
253
|
+
},
|
|
254
|
+
onEnded(listener) {
|
|
255
|
+
endedListeners.add(listener);
|
|
256
|
+
return () => endedListeners.delete(listener);
|
|
257
|
+
},
|
|
258
|
+
async resumeToken() {
|
|
259
|
+
if (!chat) return null;
|
|
260
|
+
const { sdk } = await chat;
|
|
261
|
+
const context = await sdk.getCurrentLiveChatContext();
|
|
262
|
+
return Object.keys(context ?? {}).length ? JSON.stringify(context) : null;
|
|
263
|
+
},
|
|
264
|
+
async emailTranscript({ email, message }) {
|
|
265
|
+
const { sdk } = await load();
|
|
266
|
+
await sdk.emailLiveChatTranscript({
|
|
267
|
+
emailAddress: email,
|
|
268
|
+
attachmentMessage: message ?? ""
|
|
269
|
+
});
|
|
270
|
+
},
|
|
271
|
+
async upload(file) {
|
|
272
|
+
const { sdk } = await load();
|
|
273
|
+
await sdk.uploadFileAttachment(file);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
export { createOmnichannelProvider };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { a as AiLiveChatProvider, c as AiLiveChatSurveyNote, i as AiLiveChatMessage, l as AiLiveChatTextField, n as AiLiveChatAvailability, o as AiLiveChatStartOptions, r as AiLiveChatChoiceField, s as AiLiveChatSurveyField, t as AiLiveChatAnswers, u as AiLiveChatToggleField } from "./provider.js";
|
|
2
|
+
//#region src/live-chat/survey.d.ts
|
|
3
|
+
/** Every element of the survey form carries a class under this block. */
|
|
4
|
+
declare const SURVEY_CLASS = "vv-ai-survey";
|
|
5
|
+
type AiLiveChatSurveyLabels = {
|
|
6
|
+
submit: string;
|
|
7
|
+
cancel: string;
|
|
8
|
+
required: string;
|
|
9
|
+
/** For an email field whose answer is not an email address; `required` when not given. */
|
|
10
|
+
invalidEmail?: string;
|
|
11
|
+
/** A heading and a line above the fields, each left out when empty. */
|
|
12
|
+
title?: string;
|
|
13
|
+
intro?: string;
|
|
14
|
+
/** Shown under a field the prefill filled in, when not empty. */
|
|
15
|
+
prefilled?: string;
|
|
16
|
+
};
|
|
17
|
+
type AiLiveChatSurveyOptions = {
|
|
18
|
+
labels: AiLiveChatSurveyLabels;
|
|
19
|
+
/** Values to start the fields with, by field name or id. A choice matches its value or label. */
|
|
20
|
+
prefill?: AiLiveChatAnswers;
|
|
21
|
+
};
|
|
22
|
+
type AiLiveChatSurveyForm = {
|
|
23
|
+
form: HTMLFormElement;
|
|
24
|
+
/** The answers when the visitor submits, null when they cancel. */
|
|
25
|
+
answers: Promise<AiLiveChatAnswers | null>;
|
|
26
|
+
cancel(): void;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The pre-chat survey as a form in the thread. Prefilled fields are still shown, so the visitor
|
|
30
|
+
* sees and can change everything that is sent. A required toggle must be on, as a consent is.
|
|
31
|
+
* Submit stays disabled until every answer is valid, and a field says what is wrong with it once
|
|
32
|
+
* the visitor leaves it.
|
|
33
|
+
*/
|
|
34
|
+
declare function renderSurveyForm(document: Document, fields: readonly AiLiveChatSurveyField[], options: AiLiveChatSurveyOptions): AiLiveChatSurveyForm;
|
|
35
|
+
//#endregion
|
|
36
|
+
export { type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatChoiceField, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiLiveChatSurveyForm, type AiLiveChatSurveyLabels, type AiLiveChatSurveyNote, type AiLiveChatSurveyOptions, type AiLiveChatTextField, type AiLiveChatToggleField, SURVEY_CLASS, renderSurveyForm };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
//#region src/live-chat/provider.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Whether a person can take a chat now. A provider gives `no-agents` only when it can tell; most
|
|
4
|
+
* know only their opening hours.
|
|
5
|
+
*/
|
|
6
|
+
type AiLiveChatAvailability = {
|
|
7
|
+
status: 'open';
|
|
8
|
+
} | {
|
|
9
|
+
status: 'closed';
|
|
10
|
+
reason: 'out-of-hours' | 'no-agents';
|
|
11
|
+
};
|
|
12
|
+
type AiLiveChatFieldBase = {
|
|
13
|
+
/** What the provider expects the answer under; opaque to the window. */
|
|
14
|
+
id: string;
|
|
15
|
+
/** A stable name for prefilling, such as `Email`; the id when the provider has none. */
|
|
16
|
+
name: string;
|
|
17
|
+
/** Markdown: a survey can link its privacy policy from a label. */
|
|
18
|
+
label: string;
|
|
19
|
+
required: boolean;
|
|
20
|
+
};
|
|
21
|
+
type AiLiveChatTextField = AiLiveChatFieldBase & {
|
|
22
|
+
kind: 'text';
|
|
23
|
+
inputType: 'text' | 'email' | 'tel' | 'url';
|
|
24
|
+
multiline: boolean;
|
|
25
|
+
maxLength: number | null;
|
|
26
|
+
placeholder: string | null;
|
|
27
|
+
};
|
|
28
|
+
type AiLiveChatChoiceField = AiLiveChatFieldBase & {
|
|
29
|
+
kind: 'choice';
|
|
30
|
+
choices: {
|
|
31
|
+
label: string;
|
|
32
|
+
value: string;
|
|
33
|
+
}[];
|
|
34
|
+
multiple: boolean;
|
|
35
|
+
};
|
|
36
|
+
type AiLiveChatToggleField = AiLiveChatFieldBase & {
|
|
37
|
+
kind: 'toggle';
|
|
38
|
+
};
|
|
39
|
+
/** Text the survey shows between its questions. */
|
|
40
|
+
type AiLiveChatSurveyNote = {
|
|
41
|
+
kind: 'note';
|
|
42
|
+
text: string;
|
|
43
|
+
};
|
|
44
|
+
type AiLiveChatSurveyField = AiLiveChatTextField | AiLiveChatChoiceField | AiLiveChatToggleField | AiLiveChatSurveyNote;
|
|
45
|
+
/**
|
|
46
|
+
* Answers by field id: text and a single choice as their value, several choices as their values
|
|
47
|
+
* joined with commas, a toggle as a boolean.
|
|
48
|
+
*/
|
|
49
|
+
type AiLiveChatAnswers = Record<string, string | boolean>;
|
|
50
|
+
type AiLiveChatStartOptions = {
|
|
51
|
+
answers?: AiLiveChatAnswers;
|
|
52
|
+
/** Values the agent sees with the conversation. */
|
|
53
|
+
context?: Record<string, string>;
|
|
54
|
+
/** Sent as the visitor's first message once the chat has started. */
|
|
55
|
+
openingMessage?: string;
|
|
56
|
+
/** A token from `resumeToken()`: reconnect to that chat instead of starting a new one. */
|
|
57
|
+
resume?: string;
|
|
58
|
+
};
|
|
59
|
+
type AiLiveChatMessage = {
|
|
60
|
+
id: string;
|
|
61
|
+
text: string;
|
|
62
|
+
sender: 'agent' | 'system';
|
|
63
|
+
/** The agent's display name, when the provider has one. */
|
|
64
|
+
name: string | null;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* What the chat window needs from a live chat service. `onMessage`, `onTyping` and `onEnded` may
|
|
68
|
+
* be subscribed before `start()` and each return an unsubscribe. `onEnded` is for the agent's end
|
|
69
|
+
* of the chat; the visitor's goes through `end()`.
|
|
70
|
+
*/
|
|
71
|
+
type AiLiveChatProvider = {
|
|
72
|
+
availability(): Promise<AiLiveChatAvailability>;
|
|
73
|
+
survey(): Promise<AiLiveChatSurveyField[] | null>;
|
|
74
|
+
start(options: AiLiveChatStartOptions): Promise<void>;
|
|
75
|
+
send(text: string): Promise<void>;
|
|
76
|
+
typing(): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* What the visitor has typed and not sent yet, for an agent's preview; empty once they clear the
|
|
79
|
+
* box. A provider with it gets this in place of `typing()`.
|
|
80
|
+
*/
|
|
81
|
+
draft?(text: string): Promise<void>;
|
|
82
|
+
end(): Promise<void>;
|
|
83
|
+
onMessage(listener: (message: AiLiveChatMessage) => void): () => void;
|
|
84
|
+
onTyping(listener: () => void): () => void;
|
|
85
|
+
onEnded(listener: () => void): () => void;
|
|
86
|
+
/**
|
|
87
|
+
* When an agent takes the chat, and again after a reconnect. Without it the window takes the
|
|
88
|
+
* first agent message as the join.
|
|
89
|
+
*/
|
|
90
|
+
onAgent?(listener: (agent: {
|
|
91
|
+
name: string | null;
|
|
92
|
+
}) => void): () => void;
|
|
93
|
+
/** A token that reconnects to the current chat after a page load, or null when there is none. */
|
|
94
|
+
resumeToken(): Promise<string | null>;
|
|
95
|
+
emailTranscript?(options: {
|
|
96
|
+
email: string;
|
|
97
|
+
message?: string;
|
|
98
|
+
}): Promise<void>;
|
|
99
|
+
upload?(file: File): Promise<void>;
|
|
100
|
+
};
|
|
101
|
+
//#endregion
|
|
102
|
+
export { AiLiveChatProvider as a, AiLiveChatSurveyNote as c, AiLiveChatMessage as i, AiLiveChatTextField as l, AiLiveChatAvailability as n, AiLiveChatStartOptions as o, AiLiveChatChoiceField as r, AiLiveChatSurveyField as s, AiLiveChatAnswers as t, AiLiveChatToggleField as u };
|