@boldare/askdare 0.1.0 → 0.2.0-rc.1
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/CHANGELOG.md +31 -0
- package/README.md +10 -2
- package/dist/cli.js +286 -176
- package/dist/index.js +2 -0
- package/dist/next.d.ts +169 -4
- package/dist/next.js +395 -87
- package/dist/react-marked.js +1797 -0
- package/dist/react.d.ts +470 -0
- package/dist/react.js +2691 -0
- package/dist/store.d.ts +13 -0
- package/dist/ui/askdare.css +1720 -0
- package/dist/ui/avatar.tsx +27 -0
- package/dist/ui/chat.tsx +26 -0
- package/dist/ui/confirm.tsx +71 -0
- package/dist/ui/context.ts +31 -0
- package/dist/ui/feedback.tsx +78 -0
- package/dist/ui/footer.tsx +60 -0
- package/dist/ui/header.tsx +51 -0
- package/dist/ui/icons.tsx +89 -0
- package/dist/ui/index.ts +8 -0
- package/dist/ui/message.tsx +21 -0
- package/dist/ui/panel.tsx +121 -0
- package/dist/ui/welcome.tsx +88 -0
- package/dist/version.js +12 -0
- package/docs/cli.md +30 -0
- package/docs/configuration.md +74 -4
- package/docs/costs.md +7 -1
- package/docs/embedding.md +2 -0
- package/docs/feedback.md +54 -0
- package/docs/getting-started.md +3 -0
- package/docs/going-public.md +1 -0
- package/docs/observability.md +76 -0
- package/docs/privacy.md +27 -7
- package/docs/protocol.md +13 -3
- package/docs/react.md +283 -0
- package/docs/styling.md +14 -2
- package/docs/support.md +4 -2
- package/docs/texts.md +6 -0
- package/docs/troubleshooting.md +12 -0
- package/llms.txt +5 -2
- package/package.json +21 -9
- package/skills/askdare/SKILL.md +6 -2
package/dist/react.js
ADDED
|
@@ -0,0 +1,2691 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { t as O } from "./react-marked.js";
|
|
3
|
+
import { Component, createContext, memo, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
4
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
5
|
+
// src/react/context.tsx
|
|
6
|
+
const StoreContext = createContext(null);
|
|
7
|
+
const MessageContext = createContext(null);
|
|
8
|
+
/** Provides a chat store to the primitives below. `Root` creates one; the iframe brings its own. */
|
|
9
|
+
function ChatProvider({ store, children }) {
|
|
10
|
+
return /* @__PURE__ */ jsx(StoreContext.Provider, {
|
|
11
|
+
value: store,
|
|
12
|
+
children
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
/** The store of the surrounding chat. Throws outside `Root`, with a hint. */
|
|
16
|
+
function useStore() {
|
|
17
|
+
const store = useContext(StoreContext);
|
|
18
|
+
if (!store) throw new Error("[askdare] Chat components must be inside <Root>.");
|
|
19
|
+
return store;
|
|
20
|
+
}
|
|
21
|
+
/** The chat's state; re-renders on every change. */
|
|
22
|
+
function useSnapshot(store) {
|
|
23
|
+
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
|
|
24
|
+
}
|
|
25
|
+
/** The whole chat: its state, actions, bot settings and texts. Re-renders on every change. */
|
|
26
|
+
function useChat() {
|
|
27
|
+
const store = useStore();
|
|
28
|
+
const state = useSnapshot(store);
|
|
29
|
+
const { config } = store;
|
|
30
|
+
const { page } = state;
|
|
31
|
+
const bot = useMemo(() => ({
|
|
32
|
+
id: config.botId,
|
|
33
|
+
title: config.widget.title,
|
|
34
|
+
subtitle: config.widget.subtitle,
|
|
35
|
+
greeting: page.greeting ?? config.widget.greeting,
|
|
36
|
+
starters: page.starters ?? config.widget.starters,
|
|
37
|
+
placeholder: config.widget.placeholder,
|
|
38
|
+
avatar: config.widget.avatar,
|
|
39
|
+
locale: config.widget.locale,
|
|
40
|
+
disclosure: config.widget.disclosure,
|
|
41
|
+
preset: config.widget.preset,
|
|
42
|
+
variants: config.widget.variants,
|
|
43
|
+
attachments: config.attachments,
|
|
44
|
+
maxDictationSeconds: config.voice?.maxSeconds,
|
|
45
|
+
texts: config.widget.texts
|
|
46
|
+
}), [config, page]);
|
|
47
|
+
return {
|
|
48
|
+
state,
|
|
49
|
+
actions: store.actions,
|
|
50
|
+
bot,
|
|
51
|
+
t: store.t
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* One value from the chat's state, such as `useChatState((state) => state.busy)`. Re-renders only
|
|
56
|
+
* when that value changes, so return a primitive or a part of the state, not a new object.
|
|
57
|
+
*/
|
|
58
|
+
function useChatState(select) {
|
|
59
|
+
const store = useStore();
|
|
60
|
+
return useSyncExternalStore(store.subscribe, () => select(store.getSnapshot()), () => select(store.getServerSnapshot()));
|
|
61
|
+
}
|
|
62
|
+
/** Provides one message to the components inside `MessageList`. */
|
|
63
|
+
function MessageProvider({ message, children }) {
|
|
64
|
+
return /* @__PURE__ */ jsx(MessageContext.Provider, {
|
|
65
|
+
value: message,
|
|
66
|
+
children
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/** The message being rendered, inside `MessageList`. */
|
|
70
|
+
function useMessage() {
|
|
71
|
+
const message = useContext(MessageContext);
|
|
72
|
+
if (!message) throw new Error("[askdare] useMessage() works only inside <MessageList>.");
|
|
73
|
+
return message;
|
|
74
|
+
}
|
|
75
|
+
// src/chat/prepare-file.ts
|
|
76
|
+
/** Longest image edge sent to the model; larger photos only cost upload time. */
|
|
77
|
+
const MAX_EDGE = 2048;
|
|
78
|
+
const JPEG_QUALITY = .85;
|
|
79
|
+
const IMAGE_NAME = /\.(png|jpe?g|webp|gif|heic|heif|avif|bmp)$/i;
|
|
80
|
+
var UnsupportedFileError = class extends Error {};
|
|
81
|
+
const isPdf = (file) => file.type === "application/pdf" || /\.pdf$/i.test(file.name);
|
|
82
|
+
const isImage = (file) => file.type.startsWith("image/") && file.type !== "image/svg+xml" || IMAGE_NAME.test(file.name);
|
|
83
|
+
const baseName = (name) => name.replace(/\.[^.]*$/, "") || "image";
|
|
84
|
+
/** The `accept` attribute for the file picker. */
|
|
85
|
+
function acceptTypes(allowed) {
|
|
86
|
+
return [...allowed.images ? [
|
|
87
|
+
"image/png",
|
|
88
|
+
"image/jpeg",
|
|
89
|
+
"image/webp",
|
|
90
|
+
"image/gif",
|
|
91
|
+
"image/heic"
|
|
92
|
+
] : [], ...allowed.pdf ? ["application/pdf"] : []].join(",");
|
|
93
|
+
}
|
|
94
|
+
async function encodeJpeg(bitmap, width, height) {
|
|
95
|
+
const canvas = document.createElement("canvas");
|
|
96
|
+
canvas.width = width;
|
|
97
|
+
canvas.height = height;
|
|
98
|
+
const context = canvas.getContext("2d");
|
|
99
|
+
if (!context) throw new UnsupportedFileError();
|
|
100
|
+
context.fillStyle = "#fff";
|
|
101
|
+
context.fillRect(0, 0, width, height);
|
|
102
|
+
context.drawImage(bitmap, 0, 0, width, height);
|
|
103
|
+
return new Promise((resolve, reject) => canvas.toBlob((blob) => blob ? resolve(blob) : reject(new UnsupportedFileError()), "image/jpeg", JPEG_QUALITY));
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Gets a file ready to upload. Images are decoded, downsized and re-encoded as JPEG in the
|
|
107
|
+
* browser, which drops EXIF data such as the GPS position and turns HEIC photos into a format
|
|
108
|
+
* OpenAI accepts (where the browser can decode HEIC). PDFs are sent as they are.
|
|
109
|
+
*/
|
|
110
|
+
async function prepareFile(file, allowed) {
|
|
111
|
+
if (allowed.pdf && isPdf(file)) return {
|
|
112
|
+
blob: file,
|
|
113
|
+
name: file.name,
|
|
114
|
+
kind: "pdf"
|
|
115
|
+
};
|
|
116
|
+
if (!allowed.images || !isImage(file)) throw new UnsupportedFileError();
|
|
117
|
+
let bitmap;
|
|
118
|
+
try {
|
|
119
|
+
bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
|
|
120
|
+
} catch {
|
|
121
|
+
throw new UnsupportedFileError();
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
|
|
125
|
+
const width = Math.max(1, Math.round(bitmap.width * scale));
|
|
126
|
+
const height = Math.max(1, Math.round(bitmap.height * scale));
|
|
127
|
+
return {
|
|
128
|
+
blob: await encodeJpeg(bitmap, width, height),
|
|
129
|
+
name: `${baseName(file.name)}.jpg`,
|
|
130
|
+
kind: "image"
|
|
131
|
+
};
|
|
132
|
+
} finally {
|
|
133
|
+
bitmap.close();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
// src/chat/state.ts
|
|
137
|
+
/** Whether the draft, or the files ready to go, can be sent now. */
|
|
138
|
+
function canSend(state) {
|
|
139
|
+
return state.phase === "ready" && !state.busy && !state.files.some((file) => file.status === "uploading") && (state.draft.trim() !== "" || state.files.some((file) => file.status === "ready"));
|
|
140
|
+
}
|
|
141
|
+
// src/i18n/format.ts
|
|
142
|
+
/** Text helpers the widget needs; the dictionaries stay on the server. */
|
|
143
|
+
/** Fills `{name}` placeholders. */
|
|
144
|
+
function formatText(template, params = {}) {
|
|
145
|
+
return template.replace(/\{(\w+)\}/g, (match, name) => name in params ? String(params[name]) : match);
|
|
146
|
+
}
|
|
147
|
+
/** A plural text such as `message.attachments` for a count, by the locale's plural rules. */
|
|
148
|
+
function pluralText(texts, base, count, locale) {
|
|
149
|
+
let category = "other";
|
|
150
|
+
try {
|
|
151
|
+
category = new Intl.PluralRules(locale).select(count);
|
|
152
|
+
} catch {}
|
|
153
|
+
return formatText(texts[`${base}.${category}`] ?? texts[`${base}.other`] ?? "", { count });
|
|
154
|
+
}
|
|
155
|
+
// src/react/markdown.tsx
|
|
156
|
+
const SAFE_PROTOCOLS = /* @__PURE__ */ new Set([
|
|
157
|
+
"http:",
|
|
158
|
+
"https:",
|
|
159
|
+
"mailto:"
|
|
160
|
+
]);
|
|
161
|
+
/**
|
|
162
|
+
* Deeper nesting than any real answer needs. Past it, the rest shows as plain text: a prompt-
|
|
163
|
+
* injected answer of `>>>>…` or `- - - …` must not blow the stack and take the chat down with it.
|
|
164
|
+
*/
|
|
165
|
+
const MAX_DEPTH = 16;
|
|
166
|
+
/** Keeps only http(s) and mailto links; everything else (javascript:, data:, relative) is dropped. */
|
|
167
|
+
function safeUrl(url) {
|
|
168
|
+
try {
|
|
169
|
+
const parsed = new URL(url);
|
|
170
|
+
return SAFE_PROTOCOLS.has(parsed.protocol) ? parsed.href : "";
|
|
171
|
+
} catch {
|
|
172
|
+
return "";
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const NAMED = {
|
|
176
|
+
amp: "&",
|
|
177
|
+
lt: "<",
|
|
178
|
+
gt: ">",
|
|
179
|
+
quot: "\"",
|
|
180
|
+
apos: "'",
|
|
181
|
+
nbsp: "\xA0",
|
|
182
|
+
copy: "©",
|
|
183
|
+
reg: "®",
|
|
184
|
+
trade: "™",
|
|
185
|
+
hellip: "…",
|
|
186
|
+
mdash: "—",
|
|
187
|
+
ndash: "–",
|
|
188
|
+
lsquo: "‘",
|
|
189
|
+
rsquo: "’",
|
|
190
|
+
ldquo: "“",
|
|
191
|
+
rdquo: "”",
|
|
192
|
+
laquo: "«",
|
|
193
|
+
raquo: "»",
|
|
194
|
+
bull: "•",
|
|
195
|
+
middot: "·",
|
|
196
|
+
deg: "°",
|
|
197
|
+
plusmn: "±",
|
|
198
|
+
times: "×",
|
|
199
|
+
divide: "÷",
|
|
200
|
+
euro: "€",
|
|
201
|
+
pound: "£",
|
|
202
|
+
yen: "¥",
|
|
203
|
+
cent: "¢",
|
|
204
|
+
sect: "§",
|
|
205
|
+
para: "¶"
|
|
206
|
+
};
|
|
207
|
+
/**
|
|
208
|
+
* marked leaves character references for an HTML renderer to decode; we render text, so decode
|
|
209
|
+
* them here: numeric ones and the common named ones (others stay as written). Safe, because the
|
|
210
|
+
* result is only ever text or a URL that `safeUrl` checks after decoding.
|
|
211
|
+
*/
|
|
212
|
+
function decodeEntities(text) {
|
|
213
|
+
if (!text.includes("&")) return text;
|
|
214
|
+
return text.replace(/&(#\d{1,7}|#[xX][\da-fA-F]{1,6}|[a-zA-Z]{2,8});/g, (match, entity) => {
|
|
215
|
+
if (entity[0] !== "#") return NAMED[entity] ?? match;
|
|
216
|
+
const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
|
|
217
|
+
return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : "�";
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/** Inline tokens: text, emphasis, code, links. HTML is dropped, images are never loaded. */
|
|
221
|
+
function inline(tokens, depth) {
|
|
222
|
+
if (depth > MAX_DEPTH) return [(tokens ?? []).map((token) => token.raw).join("")];
|
|
223
|
+
return (tokens ?? []).map((token, key) => {
|
|
224
|
+
switch (token.type) {
|
|
225
|
+
case "text": return "tokens" in token && token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
|
|
226
|
+
case "escape": return token.text;
|
|
227
|
+
case "strong": return /* @__PURE__ */ jsx("strong", { children: inline(token.tokens, depth + 1) }, key);
|
|
228
|
+
case "em": return /* @__PURE__ */ jsx("em", { children: inline(token.tokens, depth + 1) }, key);
|
|
229
|
+
case "del": return /* @__PURE__ */ jsx("del", { children: inline(token.tokens, depth + 1) }, key);
|
|
230
|
+
case "codespan": return /* @__PURE__ */ jsx("code", { children: token.text }, key);
|
|
231
|
+
case "br": return /* @__PURE__ */ jsx("br", {}, key);
|
|
232
|
+
case "link": {
|
|
233
|
+
const href = safeUrl(decodeEntities(token.href));
|
|
234
|
+
return href ? /* @__PURE__ */ jsx("a", {
|
|
235
|
+
href,
|
|
236
|
+
target: "_blank",
|
|
237
|
+
rel: "noopener noreferrer nofollow",
|
|
238
|
+
children: inline(token.tokens, depth + 1)
|
|
239
|
+
}, key) : /* @__PURE__ */ jsx("span", { children: inline(token.tokens, depth + 1) }, key);
|
|
240
|
+
}
|
|
241
|
+
case "image": return token.text ? /* @__PURE__ */ jsxs("span", {
|
|
242
|
+
"data-ask-part": "image-alt",
|
|
243
|
+
children: [
|
|
244
|
+
"[",
|
|
245
|
+
decodeEntities(token.text),
|
|
246
|
+
"]"
|
|
247
|
+
]
|
|
248
|
+
}, key) : null;
|
|
249
|
+
default: return null;
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
function cells(row, header, depth) {
|
|
254
|
+
return row.map((cell, key) => {
|
|
255
|
+
return /* @__PURE__ */ jsx(header ? "th" : "td", {
|
|
256
|
+
style: cell.align ? { textAlign: cell.align } : void 0,
|
|
257
|
+
children: inline(cell.tokens, depth + 1)
|
|
258
|
+
}, key);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
function blocks(tokens, depth) {
|
|
262
|
+
if (depth > MAX_DEPTH) return [tokens.map((token) => token.raw).join("")];
|
|
263
|
+
return tokens.map((token, key) => {
|
|
264
|
+
switch (token.type) {
|
|
265
|
+
case "paragraph": return /* @__PURE__ */ jsx("p", { children: inline(token.tokens, depth + 1) }, key);
|
|
266
|
+
case "text": return token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
|
|
267
|
+
case "heading": {
|
|
268
|
+
const Heading = `h${Math.min(Math.max(token.depth, 1), 6)}`;
|
|
269
|
+
return /* @__PURE__ */ jsx(Heading, { children: inline(token.tokens, depth + 1) }, key);
|
|
270
|
+
}
|
|
271
|
+
case "code": return /* @__PURE__ */ jsx("pre", { children: /* @__PURE__ */ jsx("code", { children: token.text }) }, key);
|
|
272
|
+
case "blockquote": return /* @__PURE__ */ jsx("blockquote", { children: blocks(token.tokens ?? [], depth + 1) }, key);
|
|
273
|
+
case "hr": return /* @__PURE__ */ jsx("hr", {}, key);
|
|
274
|
+
case "list": {
|
|
275
|
+
const items = token.items.map((item, index) => /* @__PURE__ */ jsxs("li", { children: [item.task && /* @__PURE__ */ jsx("input", {
|
|
276
|
+
type: "checkbox",
|
|
277
|
+
checked: item.checked ?? false,
|
|
278
|
+
disabled: true
|
|
279
|
+
}), blocks(item.tokens.filter((child) => child.type !== "checkbox"), depth + 1)] }, index));
|
|
280
|
+
return token.ordered ? /* @__PURE__ */ jsx("ol", {
|
|
281
|
+
start: typeof token.start === "number" ? token.start : void 0,
|
|
282
|
+
children: items
|
|
283
|
+
}, key) : /* @__PURE__ */ jsx("ul", { children: items }, key);
|
|
284
|
+
}
|
|
285
|
+
case "table": return /* @__PURE__ */ jsxs("table", { children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: cells(token.header, true, depth) }) }), /* @__PURE__ */ jsx("tbody", { children: token.rows.map((row, index) => /* @__PURE__ */ jsx("tr", { children: cells(row, false, depth) }, index)) })] }, key);
|
|
286
|
+
default: return null;
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
/** The text as paragraphs, when markdown can't be had. */
|
|
291
|
+
const plain = (text) => text.split(/\n{2,}/).map((paragraph, key) => /* @__PURE__ */ jsx("p", { children: paragraph }, key));
|
|
292
|
+
function render(text) {
|
|
293
|
+
try {
|
|
294
|
+
return blocks(O.lex(text, { gfm: true }), 0);
|
|
295
|
+
} catch {
|
|
296
|
+
return plain(text);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/** Shows the plain text if rendering a message ever fails, so one answer can't break the chat. */
|
|
300
|
+
var Fallback = class extends Component {
|
|
301
|
+
state = { failed: false };
|
|
302
|
+
static getDerivedStateFromError() {
|
|
303
|
+
return { failed: true };
|
|
304
|
+
}
|
|
305
|
+
render() {
|
|
306
|
+
return this.state.failed ? plain(this.props.text) : this.props.children;
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const Markdown = /* @__PURE__ */ memo(function Markdown({ text }) {
|
|
310
|
+
return /* @__PURE__ */ jsx(Fallback, {
|
|
311
|
+
text,
|
|
312
|
+
children: render(text)
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
// src/react/refs.ts
|
|
316
|
+
/** One ref callback for a primitive's own ref and the one its user passed as a prop. */
|
|
317
|
+
function useMergedRef(own, passed) {
|
|
318
|
+
return useCallback((node) => {
|
|
319
|
+
own.current = node;
|
|
320
|
+
if (typeof passed === "function") passed(node);
|
|
321
|
+
else if (passed) passed.current = node;
|
|
322
|
+
}, [own, passed]);
|
|
323
|
+
}
|
|
324
|
+
/** Where a chat ends, tried in order: its panel, its theme root, its message form. */
|
|
325
|
+
const CHAT_BOUNDARIES = [
|
|
326
|
+
"[data-ask-part=\"panel\"]",
|
|
327
|
+
"[data-askdare-root]",
|
|
328
|
+
"[data-ask-part=\"composer\"]"
|
|
329
|
+
];
|
|
330
|
+
/**
|
|
331
|
+
* Focuses the element a ref holds, if it is in the page; says whether it handled the request.
|
|
332
|
+
* Unless the request is `explicit`, focus moves only from inside the chat or from nowhere (the
|
|
333
|
+
* body), so an answer never pulls focus out of the page's own form, and the page doesn't scroll.
|
|
334
|
+
*/
|
|
335
|
+
function focusElement(ref, explicit = false) {
|
|
336
|
+
const element = ref.current;
|
|
337
|
+
if (!element?.isConnected) return false;
|
|
338
|
+
if (explicit) {
|
|
339
|
+
element.focus();
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
const { activeElement, body, documentElement } = element.ownerDocument;
|
|
343
|
+
const chat = CHAT_BOUNDARIES.map((selector) => element.closest(selector)).find(Boolean) ?? element;
|
|
344
|
+
if (!activeElement || activeElement === body || activeElement === documentElement || chat.contains(activeElement)) element.focus({ preventScroll: true });
|
|
345
|
+
return true;
|
|
346
|
+
}
|
|
347
|
+
// src/react/messages.tsx
|
|
348
|
+
/** False for an answer that ended (or failed) before any text, files or sources. */
|
|
349
|
+
const hasContent = (message) => message.role === "user" || message.status === "streaming" || message.text !== "" || message.citations.length > 0;
|
|
350
|
+
/**
|
|
351
|
+
* The conversation: a live region that follows the latest message as it streams. Holds the
|
|
352
|
+
* welcome, the `MessageList` and the `Status`.
|
|
353
|
+
*/
|
|
354
|
+
function Messages({ ref, ...props }) {
|
|
355
|
+
const own = useRef(null);
|
|
356
|
+
const loading = useChatState((state) => state.phase === "loading");
|
|
357
|
+
const latest = useChatState((state) => state.messages.at(-1));
|
|
358
|
+
const commenting = useChatState((state) => state.commenting);
|
|
359
|
+
useEffect(() => {
|
|
360
|
+
const log = own.current;
|
|
361
|
+
if (log && latest) log.scrollTop = log.scrollHeight;
|
|
362
|
+
}, [latest, commenting]);
|
|
363
|
+
return /* @__PURE__ */ jsx("div", {
|
|
364
|
+
"data-ask-part": "messages",
|
|
365
|
+
role: "log",
|
|
366
|
+
"aria-live": "polite",
|
|
367
|
+
"aria-relevant": "additions",
|
|
368
|
+
"aria-busy": loading,
|
|
369
|
+
...props,
|
|
370
|
+
ref: useMergedRef(own, ref)
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
/** Renders its children for every message worth showing. Has no element of its own. */
|
|
374
|
+
function MessageList({ children }) {
|
|
375
|
+
const messages = useChatState((state) => state.messages);
|
|
376
|
+
return /* @__PURE__ */ jsx(Fragment, { children: messages.filter(hasContent).map((message) => /* @__PURE__ */ jsx(MessageProvider, {
|
|
377
|
+
message,
|
|
378
|
+
children
|
|
379
|
+
}, message.id)) });
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* One message, with `data-role` and `data-status`. The message primitives read only their own
|
|
383
|
+
* message, so a streaming answer doesn't re-render the earlier ones.
|
|
384
|
+
*/
|
|
385
|
+
function Message(props) {
|
|
386
|
+
const message = useMessage();
|
|
387
|
+
return /* @__PURE__ */ jsx("div", {
|
|
388
|
+
"data-ask-part": "message",
|
|
389
|
+
"data-role": message.role,
|
|
390
|
+
"data-status": message.status,
|
|
391
|
+
...props
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* The message's bubble: the visitor's text as typed, an answer as Markdown, and typing dots while
|
|
396
|
+
* an answer has no text yet.
|
|
397
|
+
*/
|
|
398
|
+
function MessageText(props) {
|
|
399
|
+
const message = useMessage();
|
|
400
|
+
const { t } = useStore();
|
|
401
|
+
if (message.text !== "") return /* @__PURE__ */ jsx("div", {
|
|
402
|
+
"data-ask-part": "bubble",
|
|
403
|
+
...props,
|
|
404
|
+
children: message.role === "assistant" ? /* @__PURE__ */ jsx(Markdown, { text: message.text }) : message.text
|
|
405
|
+
});
|
|
406
|
+
if (message.status !== "streaming") return null;
|
|
407
|
+
return /* @__PURE__ */ jsx("div", {
|
|
408
|
+
"data-ask-part": "bubble",
|
|
409
|
+
...props,
|
|
410
|
+
children: /* @__PURE__ */ jsxs("span", {
|
|
411
|
+
"data-ask-part": "typing",
|
|
412
|
+
role: "img",
|
|
413
|
+
"aria-label": t("status.typing"),
|
|
414
|
+
children: [
|
|
415
|
+
/* @__PURE__ */ jsx("i", {}),
|
|
416
|
+
/* @__PURE__ */ jsx("i", {}),
|
|
417
|
+
/* @__PURE__ */ jsx("i", {})
|
|
418
|
+
]
|
|
419
|
+
})
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
/** The sources of an answer. Links go through the same check as links in answers. */
|
|
423
|
+
function Citations(props) {
|
|
424
|
+
const message = useMessage();
|
|
425
|
+
const { t } = useStore();
|
|
426
|
+
if (message.citations.length === 0) return null;
|
|
427
|
+
return /* @__PURE__ */ jsx("ol", {
|
|
428
|
+
"data-ask-part": "citations",
|
|
429
|
+
"aria-label": t("message.sources"),
|
|
430
|
+
...props,
|
|
431
|
+
children: message.citations.map((citation) => {
|
|
432
|
+
const href = citation.url ? safeUrl(citation.url) : "";
|
|
433
|
+
return /* @__PURE__ */ jsx("li", {
|
|
434
|
+
"data-ask-part": "citation",
|
|
435
|
+
children: href ? /* @__PURE__ */ jsx("a", {
|
|
436
|
+
href,
|
|
437
|
+
target: "_blank",
|
|
438
|
+
rel: "noopener noreferrer nofollow",
|
|
439
|
+
children: citation.title
|
|
440
|
+
}) : /* @__PURE__ */ jsx("span", { children: citation.title })
|
|
441
|
+
}, citation.index);
|
|
442
|
+
})
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
/** Files of a message, or those picked for the next one (which can be removed). */
|
|
446
|
+
function FileList({ files, list, onRemove, ...props }) {
|
|
447
|
+
const { t } = useStore();
|
|
448
|
+
return /* @__PURE__ */ jsx("ul", {
|
|
449
|
+
"data-ask-part": list,
|
|
450
|
+
"aria-label": t("attachment.list"),
|
|
451
|
+
...props,
|
|
452
|
+
children: files.map((file, index) => {
|
|
453
|
+
const pending = "status" in file ? file : void 0;
|
|
454
|
+
return /* @__PURE__ */ jsxs("li", {
|
|
455
|
+
"data-ask-part": "attachment",
|
|
456
|
+
"data-kind": file.kind,
|
|
457
|
+
"data-status": pending?.status,
|
|
458
|
+
children: [
|
|
459
|
+
file.previewUrl ? /* @__PURE__ */ jsx("img", {
|
|
460
|
+
"data-ask-part": "attachment-preview",
|
|
461
|
+
src: file.previewUrl,
|
|
462
|
+
alt: ""
|
|
463
|
+
}) : /* @__PURE__ */ jsx("span", {
|
|
464
|
+
"data-ask-part": "attachment-badge",
|
|
465
|
+
"aria-hidden": "true",
|
|
466
|
+
children: file.kind === "image" ? "IMG" : file.kind === "pdf" ? "PDF" : "FILE"
|
|
467
|
+
}),
|
|
468
|
+
/* @__PURE__ */ jsx("span", {
|
|
469
|
+
"data-ask-part": "attachment-name",
|
|
470
|
+
children: file.name
|
|
471
|
+
}),
|
|
472
|
+
pending?.status === "uploading" && /* @__PURE__ */ jsx("span", {
|
|
473
|
+
"data-ask-part": "attachment-status",
|
|
474
|
+
children: t("attachment.uploading")
|
|
475
|
+
}),
|
|
476
|
+
pending?.status === "error" && /* @__PURE__ */ jsx("span", {
|
|
477
|
+
"data-ask-part": "attachment-status",
|
|
478
|
+
role: "alert",
|
|
479
|
+
children: pending.error
|
|
480
|
+
}),
|
|
481
|
+
pending && onRemove && /* @__PURE__ */ jsx("button", {
|
|
482
|
+
type: "button",
|
|
483
|
+
"data-ask-part": "attachment-remove",
|
|
484
|
+
"aria-label": t("attachment.remove", { name: file.name }),
|
|
485
|
+
onClick: () => onRemove(pending),
|
|
486
|
+
children: "×"
|
|
487
|
+
})
|
|
488
|
+
]
|
|
489
|
+
}, pending?.key ?? index);
|
|
490
|
+
})
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* The files sent with a message: previews from this visit, or after a reload only how many there
|
|
495
|
+
* were (`attachments-note`).
|
|
496
|
+
*/
|
|
497
|
+
function MessageFiles({ ref, ...props }) {
|
|
498
|
+
const message = useMessage();
|
|
499
|
+
const { widget } = useStore().config;
|
|
500
|
+
if (message.files && message.files.length > 0) return /* @__PURE__ */ jsx(FileList, {
|
|
501
|
+
files: message.files,
|
|
502
|
+
list: "message-attachments",
|
|
503
|
+
...props,
|
|
504
|
+
ref
|
|
505
|
+
});
|
|
506
|
+
if (message.attachments === 0) return null;
|
|
507
|
+
return /* @__PURE__ */ jsx("p", {
|
|
508
|
+
"data-ask-part": "attachments-note",
|
|
509
|
+
...props,
|
|
510
|
+
ref,
|
|
511
|
+
children: pluralText(widget.texts, "message.attachments", message.attachments, widget.locale)
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
// src/react/composer.tsx
|
|
515
|
+
/** Grows the message field with its content, up to the height set in CSS. */
|
|
516
|
+
function fitToContent(field) {
|
|
517
|
+
field.style.height = "auto";
|
|
518
|
+
field.style.height = `${field.scrollHeight}px`;
|
|
519
|
+
}
|
|
520
|
+
const clock = (seconds) => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
|
|
521
|
+
/** The form around the message field; submitting it sends the draft. */
|
|
522
|
+
function Composer({ onSubmit, ...props }) {
|
|
523
|
+
const { actions } = useChat();
|
|
524
|
+
return /* @__PURE__ */ jsx("form", {
|
|
525
|
+
"data-ask-part": "composer",
|
|
526
|
+
onSubmit: (event) => {
|
|
527
|
+
onSubmit?.(event);
|
|
528
|
+
if (event.defaultPrevented) return;
|
|
529
|
+
event.preventDefault();
|
|
530
|
+
actions.send();
|
|
531
|
+
},
|
|
532
|
+
...props
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* The message field. Enter sends, Shift+Enter starts a new line, pasted files are attached, and
|
|
537
|
+
* it grows with its text. It takes focus when the chat moves it here.
|
|
538
|
+
*/
|
|
539
|
+
function Input({ ref, onKeyDown, onPaste, onChange, ...props }) {
|
|
540
|
+
const own = useRef(null);
|
|
541
|
+
const { state, actions, bot } = useChat();
|
|
542
|
+
const store = useStore();
|
|
543
|
+
const { draft } = state;
|
|
544
|
+
useLayoutEffect(() => {
|
|
545
|
+
if (own.current) fitToContent(own.current);
|
|
546
|
+
}, [draft]);
|
|
547
|
+
useEffect(() => store.onFocus("input", (explicit) => focusElement(own, explicit)), [store]);
|
|
548
|
+
return /* @__PURE__ */ jsx("textarea", {
|
|
549
|
+
"data-ask-part": "input",
|
|
550
|
+
rows: 1,
|
|
551
|
+
placeholder: bot.placeholder,
|
|
552
|
+
"aria-label": bot.placeholder,
|
|
553
|
+
...props,
|
|
554
|
+
ref: useMergedRef(own, ref),
|
|
555
|
+
value: draft,
|
|
556
|
+
onChange: (event) => {
|
|
557
|
+
onChange?.(event);
|
|
558
|
+
actions.setDraft(event.target.value);
|
|
559
|
+
},
|
|
560
|
+
onKeyDown: (event) => {
|
|
561
|
+
onKeyDown?.(event);
|
|
562
|
+
if (event.defaultPrevented) return;
|
|
563
|
+
if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
|
|
564
|
+
event.preventDefault();
|
|
565
|
+
const form = event.currentTarget.closest("form[data-ask-part=\"composer\"]");
|
|
566
|
+
if (form) form.requestSubmit();
|
|
567
|
+
else actions.send();
|
|
568
|
+
}
|
|
569
|
+
},
|
|
570
|
+
onPaste: (event) => {
|
|
571
|
+
onPaste?.(event);
|
|
572
|
+
if (event.defaultPrevented) return;
|
|
573
|
+
const files = Array.from(event.clipboardData.files);
|
|
574
|
+
if (!bot.attachments || files.length === 0) return;
|
|
575
|
+
event.preventDefault();
|
|
576
|
+
actions.addFiles(files);
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
/** Sends the draft; disabled until there is something to send. */
|
|
581
|
+
function Send(props) {
|
|
582
|
+
const { state, t } = useChat();
|
|
583
|
+
return /* @__PURE__ */ jsx("button", {
|
|
584
|
+
type: "submit",
|
|
585
|
+
"data-ask-part": "send",
|
|
586
|
+
"aria-label": t("composer.send"),
|
|
587
|
+
title: t("composer.send"),
|
|
588
|
+
disabled: !canSend(state),
|
|
589
|
+
...props
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Opens the file picker, next to its hidden file input. Renders nothing when the bot takes no
|
|
594
|
+
* attachments.
|
|
595
|
+
*/
|
|
596
|
+
function AttachButton({ onClick, ...props }) {
|
|
597
|
+
const file = useRef(null);
|
|
598
|
+
const { state, actions, bot, t } = useChat();
|
|
599
|
+
const allowed = bot.attachments;
|
|
600
|
+
if (!allowed) return null;
|
|
601
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("input", {
|
|
602
|
+
ref: file,
|
|
603
|
+
type: "file",
|
|
604
|
+
hidden: true,
|
|
605
|
+
multiple: true,
|
|
606
|
+
accept: acceptTypes(allowed),
|
|
607
|
+
onChange: (event) => {
|
|
608
|
+
actions.addFiles(Array.from(event.target.files ?? []));
|
|
609
|
+
event.target.value = "";
|
|
610
|
+
}
|
|
611
|
+
}), /* @__PURE__ */ jsx("button", {
|
|
612
|
+
type: "button",
|
|
613
|
+
"data-ask-part": "attach",
|
|
614
|
+
"aria-label": t("composer.attach"),
|
|
615
|
+
title: t("composer.attach"),
|
|
616
|
+
disabled: state.busy || state.files.length >= allowed.maxPerMessage,
|
|
617
|
+
onClick: (event) => {
|
|
618
|
+
onClick?.(event);
|
|
619
|
+
file.current?.click();
|
|
620
|
+
},
|
|
621
|
+
...props
|
|
622
|
+
})] });
|
|
623
|
+
}
|
|
624
|
+
/** The files picked for the next message, each with a remove button. */
|
|
625
|
+
function Files(props) {
|
|
626
|
+
const { state, actions } = useChat();
|
|
627
|
+
if (state.files.length === 0) return null;
|
|
628
|
+
return /* @__PURE__ */ jsx(FileList, {
|
|
629
|
+
files: state.files,
|
|
630
|
+
list: "attachments",
|
|
631
|
+
onRemove: (file) => actions.removeFile(file.key),
|
|
632
|
+
...props
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
/** Starts a dictation. Renders nothing without voice input or a usable microphone. */
|
|
636
|
+
function DictateButton({ onClick, ...props }) {
|
|
637
|
+
const { state, actions, t } = useChat();
|
|
638
|
+
if (!state.canDictate) return null;
|
|
639
|
+
return /* @__PURE__ */ jsx("button", {
|
|
640
|
+
type: "button",
|
|
641
|
+
"data-ask-part": "voice",
|
|
642
|
+
"aria-label": t("composer.dictate"),
|
|
643
|
+
title: t("composer.dictate"),
|
|
644
|
+
onClick: (event) => {
|
|
645
|
+
onClick?.(event);
|
|
646
|
+
actions.startDictation();
|
|
647
|
+
},
|
|
648
|
+
...props
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* The dictation in place of the message field: a level meter, the time, cancel and done. Renders
|
|
653
|
+
* nothing while no dictation runs.
|
|
654
|
+
*/
|
|
655
|
+
function Recorder({ cancelIcon = "×", ...props }) {
|
|
656
|
+
const level = useRef(null);
|
|
657
|
+
const done = useRef(null);
|
|
658
|
+
const store = useStore();
|
|
659
|
+
const { state, actions, bot, t } = useChat();
|
|
660
|
+
const { dictation } = state;
|
|
661
|
+
useEffect(() => store.onFocus("dictation", (explicit) => focusElement(done, explicit)), [store]);
|
|
662
|
+
useEffect(() => {
|
|
663
|
+
if (dictation !== "recording") return;
|
|
664
|
+
let frame = requestAnimationFrame(function tick() {
|
|
665
|
+
const value = store.level();
|
|
666
|
+
if (value !== void 0) level.current?.style.setProperty("--ask-level", value.toFixed(3));
|
|
667
|
+
frame = requestAnimationFrame(tick);
|
|
668
|
+
});
|
|
669
|
+
return () => cancelAnimationFrame(frame);
|
|
670
|
+
}, [dictation, store]);
|
|
671
|
+
if (dictation === "idle") return null;
|
|
672
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
673
|
+
"data-ask-part": "recorder",
|
|
674
|
+
"data-state": dictation,
|
|
675
|
+
...props,
|
|
676
|
+
children: [
|
|
677
|
+
/* @__PURE__ */ jsx("span", {
|
|
678
|
+
"data-ask-part": "recorder-level",
|
|
679
|
+
ref: level,
|
|
680
|
+
"aria-hidden": "true"
|
|
681
|
+
}),
|
|
682
|
+
/* @__PURE__ */ jsx("span", {
|
|
683
|
+
"data-ask-part": "recorder-label",
|
|
684
|
+
role: "status",
|
|
685
|
+
children: dictation === "recording" ? t("dictation.listening") : t("dictation.transcribing")
|
|
686
|
+
}),
|
|
687
|
+
dictation === "recording" && /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
688
|
+
/* @__PURE__ */ jsxs("span", {
|
|
689
|
+
"data-ask-part": "recorder-time",
|
|
690
|
+
children: [
|
|
691
|
+
clock(state.elapsed),
|
|
692
|
+
" / ",
|
|
693
|
+
clock(bot.maxDictationSeconds ?? 0)
|
|
694
|
+
]
|
|
695
|
+
}),
|
|
696
|
+
/* @__PURE__ */ jsx("button", {
|
|
697
|
+
type: "button",
|
|
698
|
+
"data-ask-part": "recorder-cancel",
|
|
699
|
+
"aria-label": t("dictation.cancel"),
|
|
700
|
+
title: t("dictation.cancel"),
|
|
701
|
+
onClick: () => actions.cancelDictation(),
|
|
702
|
+
children: cancelIcon
|
|
703
|
+
}),
|
|
704
|
+
/* @__PURE__ */ jsx("button", {
|
|
705
|
+
type: "button",
|
|
706
|
+
"data-ask-part": "recorder-done",
|
|
707
|
+
ref: done,
|
|
708
|
+
onClick: () => void actions.finishDictation(),
|
|
709
|
+
children: t("dictation.done")
|
|
710
|
+
})
|
|
711
|
+
] })
|
|
712
|
+
]
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
// src/react/feedback.tsx
|
|
716
|
+
/**
|
|
717
|
+
* Rates the answer it is in (ADR-0012), pressed while that is the visitor's rating. Renders
|
|
718
|
+
* nothing for the visitor's own messages, an answer still streaming, or a bot whose answers can't
|
|
719
|
+
* be rated. After 👎 the chat's `state.commenting` names the answer to ask about.
|
|
720
|
+
*/
|
|
721
|
+
function FeedbackButton({ rating, onClick, ...props }) {
|
|
722
|
+
const message = useMessage();
|
|
723
|
+
const { actions, t } = useStore();
|
|
724
|
+
const key = message.feedback?.key;
|
|
725
|
+
const current = useChatState((state) => key ? state.ratings[key] : void 0);
|
|
726
|
+
if (!key || message.role !== "assistant" || message.status !== "done") return null;
|
|
727
|
+
const label = t(rating === "up" ? "feedback.up" : "feedback.down");
|
|
728
|
+
return /* @__PURE__ */ jsx("button", {
|
|
729
|
+
type: "button",
|
|
730
|
+
"data-ask-part": "feedback-button",
|
|
731
|
+
"data-rating": rating,
|
|
732
|
+
"aria-pressed": current === rating,
|
|
733
|
+
"aria-label": label,
|
|
734
|
+
title: label,
|
|
735
|
+
onClick: (event) => {
|
|
736
|
+
onClick?.(event);
|
|
737
|
+
actions.rate(message.id, current === rating ? null : rating);
|
|
738
|
+
},
|
|
739
|
+
...props
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
// src/react/notices.tsx
|
|
743
|
+
/** What the chat is doing: loading a conversation, or what the assistant does before it writes. */
|
|
744
|
+
function Status(props) {
|
|
745
|
+
const { state, t } = useChat();
|
|
746
|
+
const text = state.phase === "loading" ? t("status.loading") : state.activity;
|
|
747
|
+
if (!text) return null;
|
|
748
|
+
return /* @__PURE__ */ jsx("p", {
|
|
749
|
+
"data-ask-part": "status",
|
|
750
|
+
role: "status",
|
|
751
|
+
...props,
|
|
752
|
+
children: text
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
/** The latest problem, in the visitor's language, announced to screen readers. */
|
|
756
|
+
function ErrorMessage(props) {
|
|
757
|
+
const error = useChat().state.error;
|
|
758
|
+
if (!error) return null;
|
|
759
|
+
return /* @__PURE__ */ jsx("p", {
|
|
760
|
+
"data-ask-part": "error",
|
|
761
|
+
role: "alert",
|
|
762
|
+
...props,
|
|
763
|
+
children: error
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
// src/react/panel.tsx
|
|
767
|
+
const hasFiles = (event) => event.dataTransfer.types.includes("Files");
|
|
768
|
+
/**
|
|
769
|
+
* The chat's frame, with `data-busy` while the assistant answers or a dictation runs. Files dropped
|
|
770
|
+
* on it are attached (`data-dragging` while they are over it).
|
|
771
|
+
*/
|
|
772
|
+
function Panel({ landmark = "region", onDragOver, onDragLeave, onDrop, ...props }) {
|
|
773
|
+
const { state, actions, bot } = useChat();
|
|
774
|
+
const [dragging, setDragging] = useState(false);
|
|
775
|
+
const attributes = {
|
|
776
|
+
"data-ask-part": "panel",
|
|
777
|
+
"data-dragging": dragging || void 0,
|
|
778
|
+
"data-busy": state.busy || state.dictation !== "idle" || void 0,
|
|
779
|
+
onDragOver: (event) => {
|
|
780
|
+
onDragOver?.(event);
|
|
781
|
+
if (!bot.attachments || !hasFiles(event)) return;
|
|
782
|
+
event.preventDefault();
|
|
783
|
+
setDragging(true);
|
|
784
|
+
},
|
|
785
|
+
onDragLeave: (event) => {
|
|
786
|
+
onDragLeave?.(event);
|
|
787
|
+
const to = event.relatedTarget;
|
|
788
|
+
if (!(to instanceof Node && event.currentTarget.contains(to))) setDragging(false);
|
|
789
|
+
},
|
|
790
|
+
onDrop: (event) => {
|
|
791
|
+
onDrop?.(event);
|
|
792
|
+
if (!bot.attachments || !hasFiles(event)) return;
|
|
793
|
+
event.preventDefault();
|
|
794
|
+
setDragging(false);
|
|
795
|
+
actions.addFiles(Array.from(event.dataTransfer.files));
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
return landmark === "main" ? /* @__PURE__ */ jsx("main", {
|
|
799
|
+
...attributes,
|
|
800
|
+
...props
|
|
801
|
+
}) : /* @__PURE__ */ jsx("section", {
|
|
802
|
+
"aria-label": bot.title,
|
|
803
|
+
...attributes,
|
|
804
|
+
...props
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
// src/base-path.ts
|
|
808
|
+
/**
|
|
809
|
+
* Whether a chat route's `basePath` is a path on the app itself, like `/api/chat`: never another
|
|
810
|
+
* origin, a relative path or anything that needs escaping (ADR-0011). The server, the React entry
|
|
811
|
+
* and the CLI each bundle their own copy.
|
|
812
|
+
*/
|
|
813
|
+
function isBasePath(value) {
|
|
814
|
+
return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
|
|
815
|
+
}
|
|
816
|
+
// src/chat/page-options.ts
|
|
817
|
+
const MAX_CONTEXT = 1e3;
|
|
818
|
+
const JWT = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
819
|
+
/**
|
|
820
|
+
* A JWT-shaped string, or null to sign out; the server verifies it. Any other string signs out
|
|
821
|
+
* too, so a broken token never leaves the previous user signed in.
|
|
822
|
+
*/
|
|
823
|
+
function identityToken(value) {
|
|
824
|
+
if (value === null) return null;
|
|
825
|
+
if (typeof value !== "string") return void 0;
|
|
826
|
+
if (value.length <= 4096 && JWT.test(value)) return value;
|
|
827
|
+
console.warn("[askdare] askdare('identify') got something that isn't a JWT; signing out.");
|
|
828
|
+
return null;
|
|
829
|
+
}
|
|
830
|
+
/** Keeps only the allowed fields, trimmed and within their limits. */
|
|
831
|
+
function pageOptions(data) {
|
|
832
|
+
const greeting = typeof data["greeting"] === "string" ? data["greeting"].trim() : "";
|
|
833
|
+
const starters = Array.isArray(data["starters"]) ? data["starters"].filter((item) => typeof item === "string").map((item) => item.trim()).filter((item) => item.length > 0 && item.length <= 80).slice(0, 4) : void 0;
|
|
834
|
+
const context = typeof data["context"] === "string" ? data["context"].trim() : "";
|
|
835
|
+
return {
|
|
836
|
+
...greeting && greeting.length <= 500 ? { greeting } : {},
|
|
837
|
+
...starters ? { starters } : {},
|
|
838
|
+
...context ? { context: context.slice(0, MAX_CONTEXT) } : {}
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
// src/protocol/events.ts
|
|
842
|
+
/** Stable error codes sent to clients. The accompanying message never contains internals. */
|
|
843
|
+
const ERROR_CODES = [
|
|
844
|
+
"invalid_input",
|
|
845
|
+
"unauthorized",
|
|
846
|
+
"session_expired",
|
|
847
|
+
"not_found",
|
|
848
|
+
"rate_limited",
|
|
849
|
+
"budget_exceeded",
|
|
850
|
+
"bot_unavailable",
|
|
851
|
+
"content_blocked",
|
|
852
|
+
"timeout",
|
|
853
|
+
"upstream_error",
|
|
854
|
+
"internal_error"
|
|
855
|
+
];
|
|
856
|
+
const MESSAGE_END_REASONS = [
|
|
857
|
+
"completed",
|
|
858
|
+
"max_steps",
|
|
859
|
+
"max_output_tokens",
|
|
860
|
+
"timeout",
|
|
861
|
+
"content_filter",
|
|
862
|
+
"aborted"
|
|
863
|
+
];
|
|
864
|
+
const PROTOCOL_EVENT_TYPES = [
|
|
865
|
+
"conversation.created",
|
|
866
|
+
"user.ack",
|
|
867
|
+
"message.start",
|
|
868
|
+
"reasoning",
|
|
869
|
+
"text.delta",
|
|
870
|
+
"citation",
|
|
871
|
+
"tool.status",
|
|
872
|
+
"message.end",
|
|
873
|
+
"error"
|
|
874
|
+
];
|
|
875
|
+
// src/protocol/validate.ts
|
|
876
|
+
const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
877
|
+
const text = (value, min = 0, max = Number.POSITIVE_INFINITY) => typeof value === "string" && value.length >= min && value.length <= max;
|
|
878
|
+
const integer = (value, min) => typeof value === "number" && Number.isSafeInteger(value) && value >= min;
|
|
879
|
+
const oneOf = (value, options) => options.includes(value);
|
|
880
|
+
const messageId = (value) => text(value, 1, 128);
|
|
881
|
+
/** A rating handle, or undefined when the value breaks the protocol. */
|
|
882
|
+
function feedbackOf(value) {
|
|
883
|
+
return record$1(value) && text(value["handle"], 1, 4096) && typeof value["key"] === "string" && /^[0-9a-f]{16,64}$/.test(value["key"]) ? {
|
|
884
|
+
handle: value["handle"],
|
|
885
|
+
key: value["key"]
|
|
886
|
+
} : void 0;
|
|
887
|
+
}
|
|
888
|
+
/** An absolute http(s) URL as the server sends it; stricter than a browser's lenient parsing. */
|
|
889
|
+
function httpUrl(value) {
|
|
890
|
+
if (typeof value !== "string" || !/^https?:\/\/[^\s/?#]+[^\s]*$/i.test(value)) return false;
|
|
891
|
+
try {
|
|
892
|
+
const { protocol } = new URL(value);
|
|
893
|
+
return protocol === "http:" || protocol === "https:";
|
|
894
|
+
} catch {
|
|
895
|
+
return false;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
function citationOf(value) {
|
|
899
|
+
if (!record$1(value) || !integer(value["index"], 1) || !text(value["title"], 1)) return void 0;
|
|
900
|
+
if (value["url"] !== void 0 && !httpUrl(value["url"])) return void 0;
|
|
901
|
+
return {
|
|
902
|
+
index: value["index"],
|
|
903
|
+
title: value["title"],
|
|
904
|
+
...value["url"] === void 0 ? {} : { url: value["url"] }
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
function paramsOf(value) {
|
|
908
|
+
if (!record$1(value)) return void 0;
|
|
909
|
+
const params = {};
|
|
910
|
+
for (const [key, item] of Object.entries(value)) {
|
|
911
|
+
if (key.length > 32 || !(text(item, 0, 200) || typeof item === "number" && Number.isFinite(item))) return void 0;
|
|
912
|
+
params[key] = item;
|
|
913
|
+
}
|
|
914
|
+
return params;
|
|
915
|
+
}
|
|
916
|
+
/** A protocol event received over the wire, or undefined when it breaks the protocol. */
|
|
917
|
+
function parseEvent(value) {
|
|
918
|
+
if (!record$1(value)) return void 0;
|
|
919
|
+
const id = value["messageId"];
|
|
920
|
+
switch (value["type"]) {
|
|
921
|
+
case "conversation.created": return text(value["resumeToken"], 1) ? {
|
|
922
|
+
type: "conversation.created",
|
|
923
|
+
resumeToken: value["resumeToken"]
|
|
924
|
+
} : void 0;
|
|
925
|
+
case "user.ack":
|
|
926
|
+
case "message.start": return messageId(id) ? {
|
|
927
|
+
type: value["type"],
|
|
928
|
+
messageId: id
|
|
929
|
+
} : void 0;
|
|
930
|
+
case "reasoning": return messageId(id) && oneOf(value["state"], ["started", "done"]) ? {
|
|
931
|
+
type: "reasoning",
|
|
932
|
+
messageId: id,
|
|
933
|
+
state: value["state"]
|
|
934
|
+
} : void 0;
|
|
935
|
+
case "text.delta": return messageId(id) && text(value["delta"]) ? {
|
|
936
|
+
type: "text.delta",
|
|
937
|
+
messageId: id,
|
|
938
|
+
delta: value["delta"]
|
|
939
|
+
} : void 0;
|
|
940
|
+
case "citation": {
|
|
941
|
+
const citation = citationOf(value);
|
|
942
|
+
return messageId(id) && citation ? {
|
|
943
|
+
type: "citation",
|
|
944
|
+
messageId: id,
|
|
945
|
+
...citation
|
|
946
|
+
} : void 0;
|
|
947
|
+
}
|
|
948
|
+
case "tool.status": return messageId(id) && text(value["callId"], 1, 128) && text(value["name"], 1, 64) && oneOf(value["state"], [
|
|
949
|
+
"running",
|
|
950
|
+
"done",
|
|
951
|
+
"error"
|
|
952
|
+
]) ? {
|
|
953
|
+
type: "tool.status",
|
|
954
|
+
messageId: id,
|
|
955
|
+
callId: value["callId"],
|
|
956
|
+
name: value["name"],
|
|
957
|
+
state: value["state"]
|
|
958
|
+
} : void 0;
|
|
959
|
+
case "message.end": {
|
|
960
|
+
const { resumeToken } = value;
|
|
961
|
+
if (!messageId(id) || !oneOf(value["reason"], MESSAGE_END_REASONS)) return;
|
|
962
|
+
if (resumeToken !== void 0 && !text(resumeToken, 1)) return void 0;
|
|
963
|
+
const feedback = value["feedback"] === void 0 ? void 0 : feedbackOf(value["feedback"]);
|
|
964
|
+
if (value["feedback"] !== void 0 && !feedback) return void 0;
|
|
965
|
+
return {
|
|
966
|
+
type: "message.end",
|
|
967
|
+
messageId: id,
|
|
968
|
+
reason: value["reason"],
|
|
969
|
+
...typeof resumeToken === "string" ? { resumeToken } : {},
|
|
970
|
+
...feedback ? { feedback } : {}
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
case "error": {
|
|
974
|
+
const { code, message, retryAfterMs, key, params } = value;
|
|
975
|
+
if (!oneOf(code, ERROR_CODES) || !text(message, 0, 500)) return void 0;
|
|
976
|
+
if (retryAfterMs !== void 0 && !integer(retryAfterMs, 0)) return void 0;
|
|
977
|
+
if (key !== void 0 && !text(key, 0, 64)) return void 0;
|
|
978
|
+
const checked = params === void 0 ? void 0 : paramsOf(params);
|
|
979
|
+
if (params !== void 0 && !checked) return void 0;
|
|
980
|
+
return {
|
|
981
|
+
type: "error",
|
|
982
|
+
code,
|
|
983
|
+
message,
|
|
984
|
+
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
985
|
+
...key === void 0 ? {} : { key },
|
|
986
|
+
...checked ? { params: checked } : {}
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
default: return;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
function historyMessageOf(value) {
|
|
993
|
+
if (!record$1(value) || !text(value["id"], 1, 256) || !oneOf(value["role"], ["user", "assistant"]) || !text(value["text"]) || !Array.isArray(value["citations"]) || !integer(value["attachments"], 0)) return;
|
|
994
|
+
const citations = value["citations"].map(citationOf);
|
|
995
|
+
if (citations.some((citation) => citation === void 0)) return void 0;
|
|
996
|
+
const feedback = value["feedback"] === void 0 ? void 0 : feedbackOf(value["feedback"]);
|
|
997
|
+
if (value["feedback"] !== void 0 && !feedback) return void 0;
|
|
998
|
+
return {
|
|
999
|
+
id: value["id"],
|
|
1000
|
+
role: value["role"],
|
|
1001
|
+
text: value["text"],
|
|
1002
|
+
citations,
|
|
1003
|
+
attachments: value["attachments"],
|
|
1004
|
+
...feedback ? { feedback } : {}
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
/** The answer of `POST /history`, or undefined when it breaks the protocol. */
|
|
1008
|
+
function parseHistory(value) {
|
|
1009
|
+
if (!record$1(value) || !Array.isArray(value["messages"])) return void 0;
|
|
1010
|
+
const messages = value["messages"].map(historyMessageOf);
|
|
1011
|
+
return messages.some((message) => message === void 0) ? void 0 : { messages };
|
|
1012
|
+
}
|
|
1013
|
+
// src/protocol/sse.ts
|
|
1014
|
+
const KNOWN_TYPES = new Set(PROTOCOL_EVENT_TYPES);
|
|
1015
|
+
/**
|
|
1016
|
+
* Validates a framed event against the protocol. Unknown event types are reported, not thrown,
|
|
1017
|
+
* so older clients keep working when newer servers add events.
|
|
1018
|
+
*/
|
|
1019
|
+
function decodeEvent(raw) {
|
|
1020
|
+
if (!KNOWN_TYPES.has(raw.event)) return {
|
|
1021
|
+
ok: false,
|
|
1022
|
+
reason: "unknown_type",
|
|
1023
|
+
type: raw.event
|
|
1024
|
+
};
|
|
1025
|
+
let json;
|
|
1026
|
+
try {
|
|
1027
|
+
json = JSON.parse(raw.data);
|
|
1028
|
+
} catch {
|
|
1029
|
+
return {
|
|
1030
|
+
ok: false,
|
|
1031
|
+
reason: "invalid_json",
|
|
1032
|
+
type: raw.event
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
const event = parseEvent(json);
|
|
1036
|
+
if (!event || event.type !== raw.event) return {
|
|
1037
|
+
ok: false,
|
|
1038
|
+
reason: "invalid_payload",
|
|
1039
|
+
type: raw.event
|
|
1040
|
+
};
|
|
1041
|
+
return {
|
|
1042
|
+
ok: true,
|
|
1043
|
+
event
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Incremental parser for `text/event-stream`, following the WHATWG framing rules: any line ending
|
|
1048
|
+
* (CRLF, LF, CR), comments, multi-line `data`, and dispatch on a blank line. Fields other than
|
|
1049
|
+
* `event` and `data` are ignored. An unterminated event at end of stream is discarded.
|
|
1050
|
+
*/
|
|
1051
|
+
var SseParser = class {
|
|
1052
|
+
#buffer = "";
|
|
1053
|
+
#pendingCr = false;
|
|
1054
|
+
#started = false;
|
|
1055
|
+
#eventType = "";
|
|
1056
|
+
#dataLines = [];
|
|
1057
|
+
/** Feeds a decoded text chunk and returns the events completed by it. */
|
|
1058
|
+
push(chunk) {
|
|
1059
|
+
let text = chunk;
|
|
1060
|
+
if (!this.#started && text.length > 0) {
|
|
1061
|
+
this.#started = true;
|
|
1062
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
1063
|
+
}
|
|
1064
|
+
if (this.#pendingCr && text.startsWith("\n")) text = text.slice(1);
|
|
1065
|
+
this.#pendingCr = false;
|
|
1066
|
+
this.#buffer += text;
|
|
1067
|
+
const events = [];
|
|
1068
|
+
let lineStart = 0;
|
|
1069
|
+
for (let i = 0; i < this.#buffer.length; i += 1) {
|
|
1070
|
+
const char = this.#buffer[i];
|
|
1071
|
+
if (char !== "\n" && char !== "\r") continue;
|
|
1072
|
+
const line = this.#buffer.slice(lineStart, i);
|
|
1073
|
+
if (char === "\r") {
|
|
1074
|
+
if (i + 1 === this.#buffer.length) this.#pendingCr = true;
|
|
1075
|
+
else if (this.#buffer[i + 1] === "\n") i += 1;
|
|
1076
|
+
}
|
|
1077
|
+
lineStart = i + 1;
|
|
1078
|
+
const event = this.#processLine(line);
|
|
1079
|
+
if (event) events.push(event);
|
|
1080
|
+
}
|
|
1081
|
+
this.#buffer = this.#buffer.slice(lineStart);
|
|
1082
|
+
return events;
|
|
1083
|
+
}
|
|
1084
|
+
#processLine(line) {
|
|
1085
|
+
if (line === "") return this.#dispatch();
|
|
1086
|
+
if (line.startsWith(":")) return void 0;
|
|
1087
|
+
const colon = line.indexOf(":");
|
|
1088
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
1089
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
1090
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
1091
|
+
if (field === "event") this.#eventType = value;
|
|
1092
|
+
else if (field === "data") this.#dataLines.push(value);
|
|
1093
|
+
}
|
|
1094
|
+
#dispatch() {
|
|
1095
|
+
const hasData = this.#dataLines.length > 0;
|
|
1096
|
+
const event = {
|
|
1097
|
+
event: this.#eventType === "" ? "message" : this.#eventType,
|
|
1098
|
+
data: this.#dataLines.join("\n")
|
|
1099
|
+
};
|
|
1100
|
+
this.#eventType = "";
|
|
1101
|
+
this.#dataLines = [];
|
|
1102
|
+
return hasData ? event : void 0;
|
|
1103
|
+
}
|
|
1104
|
+
};
|
|
1105
|
+
// src/chat/chat-client.ts
|
|
1106
|
+
const json = (value) => ({
|
|
1107
|
+
contentType: "application/json",
|
|
1108
|
+
body: JSON.stringify(value)
|
|
1109
|
+
});
|
|
1110
|
+
const RENEW_MARGIN_SECONDS = 30;
|
|
1111
|
+
/** The server refused a session and said why: a limit, a switched-off bot, a setup problem. */
|
|
1112
|
+
var SessionRefused = class extends Error {
|
|
1113
|
+
event;
|
|
1114
|
+
constructor(event) {
|
|
1115
|
+
super(event.message);
|
|
1116
|
+
this.event = event;
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
/**
|
|
1120
|
+
* Talks to the askdare API from the iframe: keeps the access token in memory, the resume token
|
|
1121
|
+
* in best-effort storage, and turns each send into a stream of protocol events. Network and
|
|
1122
|
+
* protocol problems are reported as `error` events, never thrown.
|
|
1123
|
+
*/
|
|
1124
|
+
var ChatClient = class {
|
|
1125
|
+
#options;
|
|
1126
|
+
#fetch;
|
|
1127
|
+
#botId;
|
|
1128
|
+
#session;
|
|
1129
|
+
/** The page context the current conversation already has, so it is sent only when it changes. */
|
|
1130
|
+
#sentContext;
|
|
1131
|
+
/** Shared by concurrent callers, so parallel uploads end up with one visitor. */
|
|
1132
|
+
#opening;
|
|
1133
|
+
/**
|
|
1134
|
+
* The page's latest askdare('identify'): a token, or null when signed out (ADR-0009). Sent with
|
|
1135
|
+
* every session request, so the server re-checks it and the identity ends with the token.
|
|
1136
|
+
*/
|
|
1137
|
+
#identity;
|
|
1138
|
+
/** Set when the identity changed: no request may use the previous user's session any more. */
|
|
1139
|
+
#identityChanged = false;
|
|
1140
|
+
/** Tokens already reported as refused, so a renewal doesn't warn again. */
|
|
1141
|
+
#refused;
|
|
1142
|
+
/** The signed-in user, as an opaque key from the server; undefined while anonymous. */
|
|
1143
|
+
#identityKey;
|
|
1144
|
+
/** The previous user's access token while their identity is replaced: renews the visitor only. */
|
|
1145
|
+
#renewal;
|
|
1146
|
+
constructor(options) {
|
|
1147
|
+
this.#options = options;
|
|
1148
|
+
this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
1149
|
+
this.#botId = options.botId;
|
|
1150
|
+
}
|
|
1151
|
+
/** A client-side error: the dictionary text for `key`, else the English message. */
|
|
1152
|
+
#error(code, key, english) {
|
|
1153
|
+
return {
|
|
1154
|
+
type: "error",
|
|
1155
|
+
code,
|
|
1156
|
+
key,
|
|
1157
|
+
message: this.#options.translate?.(key) ?? english
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
/** A server error in the visitor's language when it carries a known key. */
|
|
1161
|
+
#localize(event) {
|
|
1162
|
+
const text = event.key ? this.#options.translate?.(event.key, event.params) : void 0;
|
|
1163
|
+
return text ? {
|
|
1164
|
+
...event,
|
|
1165
|
+
message: text
|
|
1166
|
+
} : event;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Signs the visitor in (a token from the site's backend) or out (null) right away. Resolves to
|
|
1170
|
+
* true when the stored conversation belonged to someone else and is gone from this browser.
|
|
1171
|
+
*/
|
|
1172
|
+
async identify(token) {
|
|
1173
|
+
if (token === this.#identity) return false;
|
|
1174
|
+
this.#identity = token;
|
|
1175
|
+
this.#identityChanged = true;
|
|
1176
|
+
await this.#opening?.catch(() => void 0);
|
|
1177
|
+
const before = this.#resumeKey();
|
|
1178
|
+
this.#renewal = this.#session?.accessToken ?? this.#renewal;
|
|
1179
|
+
this.#session = void 0;
|
|
1180
|
+
try {
|
|
1181
|
+
await this.#ensureSession(false);
|
|
1182
|
+
} catch {}
|
|
1183
|
+
return this.#resumeKey() !== before;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Where this browser keeps the conversation: one place per signed-in user and one for anonymous
|
|
1187
|
+
* visits, so signing out or in never hands a conversation to someone else, nor loses it.
|
|
1188
|
+
*/
|
|
1189
|
+
#resumeKey() {
|
|
1190
|
+
const base = `askdare:${this.#botId}:resume`;
|
|
1191
|
+
return this.#identityKey ? `${base}:${this.#identityKey}` : base;
|
|
1192
|
+
}
|
|
1193
|
+
/** Forgets the stored conversation so the next message starts a new one. */
|
|
1194
|
+
reset() {
|
|
1195
|
+
this.#sentContext = void 0;
|
|
1196
|
+
this.#options.storage.remove(this.#resumeKey());
|
|
1197
|
+
}
|
|
1198
|
+
/** True when this browser holds a conversation to resume. */
|
|
1199
|
+
hasConversation() {
|
|
1200
|
+
return this.#options.storage.get(this.#resumeKey()) !== void 0;
|
|
1201
|
+
}
|
|
1202
|
+
/** Loads the visible part of the stored conversation; empty when there is none or it is gone. */
|
|
1203
|
+
async loadHistory(signal) {
|
|
1204
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
1205
|
+
if (!resumeToken) return [];
|
|
1206
|
+
const response = await this.#authorized("POST", "/history", () => json({
|
|
1207
|
+
botId: this.#options.botId,
|
|
1208
|
+
resumeToken
|
|
1209
|
+
}), signal);
|
|
1210
|
+
if (response.status === 404) {
|
|
1211
|
+
this.reset();
|
|
1212
|
+
return [];
|
|
1213
|
+
}
|
|
1214
|
+
if (!response.ok) throw new Error(`History request failed with ${response.status}`);
|
|
1215
|
+
return parseHistory(await response.json())?.messages ?? [];
|
|
1216
|
+
}
|
|
1217
|
+
/** Deletes the conversation on the server (best effort) and forgets it in this browser. */
|
|
1218
|
+
async deleteConversation() {
|
|
1219
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
1220
|
+
try {
|
|
1221
|
+
if (resumeToken) await this.#authorized("DELETE", "/conversation", () => json({
|
|
1222
|
+
botId: this.#options.botId,
|
|
1223
|
+
resumeToken
|
|
1224
|
+
}));
|
|
1225
|
+
} finally {
|
|
1226
|
+
this.reset();
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
/** This browser's ratings of answers, by feedback key (ADR-0012: askdare stores none). */
|
|
1230
|
+
ratings() {
|
|
1231
|
+
try {
|
|
1232
|
+
const stored = JSON.parse(this.#options.storage.get(this.#ratingsKey()) ?? "{}");
|
|
1233
|
+
if (typeof stored !== "object" || stored === null) return {};
|
|
1234
|
+
return Object.fromEntries(Object.entries(stored).filter((entry) => entry[1] === "up" || entry[1] === "down"));
|
|
1235
|
+
} catch {
|
|
1236
|
+
return {};
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
/** Remembers a rating, or forgets it with null. Only the latest hundred are kept. */
|
|
1240
|
+
rememberRating(key, rating) {
|
|
1241
|
+
const { [key]: _previous, ...others } = this.ratings();
|
|
1242
|
+
const entries = Object.entries(rating ? {
|
|
1243
|
+
...others,
|
|
1244
|
+
[key]: rating
|
|
1245
|
+
} : others).slice(-100);
|
|
1246
|
+
this.#options.storage.set(this.#ratingsKey(), JSON.stringify(Object.fromEntries(entries)));
|
|
1247
|
+
}
|
|
1248
|
+
#ratingsKey() {
|
|
1249
|
+
return `askdare:${this.#botId}:ratings`;
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* Sends a rating of one answer (null takes it back) with an optional comment; `handle` comes
|
|
1253
|
+
* with the answer. Resolves to what went wrong, in the visitor's language, or undefined.
|
|
1254
|
+
*/
|
|
1255
|
+
async rate(handle, rating, comment) {
|
|
1256
|
+
try {
|
|
1257
|
+
const response = await this.#authorized("POST", "/feedback", () => json({
|
|
1258
|
+
botId: this.#options.botId,
|
|
1259
|
+
feedback: handle,
|
|
1260
|
+
rating,
|
|
1261
|
+
...comment ? { comment } : {}
|
|
1262
|
+
}));
|
|
1263
|
+
return response.ok ? void 0 : (await this.#errorFromResponse(response, false)).message;
|
|
1264
|
+
} catch (error) {
|
|
1265
|
+
return this.#failure(error, "upstream_error").message;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
/** Uploads one file for the next message. The server checks its type and size again. */
|
|
1269
|
+
async upload(file, name, signal) {
|
|
1270
|
+
try {
|
|
1271
|
+
const response = await this.#authorized("POST", "/attachments", () => ({
|
|
1272
|
+
contentType: "application/octet-stream",
|
|
1273
|
+
body: file,
|
|
1274
|
+
headers: {
|
|
1275
|
+
"x-askdare-bot": this.#options.botId,
|
|
1276
|
+
"x-askdare-filename": encodeURIComponent(name)
|
|
1277
|
+
}
|
|
1278
|
+
}), signal);
|
|
1279
|
+
if (!response.ok) return {
|
|
1280
|
+
ok: false,
|
|
1281
|
+
message: (await this.#errorFromResponse(response)).message
|
|
1282
|
+
};
|
|
1283
|
+
const uploaded = (await response.json()).attachment;
|
|
1284
|
+
if (typeof uploaded?.id !== "string" || uploaded.kind !== "image" && uploaded.kind !== "pdf" || typeof uploaded.name !== "string") return {
|
|
1285
|
+
ok: false,
|
|
1286
|
+
message: this.#error("upstream_error", "error.uploadFailed", "The file could not be uploaded.").message
|
|
1287
|
+
};
|
|
1288
|
+
return {
|
|
1289
|
+
ok: true,
|
|
1290
|
+
file: {
|
|
1291
|
+
id: uploaded.id,
|
|
1292
|
+
kind: uploaded.kind,
|
|
1293
|
+
name: uploaded.name
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
} catch (error) {
|
|
1297
|
+
return {
|
|
1298
|
+
ok: false,
|
|
1299
|
+
message: this.#failure(error, "upstream_error").message
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
/** Turns a dictation into text. `languages` are hints such as the browser's and the page's language. */
|
|
1304
|
+
async transcribe(audio, languages) {
|
|
1305
|
+
try {
|
|
1306
|
+
const response = await this.#authorized("POST", "/transcriptions", () => ({
|
|
1307
|
+
contentType: "application/octet-stream",
|
|
1308
|
+
body: audio,
|
|
1309
|
+
headers: {
|
|
1310
|
+
"x-askdare-bot": this.#options.botId,
|
|
1311
|
+
"x-askdare-languages": languages.join(",")
|
|
1312
|
+
}
|
|
1313
|
+
}));
|
|
1314
|
+
if (!response.ok) return {
|
|
1315
|
+
ok: false,
|
|
1316
|
+
message: (await this.#errorFromResponse(response)).message
|
|
1317
|
+
};
|
|
1318
|
+
const body = await response.json();
|
|
1319
|
+
return typeof body.text === "string" ? {
|
|
1320
|
+
ok: true,
|
|
1321
|
+
text: body.text
|
|
1322
|
+
} : {
|
|
1323
|
+
ok: false,
|
|
1324
|
+
message: this.#error("upstream_error", "error.transcriptionFailed", "The recording could not be transcribed.").message
|
|
1325
|
+
};
|
|
1326
|
+
} catch (error) {
|
|
1327
|
+
return {
|
|
1328
|
+
ok: false,
|
|
1329
|
+
message: this.#failure(error, "upstream_error").message
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
async send(message, onEvent, signal) {
|
|
1334
|
+
const context = message.context !== this.#sentContext ? message.context : void 0;
|
|
1335
|
+
try {
|
|
1336
|
+
const response = await this.#authorized("POST", "/messages", () => {
|
|
1337
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
1338
|
+
return json({
|
|
1339
|
+
botId: this.#options.botId,
|
|
1340
|
+
text: message.text,
|
|
1341
|
+
locale: this.#options.locale,
|
|
1342
|
+
...message.attachments?.length ? { attachments: message.attachments } : {},
|
|
1343
|
+
...context ? { context } : {},
|
|
1344
|
+
...resumeToken ? { resumeToken } : {}
|
|
1345
|
+
});
|
|
1346
|
+
}, signal);
|
|
1347
|
+
if (!response.ok || !response.body) {
|
|
1348
|
+
onEvent(await this.#errorFromResponse(response));
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
if (response.headers.get("x-askdare-protocol") !== String(1)) {
|
|
1352
|
+
onEvent(this.#error("bot_unavailable", "error.updated", "The assistant was updated. Please reload the page."));
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
await this.#readStream(response.body, (event) => {
|
|
1356
|
+
if (event.type === "message.start" && context) this.#sentContext = context;
|
|
1357
|
+
onEvent(event);
|
|
1358
|
+
}, signal);
|
|
1359
|
+
} catch (error) {
|
|
1360
|
+
if (signal?.aborted) return;
|
|
1361
|
+
onEvent(this.#failure(error, error instanceof DOMException && error.name === "TimeoutError" ? "timeout" : "upstream_error"));
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
/** Sends an authenticated request, renewing an expired session once. */
|
|
1365
|
+
async #authorized(method, path, request, signal) {
|
|
1366
|
+
const attempt = async (renew) => {
|
|
1367
|
+
const session = await this.#ensureSession(renew);
|
|
1368
|
+
const { contentType, body, headers } = request();
|
|
1369
|
+
return this.#fetch(`${this.#options.basePath}${path}`, {
|
|
1370
|
+
method,
|
|
1371
|
+
headers: {
|
|
1372
|
+
...headers,
|
|
1373
|
+
"content-type": contentType,
|
|
1374
|
+
authorization: `Bearer ${session.accessToken}`
|
|
1375
|
+
},
|
|
1376
|
+
body,
|
|
1377
|
+
...signal ? { signal } : {}
|
|
1378
|
+
});
|
|
1379
|
+
};
|
|
1380
|
+
const first = await attempt(false);
|
|
1381
|
+
return first.status === 401 ? attempt(true) : first;
|
|
1382
|
+
}
|
|
1383
|
+
async #ensureSession(renew) {
|
|
1384
|
+
const now = Date.now() / 1e3;
|
|
1385
|
+
if (!renew && !this.#identityChanged && this.#session && this.#session.expiresAt - RENEW_MARGIN_SECONDS > now) return this.#session;
|
|
1386
|
+
this.#opening ??= this.#openSession().finally(() => {
|
|
1387
|
+
this.#opening = void 0;
|
|
1388
|
+
});
|
|
1389
|
+
return this.#opening;
|
|
1390
|
+
}
|
|
1391
|
+
/** Not tied to one caller's signal, because other callers may be waiting for the same session. */
|
|
1392
|
+
async #openSession() {
|
|
1393
|
+
const resumeToken = this.#options.storage.get(this.#resumeKey());
|
|
1394
|
+
const accessToken = this.#session?.accessToken ?? this.#renewal;
|
|
1395
|
+
const identityToken = this.#identity;
|
|
1396
|
+
const sentFrom = this.#resumeKey();
|
|
1397
|
+
const response = await this.#fetch(`${this.#options.basePath}/session`, {
|
|
1398
|
+
method: "POST",
|
|
1399
|
+
headers: { "content-type": "application/json" },
|
|
1400
|
+
body: JSON.stringify({
|
|
1401
|
+
botId: this.#options.botId,
|
|
1402
|
+
...resumeToken ? { resumeToken } : {},
|
|
1403
|
+
...accessToken ? { accessToken } : {},
|
|
1404
|
+
...identityToken === void 0 ? {} : { identityToken }
|
|
1405
|
+
})
|
|
1406
|
+
});
|
|
1407
|
+
if (!response.ok) throw new SessionRefused(await this.#errorFromResponse(response, false));
|
|
1408
|
+
const body = await response.json();
|
|
1409
|
+
if (this.#identity === identityToken) this.#identityChanged = false;
|
|
1410
|
+
this.#renewal = void 0;
|
|
1411
|
+
this.#identityKey = body.identified ? body.identityKey : void 0;
|
|
1412
|
+
if (identityToken && !body.identified && this.#refused !== identityToken) {
|
|
1413
|
+
this.#refused = identityToken;
|
|
1414
|
+
console.warn(`[askdare] askdare('identify') was refused (${body.identityProblem ?? "unknown"}); the chat continues anonymously.`);
|
|
1415
|
+
}
|
|
1416
|
+
if (body.resumeToken) {
|
|
1417
|
+
this.#options.storage.set(this.#resumeKey(), body.resumeToken);
|
|
1418
|
+
if (sentFrom !== this.#resumeKey()) this.#options.storage.remove(sentFrom);
|
|
1419
|
+
} else if (!body.resumable && resumeToken && sentFrom === this.#resumeKey()) this.reset();
|
|
1420
|
+
this.#session = {
|
|
1421
|
+
accessToken: body.accessToken,
|
|
1422
|
+
expiresAt: body.expiresAt
|
|
1423
|
+
};
|
|
1424
|
+
return this.#session;
|
|
1425
|
+
}
|
|
1426
|
+
/** What to show for a request that threw: the server's reason for refusing a session, if any. */
|
|
1427
|
+
#failure(error, code) {
|
|
1428
|
+
return error instanceof SessionRefused ? error.event : this.#connectionError(code);
|
|
1429
|
+
}
|
|
1430
|
+
#connectionError(code) {
|
|
1431
|
+
return this.#error(code, "error.connection", "Connection problem. Please try again.");
|
|
1432
|
+
}
|
|
1433
|
+
async #errorFromResponse(response, forgetMissing = true) {
|
|
1434
|
+
let body = {};
|
|
1435
|
+
try {
|
|
1436
|
+
body = await response.json();
|
|
1437
|
+
} catch {}
|
|
1438
|
+
if (forgetMissing && response.status === 404 && body.error?.code === "not_found") this.reset();
|
|
1439
|
+
const result = decodeEvent({
|
|
1440
|
+
event: "error",
|
|
1441
|
+
data: JSON.stringify({
|
|
1442
|
+
type: "error",
|
|
1443
|
+
...body.error
|
|
1444
|
+
})
|
|
1445
|
+
});
|
|
1446
|
+
return result.ok && result.event.type === "error" ? this.#localize(result.event) : this.#error("upstream_error", "error.upstream_error", "The assistant is temporarily unavailable. Please try again.");
|
|
1447
|
+
}
|
|
1448
|
+
async #readStream(body, onEvent, signal) {
|
|
1449
|
+
const reader = body.getReader();
|
|
1450
|
+
const decoder = new TextDecoder();
|
|
1451
|
+
const parser = new SseParser();
|
|
1452
|
+
const watchdogMs = this.#options.watchdogMs ?? 45e3;
|
|
1453
|
+
let timer;
|
|
1454
|
+
let stalled = false;
|
|
1455
|
+
const arm = () => {
|
|
1456
|
+
clearTimeout(timer);
|
|
1457
|
+
timer = setTimeout(() => {
|
|
1458
|
+
stalled = true;
|
|
1459
|
+
reader.cancel();
|
|
1460
|
+
}, watchdogMs);
|
|
1461
|
+
};
|
|
1462
|
+
const onAbort = () => void reader.cancel();
|
|
1463
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1464
|
+
try {
|
|
1465
|
+
arm();
|
|
1466
|
+
for (;;) {
|
|
1467
|
+
const { done, value } = await reader.read();
|
|
1468
|
+
if (done) break;
|
|
1469
|
+
arm();
|
|
1470
|
+
for (const raw of parser.push(decoder.decode(value, { stream: true }))) {
|
|
1471
|
+
const result = decodeEvent(raw);
|
|
1472
|
+
if (!result.ok) continue;
|
|
1473
|
+
if (result.event.type === "conversation.created") this.#options.storage.set(this.#resumeKey(), result.event.resumeToken);
|
|
1474
|
+
else if (result.event.type === "message.end" && result.event.resumeToken) this.#options.storage.set(this.#resumeKey(), result.event.resumeToken);
|
|
1475
|
+
else if (result.event.type === "error" && result.event.code === "not_found") this.reset();
|
|
1476
|
+
onEvent(result.event.type === "error" ? this.#localize(result.event) : result.event);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
if (stalled) onEvent(this.#error("timeout", "error.stalled", "The connection stalled. Please try again."));
|
|
1480
|
+
} finally {
|
|
1481
|
+
clearTimeout(timer);
|
|
1482
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
// src/chat/recorder.ts
|
|
1487
|
+
/** Formats OpenAI transcribes, best first: WebM/Opus (Chrome, Firefox, Edge), then MP4 (Safari). */
|
|
1488
|
+
const MIME_TYPES = [
|
|
1489
|
+
"audio/webm;codecs=opus",
|
|
1490
|
+
"audio/webm",
|
|
1491
|
+
"audio/mp4;codecs=mp4a.40.2",
|
|
1492
|
+
"audio/mp4"
|
|
1493
|
+
];
|
|
1494
|
+
/** Speech needs little: about 240 KB per minute where the browser honours it. */
|
|
1495
|
+
const BITS_PER_SECOND = 32e3;
|
|
1496
|
+
function recordingMimeType() {
|
|
1497
|
+
if (typeof MediaRecorder === "undefined") return void 0;
|
|
1498
|
+
return MIME_TYPES.find((type) => MediaRecorder.isTypeSupported(type));
|
|
1499
|
+
}
|
|
1500
|
+
/** True when this browser can record and the embedding page's policy lets the iframe use the microphone. */
|
|
1501
|
+
function canRecord() {
|
|
1502
|
+
if (!navigator.mediaDevices?.getUserMedia || !recordingMimeType()) return false;
|
|
1503
|
+
return document.featurePolicy?.allowsFeature("microphone") ?? true;
|
|
1504
|
+
}
|
|
1505
|
+
var MicrophoneError = class extends Error {
|
|
1506
|
+
reason;
|
|
1507
|
+
constructor(reason, options) {
|
|
1508
|
+
super(`Microphone ${reason}`, options);
|
|
1509
|
+
this.reason = reason;
|
|
1510
|
+
}
|
|
1511
|
+
};
|
|
1512
|
+
/**
|
|
1513
|
+
* Asks for the microphone and starts recording. Recording stops by itself after `maxSeconds`,
|
|
1514
|
+
* even in a hidden frame. Throws {@link MicrophoneError}.
|
|
1515
|
+
*/
|
|
1516
|
+
async function startRecording(maxSeconds) {
|
|
1517
|
+
const mimeType = recordingMimeType();
|
|
1518
|
+
if (!mimeType) throw new MicrophoneError("failed");
|
|
1519
|
+
let stream;
|
|
1520
|
+
try {
|
|
1521
|
+
stream = await navigator.mediaDevices.getUserMedia({ audio: {
|
|
1522
|
+
echoCancellation: true,
|
|
1523
|
+
noiseSuppression: true
|
|
1524
|
+
} });
|
|
1525
|
+
} catch (error) {
|
|
1526
|
+
const name = error instanceof DOMException ? error.name : "";
|
|
1527
|
+
if (name === "NotAllowedError" || name === "SecurityError") throw new MicrophoneError("blocked", { cause: error });
|
|
1528
|
+
if (name === "NotFoundError" || name === "OverconstrainedError") throw new MicrophoneError("missing", { cause: error });
|
|
1529
|
+
throw new MicrophoneError("failed", { cause: error });
|
|
1530
|
+
}
|
|
1531
|
+
try {
|
|
1532
|
+
return record(stream, mimeType, maxSeconds);
|
|
1533
|
+
} catch (error) {
|
|
1534
|
+
for (const track of stream.getTracks()) track.stop();
|
|
1535
|
+
throw new MicrophoneError("failed", { cause: error });
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
function record(stream, mimeType, maxSeconds) {
|
|
1539
|
+
const recorder = new MediaRecorder(stream, {
|
|
1540
|
+
mimeType,
|
|
1541
|
+
audioBitsPerSecond: BITS_PER_SECOND
|
|
1542
|
+
});
|
|
1543
|
+
const chunks = [];
|
|
1544
|
+
recorder.addEventListener("dataavailable", (event) => {
|
|
1545
|
+
if (event.data.size > 0) chunks.push(event.data);
|
|
1546
|
+
});
|
|
1547
|
+
const stopped = new Promise((resolve) => recorder.addEventListener("stop", () => resolve(), { once: true }));
|
|
1548
|
+
const context = new AudioContext();
|
|
1549
|
+
const analyser = context.createAnalyser();
|
|
1550
|
+
analyser.fftSize = 512;
|
|
1551
|
+
context.createMediaStreamSource(stream).connect(analyser);
|
|
1552
|
+
const samples = new Uint8Array(analyser.fftSize);
|
|
1553
|
+
const release = () => {
|
|
1554
|
+
for (const track of stream.getTracks()) track.stop();
|
|
1555
|
+
context.close();
|
|
1556
|
+
};
|
|
1557
|
+
let limit;
|
|
1558
|
+
const halt = () => {
|
|
1559
|
+
clearTimeout(limit);
|
|
1560
|
+
if (recorder.state !== "inactive") recorder.stop();
|
|
1561
|
+
};
|
|
1562
|
+
recorder.start(250);
|
|
1563
|
+
limit = setTimeout(halt, maxSeconds * 1e3);
|
|
1564
|
+
return {
|
|
1565
|
+
level() {
|
|
1566
|
+
analyser.getByteTimeDomainData(samples);
|
|
1567
|
+
let sum = 0;
|
|
1568
|
+
for (const sample of samples) {
|
|
1569
|
+
const value = (sample - 128) / 128;
|
|
1570
|
+
sum += value * value;
|
|
1571
|
+
}
|
|
1572
|
+
return Math.min(1, Math.sqrt(sum / samples.length) * 4);
|
|
1573
|
+
},
|
|
1574
|
+
async stop() {
|
|
1575
|
+
halt();
|
|
1576
|
+
await stopped;
|
|
1577
|
+
release();
|
|
1578
|
+
return new Blob(chunks, { type: mimeType.split(";")[0] ?? mimeType });
|
|
1579
|
+
},
|
|
1580
|
+
cancel() {
|
|
1581
|
+
halt();
|
|
1582
|
+
release();
|
|
1583
|
+
}
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
// src/chat/reducer.ts
|
|
1587
|
+
/** Looks texts up in a bot's dictionary; an unknown key shows as itself. */
|
|
1588
|
+
function translator(texts) {
|
|
1589
|
+
return (key, params) => formatText(texts[key] ?? key, params);
|
|
1590
|
+
}
|
|
1591
|
+
const fromHistory = (message) => ({
|
|
1592
|
+
id: message.id,
|
|
1593
|
+
role: message.role,
|
|
1594
|
+
text: message.text,
|
|
1595
|
+
citations: message.citations,
|
|
1596
|
+
attachments: message.attachments,
|
|
1597
|
+
status: "done",
|
|
1598
|
+
...message.feedback ? { feedback: message.feedback } : {}
|
|
1599
|
+
});
|
|
1600
|
+
/** The messages after one protocol event of a streamed answer. */
|
|
1601
|
+
function applyEvent(messages, event) {
|
|
1602
|
+
const update = (id, change) => messages.map((message) => message.id === id ? change(message) : message);
|
|
1603
|
+
switch (event.type) {
|
|
1604
|
+
case "message.start": return [...messages, {
|
|
1605
|
+
id: event.messageId,
|
|
1606
|
+
role: "assistant",
|
|
1607
|
+
text: "",
|
|
1608
|
+
citations: [],
|
|
1609
|
+
attachments: 0,
|
|
1610
|
+
status: "streaming"
|
|
1611
|
+
}];
|
|
1612
|
+
case "text.delta": return update(event.messageId, (message) => ({
|
|
1613
|
+
...message,
|
|
1614
|
+
text: message.text + event.delta
|
|
1615
|
+
}));
|
|
1616
|
+
case "citation": return update(event.messageId, (message) => ({
|
|
1617
|
+
...message,
|
|
1618
|
+
citations: [...message.citations, {
|
|
1619
|
+
index: event.index,
|
|
1620
|
+
title: event.title,
|
|
1621
|
+
url: event.url
|
|
1622
|
+
}]
|
|
1623
|
+
}));
|
|
1624
|
+
case "message.end": return update(event.messageId, (message) => ({
|
|
1625
|
+
...message,
|
|
1626
|
+
status: "done",
|
|
1627
|
+
...event.feedback ? { feedback: event.feedback } : {}
|
|
1628
|
+
}));
|
|
1629
|
+
default: return messages;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
/** Marks the answer that was streaming when the turn failed. */
|
|
1633
|
+
const failStreaming = (messages) => messages.map((message) => message.status === "streaming" ? {
|
|
1634
|
+
...message,
|
|
1635
|
+
status: "error"
|
|
1636
|
+
} : message);
|
|
1637
|
+
/** What the assistant is doing right now, shown while no text streams; undefined: unchanged. */
|
|
1638
|
+
function activityFor(event, t) {
|
|
1639
|
+
if (event.type === "reasoning") return event.state === "started" ? t("status.thinking") : null;
|
|
1640
|
+
if (event.type === "tool.status") return event.state === "running" ? event.name === "file_search" ? t("status.searching") : t("status.tool", { name: event.name }) : null;
|
|
1641
|
+
if (event.type === "text.delta" || event.type === "message.end") return null;
|
|
1642
|
+
}
|
|
1643
|
+
// src/chat/storage.ts
|
|
1644
|
+
function browserStorage() {
|
|
1645
|
+
return {
|
|
1646
|
+
get(key) {
|
|
1647
|
+
try {
|
|
1648
|
+
return window.localStorage.getItem(key) ?? void 0;
|
|
1649
|
+
} catch {
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
},
|
|
1653
|
+
set(key, value) {
|
|
1654
|
+
try {
|
|
1655
|
+
window.localStorage.setItem(key, value);
|
|
1656
|
+
} catch {}
|
|
1657
|
+
},
|
|
1658
|
+
remove(key) {
|
|
1659
|
+
try {
|
|
1660
|
+
window.localStorage.removeItem(key);
|
|
1661
|
+
} catch {}
|
|
1662
|
+
}
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
// src/chat/store.ts
|
|
1666
|
+
/** How long a focus request waits for its element to appear, such as the field after a dictation. */
|
|
1667
|
+
const FOCUS_WAIT_MS = 2e3;
|
|
1668
|
+
/**
|
|
1669
|
+
* Where the chat wants focus next. A request stays pending until a listener for its target really
|
|
1670
|
+
* takes it: the message field comes back only after a dictation ends, and a listener whose element
|
|
1671
|
+
* has just unmounted must not swallow the request. Only the latest request is kept.
|
|
1672
|
+
*/
|
|
1673
|
+
function focusRequests() {
|
|
1674
|
+
const listeners = {
|
|
1675
|
+
input: /* @__PURE__ */ new Set(),
|
|
1676
|
+
dictation: /* @__PURE__ */ new Set()
|
|
1677
|
+
};
|
|
1678
|
+
let pending;
|
|
1679
|
+
const deliver = (target, explicit) => {
|
|
1680
|
+
let taken = false;
|
|
1681
|
+
for (const listener of listeners[target]) taken = listener(explicit) || taken;
|
|
1682
|
+
return taken;
|
|
1683
|
+
};
|
|
1684
|
+
return {
|
|
1685
|
+
focus(target, explicit = false) {
|
|
1686
|
+
pending = deliver(target, explicit) ? void 0 : {
|
|
1687
|
+
target,
|
|
1688
|
+
explicit,
|
|
1689
|
+
at: Date.now()
|
|
1690
|
+
};
|
|
1691
|
+
},
|
|
1692
|
+
onFocus(target, listener) {
|
|
1693
|
+
listeners[target].add(listener);
|
|
1694
|
+
if (pending?.target === target && Date.now() - pending.at < FOCUS_WAIT_MS && listener(pending?.explicit ?? false)) pending = void 0;
|
|
1695
|
+
return () => listeners[target].delete(listener);
|
|
1696
|
+
}
|
|
1697
|
+
};
|
|
1698
|
+
}
|
|
1699
|
+
const MICROPHONE_MESSAGES = {
|
|
1700
|
+
blocked: "microphone.blocked",
|
|
1701
|
+
missing: "microphone.missing",
|
|
1702
|
+
failed: "microphone.failed"
|
|
1703
|
+
};
|
|
1704
|
+
/** As the server's limit for a rating's comment. */
|
|
1705
|
+
const MAX_COMMENT$1 = 500;
|
|
1706
|
+
const megabytes = (bytes) => `${Math.floor(bytes / 1e5) / 10} MB`;
|
|
1707
|
+
function revokePreviews(files) {
|
|
1708
|
+
for (const file of files) if (file.previewUrl) URL.revokeObjectURL(file.previewUrl);
|
|
1709
|
+
}
|
|
1710
|
+
/** The chat's state and actions for one bot, without any UI (ADR-0011). */
|
|
1711
|
+
function createChatStore(config, options = {}) {
|
|
1712
|
+
const t = translator(config.widget.texts);
|
|
1713
|
+
const client = options.client ?? new ChatClient({
|
|
1714
|
+
basePath: config.basePath,
|
|
1715
|
+
botId: config.botId,
|
|
1716
|
+
locale: config.widget.locale,
|
|
1717
|
+
storage: browserStorage(),
|
|
1718
|
+
translate: (key, params) => config.widget.texts[key] === void 0 ? void 0 : t(key, params)
|
|
1719
|
+
});
|
|
1720
|
+
const recorder = options.recorder ?? {
|
|
1721
|
+
canRecord,
|
|
1722
|
+
startRecording
|
|
1723
|
+
};
|
|
1724
|
+
const voice = config.voice;
|
|
1725
|
+
const allowed = config.attachments;
|
|
1726
|
+
const initial = {
|
|
1727
|
+
phase: "starting",
|
|
1728
|
+
busy: false,
|
|
1729
|
+
messages: [],
|
|
1730
|
+
draft: "",
|
|
1731
|
+
error: void 0,
|
|
1732
|
+
activity: null,
|
|
1733
|
+
files: [],
|
|
1734
|
+
dictation: "idle",
|
|
1735
|
+
elapsed: 0,
|
|
1736
|
+
canDictate: false,
|
|
1737
|
+
page: options.page ?? {},
|
|
1738
|
+
ratings: {},
|
|
1739
|
+
commenting: void 0
|
|
1740
|
+
};
|
|
1741
|
+
let state = initial;
|
|
1742
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1743
|
+
const set = (change) => {
|
|
1744
|
+
state = {
|
|
1745
|
+
...state,
|
|
1746
|
+
...change
|
|
1747
|
+
};
|
|
1748
|
+
for (const listener of listeners) listener();
|
|
1749
|
+
};
|
|
1750
|
+
const { focus, onFocus } = focusRequests();
|
|
1751
|
+
let localId = 0;
|
|
1752
|
+
const nextLocalId = () => `local_${++localId}`;
|
|
1753
|
+
/** The current run between start() and stop(); async work of an earlier run stops there. */
|
|
1754
|
+
let run;
|
|
1755
|
+
/** Signed in (or anonymous) for good: requests may go out. */
|
|
1756
|
+
let identityReady = false;
|
|
1757
|
+
/** The visible conversation is the one this browser should show. */
|
|
1758
|
+
let loaded = false;
|
|
1759
|
+
let identities = Promise.resolve();
|
|
1760
|
+
let history;
|
|
1761
|
+
/** The turn being answered, aborted when the chat stops. */
|
|
1762
|
+
let turn;
|
|
1763
|
+
/**
|
|
1764
|
+
* Per rating key: what the server confirmed, and the latest request. Ratings of one answer go out
|
|
1765
|
+
* one at a time, so the server ends with the latest that succeeded and a failure rolls back to it.
|
|
1766
|
+
*/
|
|
1767
|
+
const rated = /* @__PURE__ */ new Map();
|
|
1768
|
+
/** In-flight uploads by pending file key, cancelled when the file is removed. */
|
|
1769
|
+
const uploads = /* @__PURE__ */ new Map();
|
|
1770
|
+
let recording;
|
|
1771
|
+
/** Set while the browser asks for the microphone, so a double click starts one recording. */
|
|
1772
|
+
let starting = false;
|
|
1773
|
+
/** Ends the dictation at maxSeconds; a timer, because animation frames stop in hidden frames. */
|
|
1774
|
+
let limit;
|
|
1775
|
+
let clock;
|
|
1776
|
+
/** Stops a dictation and throws the audio away. */
|
|
1777
|
+
const discardRecording = () => {
|
|
1778
|
+
clearTimeout(limit);
|
|
1779
|
+
clearInterval(clock);
|
|
1780
|
+
recording?.cancel();
|
|
1781
|
+
recording = void 0;
|
|
1782
|
+
if (state.dictation !== "idle") set({ dictation: "idle" });
|
|
1783
|
+
};
|
|
1784
|
+
/** Restores the stored conversation (about 2 s upstream, so the chat shows a loading state). */
|
|
1785
|
+
const loadHistory = () => {
|
|
1786
|
+
history?.abort();
|
|
1787
|
+
if (!client.hasConversation()) {
|
|
1788
|
+
history = void 0;
|
|
1789
|
+
loaded = true;
|
|
1790
|
+
set({ phase: "ready" });
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
const controller = new AbortController();
|
|
1794
|
+
history = controller;
|
|
1795
|
+
set({ phase: "loading" });
|
|
1796
|
+
client.loadHistory(controller.signal).then((messages) => {
|
|
1797
|
+
if (controller.signal.aborted) return;
|
|
1798
|
+
loaded = true;
|
|
1799
|
+
set({ messages: messages.map(fromHistory) });
|
|
1800
|
+
}).catch((error) => {
|
|
1801
|
+
if (!controller.signal.aborted) set({ error: error instanceof SessionRefused ? error.message : t("error.history") });
|
|
1802
|
+
}).finally(() => {
|
|
1803
|
+
if (history !== controller) return;
|
|
1804
|
+
history = void 0;
|
|
1805
|
+
set({ phase: "ready" });
|
|
1806
|
+
});
|
|
1807
|
+
};
|
|
1808
|
+
const onVisibility = () => {
|
|
1809
|
+
if (document.visibilityState === "hidden") discardRecording();
|
|
1810
|
+
};
|
|
1811
|
+
const cancelUploads = (keys) => {
|
|
1812
|
+
for (const key of [...keys]) {
|
|
1813
|
+
uploads.get(key)?.abort();
|
|
1814
|
+
uploads.delete(key);
|
|
1815
|
+
}
|
|
1816
|
+
};
|
|
1817
|
+
const attach = async (file) => {
|
|
1818
|
+
if (!allowed) return;
|
|
1819
|
+
const key = nextLocalId();
|
|
1820
|
+
const update = (change) => set({ files: state.files.map((item) => item.key === key ? {
|
|
1821
|
+
...item,
|
|
1822
|
+
...change
|
|
1823
|
+
} : item) });
|
|
1824
|
+
const controller = new AbortController();
|
|
1825
|
+
uploads.set(key, controller);
|
|
1826
|
+
set({ files: [...state.files, {
|
|
1827
|
+
key,
|
|
1828
|
+
name: file.name,
|
|
1829
|
+
status: "uploading"
|
|
1830
|
+
}] });
|
|
1831
|
+
const fail = (error) => {
|
|
1832
|
+
uploads.delete(key);
|
|
1833
|
+
if (!controller.signal.aborted) update({
|
|
1834
|
+
status: "error",
|
|
1835
|
+
error
|
|
1836
|
+
});
|
|
1837
|
+
};
|
|
1838
|
+
let prepared;
|
|
1839
|
+
try {
|
|
1840
|
+
prepared = await prepareFile(file, allowed);
|
|
1841
|
+
} catch {
|
|
1842
|
+
fail(t("attachment.unsupported"));
|
|
1843
|
+
return;
|
|
1844
|
+
}
|
|
1845
|
+
if (prepared.blob.size > allowed.maxBytes) {
|
|
1846
|
+
fail(t("attachment.tooLarge", { size: megabytes(allowed.maxBytes) }));
|
|
1847
|
+
return;
|
|
1848
|
+
}
|
|
1849
|
+
if (controller.signal.aborted) return;
|
|
1850
|
+
const previewUrl = prepared.kind === "image" ? URL.createObjectURL(prepared.blob) : void 0;
|
|
1851
|
+
update({
|
|
1852
|
+
name: prepared.name,
|
|
1853
|
+
kind: prepared.kind,
|
|
1854
|
+
previewUrl
|
|
1855
|
+
});
|
|
1856
|
+
const result = await client.upload(prepared.blob, prepared.name, controller.signal);
|
|
1857
|
+
uploads.delete(key);
|
|
1858
|
+
if (controller.signal.aborted) {
|
|
1859
|
+
revokePreviews([{ previewUrl }]);
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
update(result.ok ? {
|
|
1863
|
+
status: "ready",
|
|
1864
|
+
handle: result.file.id,
|
|
1865
|
+
name: result.file.name
|
|
1866
|
+
} : {
|
|
1867
|
+
status: "error",
|
|
1868
|
+
error: result.message
|
|
1869
|
+
});
|
|
1870
|
+
};
|
|
1871
|
+
const actions = {
|
|
1872
|
+
async send(picked) {
|
|
1873
|
+
const text = (picked ?? state.draft).trim();
|
|
1874
|
+
const uploading = state.files.some((file) => file.status === "uploading");
|
|
1875
|
+
if (picked === void 0 ? !canSend(state) : state.phase !== "ready" || state.busy || uploading || text === "") return;
|
|
1876
|
+
const ready = state.files.filter((file) => file.status === "ready");
|
|
1877
|
+
const files = ready.flatMap(({ name, kind, previewUrl }) => kind ? [{
|
|
1878
|
+
name,
|
|
1879
|
+
kind,
|
|
1880
|
+
previewUrl
|
|
1881
|
+
}] : []);
|
|
1882
|
+
const handles = ready.flatMap((file) => file.handle ? [file.handle] : []);
|
|
1883
|
+
revokePreviews(state.files.filter((file) => file.status !== "ready"));
|
|
1884
|
+
set({
|
|
1885
|
+
files: [],
|
|
1886
|
+
...picked === void 0 ? { draft: "" } : {},
|
|
1887
|
+
error: void 0,
|
|
1888
|
+
busy: true,
|
|
1889
|
+
messages: [...state.messages, {
|
|
1890
|
+
id: nextLocalId(),
|
|
1891
|
+
role: "user",
|
|
1892
|
+
text,
|
|
1893
|
+
citations: [],
|
|
1894
|
+
attachments: files.length,
|
|
1895
|
+
files,
|
|
1896
|
+
status: "done"
|
|
1897
|
+
}]
|
|
1898
|
+
});
|
|
1899
|
+
const context = config.pageContext ? state.page.context : void 0;
|
|
1900
|
+
const controller = new AbortController();
|
|
1901
|
+
turn = controller;
|
|
1902
|
+
await client.send({
|
|
1903
|
+
text,
|
|
1904
|
+
attachments: handles,
|
|
1905
|
+
context
|
|
1906
|
+
}, (event) => {
|
|
1907
|
+
const next = activityFor(event, t);
|
|
1908
|
+
if (next !== void 0) set({ activity: next });
|
|
1909
|
+
if (event.type === "error") {
|
|
1910
|
+
set({
|
|
1911
|
+
error: event.message,
|
|
1912
|
+
messages: failStreaming(state.messages)
|
|
1913
|
+
});
|
|
1914
|
+
return;
|
|
1915
|
+
}
|
|
1916
|
+
set({ messages: applyEvent(state.messages, event) });
|
|
1917
|
+
}, controller.signal);
|
|
1918
|
+
if (turn === controller) turn = void 0;
|
|
1919
|
+
if (controller.signal.aborted) {
|
|
1920
|
+
set({
|
|
1921
|
+
activity: null,
|
|
1922
|
+
busy: false,
|
|
1923
|
+
messages: failStreaming(state.messages)
|
|
1924
|
+
});
|
|
1925
|
+
return;
|
|
1926
|
+
}
|
|
1927
|
+
set({
|
|
1928
|
+
activity: null,
|
|
1929
|
+
busy: false
|
|
1930
|
+
});
|
|
1931
|
+
focus("input");
|
|
1932
|
+
},
|
|
1933
|
+
setDraft(text) {
|
|
1934
|
+
set({ draft: text });
|
|
1935
|
+
},
|
|
1936
|
+
addFiles(files) {
|
|
1937
|
+
if (!allowed || files.length === 0) return;
|
|
1938
|
+
const room = allowed.maxPerMessage - state.files.length;
|
|
1939
|
+
if (files.length > room) set({ error: t("attachment.tooMany", { count: allowed.maxPerMessage }) });
|
|
1940
|
+
for (const file of files.slice(0, Math.max(0, room))) attach(file);
|
|
1941
|
+
},
|
|
1942
|
+
removeFile(key) {
|
|
1943
|
+
cancelUploads([key]);
|
|
1944
|
+
revokePreviews(state.files.filter((item) => item.key === key));
|
|
1945
|
+
set({ files: state.files.filter((item) => item.key !== key) });
|
|
1946
|
+
},
|
|
1947
|
+
async startDictation() {
|
|
1948
|
+
if (!voice || recording || starting || state.dictation !== "idle") return;
|
|
1949
|
+
set({ error: void 0 });
|
|
1950
|
+
starting = true;
|
|
1951
|
+
let started;
|
|
1952
|
+
try {
|
|
1953
|
+
started = await recorder.startRecording(voice.maxSeconds);
|
|
1954
|
+
} catch (error) {
|
|
1955
|
+
set({ error: t(MICROPHONE_MESSAGES[error instanceof MicrophoneError ? error.reason : "failed"]) });
|
|
1956
|
+
return;
|
|
1957
|
+
} finally {
|
|
1958
|
+
starting = false;
|
|
1959
|
+
}
|
|
1960
|
+
if (!run) {
|
|
1961
|
+
started.cancel();
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
recording = started;
|
|
1965
|
+
set({
|
|
1966
|
+
elapsed: 0,
|
|
1967
|
+
dictation: "recording"
|
|
1968
|
+
});
|
|
1969
|
+
focus("dictation");
|
|
1970
|
+
limit = setTimeout(() => void actions.finishDictation(), voice.maxSeconds * 1e3);
|
|
1971
|
+
const begun = Date.now();
|
|
1972
|
+
clock = setInterval(() => {
|
|
1973
|
+
const elapsed = Math.min(voice.maxSeconds, Math.floor((Date.now() - begun) / 1e3));
|
|
1974
|
+
if (elapsed !== state.elapsed) set({ elapsed });
|
|
1975
|
+
}, 250);
|
|
1976
|
+
},
|
|
1977
|
+
async finishDictation() {
|
|
1978
|
+
const current = recording;
|
|
1979
|
+
if (!current) return;
|
|
1980
|
+
recording = void 0;
|
|
1981
|
+
clearTimeout(limit);
|
|
1982
|
+
clearInterval(clock);
|
|
1983
|
+
set({ dictation: "transcribing" });
|
|
1984
|
+
const audio = await current.stop();
|
|
1985
|
+
if (audio.size < 1e3) {
|
|
1986
|
+
set({
|
|
1987
|
+
dictation: "idle",
|
|
1988
|
+
error: t("dictation.empty")
|
|
1989
|
+
});
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1992
|
+
const languages = [...navigator.languages.slice(0, 2), config.widget.locale];
|
|
1993
|
+
const result = await client.transcribe(audio, languages);
|
|
1994
|
+
set({ dictation: "idle" });
|
|
1995
|
+
if (!result.ok) set({ error: result.message });
|
|
1996
|
+
else if (result.text) {
|
|
1997
|
+
const draft = state.draft;
|
|
1998
|
+
set({ draft: draft.trim() ? `${draft.trimEnd()} ${result.text}` : result.text });
|
|
1999
|
+
}
|
|
2000
|
+
focus("input");
|
|
2001
|
+
},
|
|
2002
|
+
cancelDictation() {
|
|
2003
|
+
discardRecording();
|
|
2004
|
+
focus("input");
|
|
2005
|
+
},
|
|
2006
|
+
async newConversation() {
|
|
2007
|
+
set({ busy: true });
|
|
2008
|
+
await client.deleteConversation().catch(() => void 0);
|
|
2009
|
+
revokePreviews(state.messages.flatMap((message) => message.files ?? []));
|
|
2010
|
+
cancelUploads(uploads.keys());
|
|
2011
|
+
revokePreviews(state.files);
|
|
2012
|
+
set({
|
|
2013
|
+
files: [],
|
|
2014
|
+
messages: [],
|
|
2015
|
+
error: void 0,
|
|
2016
|
+
busy: false,
|
|
2017
|
+
commenting: void 0
|
|
2018
|
+
});
|
|
2019
|
+
focus("input");
|
|
2020
|
+
},
|
|
2021
|
+
async rate(messageId, rating, comment) {
|
|
2022
|
+
const feedback = state.messages.find((message) => message.id === messageId)?.feedback;
|
|
2023
|
+
if (!feedback) return;
|
|
2024
|
+
const { key } = feedback;
|
|
2025
|
+
const before = state.ratings[key];
|
|
2026
|
+
const text = comment?.trim().slice(0, MAX_COMMENT$1);
|
|
2027
|
+
const commented = rating === "down" && Boolean(text);
|
|
2028
|
+
const ratings = (value) => {
|
|
2029
|
+
const { [key]: _previous, ...others } = state.ratings;
|
|
2030
|
+
return value ? {
|
|
2031
|
+
...others,
|
|
2032
|
+
[key]: value
|
|
2033
|
+
} : others;
|
|
2034
|
+
};
|
|
2035
|
+
const entry = rated.get(key) ?? {
|
|
2036
|
+
confirmed: before,
|
|
2037
|
+
latest: 0,
|
|
2038
|
+
queue: Promise.resolve()
|
|
2039
|
+
};
|
|
2040
|
+
rated.set(key, entry);
|
|
2041
|
+
const request = ++entry.latest;
|
|
2042
|
+
set({
|
|
2043
|
+
ratings: ratings(rating),
|
|
2044
|
+
error: void 0,
|
|
2045
|
+
commenting: commented || rating === "down" && before !== "down" ? messageId : void 0
|
|
2046
|
+
});
|
|
2047
|
+
const sent = entry.queue.then(() => client.rate(feedback.handle, rating, rating === null ? void 0 : text));
|
|
2048
|
+
entry.queue = sent;
|
|
2049
|
+
const problem = await sent;
|
|
2050
|
+
if (!problem) {
|
|
2051
|
+
entry.confirmed = rating ?? void 0;
|
|
2052
|
+
client.rememberRating(key, rating);
|
|
2053
|
+
}
|
|
2054
|
+
if (entry.latest !== request) return;
|
|
2055
|
+
if (problem) set({
|
|
2056
|
+
ratings: ratings(entry.confirmed),
|
|
2057
|
+
error: problem,
|
|
2058
|
+
...commented ? {} : { commenting: void 0 }
|
|
2059
|
+
});
|
|
2060
|
+
else if (commented && state.commenting === messageId) set({ commenting: void 0 });
|
|
2061
|
+
},
|
|
2062
|
+
dismissComment() {
|
|
2063
|
+
if (state.commenting !== void 0) set({ commenting: void 0 });
|
|
2064
|
+
},
|
|
2065
|
+
focus() {
|
|
2066
|
+
focus("input", true);
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
2069
|
+
return {
|
|
2070
|
+
config,
|
|
2071
|
+
actions,
|
|
2072
|
+
t,
|
|
2073
|
+
subscribe(listener) {
|
|
2074
|
+
listeners.add(listener);
|
|
2075
|
+
return () => listeners.delete(listener);
|
|
2076
|
+
},
|
|
2077
|
+
getSnapshot: () => state,
|
|
2078
|
+
getServerSnapshot: () => initial,
|
|
2079
|
+
start(startOptions = {}) {
|
|
2080
|
+
if (run) return;
|
|
2081
|
+
const current = {};
|
|
2082
|
+
run = current;
|
|
2083
|
+
set({
|
|
2084
|
+
ratings: client.ratings(),
|
|
2085
|
+
canDictate: voice !== void 0 && recorder.canRecord(),
|
|
2086
|
+
...state.phase === "starting" && client.hasConversation() ? { phase: "loading" } : {}
|
|
2087
|
+
});
|
|
2088
|
+
document.addEventListener("visibilitychange", onVisibility);
|
|
2089
|
+
(startOptions.handshake ?? Promise.resolve()).then(() => identities, () => identities).finally(() => {
|
|
2090
|
+
if (run !== current) return;
|
|
2091
|
+
identityReady = true;
|
|
2092
|
+
if (!loaded) loadHistory();
|
|
2093
|
+
else if (state.phase !== "ready") set({ phase: "ready" });
|
|
2094
|
+
});
|
|
2095
|
+
},
|
|
2096
|
+
stop() {
|
|
2097
|
+
if (!run) return;
|
|
2098
|
+
run = void 0;
|
|
2099
|
+
document.removeEventListener("visibilitychange", onVisibility);
|
|
2100
|
+
history?.abort();
|
|
2101
|
+
history = void 0;
|
|
2102
|
+
turn?.abort();
|
|
2103
|
+
turn = void 0;
|
|
2104
|
+
discardRecording();
|
|
2105
|
+
if (uploads.size > 0) {
|
|
2106
|
+
cancelUploads(uploads.keys());
|
|
2107
|
+
set({ files: state.files.filter((file) => file.status !== "uploading") });
|
|
2108
|
+
}
|
|
2109
|
+
},
|
|
2110
|
+
identify(token) {
|
|
2111
|
+
identities = identities.then(async () => {
|
|
2112
|
+
if (!await client.identify(token)) return;
|
|
2113
|
+
loaded = false;
|
|
2114
|
+
set({
|
|
2115
|
+
messages: [],
|
|
2116
|
+
error: void 0,
|
|
2117
|
+
commenting: void 0
|
|
2118
|
+
});
|
|
2119
|
+
if (identityReady && run) loadHistory();
|
|
2120
|
+
});
|
|
2121
|
+
},
|
|
2122
|
+
configure(page) {
|
|
2123
|
+
set({ page });
|
|
2124
|
+
},
|
|
2125
|
+
hide() {
|
|
2126
|
+
discardRecording();
|
|
2127
|
+
},
|
|
2128
|
+
level: () => recording?.level(),
|
|
2129
|
+
onFocus
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
// src/react/root.tsx
|
|
2133
|
+
/**
|
|
2134
|
+
* Runs one bot's chat for the components inside it, without rendering any element. Its props
|
|
2135
|
+
* take what `askdare('identify')` and `askdare('configure')` take, checked the same way.
|
|
2136
|
+
*/
|
|
2137
|
+
function Root({ config, identity, context, greeting, starters, children }) {
|
|
2138
|
+
if (!isBasePath(config.basePath)) throw new TypeError(`[askdare] The chat's basePath must be a path on this app, like /api/chat; got "${config.basePath}".`);
|
|
2139
|
+
for (const href of Object.values(config.styles ?? {})) if (!href.startsWith(`${config.basePath}/`) || href.includes("//") || href.includes("\\")) throw new TypeError(`[askdare] The chat's stylesheets must come from ${config.basePath}.`);
|
|
2140
|
+
const page = pageOptions({
|
|
2141
|
+
greeting,
|
|
2142
|
+
starters,
|
|
2143
|
+
context
|
|
2144
|
+
});
|
|
2145
|
+
const id = `${config.basePath} ${config.botId} ${config.widget.locale}`;
|
|
2146
|
+
const [held, setHeld] = useState(() => ({
|
|
2147
|
+
id,
|
|
2148
|
+
store: createChatStore(config, { page })
|
|
2149
|
+
}));
|
|
2150
|
+
let { store } = held;
|
|
2151
|
+
if (held.id !== id) {
|
|
2152
|
+
store = createChatStore(config, { page });
|
|
2153
|
+
setHeld({
|
|
2154
|
+
id,
|
|
2155
|
+
store
|
|
2156
|
+
});
|
|
2157
|
+
}
|
|
2158
|
+
useEffect(() => {
|
|
2159
|
+
if (identity === void 0) return;
|
|
2160
|
+
const token = identityToken(identity);
|
|
2161
|
+
if (token !== void 0) store.identify(token);
|
|
2162
|
+
}, [identity, store]);
|
|
2163
|
+
useEffect(() => {
|
|
2164
|
+
store.start();
|
|
2165
|
+
return () => store.stop();
|
|
2166
|
+
}, [store]);
|
|
2167
|
+
const key = JSON.stringify(page);
|
|
2168
|
+
useEffect(() => {
|
|
2169
|
+
if (JSON.stringify(store.getSnapshot().page) !== key) store.configure(page);
|
|
2170
|
+
}, [key, store]);
|
|
2171
|
+
return /* @__PURE__ */ jsx(ChatProvider, {
|
|
2172
|
+
store,
|
|
2173
|
+
children
|
|
2174
|
+
});
|
|
2175
|
+
}
|
|
2176
|
+
// src/react/theme.tsx
|
|
2177
|
+
/** React 19 hoists these into <head> and waits for them, in this order, before showing the chat. */
|
|
2178
|
+
const PRECEDENCE = "askdare";
|
|
2179
|
+
/**
|
|
2180
|
+
* The theme root of a chat inside a page: sets the bot's tokens (`--ask-*`) and variant attributes
|
|
2181
|
+
* for everything inside it, and loads the bot's theme and fonts from the chat route. Size it with
|
|
2182
|
+
* `className` or `style`; the chat fills it.
|
|
2183
|
+
*/
|
|
2184
|
+
function Theme({ colorScheme, children, ...props }) {
|
|
2185
|
+
const { botId, widget, styles } = useStore().config;
|
|
2186
|
+
const variants = Object.fromEntries(Object.entries(widget.variants).map(([name, value]) => [`data-ask-${name}`, value]));
|
|
2187
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
2188
|
+
"data-askdare-root": "",
|
|
2189
|
+
"data-ask-bot": botId,
|
|
2190
|
+
"data-ask-preset": widget.preset,
|
|
2191
|
+
"data-ask-scheme": colorScheme ?? widget.colorScheme,
|
|
2192
|
+
...variants,
|
|
2193
|
+
...props,
|
|
2194
|
+
children: [styles && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("link", {
|
|
2195
|
+
rel: "stylesheet",
|
|
2196
|
+
href: styles.fonts,
|
|
2197
|
+
precedence: PRECEDENCE
|
|
2198
|
+
}), /* @__PURE__ */ jsx("link", {
|
|
2199
|
+
rel: "stylesheet",
|
|
2200
|
+
href: styles.theme,
|
|
2201
|
+
precedence: PRECEDENCE
|
|
2202
|
+
})] }), children]
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
// src/react/skin/icons.tsx
|
|
2206
|
+
/** Line icons on a 24px grid, drawn with the current text color. */
|
|
2207
|
+
function Icon({ children, size = 20 }) {
|
|
2208
|
+
return /* @__PURE__ */ jsx("svg", {
|
|
2209
|
+
viewBox: "0 0 24 24",
|
|
2210
|
+
width: size,
|
|
2211
|
+
height: size,
|
|
2212
|
+
"aria-hidden": "true",
|
|
2213
|
+
fill: "none",
|
|
2214
|
+
stroke: "currentColor",
|
|
2215
|
+
strokeWidth: "1.8",
|
|
2216
|
+
strokeLinecap: "round",
|
|
2217
|
+
strokeLinejoin: "round",
|
|
2218
|
+
children
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
2221
|
+
const SendIcon = () => /* @__PURE__ */ jsx(Icon, { children: /* @__PURE__ */ jsx("path", { d: "M12 19V5M5.5 11.5 12 5l6.5 6.5" }) });
|
|
2222
|
+
const AttachIcon = () => /* @__PURE__ */ jsx(Icon, { children: /* @__PURE__ */ jsx("path", { d: "M20 11.5 12.2 19.3a5 5 0 0 1-7.1-7.1l8.1-8.1a3.4 3.4 0 0 1 4.8 4.8l-8 8a1.8 1.8 0 0 1-2.6-2.6l7.3-7.3" }) });
|
|
2223
|
+
const MicIcon = () => /* @__PURE__ */ jsxs(Icon, { children: [/* @__PURE__ */ jsx("rect", {
|
|
2224
|
+
x: "9",
|
|
2225
|
+
y: "3",
|
|
2226
|
+
width: "6",
|
|
2227
|
+
height: "11",
|
|
2228
|
+
rx: "3"
|
|
2229
|
+
}), /* @__PURE__ */ jsx("path", { d: "M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21" })] });
|
|
2230
|
+
const CloseIcon = ({ size = 18 }) => /* @__PURE__ */ jsx(Icon, {
|
|
2231
|
+
size,
|
|
2232
|
+
children: /* @__PURE__ */ jsx("path", { d: "M6 6l12 12M18 6 6 18" })
|
|
2233
|
+
});
|
|
2234
|
+
const RestartIcon = () => /* @__PURE__ */ jsx(Icon, {
|
|
2235
|
+
size: 18,
|
|
2236
|
+
children: /* @__PURE__ */ jsx("path", { d: "M4 12a8 8 0 1 0 2.4-5.7M4 4v4.5h4.5" })
|
|
2237
|
+
});
|
|
2238
|
+
const CheckIcon = () => /* @__PURE__ */ jsx(Icon, {
|
|
2239
|
+
size: 18,
|
|
2240
|
+
children: /* @__PURE__ */ jsx("path", { d: "M5 12.5l4.5 4.5L19 7.5" })
|
|
2241
|
+
});
|
|
2242
|
+
const SparkIcon = ({ size = 16 }) => /* @__PURE__ */ jsxs(Icon, {
|
|
2243
|
+
size,
|
|
2244
|
+
children: [/* @__PURE__ */ jsx("path", { d: "M12 3.5c.5 4.3 2.2 6 6.5 6.5-4.3.5-6 2.2-6.5 6.5-.5-4.3-2.2-6-6.5-6.5 4.3-.5 6-2.2 6.5-6.5Z" }), /* @__PURE__ */ jsx("path", { d: "M18.5 15.5c.2 1.6.9 2.3 2.5 2.5-1.6.2-2.3.9-2.5 2.5-.2-1.6-.9-2.3-2.5-2.5 1.6-.2 2.3-.9 2.5-2.5Z" })]
|
|
2245
|
+
});
|
|
2246
|
+
const ArrowIcon = () => /* @__PURE__ */ jsx(Icon, {
|
|
2247
|
+
size: 16,
|
|
2248
|
+
children: /* @__PURE__ */ jsx("path", { d: "M5 12h14M13 6l6 6-6 6" })
|
|
2249
|
+
});
|
|
2250
|
+
const ThumbUpIcon = () => /* @__PURE__ */ jsx(Icon, {
|
|
2251
|
+
size: 16,
|
|
2252
|
+
children: /* @__PURE__ */ jsx("path", { d: "M7 10.5v9.5M7 10.5l4.2-7a2.2 2.2 0 0 1 2.6 2.7L13 9.5h5.2a2 2 0 0 1 2 2.4l-1.2 6.5a2 2 0 0 1-2 1.6H4.5V10.5H7Z" })
|
|
2253
|
+
});
|
|
2254
|
+
const ThumbDownIcon = () => /* @__PURE__ */ jsx(Icon, {
|
|
2255
|
+
size: 16,
|
|
2256
|
+
children: /* @__PURE__ */ jsx("path", { d: "M17 13.5V4M17 13.5l-4.2 7a2.2 2.2 0 0 1-2.6-2.7l.8-3.3H5.8a2 2 0 0 1-2-2.4L5 5.6A2 2 0 0 1 7 4h12.5v9.5H17Z" })
|
|
2257
|
+
});
|
|
2258
|
+
// src/react/skin/confirm.tsx
|
|
2259
|
+
/** Keeps Tab inside the question while it is open. */
|
|
2260
|
+
function trapTab(event) {
|
|
2261
|
+
if (event.key !== "Tab") return;
|
|
2262
|
+
const buttons = Array.from(event.currentTarget.querySelectorAll("button"));
|
|
2263
|
+
const first = buttons[0];
|
|
2264
|
+
const last = buttons[buttons.length - 1];
|
|
2265
|
+
if (event.shiftKey && document.activeElement === first) {
|
|
2266
|
+
event.preventDefault();
|
|
2267
|
+
last?.focus();
|
|
2268
|
+
} else if (!event.shiftKey && document.activeElement === last) {
|
|
2269
|
+
event.preventDefault();
|
|
2270
|
+
first?.focus();
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
/**
|
|
2274
|
+
* Asks before a new conversation deletes the current one: in the chat, not a browser dialog,
|
|
2275
|
+
* over the conversation, which stays in view.
|
|
2276
|
+
*/
|
|
2277
|
+
function StartOverQuestion({ modal, onCancel, onAccept }) {
|
|
2278
|
+
const { t } = useChat();
|
|
2279
|
+
const dialog = useRef(null);
|
|
2280
|
+
const textId = useId();
|
|
2281
|
+
useEffect(() => {
|
|
2282
|
+
const frame = requestAnimationFrame(() => dialog.current?.querySelector("button")?.focus());
|
|
2283
|
+
return () => cancelAnimationFrame(frame);
|
|
2284
|
+
}, []);
|
|
2285
|
+
return /* @__PURE__ */ jsx("div", {
|
|
2286
|
+
"data-ask-part": "confirm-backdrop",
|
|
2287
|
+
children: /* @__PURE__ */ jsxs("div", {
|
|
2288
|
+
ref: dialog,
|
|
2289
|
+
"data-ask-part": "confirm",
|
|
2290
|
+
role: "alertdialog",
|
|
2291
|
+
"aria-modal": modal || void 0,
|
|
2292
|
+
"aria-describedby": textId,
|
|
2293
|
+
"aria-label": t("header.newConversation"),
|
|
2294
|
+
onKeyDown: trapTab,
|
|
2295
|
+
children: [
|
|
2296
|
+
/* @__PURE__ */ jsx("span", {
|
|
2297
|
+
"data-ask-part": "confirm-icon",
|
|
2298
|
+
"aria-hidden": "true",
|
|
2299
|
+
children: /* @__PURE__ */ jsx(RestartIcon, {})
|
|
2300
|
+
}),
|
|
2301
|
+
/* @__PURE__ */ jsx("p", {
|
|
2302
|
+
id: textId,
|
|
2303
|
+
"data-ask-part": "confirm-text",
|
|
2304
|
+
children: t("confirm.newConversation")
|
|
2305
|
+
}),
|
|
2306
|
+
/* @__PURE__ */ jsxs("div", {
|
|
2307
|
+
"data-ask-part": "confirm-actions",
|
|
2308
|
+
children: [/* @__PURE__ */ jsx("button", {
|
|
2309
|
+
type: "button",
|
|
2310
|
+
"data-ask-part": "confirm-cancel",
|
|
2311
|
+
onClick: onCancel,
|
|
2312
|
+
children: t("confirm.cancel")
|
|
2313
|
+
}), /* @__PURE__ */ jsx("button", {
|
|
2314
|
+
type: "button",
|
|
2315
|
+
"data-ask-part": "confirm-accept",
|
|
2316
|
+
onClick: onAccept,
|
|
2317
|
+
children: t("confirm.accept")
|
|
2318
|
+
})]
|
|
2319
|
+
})
|
|
2320
|
+
]
|
|
2321
|
+
})
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
// src/react/skin/context.ts
|
|
2325
|
+
const SkinContext = /* @__PURE__ */ createContext(null);
|
|
2326
|
+
function useSkin() {
|
|
2327
|
+
const skin = useContext(SkinContext);
|
|
2328
|
+
if (!skin) throw new Error("[askdare] The default look only works inside <DefaultChat>.");
|
|
2329
|
+
return skin;
|
|
2330
|
+
}
|
|
2331
|
+
/** An h1–h6 tag name for a level, capped at 6. */
|
|
2332
|
+
const heading = (level) => `h${Math.min(Math.max(level, 1), 6)}`;
|
|
2333
|
+
// src/react/skin/footer.tsx
|
|
2334
|
+
/** The message field with its buttons, or the dictation in its place, then the AI notice. */
|
|
2335
|
+
function DefaultFooter() {
|
|
2336
|
+
const { state, bot, t } = useChat();
|
|
2337
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Composer, { children: [/* @__PURE__ */ jsx(Files, {}), /* @__PURE__ */ jsx("div", {
|
|
2338
|
+
"data-ask-part": "composer-box",
|
|
2339
|
+
children: state.dictation === "idle" ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
2340
|
+
/* @__PURE__ */ jsx(AttachButton, { children: /* @__PURE__ */ jsx(AttachIcon, {}) }),
|
|
2341
|
+
/* @__PURE__ */ jsx(Input, {}),
|
|
2342
|
+
/* @__PURE__ */ jsx(DictateButton, { children: /* @__PURE__ */ jsx(MicIcon, {}) }),
|
|
2343
|
+
/* @__PURE__ */ jsxs(Send, { children: [/* @__PURE__ */ jsx(SendIcon, {}), /* @__PURE__ */ jsx("span", {
|
|
2344
|
+
"data-ask-part": "send-label",
|
|
2345
|
+
"aria-hidden": "true",
|
|
2346
|
+
children: t("composer.send")
|
|
2347
|
+
})] })
|
|
2348
|
+
] }) : /* @__PURE__ */ jsx(Recorder, { cancelIcon: /* @__PURE__ */ jsx(CloseIcon, {}) })
|
|
2349
|
+
})] }), bot.disclosure !== false && /* @__PURE__ */ jsxs("p", {
|
|
2350
|
+
"data-ask-part": "disclosure",
|
|
2351
|
+
children: [t("disclosure.text"), bot.disclosure.privacyUrl && /* @__PURE__ */ jsxs(Fragment, { children: [" ", /* @__PURE__ */ jsx("a", {
|
|
2352
|
+
href: bot.disclosure.privacyUrl,
|
|
2353
|
+
target: "_blank",
|
|
2354
|
+
rel: "noopener noreferrer",
|
|
2355
|
+
children: t("disclosure.privacy")
|
|
2356
|
+
})] })]
|
|
2357
|
+
})] });
|
|
2358
|
+
}
|
|
2359
|
+
// src/react/skin/avatar.tsx
|
|
2360
|
+
const initials = (title) => title.split(/\s+/).filter(Boolean).slice(0, 2).map((word) => word[0]?.toUpperCase() ?? "").join("") || "AI";
|
|
2361
|
+
/** The assistant's face: the configured picture, else the preset's orb, icon or initials. */
|
|
2362
|
+
function Avatar({ size }) {
|
|
2363
|
+
const { bot } = useSkin();
|
|
2364
|
+
const variant = bot.avatar ? "image" : bot.variants.avatar;
|
|
2365
|
+
if (variant === "none") return null;
|
|
2366
|
+
return /* @__PURE__ */ jsxs("span", {
|
|
2367
|
+
"data-ask-part": "avatar",
|
|
2368
|
+
"data-kind": variant,
|
|
2369
|
+
"data-size": size,
|
|
2370
|
+
"aria-hidden": "true",
|
|
2371
|
+
children: [
|
|
2372
|
+
variant === "image" && /* @__PURE__ */ jsx("img", {
|
|
2373
|
+
src: bot.avatar,
|
|
2374
|
+
alt: ""
|
|
2375
|
+
}),
|
|
2376
|
+
variant === "orb" && /* @__PURE__ */ jsx("span", { "data-ask-part": "orb" }),
|
|
2377
|
+
variant === "icon" && /* @__PURE__ */ jsx(SparkIcon, { size: size === "large" ? 28 : 16 }),
|
|
2378
|
+
variant === "initials" && initials(bot.title)
|
|
2379
|
+
]
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
// src/react/skin/header.tsx
|
|
2383
|
+
/** The bot's name and picture, a new-conversation button and, when it can close, a close button. */
|
|
2384
|
+
function DefaultHeader() {
|
|
2385
|
+
const { state, bot, t } = useChat();
|
|
2386
|
+
const { headingLevel, onClose, askStartOver, restartRef } = useSkin();
|
|
2387
|
+
const Title = heading(headingLevel);
|
|
2388
|
+
return /* @__PURE__ */ jsxs("header", {
|
|
2389
|
+
"data-ask-part": "header",
|
|
2390
|
+
children: [/* @__PURE__ */ jsxs("div", {
|
|
2391
|
+
"data-ask-part": "identity",
|
|
2392
|
+
children: [/* @__PURE__ */ jsx(Avatar, { size: "small" }), /* @__PURE__ */ jsxs("div", {
|
|
2393
|
+
"data-ask-part": "identity-text",
|
|
2394
|
+
children: [/* @__PURE__ */ jsx(Title, {
|
|
2395
|
+
"data-ask-part": "title",
|
|
2396
|
+
children: bot.title
|
|
2397
|
+
}), bot.subtitle && /* @__PURE__ */ jsx("p", {
|
|
2398
|
+
"data-ask-part": "subtitle",
|
|
2399
|
+
children: bot.subtitle
|
|
2400
|
+
})]
|
|
2401
|
+
})]
|
|
2402
|
+
}), /* @__PURE__ */ jsxs("div", {
|
|
2403
|
+
"data-ask-part": "actions",
|
|
2404
|
+
children: [state.messages.length > 0 && /* @__PURE__ */ jsx("button", {
|
|
2405
|
+
ref: restartRef,
|
|
2406
|
+
type: "button",
|
|
2407
|
+
"data-ask-part": "new-conversation",
|
|
2408
|
+
"aria-label": t("header.newConversation"),
|
|
2409
|
+
"aria-haspopup": "dialog",
|
|
2410
|
+
title: t("header.newConversation"),
|
|
2411
|
+
disabled: state.busy,
|
|
2412
|
+
onClick: askStartOver,
|
|
2413
|
+
children: /* @__PURE__ */ jsx(RestartIcon, {})
|
|
2414
|
+
}), onClose && /* @__PURE__ */ jsx("button", {
|
|
2415
|
+
type: "button",
|
|
2416
|
+
"data-ask-part": "close",
|
|
2417
|
+
"aria-label": t("header.close"),
|
|
2418
|
+
title: t("header.close"),
|
|
2419
|
+
onClick: onClose,
|
|
2420
|
+
children: /* @__PURE__ */ jsx(CloseIcon, {})
|
|
2421
|
+
})]
|
|
2422
|
+
})]
|
|
2423
|
+
});
|
|
2424
|
+
}
|
|
2425
|
+
// src/react/skin/feedback.tsx
|
|
2426
|
+
/** As the server's limit. */
|
|
2427
|
+
const MAX_COMMENT = 500;
|
|
2428
|
+
/** Asks what went wrong after a 👎; sending is optional. */
|
|
2429
|
+
function Comment() {
|
|
2430
|
+
const message = useMessage();
|
|
2431
|
+
const { actions, t } = useChat();
|
|
2432
|
+
const [text, setText] = useState("");
|
|
2433
|
+
const [sending, setSending] = useState(false);
|
|
2434
|
+
const field = useRef(null);
|
|
2435
|
+
const fieldId = useId();
|
|
2436
|
+
useEffect(() => field.current?.focus(), []);
|
|
2437
|
+
const onSubmit = (event) => {
|
|
2438
|
+
event.preventDefault();
|
|
2439
|
+
if (!text.trim()) {
|
|
2440
|
+
actions.dismissComment();
|
|
2441
|
+
return;
|
|
2442
|
+
}
|
|
2443
|
+
setSending(true);
|
|
2444
|
+
actions.rate(message.id, "down", text).finally(() => setSending(false));
|
|
2445
|
+
};
|
|
2446
|
+
return /* @__PURE__ */ jsxs("form", {
|
|
2447
|
+
"data-ask-part": "feedback-comment",
|
|
2448
|
+
onSubmit,
|
|
2449
|
+
children: [
|
|
2450
|
+
/* @__PURE__ */ jsx("label", {
|
|
2451
|
+
htmlFor: fieldId,
|
|
2452
|
+
children: t("feedback.comment")
|
|
2453
|
+
}),
|
|
2454
|
+
/* @__PURE__ */ jsx("textarea", {
|
|
2455
|
+
ref: field,
|
|
2456
|
+
id: fieldId,
|
|
2457
|
+
"data-ask-part": "feedback-comment-input",
|
|
2458
|
+
rows: 2,
|
|
2459
|
+
maxLength: MAX_COMMENT,
|
|
2460
|
+
value: text,
|
|
2461
|
+
onChange: (event) => setText(event.target.value)
|
|
2462
|
+
}),
|
|
2463
|
+
/* @__PURE__ */ jsxs("div", {
|
|
2464
|
+
"data-ask-part": "feedback-comment-actions",
|
|
2465
|
+
children: [/* @__PURE__ */ jsx("button", {
|
|
2466
|
+
type: "button",
|
|
2467
|
+
"data-ask-part": "feedback-skip",
|
|
2468
|
+
onClick: actions.dismissComment,
|
|
2469
|
+
children: t("feedback.skip")
|
|
2470
|
+
}), /* @__PURE__ */ jsx("button", {
|
|
2471
|
+
type: "submit",
|
|
2472
|
+
"data-ask-part": "feedback-send",
|
|
2473
|
+
disabled: sending || text.trim() === "",
|
|
2474
|
+
children: t("feedback.send")
|
|
2475
|
+
})]
|
|
2476
|
+
})
|
|
2477
|
+
]
|
|
2478
|
+
});
|
|
2479
|
+
}
|
|
2480
|
+
/** 👍 and 👎 under an answer that can be rated, and the question after a 👎. */
|
|
2481
|
+
function Feedback() {
|
|
2482
|
+
const message = useMessage();
|
|
2483
|
+
const { t } = useSkin();
|
|
2484
|
+
const commenting = useChatState((state) => state.commenting === message.id);
|
|
2485
|
+
if (!message.feedback || message.role !== "assistant" || message.status !== "done") return null;
|
|
2486
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("div", {
|
|
2487
|
+
"data-ask-part": "feedback",
|
|
2488
|
+
role: "group",
|
|
2489
|
+
"aria-label": t("feedback.label"),
|
|
2490
|
+
children: [/* @__PURE__ */ jsx(FeedbackButton, {
|
|
2491
|
+
rating: "up",
|
|
2492
|
+
children: /* @__PURE__ */ jsx(ThumbUpIcon, {})
|
|
2493
|
+
}), /* @__PURE__ */ jsx(FeedbackButton, {
|
|
2494
|
+
rating: "down",
|
|
2495
|
+
children: /* @__PURE__ */ jsx(ThumbDownIcon, {})
|
|
2496
|
+
})]
|
|
2497
|
+
}), commenting && /* @__PURE__ */ jsx(Comment, {})] });
|
|
2498
|
+
}
|
|
2499
|
+
// src/react/skin/message.tsx
|
|
2500
|
+
/** One message: the assistant's face beside its answers, then text, files, sources and rating. */
|
|
2501
|
+
function DefaultMessage() {
|
|
2502
|
+
const message = useMessage();
|
|
2503
|
+
return /* @__PURE__ */ jsxs(Message, { children: [message.role === "assistant" && /* @__PURE__ */ jsx(Avatar, { size: "small" }), /* @__PURE__ */ jsxs("div", {
|
|
2504
|
+
"data-ask-part": "message-body",
|
|
2505
|
+
children: [
|
|
2506
|
+
/* @__PURE__ */ jsx(MessageText, {}),
|
|
2507
|
+
/* @__PURE__ */ jsx(MessageFiles, {}),
|
|
2508
|
+
/* @__PURE__ */ jsx(Citations, {}),
|
|
2509
|
+
/* @__PURE__ */ jsx(Feedback, {})
|
|
2510
|
+
]
|
|
2511
|
+
})] });
|
|
2512
|
+
}
|
|
2513
|
+
// src/react/skin/welcome.tsx
|
|
2514
|
+
/** `**words**` in a greeting are shown in bold, as in Aura's two-weight headline; nothing else is markup. */
|
|
2515
|
+
function emphasized(text) {
|
|
2516
|
+
return text.split("**").map((part, index) => index % 2 === 1 ? /* @__PURE__ */ jsx("strong", { children: part }, index) : part);
|
|
2517
|
+
}
|
|
2518
|
+
function Starters() {
|
|
2519
|
+
const { state, actions, bot } = useChat();
|
|
2520
|
+
if (bot.starters.length === 0) return null;
|
|
2521
|
+
const checklist = bot.variants.welcome === "intro";
|
|
2522
|
+
const disabled = state.busy || state.phase !== "ready";
|
|
2523
|
+
return /* @__PURE__ */ jsx("ul", {
|
|
2524
|
+
"data-ask-part": "starters",
|
|
2525
|
+
"aria-label": bot.texts["welcome.suggestions"],
|
|
2526
|
+
children: bot.starters.map((starter) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs("button", {
|
|
2527
|
+
type: "button",
|
|
2528
|
+
"data-ask-part": "starter",
|
|
2529
|
+
disabled,
|
|
2530
|
+
onClick: () => void actions.send(starter),
|
|
2531
|
+
children: [
|
|
2532
|
+
checklist ? /* @__PURE__ */ jsx(CheckIcon, {}) : /* @__PURE__ */ jsx(SparkIcon, {}),
|
|
2533
|
+
/* @__PURE__ */ jsx("span", { children: starter }),
|
|
2534
|
+
bot.variants.welcome === "persona" && /* @__PURE__ */ jsx(ArrowIcon, {})
|
|
2535
|
+
]
|
|
2536
|
+
}) }, starter))
|
|
2537
|
+
});
|
|
2538
|
+
}
|
|
2539
|
+
/**
|
|
2540
|
+
* What a visitor sees before the first message. The preset picks the layout: a centered hero,
|
|
2541
|
+
* a persona card, or an opening message with a checklist of what the assistant can do.
|
|
2542
|
+
*/
|
|
2543
|
+
function DefaultWelcome() {
|
|
2544
|
+
const { bot } = useChat();
|
|
2545
|
+
const Heading = heading(useSkin().headingLevel + 1);
|
|
2546
|
+
const layout = bot.variants.welcome;
|
|
2547
|
+
if (layout === "intro") return /* @__PURE__ */ jsx("section", {
|
|
2548
|
+
"data-ask-part": "welcome",
|
|
2549
|
+
"data-layout": "intro",
|
|
2550
|
+
"aria-label": bot.texts["welcome.label"],
|
|
2551
|
+
children: /* @__PURE__ */ jsxs("div", {
|
|
2552
|
+
"data-ask-part": "intro",
|
|
2553
|
+
children: [/* @__PURE__ */ jsx(Avatar, { size: "small" }), /* @__PURE__ */ jsxs("div", {
|
|
2554
|
+
"data-ask-part": "intro-card",
|
|
2555
|
+
children: [/* @__PURE__ */ jsx("p", {
|
|
2556
|
+
"data-ask-part": "greeting",
|
|
2557
|
+
children: emphasized(bot.greeting)
|
|
2558
|
+
}), /* @__PURE__ */ jsx(Starters, {})]
|
|
2559
|
+
})]
|
|
2560
|
+
})
|
|
2561
|
+
});
|
|
2562
|
+
if (layout === "persona") return /* @__PURE__ */ jsxs("section", {
|
|
2563
|
+
"data-ask-part": "welcome",
|
|
2564
|
+
"data-layout": "persona",
|
|
2565
|
+
"aria-label": bot.texts["welcome.label"],
|
|
2566
|
+
children: [
|
|
2567
|
+
/* @__PURE__ */ jsxs("div", {
|
|
2568
|
+
"data-ask-part": "persona",
|
|
2569
|
+
children: [/* @__PURE__ */ jsx(Avatar, { size: "large" }), /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(Heading, {
|
|
2570
|
+
"data-ask-part": "persona-name",
|
|
2571
|
+
children: bot.title
|
|
2572
|
+
}), /* @__PURE__ */ jsx("span", {
|
|
2573
|
+
"data-ask-part": "presence",
|
|
2574
|
+
children: bot.texts["welcome.online"]
|
|
2575
|
+
})] })]
|
|
2576
|
+
}),
|
|
2577
|
+
/* @__PURE__ */ jsx("p", {
|
|
2578
|
+
"data-ask-part": "greeting",
|
|
2579
|
+
children: emphasized(bot.greeting)
|
|
2580
|
+
}),
|
|
2581
|
+
/* @__PURE__ */ jsx(Starters, {})
|
|
2582
|
+
]
|
|
2583
|
+
});
|
|
2584
|
+
return /* @__PURE__ */ jsxs("section", {
|
|
2585
|
+
"data-ask-part": "welcome",
|
|
2586
|
+
"data-layout": "hero",
|
|
2587
|
+
"aria-label": bot.texts["welcome.label"],
|
|
2588
|
+
children: [
|
|
2589
|
+
/* @__PURE__ */ jsx(Avatar, { size: "large" }),
|
|
2590
|
+
/* @__PURE__ */ jsx(Heading, {
|
|
2591
|
+
"data-ask-part": "greeting",
|
|
2592
|
+
children: emphasized(bot.greeting)
|
|
2593
|
+
}),
|
|
2594
|
+
/* @__PURE__ */ jsx(Starters, {})
|
|
2595
|
+
]
|
|
2596
|
+
});
|
|
2597
|
+
}
|
|
2598
|
+
// src/react/skin/panel.tsx
|
|
2599
|
+
/** The default look of the chat inside its frame: header, conversation and message field. */
|
|
2600
|
+
function DefaultPanel({ headingLevel = 2, onClose, components = {}, ownsDocument = false }) {
|
|
2601
|
+
const { state, actions, bot, t } = useChat();
|
|
2602
|
+
const [confirming, setConfirming] = useState(false);
|
|
2603
|
+
const restartRef = useRef(null);
|
|
2604
|
+
const askStartOver = useCallback(() => setConfirming(true), []);
|
|
2605
|
+
const skin = useMemo(() => ({
|
|
2606
|
+
bot,
|
|
2607
|
+
t,
|
|
2608
|
+
headingLevel,
|
|
2609
|
+
onClose,
|
|
2610
|
+
askStartOver,
|
|
2611
|
+
restartRef
|
|
2612
|
+
}), [
|
|
2613
|
+
bot,
|
|
2614
|
+
t,
|
|
2615
|
+
headingLevel,
|
|
2616
|
+
onClose,
|
|
2617
|
+
askStartOver
|
|
2618
|
+
]);
|
|
2619
|
+
const cancelStartOver = () => {
|
|
2620
|
+
setConfirming(false);
|
|
2621
|
+
requestAnimationFrame(() => restartRef.current?.focus());
|
|
2622
|
+
};
|
|
2623
|
+
const main = headingLevel === 1;
|
|
2624
|
+
const panelRef = useRef(null);
|
|
2625
|
+
const onEscape = useRef(() => {});
|
|
2626
|
+
onEscape.current = () => {
|
|
2627
|
+
if (confirming) cancelStartOver();
|
|
2628
|
+
else if (state.commenting !== void 0) actions.dismissComment();
|
|
2629
|
+
else if (state.dictation === "recording") actions.cancelDictation();
|
|
2630
|
+
else onClose?.();
|
|
2631
|
+
};
|
|
2632
|
+
useEffect(() => {
|
|
2633
|
+
const onKey = (event) => {
|
|
2634
|
+
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
|
|
2635
|
+
const inside = event.target instanceof Node && panelRef.current?.contains(event.target);
|
|
2636
|
+
if (ownsDocument || inside) onEscape.current();
|
|
2637
|
+
};
|
|
2638
|
+
window.addEventListener("keydown", onKey);
|
|
2639
|
+
return () => window.removeEventListener("keydown", onKey);
|
|
2640
|
+
}, [ownsDocument]);
|
|
2641
|
+
const Header = components.Header ?? DefaultHeader;
|
|
2642
|
+
const Welcome = components.Welcome ?? DefaultWelcome;
|
|
2643
|
+
const Message = components.Message ?? DefaultMessage;
|
|
2644
|
+
const Footer = components.Footer ?? DefaultFooter;
|
|
2645
|
+
const message = useMemo(() => /* @__PURE__ */ jsx(Message, {}), [Message]);
|
|
2646
|
+
const showWelcome = state.messages.length === 0 && state.phase !== "loading";
|
|
2647
|
+
return /* @__PURE__ */ jsx(SkinContext.Provider, {
|
|
2648
|
+
value: skin,
|
|
2649
|
+
children: /* @__PURE__ */ jsxs(Panel, {
|
|
2650
|
+
ref: panelRef,
|
|
2651
|
+
landmark: main ? "main" : "region",
|
|
2652
|
+
children: [
|
|
2653
|
+
/* @__PURE__ */ jsx(Header, {}),
|
|
2654
|
+
confirming && /* @__PURE__ */ jsx(StartOverQuestion, {
|
|
2655
|
+
modal: ownsDocument,
|
|
2656
|
+
onCancel: cancelStartOver,
|
|
2657
|
+
onAccept: () => {
|
|
2658
|
+
setConfirming(false);
|
|
2659
|
+
actions.newConversation();
|
|
2660
|
+
}
|
|
2661
|
+
}),
|
|
2662
|
+
/* @__PURE__ */ jsxs(Messages, { children: [
|
|
2663
|
+
showWelcome && /* @__PURE__ */ jsx(Welcome, {}),
|
|
2664
|
+
/* @__PURE__ */ jsx(MessageList, { children: message }),
|
|
2665
|
+
/* @__PURE__ */ jsx(Status, {})
|
|
2666
|
+
] }),
|
|
2667
|
+
/* @__PURE__ */ jsx(ErrorMessage, {}),
|
|
2668
|
+
/* @__PURE__ */ jsx(Footer, {})
|
|
2669
|
+
]
|
|
2670
|
+
})
|
|
2671
|
+
});
|
|
2672
|
+
}
|
|
2673
|
+
// src/react/default-chat.tsx
|
|
2674
|
+
/**
|
|
2675
|
+
* The widget's look inside your page: `<Root config={config}><DefaultChat className="…" /></Root>`.
|
|
2676
|
+
* It loads its stylesheets from the chat route, so there is nothing to import or configure.
|
|
2677
|
+
*/
|
|
2678
|
+
function DefaultChat({ className, colorScheme, ...panel }) {
|
|
2679
|
+
const { styles } = useStore().config;
|
|
2680
|
+
return /* @__PURE__ */ jsxs(Theme, {
|
|
2681
|
+
className,
|
|
2682
|
+
colorScheme,
|
|
2683
|
+
"data-ask-skin": "",
|
|
2684
|
+
children: [styles && /* @__PURE__ */ jsx("link", {
|
|
2685
|
+
rel: "stylesheet",
|
|
2686
|
+
href: styles.skin,
|
|
2687
|
+
precedence: "askdare"
|
|
2688
|
+
}), /* @__PURE__ */ jsx(DefaultPanel, { ...panel })]
|
|
2689
|
+
});
|
|
2690
|
+
}
|
|
2691
|
+
export { AttachButton, Citations, Composer, DefaultChat, DictateButton, ErrorMessage, FeedbackButton, Files, Input, Markdown, Message, MessageFiles, MessageList, MessageText, Messages, Panel, Recorder, Root, Send, Status, Theme, useChat, useChatState, useMessage };
|