@boldare/askdare 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +14 -4
  3. package/dist/cli.js +111 -26
  4. package/dist/define-tool.js +1006 -8
  5. package/dist/embed.d.ts +19 -0
  6. package/dist/embed.js +250 -0
  7. package/dist/{store.d.ts → events.d.ts} +163 -54
  8. package/dist/index.d.ts +28 -2
  9. package/dist/index.js +74 -158
  10. package/dist/next.d.ts +70 -9
  11. package/dist/next.js +767 -169
  12. package/dist/react-marked.js +648 -624
  13. package/dist/react.d.ts +63 -77
  14. package/dist/react.js +148 -1854
  15. package/dist/root.js +2254 -0
  16. package/dist/tool-results.d.ts +140 -0
  17. package/dist/ui/askdare.css +21 -1
  18. package/dist/ui/avatar.tsx +1 -1
  19. package/dist/ui/chat.tsx +1 -1
  20. package/dist/ui/confirm.tsx +1 -1
  21. package/dist/ui/context.ts +1 -1
  22. package/dist/ui/feedback.tsx +1 -1
  23. package/dist/ui/footer.tsx +3 -15
  24. package/dist/ui/header.tsx +1 -1
  25. package/dist/ui/icons.tsx +1 -1
  26. package/dist/ui/index.ts +1 -1
  27. package/dist/ui/message.tsx +6 -4
  28. package/dist/ui/panel.tsx +17 -6
  29. package/dist/ui/welcome.tsx +1 -1
  30. package/docs/accessibility.md +83 -0
  31. package/docs/cli.md +5 -3
  32. package/docs/compliance.md +160 -0
  33. package/docs/configuration.md +58 -2
  34. package/docs/costs.md +8 -1
  35. package/docs/custom-store.md +2 -0
  36. package/docs/embedding.md +104 -0
  37. package/docs/events.md +1 -1
  38. package/docs/feedback.md +1 -1
  39. package/docs/going-public.md +15 -3
  40. package/docs/guardrails.md +128 -0
  41. package/docs/migrating-from-openai-assistant.md +1 -1
  42. package/docs/privacy.md +27 -3
  43. package/docs/protocol.md +15 -1
  44. package/docs/react.md +57 -3
  45. package/docs/styling.md +4 -3
  46. package/docs/support.md +3 -3
  47. package/docs/texts.md +127 -98
  48. package/docs/tools.md +20 -0
  49. package/docs/troubleshooting.md +30 -3
  50. package/llms.txt +14 -11
  51. package/package.json +10 -6
  52. package/skills/askdare/SKILL.md +12 -2
package/dist/react.js CHANGED
@@ -1,321 +1,7 @@
1
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";
2
+ import { C as useFrame, D as useTexts, E as useStore, S as useChatState, T as useOptionalMessage, a as ToolResults, b as useChat, f as Markdown, g as acceptTypes, h as canSend, m as pluralText, p as safeUrl, r as Link, t as Root, u as Disclosure, w as useMessage, x as useChatConfig, y as MessageProvider } from "./root.js";
3
+ import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
4
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, or null outside `MessageList`. */
70
- function useOptionalMessage() {
71
- return useContext(MessageContext);
72
- }
73
- /** The message being rendered, inside `MessageList`. */
74
- function useMessage() {
75
- const message = useContext(MessageContext);
76
- if (!message) throw new Error("[askdare] useMessage() works only inside <MessageList>.");
77
- return message;
78
- }
79
- // src/chat/prepare-file.ts
80
- /** Longest image edge sent to the model; larger photos only cost upload time. */
81
- const MAX_EDGE = 2048;
82
- const JPEG_QUALITY = .85;
83
- const IMAGE_NAME = /\.(png|jpe?g|webp|gif|heic|heif|avif|bmp)$/i;
84
- var UnsupportedFileError = class extends Error {};
85
- const isPdf = (file) => file.type === "application/pdf" || /\.pdf$/i.test(file.name);
86
- const isImage = (file) => file.type.startsWith("image/") && file.type !== "image/svg+xml" || IMAGE_NAME.test(file.name);
87
- const baseName = (name) => name.replace(/\.[^.]*$/, "") || "image";
88
- /** The `accept` attribute for the file picker. */
89
- function acceptTypes(allowed) {
90
- return [...allowed.images ? [
91
- "image/png",
92
- "image/jpeg",
93
- "image/webp",
94
- "image/gif",
95
- "image/heic"
96
- ] : [], ...allowed.pdf ? ["application/pdf"] : []].join(",");
97
- }
98
- async function encodeJpeg(bitmap, width, height) {
99
- const canvas = document.createElement("canvas");
100
- canvas.width = width;
101
- canvas.height = height;
102
- const context = canvas.getContext("2d");
103
- if (!context) throw new UnsupportedFileError();
104
- context.fillStyle = "#fff";
105
- context.fillRect(0, 0, width, height);
106
- context.drawImage(bitmap, 0, 0, width, height);
107
- return new Promise((resolve, reject) => canvas.toBlob((blob) => blob ? resolve(blob) : reject(new UnsupportedFileError()), "image/jpeg", JPEG_QUALITY));
108
- }
109
- /**
110
- * Gets a file ready to upload. Images are decoded, downsized and re-encoded as JPEG in the
111
- * browser, which drops EXIF data such as the GPS position and turns HEIC photos into a format
112
- * OpenAI accepts (where the browser can decode HEIC). PDFs are sent as they are.
113
- */
114
- async function prepareFile(file, allowed) {
115
- if (allowed.pdf && isPdf(file)) return {
116
- blob: file,
117
- name: file.name,
118
- kind: "pdf"
119
- };
120
- if (!allowed.images || !isImage(file)) throw new UnsupportedFileError();
121
- let bitmap;
122
- try {
123
- bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
124
- } catch {
125
- throw new UnsupportedFileError();
126
- }
127
- try {
128
- const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
129
- const width = Math.max(1, Math.round(bitmap.width * scale));
130
- const height = Math.max(1, Math.round(bitmap.height * scale));
131
- return {
132
- blob: await encodeJpeg(bitmap, width, height),
133
- name: `${baseName(file.name)}.jpg`,
134
- kind: "image"
135
- };
136
- } finally {
137
- bitmap.close();
138
- }
139
- }
140
- // src/chat/state.ts
141
- /** Whether the draft, or the files ready to go, can be sent now. */
142
- function canSend(state) {
143
- return state.phase === "ready" && !state.busy && !state.files.some((file) => file.status === "uploading") && (state.draft.trim() !== "" || state.files.some((file) => file.status === "ready"));
144
- }
145
- // src/i18n/format.ts
146
- /** Text helpers the widget needs; the dictionaries stay on the server. */
147
- /** Fills `{name}` placeholders. */
148
- function formatText(template, params = {}) {
149
- return template.replace(/\{(\w+)\}/g, (match, name) => name in params ? String(params[name]) : match);
150
- }
151
- /** A plural text such as `message.attachments` for a count, by the locale's plural rules. */
152
- function pluralText(texts, base, count, locale) {
153
- let category = "other";
154
- try {
155
- category = new Intl.PluralRules(locale).select(count);
156
- } catch {}
157
- return formatText(texts[`${base}.${category}`] ?? texts[`${base}.other`] ?? "", { count });
158
- }
159
- // src/react/markdown.tsx
160
- const SAFE_PROTOCOLS = /* @__PURE__ */ new Set([
161
- "http:",
162
- "https:",
163
- "mailto:"
164
- ]);
165
- /**
166
- * Deeper nesting than any real answer needs. Past it, the rest shows as plain text: a prompt-
167
- * injected answer of `>>>>…` or `- - - …` must not blow the stack and take the chat down with it.
168
- */
169
- const MAX_DEPTH = 16;
170
- /** Keeps only http(s) and mailto links; everything else (javascript:, data:, relative) is dropped. */
171
- function safeUrl(url) {
172
- try {
173
- const parsed = new URL(url);
174
- return SAFE_PROTOCOLS.has(parsed.protocol) ? parsed.href : "";
175
- } catch {
176
- return "";
177
- }
178
- }
179
- const NAMED = {
180
- amp: "&",
181
- lt: "<",
182
- gt: ">",
183
- quot: "\"",
184
- apos: "'",
185
- nbsp: "\xA0",
186
- copy: "©",
187
- reg: "®",
188
- trade: "™",
189
- hellip: "…",
190
- mdash: "—",
191
- ndash: "–",
192
- lsquo: "‘",
193
- rsquo: "’",
194
- ldquo: "“",
195
- rdquo: "”",
196
- laquo: "«",
197
- raquo: "»",
198
- bull: "•",
199
- middot: "·",
200
- deg: "°",
201
- plusmn: "±",
202
- times: "×",
203
- divide: "÷",
204
- euro: "€",
205
- pound: "£",
206
- yen: "¥",
207
- cent: "¢",
208
- sect: "§",
209
- para: "¶"
210
- };
211
- /**
212
- * marked leaves character references for an HTML renderer to decode; we render text, so decode
213
- * them here: numeric ones and the common named ones (others stay as written). Safe, because the
214
- * result is only ever text or a URL that `safeUrl` checks after decoding.
215
- */
216
- function decodeEntities(text) {
217
- if (!text.includes("&")) return text;
218
- return text.replace(/&(#\d{1,7}|#[xX][\da-fA-F]{1,6}|[a-zA-Z]{2,8});/g, (match, entity) => {
219
- if (entity[0] !== "#") return NAMED[entity] ?? match;
220
- const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
221
- return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : "�";
222
- });
223
- }
224
- /** Inline tokens: text, emphasis, code, links. HTML is dropped, images are never loaded. */
225
- function inline(tokens, depth) {
226
- if (depth > MAX_DEPTH) return [(tokens ?? []).map((token) => token.raw).join("")];
227
- return (tokens ?? []).map((token, key) => {
228
- switch (token.type) {
229
- case "text": return "tokens" in token && token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
230
- case "escape": return token.text;
231
- case "strong": return /* @__PURE__ */ jsx("strong", { children: inline(token.tokens, depth + 1) }, key);
232
- case "em": return /* @__PURE__ */ jsx("em", { children: inline(token.tokens, depth + 1) }, key);
233
- case "del": return /* @__PURE__ */ jsx("del", { children: inline(token.tokens, depth + 1) }, key);
234
- case "codespan": return /* @__PURE__ */ jsx("code", { children: token.text }, key);
235
- case "br": return /* @__PURE__ */ jsx("br", {}, key);
236
- case "link": {
237
- const href = safeUrl(decodeEntities(token.href));
238
- return href ? /* @__PURE__ */ jsx("a", {
239
- href,
240
- target: "_blank",
241
- rel: "noopener noreferrer nofollow",
242
- children: inline(token.tokens, depth + 1)
243
- }, key) : /* @__PURE__ */ jsx("span", { children: inline(token.tokens, depth + 1) }, key);
244
- }
245
- case "image": return token.text ? /* @__PURE__ */ jsxs("span", {
246
- "data-ask-part": "image-alt",
247
- children: [
248
- "[",
249
- decodeEntities(token.text),
250
- "]"
251
- ]
252
- }, key) : null;
253
- default: return null;
254
- }
255
- });
256
- }
257
- function cells(row, header, depth) {
258
- return row.map((cell, key) => {
259
- return /* @__PURE__ */ jsx(header ? "th" : "td", {
260
- style: cell.align ? { textAlign: cell.align } : void 0,
261
- children: inline(cell.tokens, depth + 1)
262
- }, key);
263
- });
264
- }
265
- function blocks(tokens, depth) {
266
- if (depth > MAX_DEPTH) return [tokens.map((token) => token.raw).join("")];
267
- return tokens.map((token, key) => {
268
- switch (token.type) {
269
- case "paragraph": return /* @__PURE__ */ jsx("p", { children: inline(token.tokens, depth + 1) }, key);
270
- case "text": return token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
271
- case "heading": {
272
- const Heading = `h${Math.min(Math.max(token.depth, 1), 6)}`;
273
- return /* @__PURE__ */ jsx(Heading, { children: inline(token.tokens, depth + 1) }, key);
274
- }
275
- case "code": return /* @__PURE__ */ jsx("pre", { children: /* @__PURE__ */ jsx("code", { children: token.text }) }, key);
276
- case "blockquote": return /* @__PURE__ */ jsx("blockquote", { children: blocks(token.tokens ?? [], depth + 1) }, key);
277
- case "hr": return /* @__PURE__ */ jsx("hr", {}, key);
278
- case "list": {
279
- const items = token.items.map((item, index) => /* @__PURE__ */ jsxs("li", { children: [item.task && /* @__PURE__ */ jsx("input", {
280
- type: "checkbox",
281
- checked: item.checked ?? false,
282
- disabled: true
283
- }), blocks(item.tokens.filter((child) => child.type !== "checkbox"), depth + 1)] }, index));
284
- return token.ordered ? /* @__PURE__ */ jsx("ol", {
285
- start: typeof token.start === "number" ? token.start : void 0,
286
- children: items
287
- }, key) : /* @__PURE__ */ jsx("ul", { children: items }, key);
288
- }
289
- 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);
290
- default: return null;
291
- }
292
- });
293
- }
294
- /** The text as paragraphs, when markdown can't be had. */
295
- const plain = (text) => text.split(/\n{2,}/).map((paragraph, key) => /* @__PURE__ */ jsx("p", { children: paragraph }, key));
296
- function render(text) {
297
- try {
298
- return blocks(O.lex(text, { gfm: true }), 0);
299
- } catch {
300
- return plain(text);
301
- }
302
- }
303
- /** Shows the plain text if rendering a message ever fails, so one answer can't break the chat. */
304
- var Fallback = class extends Component {
305
- state = { failed: false };
306
- static getDerivedStateFromError() {
307
- return { failed: true };
308
- }
309
- render() {
310
- return this.state.failed ? plain(this.props.text) : this.props.children;
311
- }
312
- };
313
- const Markdown = /* @__PURE__ */ memo(function Markdown({ text }) {
314
- return /* @__PURE__ */ jsx(Fallback, {
315
- text,
316
- children: render(text)
317
- });
318
- });
319
5
  // src/react/refs.ts
320
6
  /** One ref callback for a primitive's own ref and the one its user passed as a prop. */
321
7
  function useMergedRef(own, passed) {
@@ -351,28 +37,55 @@ function focusElement(ref, explicit = false) {
351
37
  // src/react/messages.tsx
352
38
  /** False for an answer that ended (or failed) before any text or sources, or options to show. */
353
39
  const hasContent = (message) => message.role === "user" || message.status === "streaming" || message.text !== "" || message.citations.length > 0 || message.status === "done" && (message.replies?.length ?? 0) > 0;
40
+ /** Visually hidden, but read by screen readers. */
41
+ const hidden = {
42
+ position: "absolute",
43
+ width: 1,
44
+ height: 1,
45
+ overflow: "hidden",
46
+ clipPath: "inset(50%)",
47
+ whiteSpace: "nowrap"
48
+ };
354
49
  /**
355
- * The conversation: a live region that follows the latest message as it streams. Holds the
356
- * welcome, the `MessageList` and the `Status`.
50
+ * The conversation, following the latest message as it streams. Holds the welcome, the
51
+ * `MessageList` and the `Status`. It is a log but not a live region: text growing inside a node is
52
+ * read in fragments or not at all, so a finished answer is announced once, through a status region
53
+ * next to it.
357
54
  */
358
55
  function Messages({ ref, ...props }) {
359
56
  const own = useRef(null);
57
+ const streaming = useRef(void 0);
58
+ const [finished, setFinished] = useState("");
360
59
  const loading = useChatState((state) => state.phase === "loading");
361
60
  const latest = useChatState((state) => state.messages.at(-1));
362
61
  const commenting = useChatState((state) => state.commenting);
363
62
  useEffect(() => {
364
63
  const log = own.current;
365
- if (log && latest) log.scrollTop = log.scrollHeight;
64
+ if (!log || !latest) return;
65
+ log.scrollTop = log.scrollHeight;
66
+ if (latest.role !== "assistant") return;
67
+ if (latest.status === "streaming") {
68
+ if (streaming.current !== latest.id) setFinished("");
69
+ streaming.current = latest.id;
70
+ } else if (streaming.current === latest.id) {
71
+ streaming.current = void 0;
72
+ const bubbles = log.querySelectorAll("[data-ask-part=\"bubble\"]");
73
+ if (latest.status === "done" && latest.text !== "") setFinished(bubbles[bubbles.length - 1]?.textContent || latest.text);
74
+ }
366
75
  }, [latest, commenting]);
367
- return /* @__PURE__ */ jsx("div", {
76
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
368
77
  "data-ask-part": "messages",
369
78
  role: "log",
370
- "aria-live": "polite",
371
- "aria-relevant": "additions",
79
+ "aria-live": "off",
372
80
  "aria-busy": loading,
373
81
  ...props,
374
82
  ref: useMergedRef(own, ref)
375
- });
83
+ }), /* @__PURE__ */ jsx("div", {
84
+ "data-ask-part": "announcement",
85
+ role: "status",
86
+ style: hidden,
87
+ children: finished
88
+ })] });
376
89
  }
377
90
  /** Renders its children for every message worth showing. Has no element of its own. */
378
91
  function MessageList({ children }) {
@@ -401,7 +114,7 @@ function Message(props) {
401
114
  */
402
115
  function MessageText(props) {
403
116
  const message = useMessage();
404
- const { t } = useStore();
117
+ const t = useTexts();
405
118
  if (message.text !== "") return /* @__PURE__ */ jsx("div", {
406
119
  "data-ask-part": "bubble",
407
120
  ...props,
@@ -426,7 +139,7 @@ function MessageText(props) {
426
139
  /** The sources of an answer. Links go through the same check as links in answers. */
427
140
  function Citations(props) {
428
141
  const message = useMessage();
429
- const { t } = useStore();
142
+ const t = useTexts();
430
143
  if (message.citations.length === 0) return null;
431
144
  return /* @__PURE__ */ jsx("ol", {
432
145
  "data-ask-part": "citations",
@@ -448,7 +161,7 @@ function Citations(props) {
448
161
  }
449
162
  /** Files of a message, or those picked for the next one (which can be removed). */
450
163
  function FileList({ files, list, onRemove, ...props }) {
451
- const { t } = useStore();
164
+ const t = useTexts();
452
165
  return /* @__PURE__ */ jsx("ul", {
453
166
  "data-ask-part": list,
454
167
  "aria-label": t("attachment.list"),
@@ -500,7 +213,7 @@ function FileList({ files, list, onRemove, ...props }) {
500
213
  */
501
214
  function MessageFiles({ ref, ...props }) {
502
215
  const message = useMessage();
503
- const { widget } = useStore().config;
216
+ const { widget } = useChatConfig();
504
217
  if (message.files && message.files.length > 0) return /* @__PURE__ */ jsx(FileList, {
505
218
  files: message.files,
506
219
  list: "message-attachments",
@@ -548,6 +261,10 @@ function Input({ ref, onKeyDown, onPaste, onChange, ...props }) {
548
261
  useLayoutEffect(() => {
549
262
  if (own.current) fitToContent(own.current);
550
263
  }, [draft]);
264
+ useEffect(() => {
265
+ const typed = own.current?.value;
266
+ if (typed && typed !== store.getSnapshot().draft) actions.setDraft(typed);
267
+ }, []);
551
268
  useEffect(() => store.onFocus("input", (explicit) => focusElement(own, explicit)), [store]);
552
269
  return /* @__PURE__ */ jsx("textarea", {
553
270
  "data-ask-part": "input",
@@ -724,7 +441,8 @@ function Recorder({ cancelIcon = "×", ...props }) {
724
441
  */
725
442
  function FeedbackButton({ rating, onClick, ...props }) {
726
443
  const message = useMessage();
727
- const { actions, t } = useStore();
444
+ const { actions } = useStore();
445
+ const t = useTexts();
728
446
  const key = message.feedback?.key;
729
447
  const current = useChatState((state) => key ? state.ratings[key] : void 0);
730
448
  if (!key || message.role !== "assistant" || message.status !== "done") return null;
@@ -743,6 +461,94 @@ function FeedbackButton({ rating, onClick, ...props }) {
743
461
  ...props
744
462
  });
745
463
  }
464
+ /** Loaded on demand by the chat, with explicit rendering. */
465
+ const TURNSTILE_SCRIPT = `https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`;
466
+ /**
467
+ * The Turnstile `action` the chat renders for a bot and the server expects back: the bot id, cut
468
+ * to Turnstile's 32 characters (bot ids use only characters it accepts).
469
+ */
470
+ const turnstileAction = (botId) => botId.slice(0, 32);
471
+ // src/react/human-check.tsx
472
+ let loading;
473
+ /** Errors (each followed by Turnstile's own retry) before the check counts as failed. */
474
+ const MAX_ERRORS = 3;
475
+ /** Turnstile's API, its script loaded once, when the first check is needed. */
476
+ const turnstile = () => {
477
+ const ready = () => window.turnstile;
478
+ loading ??= new Promise((resolve, reject) => {
479
+ const api = ready();
480
+ if (api) return resolve(api);
481
+ const script = document.createElement("script");
482
+ script.src = TURNSTILE_SCRIPT;
483
+ const fail = () => {
484
+ loading = void 0;
485
+ script.remove();
486
+ reject();
487
+ };
488
+ script.onload = () => {
489
+ const loaded = ready();
490
+ if (loaded) resolve(loaded);
491
+ else fail();
492
+ };
493
+ script.onerror = fail;
494
+ document.head.append(script);
495
+ });
496
+ return loading;
497
+ };
498
+ /**
499
+ * The bot's human check (`security.humanVerifier`), shown while the chat waits for it before it
500
+ * connects; nothing otherwise. The default look includes it; a headless chat whose bot has a check
501
+ * must render it, or it can't connect.
502
+ */
503
+ function HumanCheck(props) {
504
+ const store = useStore();
505
+ const { state, t } = useChat();
506
+ const { humanCheck: challenge, widget, botId } = useChatConfig();
507
+ const container = useRef(null);
508
+ const active = state.humanCheck && challenge !== void 0;
509
+ useEffect(() => store.attachHumanCheck(), [store]);
510
+ useEffect(() => {
511
+ const element = container.current;
512
+ if (!active || !challenge || !element) return;
513
+ let live = true;
514
+ let errors = 0;
515
+ let remove = () => {};
516
+ turnstile().then((api) => {
517
+ if (!live) return;
518
+ const id = api.render(element, {
519
+ sitekey: challenge.siteKey,
520
+ action: turnstileAction(botId),
521
+ callback: (token) => store.answerHumanCheck(token),
522
+ "error-callback": () => {
523
+ if (++errors < MAX_ERRORS) return false;
524
+ store.answerHumanCheck(null);
525
+ return true;
526
+ },
527
+ size: "flexible",
528
+ language: widget.locale
529
+ });
530
+ if (id !== void 0) remove = () => api.remove(id);
531
+ }, () => live && store.answerHumanCheck(null));
532
+ return () => {
533
+ live = false;
534
+ remove();
535
+ };
536
+ }, [
537
+ active,
538
+ challenge,
539
+ widget.locale,
540
+ botId,
541
+ store
542
+ ]);
543
+ if (!active) return null;
544
+ return /* @__PURE__ */ jsx("div", {
545
+ "data-ask-part": "human-check",
546
+ role: "group",
547
+ "aria-label": t("humanCheck.label"),
548
+ ...props,
549
+ ref: container
550
+ });
551
+ }
746
552
  // src/react/notices.tsx
747
553
  /** What the chat is doing: loading a conversation, or what the assistant does before it writes. */
748
554
  function Status(props) {
@@ -818,7 +624,8 @@ function Panel({ landmark = "region", onDragOver, onDragLeave, onDrop, ...props
818
624
  */
819
625
  function QuickReplies(props) {
820
626
  const own = useOptionalMessage();
821
- const { actions, t } = useStore();
627
+ const { actions } = useStore();
628
+ const t = useTexts();
822
629
  const replies = useChatState((state) => {
823
630
  const latest = state.messages.at(-1);
824
631
  if (latest?.role !== "assistant" || latest.status !== "done") return void 0;
@@ -840,1517 +647,6 @@ function QuickReplies(props) {
840
647
  }, index))
841
648
  });
842
649
  }
843
- // src/base-path.ts
844
- /**
845
- * Whether a chat route's `basePath` is a path on the app itself, like `/api/chat`: never another
846
- * origin, a relative path or anything that needs escaping (ADR-0011). The server, the React entry
847
- * and the CLI each bundle their own copy.
848
- */
849
- function isBasePath(value) {
850
- return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
851
- }
852
- // src/chat/page-options.ts
853
- const MAX_CONTEXT = 1e3;
854
- const JWT = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
855
- /**
856
- * A JWT-shaped string, or null to sign out; the server verifies it. Any other string signs out
857
- * too, so a broken token never leaves the previous user signed in.
858
- */
859
- function identityToken(value) {
860
- if (value === null) return null;
861
- if (typeof value !== "string") return void 0;
862
- if (value.length <= 4096 && JWT.test(value)) return value;
863
- console.warn("[askdare] askdare('identify') got something that isn't a JWT; signing out.");
864
- return null;
865
- }
866
- /** Keeps only the allowed fields, trimmed and within their limits. */
867
- function pageOptions(data) {
868
- const greeting = typeof data["greeting"] === "string" ? data["greeting"].trim() : "";
869
- 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;
870
- const context = typeof data["context"] === "string" ? data["context"].trim() : "";
871
- return {
872
- ...greeting && greeting.length <= 500 ? { greeting } : {},
873
- ...starters ? { starters } : {},
874
- ...context ? { context: context.slice(0, MAX_CONTEXT) } : {}
875
- };
876
- }
877
- // src/protocol/events.ts
878
- /** Stable error codes sent to clients. The accompanying message never contains internals. */
879
- const ERROR_CODES = [
880
- "invalid_input",
881
- "unauthorized",
882
- "session_expired",
883
- "not_found",
884
- "rate_limited",
885
- "budget_exceeded",
886
- "bot_unavailable",
887
- "content_blocked",
888
- "timeout",
889
- "upstream_error",
890
- "internal_error"
891
- ];
892
- const MESSAGE_END_REASONS = [
893
- "completed",
894
- "max_steps",
895
- "max_output_tokens",
896
- "timeout",
897
- "content_filter",
898
- "aborted"
899
- ];
900
- const PROTOCOL_EVENT_TYPES = [
901
- "conversation.created",
902
- "user.ack",
903
- "message.start",
904
- "reasoning",
905
- "text.delta",
906
- "citation",
907
- "tool.status",
908
- "replies",
909
- "message.end",
910
- "error"
911
- ];
912
- /**
913
- * A URL or something a browser or a chat app would turn into a link: a scheme (`https://`,
914
- * `mailto:`, `javascript:` …), `www.`, an IP address or a domain name such as `example.com`.
915
- * Strict on purpose: a few odd names (`Node.js`) are dropped with them.
916
- */
917
- const LINK = /[a-z][a-z\d+.-]*:\/\/|\b(?:mailto|tel|sms|javascript|vbscript|data|file):|\bwww\.|\b\d{1,3}(?:\.\d{1,3}){3}\b|[\p{L}\d-]\.[a-z]{2,}(?![\p{L}\d])/iu;
918
- /**
919
- * Characters the visitor can't see or read: line breaks and other control characters, format
920
- * characters (bidirectional overrides that reorder text, zero-width characters, tag characters
921
- * that can spell hidden words), private-use and unassigned code points. A click sends the option
922
- * as the visitor's own message, so it must say exactly what they read. The zero-width joiner stays
923
- * for emoji built from several, such as "woman technologist".
924
- */
925
- const CONTROL = /[\p{Cc}\p{Co}\p{Cn}\u2028\u2029]|(?!\u200d)\p{Cf}/u;
926
- /** One option as it goes over the wire: trimmed, 1 to 80 characters, one line, no links. */
927
- function isReplyText(value) {
928
- return typeof value === "string" && value.length > 0 && value.length <= 80 && value === value.trim() && !CONTROL.test(value) && !LINK.test(value);
929
- }
930
- /** A list of options as it goes over the wire: 1 to 4 valid options, no duplicates. */
931
- function isReplyList(value) {
932
- return Array.isArray(value) && value.length > 0 && value.length <= 4 && value.every(isReplyText) && new Set(value).size === value.length;
933
- }
934
- // src/protocol/validate.ts
935
- const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
936
- const text = (value, min = 0, max = Number.POSITIVE_INFINITY) => typeof value === "string" && value.length >= min && value.length <= max;
937
- const integer = (value, min) => typeof value === "number" && Number.isSafeInteger(value) && value >= min;
938
- const oneOf = (value, options) => options.includes(value);
939
- const messageId = (value) => text(value, 1, 128);
940
- /** A rating handle, or undefined when the value breaks the protocol. */
941
- function feedbackOf(value) {
942
- return record$1(value) && text(value["handle"], 1, 4096) && typeof value["key"] === "string" && /^[0-9a-f]{16,64}$/.test(value["key"]) ? {
943
- handle: value["handle"],
944
- key: value["key"]
945
- } : void 0;
946
- }
947
- /** An absolute http(s) URL as the server sends it; stricter than a browser's lenient parsing. */
948
- function httpUrl(value) {
949
- if (typeof value !== "string" || !/^https?:\/\/[^\s/?#]+[^\s]*$/i.test(value)) return false;
950
- try {
951
- const { protocol } = new URL(value);
952
- return protocol === "http:" || protocol === "https:";
953
- } catch {
954
- return false;
955
- }
956
- }
957
- function citationOf(value) {
958
- if (!record$1(value) || !integer(value["index"], 1) || !text(value["title"], 1)) return void 0;
959
- if (value["url"] !== void 0 && !httpUrl(value["url"])) return void 0;
960
- return {
961
- index: value["index"],
962
- title: value["title"],
963
- ...value["url"] === void 0 ? {} : { url: value["url"] }
964
- };
965
- }
966
- function paramsOf(value) {
967
- if (!record$1(value)) return void 0;
968
- const params = {};
969
- for (const [key, item] of Object.entries(value)) {
970
- if (key.length > 32 || !(text(item, 0, 200) || typeof item === "number" && Number.isFinite(item))) return void 0;
971
- params[key] = item;
972
- }
973
- return params;
974
- }
975
- /** A protocol event received over the wire, or undefined when it breaks the protocol. */
976
- function parseEvent(value) {
977
- if (!record$1(value)) return void 0;
978
- const id = value["messageId"];
979
- switch (value["type"]) {
980
- case "conversation.created": return text(value["resumeToken"], 1) ? {
981
- type: "conversation.created",
982
- resumeToken: value["resumeToken"]
983
- } : void 0;
984
- case "user.ack":
985
- case "message.start": return messageId(id) ? {
986
- type: value["type"],
987
- messageId: id
988
- } : void 0;
989
- case "reasoning": return messageId(id) && oneOf(value["state"], ["started", "done"]) ? {
990
- type: "reasoning",
991
- messageId: id,
992
- state: value["state"]
993
- } : void 0;
994
- case "text.delta": return messageId(id) && text(value["delta"]) ? {
995
- type: "text.delta",
996
- messageId: id,
997
- delta: value["delta"]
998
- } : void 0;
999
- case "citation": {
1000
- const citation = citationOf(value);
1001
- return messageId(id) && citation ? {
1002
- type: "citation",
1003
- messageId: id,
1004
- ...citation
1005
- } : void 0;
1006
- }
1007
- case "tool.status": return messageId(id) && text(value["callId"], 1, 128) && text(value["name"], 1, 64) && oneOf(value["state"], [
1008
- "running",
1009
- "done",
1010
- "error"
1011
- ]) ? {
1012
- type: "tool.status",
1013
- messageId: id,
1014
- callId: value["callId"],
1015
- name: value["name"],
1016
- state: value["state"]
1017
- } : void 0;
1018
- case "replies": return messageId(id) && isReplyList(value["items"]) ? {
1019
- type: "replies",
1020
- messageId: id,
1021
- items: [...value["items"]]
1022
- } : void 0;
1023
- case "message.end": {
1024
- const { resumeToken } = value;
1025
- if (!messageId(id) || !oneOf(value["reason"], MESSAGE_END_REASONS)) return;
1026
- if (resumeToken !== void 0 && !text(resumeToken, 1)) return void 0;
1027
- const feedback = value["feedback"] === void 0 ? void 0 : feedbackOf(value["feedback"]);
1028
- if (value["feedback"] !== void 0 && !feedback) return void 0;
1029
- return {
1030
- type: "message.end",
1031
- messageId: id,
1032
- reason: value["reason"],
1033
- ...typeof resumeToken === "string" ? { resumeToken } : {},
1034
- ...feedback ? { feedback } : {}
1035
- };
1036
- }
1037
- case "error": {
1038
- const { code, message, retryAfterMs, key, params } = value;
1039
- if (!oneOf(code, ERROR_CODES) || !text(message, 0, 500)) return void 0;
1040
- if (retryAfterMs !== void 0 && !integer(retryAfterMs, 0)) return void 0;
1041
- if (key !== void 0 && !text(key, 0, 64)) return void 0;
1042
- const checked = params === void 0 ? void 0 : paramsOf(params);
1043
- if (params !== void 0 && !checked) return void 0;
1044
- return {
1045
- type: "error",
1046
- code,
1047
- message,
1048
- ...retryAfterMs === void 0 ? {} : { retryAfterMs },
1049
- ...key === void 0 ? {} : { key },
1050
- ...checked ? { params: checked } : {}
1051
- };
1052
- }
1053
- default: return;
1054
- }
1055
- }
1056
- function historyMessageOf(value) {
1057
- 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;
1058
- const citations = value["citations"].map(citationOf);
1059
- if (citations.some((citation) => citation === void 0)) return void 0;
1060
- const feedback = value["feedback"] === void 0 ? void 0 : feedbackOf(value["feedback"]);
1061
- if (value["feedback"] !== void 0 && !feedback) return void 0;
1062
- const { replies } = value;
1063
- if (replies !== void 0 && !isReplyList(replies)) return void 0;
1064
- return {
1065
- id: value["id"],
1066
- role: value["role"],
1067
- text: value["text"],
1068
- citations,
1069
- attachments: value["attachments"],
1070
- ...feedback ? { feedback } : {},
1071
- ...replies === void 0 ? {} : { replies: [...replies] }
1072
- };
1073
- }
1074
- /** The answer of `POST /history`, or undefined when it breaks the protocol. */
1075
- function parseHistory(value) {
1076
- if (!record$1(value) || !Array.isArray(value["messages"])) return void 0;
1077
- const messages = value["messages"].map(historyMessageOf);
1078
- return messages.some((message) => message === void 0) ? void 0 : { messages };
1079
- }
1080
- // src/protocol/sse.ts
1081
- const KNOWN_TYPES = new Set(PROTOCOL_EVENT_TYPES);
1082
- /**
1083
- * Validates a framed event against the protocol. Unknown event types are reported, not thrown,
1084
- * so older clients keep working when newer servers add events.
1085
- */
1086
- function decodeEvent(raw) {
1087
- if (!KNOWN_TYPES.has(raw.event)) return {
1088
- ok: false,
1089
- reason: "unknown_type",
1090
- type: raw.event
1091
- };
1092
- let json;
1093
- try {
1094
- json = JSON.parse(raw.data);
1095
- } catch {
1096
- return {
1097
- ok: false,
1098
- reason: "invalid_json",
1099
- type: raw.event
1100
- };
1101
- }
1102
- const event = parseEvent(json);
1103
- if (!event || event.type !== raw.event) return {
1104
- ok: false,
1105
- reason: "invalid_payload",
1106
- type: raw.event
1107
- };
1108
- return {
1109
- ok: true,
1110
- event
1111
- };
1112
- }
1113
- /**
1114
- * Incremental parser for `text/event-stream`, following the WHATWG framing rules: any line ending
1115
- * (CRLF, LF, CR), comments, multi-line `data`, and dispatch on a blank line. Fields other than
1116
- * `event` and `data` are ignored. An unterminated event at end of stream is discarded.
1117
- */
1118
- var SseParser = class {
1119
- #buffer = "";
1120
- #pendingCr = false;
1121
- #started = false;
1122
- #eventType = "";
1123
- #dataLines = [];
1124
- /** Feeds a decoded text chunk and returns the events completed by it. */
1125
- push(chunk) {
1126
- let text = chunk;
1127
- if (!this.#started && text.length > 0) {
1128
- this.#started = true;
1129
- if (text.charCodeAt(0) === 65279) text = text.slice(1);
1130
- }
1131
- if (this.#pendingCr && text.startsWith("\n")) text = text.slice(1);
1132
- this.#pendingCr = false;
1133
- this.#buffer += text;
1134
- const events = [];
1135
- let lineStart = 0;
1136
- for (let i = 0; i < this.#buffer.length; i += 1) {
1137
- const char = this.#buffer[i];
1138
- if (char !== "\n" && char !== "\r") continue;
1139
- const line = this.#buffer.slice(lineStart, i);
1140
- if (char === "\r") {
1141
- if (i + 1 === this.#buffer.length) this.#pendingCr = true;
1142
- else if (this.#buffer[i + 1] === "\n") i += 1;
1143
- }
1144
- lineStart = i + 1;
1145
- const event = this.#processLine(line);
1146
- if (event) events.push(event);
1147
- }
1148
- this.#buffer = this.#buffer.slice(lineStart);
1149
- return events;
1150
- }
1151
- #processLine(line) {
1152
- if (line === "") return this.#dispatch();
1153
- if (line.startsWith(":")) return void 0;
1154
- const colon = line.indexOf(":");
1155
- const field = colon === -1 ? line : line.slice(0, colon);
1156
- let value = colon === -1 ? "" : line.slice(colon + 1);
1157
- if (value.startsWith(" ")) value = value.slice(1);
1158
- if (field === "event") this.#eventType = value;
1159
- else if (field === "data") this.#dataLines.push(value);
1160
- }
1161
- #dispatch() {
1162
- const hasData = this.#dataLines.length > 0;
1163
- const event = {
1164
- event: this.#eventType === "" ? "message" : this.#eventType,
1165
- data: this.#dataLines.join("\n")
1166
- };
1167
- this.#eventType = "";
1168
- this.#dataLines = [];
1169
- return hasData ? event : void 0;
1170
- }
1171
- };
1172
- // src/chat/chat-client.ts
1173
- const json = (value) => ({
1174
- contentType: "application/json",
1175
- body: JSON.stringify(value)
1176
- });
1177
- const RENEW_MARGIN_SECONDS = 30;
1178
- /** The server refused a session and said why: a limit, a switched-off bot, a setup problem. */
1179
- var SessionRefused = class extends Error {
1180
- event;
1181
- constructor(event) {
1182
- super(event.message);
1183
- this.event = event;
1184
- }
1185
- };
1186
- /**
1187
- * Talks to the askdare API from the iframe: keeps the access token in memory, the resume token
1188
- * in best-effort storage, and turns each send into a stream of protocol events. Network and
1189
- * protocol problems are reported as `error` events, never thrown.
1190
- */
1191
- var ChatClient = class {
1192
- #options;
1193
- #fetch;
1194
- #botId;
1195
- #session;
1196
- /** The page context the current conversation already has, so it is sent only when it changes. */
1197
- #sentContext;
1198
- /** Shared by concurrent callers, so parallel uploads end up with one visitor. */
1199
- #opening;
1200
- /**
1201
- * The page's latest askdare('identify'): a token, or null when signed out (ADR-0009). Sent with
1202
- * every session request, so the server re-checks it and the identity ends with the token.
1203
- */
1204
- #identity;
1205
- /** Set when the identity changed: no request may use the previous user's session any more. */
1206
- #identityChanged = false;
1207
- /** Tokens already reported as refused, so a renewal doesn't warn again. */
1208
- #refused;
1209
- /** The signed-in user, as an opaque key from the server; undefined while anonymous. */
1210
- #identityKey;
1211
- /** The previous user's access token while their identity is replaced: renews the visitor only. */
1212
- #renewal;
1213
- constructor(options) {
1214
- this.#options = options;
1215
- this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
1216
- this.#botId = options.botId;
1217
- }
1218
- /** A client-side error: the dictionary text for `key`, else the English message. */
1219
- #error(code, key, english) {
1220
- return {
1221
- type: "error",
1222
- code,
1223
- key,
1224
- message: this.#options.translate?.(key) ?? english
1225
- };
1226
- }
1227
- /** A server error in the visitor's language when it carries a known key. */
1228
- #localize(event) {
1229
- const text = event.key ? this.#options.translate?.(event.key, event.params) : void 0;
1230
- return text ? {
1231
- ...event,
1232
- message: text
1233
- } : event;
1234
- }
1235
- /**
1236
- * Signs the visitor in (a token from the site's backend) or out (null) right away. Resolves to
1237
- * true when the stored conversation belonged to someone else and is gone from this browser.
1238
- */
1239
- async identify(token) {
1240
- if (token === this.#identity) return false;
1241
- this.#identity = token;
1242
- this.#identityChanged = true;
1243
- await this.#opening?.catch(() => void 0);
1244
- const before = this.#resumeKey();
1245
- this.#renewal = this.#session?.accessToken ?? this.#renewal;
1246
- this.#session = void 0;
1247
- try {
1248
- await this.#ensureSession(false);
1249
- } catch {}
1250
- return this.#resumeKey() !== before;
1251
- }
1252
- /**
1253
- * Where this browser keeps the conversation: one place per signed-in user and one for anonymous
1254
- * visits, so signing out or in never hands a conversation to someone else, nor loses it.
1255
- */
1256
- #resumeKey() {
1257
- const base = `askdare:${this.#botId}:resume`;
1258
- return this.#identityKey ? `${base}:${this.#identityKey}` : base;
1259
- }
1260
- /** Forgets the stored conversation so the next message starts a new one. */
1261
- reset() {
1262
- this.#sentContext = void 0;
1263
- this.#options.storage.remove(this.#resumeKey());
1264
- }
1265
- /** True when this browser holds a conversation to resume. */
1266
- hasConversation() {
1267
- return this.#options.storage.get(this.#resumeKey()) !== void 0;
1268
- }
1269
- /** Loads the visible part of the stored conversation; empty when there is none or it is gone. */
1270
- async loadHistory(signal) {
1271
- const resumeToken = this.#options.storage.get(this.#resumeKey());
1272
- if (!resumeToken) return [];
1273
- const response = await this.#authorized("POST", "/history", () => json({
1274
- botId: this.#options.botId,
1275
- resumeToken
1276
- }), signal);
1277
- if (response.status === 404) {
1278
- this.reset();
1279
- return [];
1280
- }
1281
- if (!response.ok) throw new Error(`History request failed with ${response.status}`);
1282
- return parseHistory(await response.json())?.messages ?? [];
1283
- }
1284
- /** Deletes the conversation on the server (best effort) and forgets it in this browser. */
1285
- async deleteConversation() {
1286
- const resumeToken = this.#options.storage.get(this.#resumeKey());
1287
- try {
1288
- if (resumeToken) await this.#authorized("DELETE", "/conversation", () => json({
1289
- botId: this.#options.botId,
1290
- resumeToken
1291
- }));
1292
- } finally {
1293
- this.reset();
1294
- }
1295
- }
1296
- /** This browser's ratings of answers, by feedback key (ADR-0012: askdare stores none). */
1297
- ratings() {
1298
- try {
1299
- const stored = JSON.parse(this.#options.storage.get(this.#ratingsKey()) ?? "{}");
1300
- if (typeof stored !== "object" || stored === null) return {};
1301
- return Object.fromEntries(Object.entries(stored).filter((entry) => entry[1] === "up" || entry[1] === "down"));
1302
- } catch {
1303
- return {};
1304
- }
1305
- }
1306
- /** Remembers a rating, or forgets it with null. Only the latest hundred are kept. */
1307
- rememberRating(key, rating) {
1308
- const { [key]: _previous, ...others } = this.ratings();
1309
- const entries = Object.entries(rating ? {
1310
- ...others,
1311
- [key]: rating
1312
- } : others).slice(-100);
1313
- this.#options.storage.set(this.#ratingsKey(), JSON.stringify(Object.fromEntries(entries)));
1314
- }
1315
- #ratingsKey() {
1316
- return `askdare:${this.#botId}:ratings`;
1317
- }
1318
- /**
1319
- * Sends a rating of one answer (null takes it back) with an optional comment; `handle` comes
1320
- * with the answer. Resolves to what went wrong, in the visitor's language, or undefined.
1321
- */
1322
- async rate(handle, rating, comment) {
1323
- try {
1324
- const response = await this.#authorized("POST", "/feedback", () => json({
1325
- botId: this.#options.botId,
1326
- feedback: handle,
1327
- rating,
1328
- ...comment ? { comment } : {}
1329
- }));
1330
- return response.ok ? void 0 : (await this.#errorFromResponse(response, false)).message;
1331
- } catch (error) {
1332
- return this.#failure(error, "upstream_error").message;
1333
- }
1334
- }
1335
- /** Uploads one file for the next message. The server checks its type and size again. */
1336
- async upload(file, name, signal) {
1337
- try {
1338
- const response = await this.#authorized("POST", "/attachments", () => ({
1339
- contentType: "application/octet-stream",
1340
- body: file,
1341
- headers: {
1342
- "x-askdare-bot": this.#options.botId,
1343
- "x-askdare-filename": encodeURIComponent(name)
1344
- }
1345
- }), signal);
1346
- if (!response.ok) return {
1347
- ok: false,
1348
- message: (await this.#errorFromResponse(response)).message
1349
- };
1350
- const uploaded = (await response.json()).attachment;
1351
- if (typeof uploaded?.id !== "string" || uploaded.kind !== "image" && uploaded.kind !== "pdf" || typeof uploaded.name !== "string") return {
1352
- ok: false,
1353
- message: this.#error("upstream_error", "error.uploadFailed", "The file could not be uploaded.").message
1354
- };
1355
- return {
1356
- ok: true,
1357
- file: {
1358
- id: uploaded.id,
1359
- kind: uploaded.kind,
1360
- name: uploaded.name
1361
- }
1362
- };
1363
- } catch (error) {
1364
- return {
1365
- ok: false,
1366
- message: this.#failure(error, "upstream_error").message
1367
- };
1368
- }
1369
- }
1370
- /** Turns a dictation into text. `languages` are hints such as the browser's and the page's language. */
1371
- async transcribe(audio, languages) {
1372
- try {
1373
- const response = await this.#authorized("POST", "/transcriptions", () => ({
1374
- contentType: "application/octet-stream",
1375
- body: audio,
1376
- headers: {
1377
- "x-askdare-bot": this.#options.botId,
1378
- "x-askdare-languages": languages.join(",")
1379
- }
1380
- }));
1381
- if (!response.ok) return {
1382
- ok: false,
1383
- message: (await this.#errorFromResponse(response)).message
1384
- };
1385
- const body = await response.json();
1386
- return typeof body.text === "string" ? {
1387
- ok: true,
1388
- text: body.text
1389
- } : {
1390
- ok: false,
1391
- message: this.#error("upstream_error", "error.transcriptionFailed", "The recording could not be transcribed.").message
1392
- };
1393
- } catch (error) {
1394
- return {
1395
- ok: false,
1396
- message: this.#failure(error, "upstream_error").message
1397
- };
1398
- }
1399
- }
1400
- async send(message, onEvent, signal) {
1401
- const context = message.context !== this.#sentContext ? message.context : void 0;
1402
- try {
1403
- const response = await this.#authorized("POST", "/messages", () => {
1404
- const resumeToken = this.#options.storage.get(this.#resumeKey());
1405
- return json({
1406
- botId: this.#options.botId,
1407
- text: message.text,
1408
- locale: this.#options.locale,
1409
- ...message.attachments?.length ? { attachments: message.attachments } : {},
1410
- ...context ? { context } : {},
1411
- ...resumeToken ? { resumeToken } : {}
1412
- });
1413
- }, signal);
1414
- if (!response.ok || !response.body) {
1415
- onEvent(await this.#errorFromResponse(response));
1416
- return;
1417
- }
1418
- if (response.headers.get("x-askdare-protocol") !== String(1)) {
1419
- onEvent(this.#error("bot_unavailable", "error.updated", "The assistant was updated. Please reload the page."));
1420
- return;
1421
- }
1422
- await this.#readStream(response.body, (event) => {
1423
- if (event.type === "message.start" && context) this.#sentContext = context;
1424
- onEvent(event);
1425
- }, signal);
1426
- } catch (error) {
1427
- if (signal?.aborted) return;
1428
- onEvent(this.#failure(error, error instanceof DOMException && error.name === "TimeoutError" ? "timeout" : "upstream_error"));
1429
- }
1430
- }
1431
- /** Sends an authenticated request, renewing an expired session once. */
1432
- async #authorized(method, path, request, signal) {
1433
- const attempt = async (renew) => {
1434
- const session = await this.#ensureSession(renew);
1435
- const { contentType, body, headers } = request();
1436
- return this.#fetch(`${this.#options.basePath}${path}`, {
1437
- method,
1438
- headers: {
1439
- ...headers,
1440
- "content-type": contentType,
1441
- authorization: `Bearer ${session.accessToken}`
1442
- },
1443
- body,
1444
- ...signal ? { signal } : {}
1445
- });
1446
- };
1447
- const first = await attempt(false);
1448
- return first.status === 401 ? attempt(true) : first;
1449
- }
1450
- async #ensureSession(renew) {
1451
- const now = Date.now() / 1e3;
1452
- if (!renew && !this.#identityChanged && this.#session && this.#session.expiresAt - RENEW_MARGIN_SECONDS > now) return this.#session;
1453
- this.#opening ??= this.#openSession().finally(() => {
1454
- this.#opening = void 0;
1455
- });
1456
- return this.#opening;
1457
- }
1458
- /** Not tied to one caller's signal, because other callers may be waiting for the same session. */
1459
- async #openSession() {
1460
- const resumeToken = this.#options.storage.get(this.#resumeKey());
1461
- const accessToken = this.#session?.accessToken ?? this.#renewal;
1462
- const identityToken = this.#identity;
1463
- const sentFrom = this.#resumeKey();
1464
- const response = await this.#fetch(`${this.#options.basePath}/session`, {
1465
- method: "POST",
1466
- headers: { "content-type": "application/json" },
1467
- body: JSON.stringify({
1468
- botId: this.#options.botId,
1469
- ...resumeToken ? { resumeToken } : {},
1470
- ...accessToken ? { accessToken } : {},
1471
- ...identityToken === void 0 ? {} : { identityToken }
1472
- })
1473
- });
1474
- if (!response.ok) throw new SessionRefused(await this.#errorFromResponse(response, false));
1475
- const body = await response.json();
1476
- if (this.#identity === identityToken) this.#identityChanged = false;
1477
- this.#renewal = void 0;
1478
- this.#identityKey = body.identified ? body.identityKey : void 0;
1479
- if (identityToken && !body.identified && this.#refused !== identityToken) {
1480
- this.#refused = identityToken;
1481
- console.warn(`[askdare] askdare('identify') was refused (${body.identityProblem ?? "unknown"}); the chat continues anonymously.`);
1482
- }
1483
- if (body.resumeToken) {
1484
- this.#options.storage.set(this.#resumeKey(), body.resumeToken);
1485
- if (sentFrom !== this.#resumeKey()) this.#options.storage.remove(sentFrom);
1486
- } else if (!body.resumable && resumeToken && sentFrom === this.#resumeKey()) this.reset();
1487
- this.#session = {
1488
- accessToken: body.accessToken,
1489
- expiresAt: body.expiresAt
1490
- };
1491
- return this.#session;
1492
- }
1493
- /** What to show for a request that threw: the server's reason for refusing a session, if any. */
1494
- #failure(error, code) {
1495
- return error instanceof SessionRefused ? error.event : this.#connectionError(code);
1496
- }
1497
- #connectionError(code) {
1498
- return this.#error(code, "error.connection", "Connection problem. Please try again.");
1499
- }
1500
- async #errorFromResponse(response, forgetMissing = true) {
1501
- let body = {};
1502
- try {
1503
- body = await response.json();
1504
- } catch {}
1505
- if (forgetMissing && response.status === 404 && body.error?.code === "not_found") this.reset();
1506
- const result = decodeEvent({
1507
- event: "error",
1508
- data: JSON.stringify({
1509
- type: "error",
1510
- ...body.error
1511
- })
1512
- });
1513
- 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.");
1514
- }
1515
- async #readStream(body, onEvent, signal) {
1516
- const reader = body.getReader();
1517
- const decoder = new TextDecoder();
1518
- const parser = new SseParser();
1519
- const watchdogMs = this.#options.watchdogMs ?? 45e3;
1520
- let timer;
1521
- let stalled = false;
1522
- const arm = () => {
1523
- clearTimeout(timer);
1524
- timer = setTimeout(() => {
1525
- stalled = true;
1526
- reader.cancel();
1527
- }, watchdogMs);
1528
- };
1529
- const onAbort = () => void reader.cancel();
1530
- signal?.addEventListener("abort", onAbort, { once: true });
1531
- try {
1532
- arm();
1533
- for (;;) {
1534
- const { done, value } = await reader.read();
1535
- if (done) break;
1536
- arm();
1537
- for (const raw of parser.push(decoder.decode(value, { stream: true }))) {
1538
- const result = decodeEvent(raw);
1539
- if (!result.ok) continue;
1540
- if (result.event.type === "conversation.created") this.#options.storage.set(this.#resumeKey(), result.event.resumeToken);
1541
- else if (result.event.type === "message.end" && result.event.resumeToken) this.#options.storage.set(this.#resumeKey(), result.event.resumeToken);
1542
- else if (result.event.type === "error" && result.event.code === "not_found") this.reset();
1543
- onEvent(result.event.type === "error" ? this.#localize(result.event) : result.event);
1544
- }
1545
- }
1546
- if (stalled) onEvent(this.#error("timeout", "error.stalled", "The connection stalled. Please try again."));
1547
- } finally {
1548
- clearTimeout(timer);
1549
- signal?.removeEventListener("abort", onAbort);
1550
- }
1551
- }
1552
- };
1553
- // src/chat/events.ts
1554
- /**
1555
- * Listeners by event type, or '*' for every type; used by the chat store and by the loader on the
1556
- * host page. Each event is frozen, so one listener can't change what the next one gets. A listener
1557
- * that throws can't break the chat: it is logged in one line, without details, and the others
1558
- * still run.
1559
- */
1560
- function eventListeners() {
1561
- const listeners = [];
1562
- const off = (type, listener) => {
1563
- const index = listeners.findIndex(([t, l]) => t === type && l === listener);
1564
- if (index >= 0) listeners.splice(index, 1);
1565
- };
1566
- return {
1567
- on(type, listener) {
1568
- if (typeof type === "string" && typeof listener === "function") listeners.push([type, listener]);
1569
- else console.warn("[askdare] askdare('on') expects an event type and a function.");
1570
- return () => off(type, listener);
1571
- },
1572
- off,
1573
- emit(event) {
1574
- Object.freeze(event);
1575
- for (const [type, listener] of [...listeners]) {
1576
- if (type !== "*" && type !== event.type) continue;
1577
- try {
1578
- listener(event);
1579
- } catch {
1580
- console.warn(`[askdare] A listener for "${event.type}" threw.`);
1581
- }
1582
- }
1583
- }
1584
- };
1585
- }
1586
- // src/chat/recorder.ts
1587
- /** Formats OpenAI transcribes, best first: WebM/Opus (Chrome, Firefox, Edge), then MP4 (Safari). */
1588
- const MIME_TYPES = [
1589
- "audio/webm;codecs=opus",
1590
- "audio/webm",
1591
- "audio/mp4;codecs=mp4a.40.2",
1592
- "audio/mp4"
1593
- ];
1594
- /** Speech needs little: about 240 KB per minute where the browser honours it. */
1595
- const BITS_PER_SECOND = 32e3;
1596
- function recordingMimeType() {
1597
- if (typeof MediaRecorder === "undefined") return void 0;
1598
- return MIME_TYPES.find((type) => MediaRecorder.isTypeSupported(type));
1599
- }
1600
- /** True when this browser can record and the embedding page's policy lets the iframe use the microphone. */
1601
- function canRecord() {
1602
- if (!navigator.mediaDevices?.getUserMedia || !recordingMimeType()) return false;
1603
- return document.featurePolicy?.allowsFeature("microphone") ?? true;
1604
- }
1605
- var MicrophoneError = class extends Error {
1606
- reason;
1607
- constructor(reason, options) {
1608
- super(`Microphone ${reason}`, options);
1609
- this.reason = reason;
1610
- }
1611
- };
1612
- /**
1613
- * Asks for the microphone and starts recording. Recording stops by itself after `maxSeconds`,
1614
- * even in a hidden frame. Throws {@link MicrophoneError}.
1615
- */
1616
- async function startRecording(maxSeconds) {
1617
- const mimeType = recordingMimeType();
1618
- if (!mimeType) throw new MicrophoneError("failed");
1619
- let stream;
1620
- try {
1621
- stream = await navigator.mediaDevices.getUserMedia({ audio: {
1622
- echoCancellation: true,
1623
- noiseSuppression: true
1624
- } });
1625
- } catch (error) {
1626
- const name = error instanceof DOMException ? error.name : "";
1627
- if (name === "NotAllowedError" || name === "SecurityError") throw new MicrophoneError("blocked", { cause: error });
1628
- if (name === "NotFoundError" || name === "OverconstrainedError") throw new MicrophoneError("missing", { cause: error });
1629
- throw new MicrophoneError("failed", { cause: error });
1630
- }
1631
- try {
1632
- return record(stream, mimeType, maxSeconds);
1633
- } catch (error) {
1634
- for (const track of stream.getTracks()) track.stop();
1635
- throw new MicrophoneError("failed", { cause: error });
1636
- }
1637
- }
1638
- function record(stream, mimeType, maxSeconds) {
1639
- const recorder = new MediaRecorder(stream, {
1640
- mimeType,
1641
- audioBitsPerSecond: BITS_PER_SECOND
1642
- });
1643
- const chunks = [];
1644
- recorder.addEventListener("dataavailable", (event) => {
1645
- if (event.data.size > 0) chunks.push(event.data);
1646
- });
1647
- const stopped = new Promise((resolve) => recorder.addEventListener("stop", () => resolve(), { once: true }));
1648
- const context = new AudioContext();
1649
- const analyser = context.createAnalyser();
1650
- analyser.fftSize = 512;
1651
- context.createMediaStreamSource(stream).connect(analyser);
1652
- const samples = new Uint8Array(analyser.fftSize);
1653
- const release = () => {
1654
- for (const track of stream.getTracks()) track.stop();
1655
- context.close();
1656
- };
1657
- let limit;
1658
- const halt = () => {
1659
- clearTimeout(limit);
1660
- if (recorder.state !== "inactive") recorder.stop();
1661
- };
1662
- recorder.start(250);
1663
- limit = setTimeout(halt, maxSeconds * 1e3);
1664
- return {
1665
- level() {
1666
- analyser.getByteTimeDomainData(samples);
1667
- let sum = 0;
1668
- for (const sample of samples) {
1669
- const value = (sample - 128) / 128;
1670
- sum += value * value;
1671
- }
1672
- return Math.min(1, Math.sqrt(sum / samples.length) * 4);
1673
- },
1674
- async stop() {
1675
- halt();
1676
- await stopped;
1677
- release();
1678
- return new Blob(chunks, { type: mimeType.split(";")[0] ?? mimeType });
1679
- },
1680
- cancel() {
1681
- halt();
1682
- release();
1683
- }
1684
- };
1685
- }
1686
- // src/chat/reducer.ts
1687
- /** Looks texts up in a bot's dictionary; an unknown key shows as itself. */
1688
- function translator(texts) {
1689
- return (key, params) => formatText(texts[key] ?? key, params);
1690
- }
1691
- const fromHistory = (message) => ({
1692
- id: message.id,
1693
- role: message.role,
1694
- text: message.text,
1695
- citations: message.citations,
1696
- attachments: message.attachments,
1697
- status: "done",
1698
- ...message.feedback ? { feedback: message.feedback } : {},
1699
- ...message.replies ? { replies: message.replies } : {}
1700
- });
1701
- /** The messages after one protocol event of a streamed answer. */
1702
- function applyEvent(messages, event) {
1703
- const update = (id, change) => messages.map((message) => message.id === id ? change(message) : message);
1704
- switch (event.type) {
1705
- case "message.start": return [...messages, {
1706
- id: event.messageId,
1707
- role: "assistant",
1708
- text: "",
1709
- citations: [],
1710
- attachments: 0,
1711
- status: "streaming"
1712
- }];
1713
- case "text.delta": return update(event.messageId, (message) => ({
1714
- ...message,
1715
- text: message.text + event.delta
1716
- }));
1717
- case "citation": return update(event.messageId, (message) => ({
1718
- ...message,
1719
- citations: [...message.citations, {
1720
- index: event.index,
1721
- title: event.title,
1722
- url: event.url
1723
- }]
1724
- }));
1725
- case "replies": return update(event.messageId, (message) => ({
1726
- ...message,
1727
- replies: event.items
1728
- }));
1729
- case "message.end": return update(event.messageId, (message) => ({
1730
- ...message,
1731
- status: "done",
1732
- ...event.feedback ? { feedback: event.feedback } : {}
1733
- }));
1734
- default: return messages;
1735
- }
1736
- }
1737
- /** Marks the answer that was streaming when the turn failed. */
1738
- const failStreaming = (messages) => messages.map((message) => message.status === "streaming" ? {
1739
- ...message,
1740
- status: "error"
1741
- } : message);
1742
- /** What the assistant is doing right now, shown while no text streams; undefined: unchanged. */
1743
- function activityFor(event, t) {
1744
- if (event.type === "reasoning") return event.state === "started" ? t("status.thinking") : null;
1745
- if (event.type === "tool.status") return event.state === "running" ? event.name === "file_search" ? t("status.searching") : t("status.tool", { name: event.name }) : null;
1746
- if (event.type === "text.delta" || event.type === "message.end") return null;
1747
- }
1748
- // src/chat/storage.ts
1749
- function browserStorage() {
1750
- return {
1751
- get(key) {
1752
- try {
1753
- return window.localStorage.getItem(key) ?? void 0;
1754
- } catch {
1755
- return;
1756
- }
1757
- },
1758
- set(key, value) {
1759
- try {
1760
- window.localStorage.setItem(key, value);
1761
- } catch {}
1762
- },
1763
- remove(key) {
1764
- try {
1765
- window.localStorage.removeItem(key);
1766
- } catch {}
1767
- }
1768
- };
1769
- }
1770
- // src/chat/store.ts
1771
- /** How long a focus request waits for its element to appear, such as the field after a dictation. */
1772
- const FOCUS_WAIT_MS = 2e3;
1773
- /**
1774
- * Where the chat wants focus next. A request stays pending until a listener for its target really
1775
- * takes it: the message field comes back only after a dictation ends, and a listener whose element
1776
- * has just unmounted must not swallow the request. Only the latest request is kept.
1777
- */
1778
- function focusRequests() {
1779
- const listeners = {
1780
- input: /* @__PURE__ */ new Set(),
1781
- dictation: /* @__PURE__ */ new Set()
1782
- };
1783
- let pending;
1784
- const deliver = (target, explicit) => {
1785
- let taken = false;
1786
- for (const listener of listeners[target]) taken = listener(explicit) || taken;
1787
- return taken;
1788
- };
1789
- return {
1790
- focus(target, explicit = false) {
1791
- pending = deliver(target, explicit) ? void 0 : {
1792
- target,
1793
- explicit,
1794
- at: Date.now()
1795
- };
1796
- },
1797
- onFocus(target, listener) {
1798
- listeners[target].add(listener);
1799
- if (pending?.target === target && Date.now() - pending.at < FOCUS_WAIT_MS && listener(pending?.explicit ?? false)) pending = void 0;
1800
- return () => listeners[target].delete(listener);
1801
- }
1802
- };
1803
- }
1804
- const MICROPHONE_MESSAGES = {
1805
- blocked: "microphone.blocked",
1806
- missing: "microphone.missing",
1807
- failed: "microphone.failed"
1808
- };
1809
- /** As the server's limit for a rating's comment. */
1810
- const MAX_COMMENT$1 = 500;
1811
- const megabytes = (bytes) => `${Math.floor(bytes / 1e5) / 10} MB`;
1812
- function revokePreviews(files) {
1813
- for (const file of files) if (file.previewUrl) URL.revokeObjectURL(file.previewUrl);
1814
- }
1815
- /** The chat's state and actions for one bot, without any UI (ADR-0011). */
1816
- function createChatStore(config, options = {}) {
1817
- const t = translator(config.widget.texts);
1818
- const client = options.client ?? new ChatClient({
1819
- basePath: config.basePath,
1820
- botId: config.botId,
1821
- locale: config.widget.locale,
1822
- storage: browserStorage(),
1823
- translate: (key, params) => config.widget.texts[key] === void 0 ? void 0 : t(key, params)
1824
- });
1825
- const recorder = options.recorder ?? {
1826
- canRecord,
1827
- startRecording
1828
- };
1829
- const voice = config.voice;
1830
- const allowed = config.attachments;
1831
- const initial = {
1832
- phase: "starting",
1833
- busy: false,
1834
- messages: [],
1835
- draft: "",
1836
- error: void 0,
1837
- activity: null,
1838
- files: [],
1839
- dictation: "idle",
1840
- elapsed: 0,
1841
- canDictate: false,
1842
- page: options.page ?? {},
1843
- ratings: {},
1844
- commenting: void 0
1845
- };
1846
- let state = initial;
1847
- const listeners = /* @__PURE__ */ new Set();
1848
- const set = (change) => {
1849
- state = {
1850
- ...state,
1851
- ...change
1852
- };
1853
- for (const listener of listeners) listener();
1854
- };
1855
- const events = eventListeners();
1856
- const bot = config.botId;
1857
- /** `ready` fires once per chat, not again when a sign-in reloads the conversation. */
1858
- let announced = false;
1859
- const announce = () => {
1860
- if (announced) return;
1861
- announced = true;
1862
- events.emit({
1863
- type: "ready",
1864
- bot
1865
- });
1866
- };
1867
- const { focus, onFocus } = focusRequests();
1868
- let localId = 0;
1869
- const nextLocalId = () => `local_${++localId}`;
1870
- /** The current run between start() and stop(); async work of an earlier run stops there. */
1871
- let run;
1872
- /** Signed in (or anonymous) for good: requests may go out. */
1873
- let identityReady = false;
1874
- /** The visible conversation is the one this browser should show. */
1875
- let loaded = false;
1876
- let identities = Promise.resolve();
1877
- let history;
1878
- /** The turn being answered, aborted when the chat stops. */
1879
- let turn;
1880
- /** Reports how the turn being answered ended; stop() calls it before anyone stops listening. */
1881
- let endTurn;
1882
- /**
1883
- * Per rating key: what the server confirmed, and the latest request. Ratings of one answer go out
1884
- * one at a time, so the server ends with the latest that succeeded and a failure rolls back to it.
1885
- */
1886
- const rated = /* @__PURE__ */ new Map();
1887
- /** In-flight uploads by pending file key, cancelled when the file is removed. */
1888
- const uploads = /* @__PURE__ */ new Map();
1889
- let recording;
1890
- /** Set while the browser asks for the microphone, so a double click starts one recording. */
1891
- let starting = false;
1892
- /** Ends the dictation at maxSeconds; a timer, because animation frames stop in hidden frames. */
1893
- let limit;
1894
- let clock;
1895
- /** Stops a dictation and throws the audio away. */
1896
- const discardRecording = () => {
1897
- clearTimeout(limit);
1898
- clearInterval(clock);
1899
- recording?.cancel();
1900
- recording = void 0;
1901
- if (state.dictation !== "idle") set({ dictation: "idle" });
1902
- };
1903
- /** Restores the stored conversation (about 2 s upstream, so the chat shows a loading state). */
1904
- const loadHistory = () => {
1905
- history?.abort();
1906
- if (!client.hasConversation()) {
1907
- history = void 0;
1908
- loaded = true;
1909
- set({ phase: "ready" });
1910
- announce();
1911
- return;
1912
- }
1913
- const controller = new AbortController();
1914
- history = controller;
1915
- set({ phase: "loading" });
1916
- client.loadHistory(controller.signal).then((messages) => {
1917
- if (controller.signal.aborted) return;
1918
- loaded = true;
1919
- set({ messages: messages.map(fromHistory) });
1920
- }).catch((error) => {
1921
- if (!controller.signal.aborted) set({ error: error instanceof SessionRefused ? error.message : t("error.history") });
1922
- }).finally(() => {
1923
- if (history !== controller) return;
1924
- history = void 0;
1925
- set({ phase: "ready" });
1926
- if (loaded) announce();
1927
- });
1928
- };
1929
- const onVisibility = () => {
1930
- if (document.visibilityState === "hidden") discardRecording();
1931
- };
1932
- const cancelUploads = (keys) => {
1933
- for (const key of [...keys]) {
1934
- uploads.get(key)?.abort();
1935
- uploads.delete(key);
1936
- }
1937
- };
1938
- const attach = async (file) => {
1939
- if (!allowed) return;
1940
- const key = nextLocalId();
1941
- const update = (change) => set({ files: state.files.map((item) => item.key === key ? {
1942
- ...item,
1943
- ...change
1944
- } : item) });
1945
- const controller = new AbortController();
1946
- uploads.set(key, controller);
1947
- set({ files: [...state.files, {
1948
- key,
1949
- name: file.name,
1950
- status: "uploading"
1951
- }] });
1952
- const fail = (error) => {
1953
- uploads.delete(key);
1954
- if (!controller.signal.aborted) update({
1955
- status: "error",
1956
- error
1957
- });
1958
- };
1959
- let prepared;
1960
- try {
1961
- prepared = await prepareFile(file, allowed);
1962
- } catch {
1963
- fail(t("attachment.unsupported"));
1964
- return;
1965
- }
1966
- if (prepared.blob.size > allowed.maxBytes) {
1967
- fail(t("attachment.tooLarge", { size: megabytes(allowed.maxBytes) }));
1968
- return;
1969
- }
1970
- if (controller.signal.aborted) return;
1971
- const previewUrl = prepared.kind === "image" ? URL.createObjectURL(prepared.blob) : void 0;
1972
- update({
1973
- name: prepared.name,
1974
- kind: prepared.kind,
1975
- previewUrl
1976
- });
1977
- const result = await client.upload(prepared.blob, prepared.name, controller.signal);
1978
- uploads.delete(key);
1979
- if (controller.signal.aborted) {
1980
- revokePreviews([{ previewUrl }]);
1981
- return;
1982
- }
1983
- update(result.ok ? {
1984
- status: "ready",
1985
- handle: result.file.id,
1986
- name: result.file.name
1987
- } : {
1988
- status: "error",
1989
- error: result.message
1990
- });
1991
- };
1992
- const actions = {
1993
- async send(picked) {
1994
- const text = (picked ?? state.draft).trim();
1995
- if (picked === void 0 ? !canSend(state) : state.phase !== "ready" || state.busy || text === "") return;
1996
- const ready = picked === void 0 ? state.files.filter((file) => file.status === "ready") : [];
1997
- const files = ready.flatMap(({ name, kind, previewUrl }) => kind ? [{
1998
- name,
1999
- kind,
2000
- previewUrl
2001
- }] : []);
2002
- const handles = ready.flatMap((file) => file.handle ? [file.handle] : []);
2003
- const latest = state.messages.at(-1);
2004
- const source = picked === void 0 ? "typed" : latest?.role === "assistant" && latest.replies?.includes(text) ? "reply" : "starter";
2005
- if (picked === void 0) revokePreviews(state.files.filter((file) => file.status !== "ready"));
2006
- set({
2007
- ...picked === void 0 ? {
2008
- files: [],
2009
- draft: ""
2010
- } : {},
2011
- error: void 0,
2012
- busy: true,
2013
- messages: [...state.messages, {
2014
- id: nextLocalId(),
2015
- role: "user",
2016
- text,
2017
- citations: [],
2018
- attachments: files.length,
2019
- files,
2020
- status: "done"
2021
- }]
2022
- });
2023
- events.emit({
2024
- type: "message.sent",
2025
- bot,
2026
- length: [...text].length,
2027
- attachments: files.length,
2028
- source
2029
- });
2030
- const context = config.pageContext ? state.page.context : void 0;
2031
- const controller = new AbortController();
2032
- turn = controller;
2033
- const begun = Date.now();
2034
- let failed = false;
2035
- let answer;
2036
- const end = (outcome) => {
2037
- if (endTurn !== end) return;
2038
- endTurn = void 0;
2039
- const received = state.messages.find((message) => message.id === answer);
2040
- events.emit({
2041
- type: "message.received",
2042
- bot,
2043
- outcome,
2044
- durationMs: Date.now() - begun,
2045
- citations: received?.citations.length ?? 0
2046
- });
2047
- };
2048
- endTurn = end;
2049
- await client.send({
2050
- text,
2051
- attachments: handles,
2052
- context
2053
- }, (event) => {
2054
- const next = activityFor(event, t);
2055
- if (next !== void 0) set({ activity: next });
2056
- if (event.type === "message.start") answer = event.messageId;
2057
- if (event.type === "error") {
2058
- failed = true;
2059
- events.emit({
2060
- type: "error",
2061
- bot,
2062
- code: event.code
2063
- });
2064
- set({
2065
- error: event.message,
2066
- messages: failStreaming(state.messages)
2067
- });
2068
- return;
2069
- }
2070
- set({ messages: applyEvent(state.messages, event) });
2071
- }, controller.signal);
2072
- if (turn === controller) turn = void 0;
2073
- end(failed ? "failed" : controller.signal.aborted ? "stopped" : "completed");
2074
- if (controller.signal.aborted) {
2075
- set({
2076
- activity: null,
2077
- busy: false,
2078
- messages: failStreaming(state.messages)
2079
- });
2080
- return;
2081
- }
2082
- set({
2083
- activity: null,
2084
- busy: false
2085
- });
2086
- focus("input");
2087
- },
2088
- setDraft(text) {
2089
- set({ draft: text });
2090
- },
2091
- addFiles(files) {
2092
- if (!allowed || files.length === 0) return;
2093
- const room = allowed.maxPerMessage - state.files.length;
2094
- if (files.length > room) set({ error: t("attachment.tooMany", { count: allowed.maxPerMessage }) });
2095
- for (const file of files.slice(0, Math.max(0, room))) attach(file);
2096
- },
2097
- removeFile(key) {
2098
- cancelUploads([key]);
2099
- revokePreviews(state.files.filter((item) => item.key === key));
2100
- set({ files: state.files.filter((item) => item.key !== key) });
2101
- },
2102
- async startDictation() {
2103
- if (!voice || recording || starting || state.dictation !== "idle") return;
2104
- set({ error: void 0 });
2105
- starting = true;
2106
- let started;
2107
- try {
2108
- started = await recorder.startRecording(voice.maxSeconds);
2109
- } catch (error) {
2110
- set({ error: t(MICROPHONE_MESSAGES[error instanceof MicrophoneError ? error.reason : "failed"]) });
2111
- return;
2112
- } finally {
2113
- starting = false;
2114
- }
2115
- if (!run) {
2116
- started.cancel();
2117
- return;
2118
- }
2119
- recording = started;
2120
- set({
2121
- elapsed: 0,
2122
- dictation: "recording"
2123
- });
2124
- focus("dictation");
2125
- limit = setTimeout(() => void actions.finishDictation(), voice.maxSeconds * 1e3);
2126
- const begun = Date.now();
2127
- clock = setInterval(() => {
2128
- const elapsed = Math.min(voice.maxSeconds, Math.floor((Date.now() - begun) / 1e3));
2129
- if (elapsed !== state.elapsed) set({ elapsed });
2130
- }, 250);
2131
- },
2132
- async finishDictation() {
2133
- const current = recording;
2134
- if (!current) return;
2135
- recording = void 0;
2136
- clearTimeout(limit);
2137
- clearInterval(clock);
2138
- set({ dictation: "transcribing" });
2139
- const audio = await current.stop();
2140
- if (audio.size < 1e3) {
2141
- set({
2142
- dictation: "idle",
2143
- error: t("dictation.empty")
2144
- });
2145
- return;
2146
- }
2147
- const languages = [...navigator.languages.slice(0, 2), config.widget.locale];
2148
- const result = await client.transcribe(audio, languages);
2149
- set({ dictation: "idle" });
2150
- if (!result.ok) set({ error: result.message });
2151
- else if (result.text) {
2152
- const draft = state.draft;
2153
- set({ draft: draft.trim() ? `${draft.trimEnd()} ${result.text}` : result.text });
2154
- }
2155
- focus("input");
2156
- },
2157
- cancelDictation() {
2158
- discardRecording();
2159
- focus("input");
2160
- },
2161
- async newConversation() {
2162
- set({ busy: true });
2163
- await client.deleteConversation().catch(() => void 0);
2164
- revokePreviews(state.messages.flatMap((message) => message.files ?? []));
2165
- cancelUploads(uploads.keys());
2166
- revokePreviews(state.files);
2167
- set({
2168
- files: [],
2169
- messages: [],
2170
- error: void 0,
2171
- busy: false,
2172
- commenting: void 0
2173
- });
2174
- events.emit({
2175
- type: "conversation.reset",
2176
- bot
2177
- });
2178
- focus("input");
2179
- },
2180
- async rate(messageId, rating, comment) {
2181
- const feedback = state.messages.find((message) => message.id === messageId)?.feedback;
2182
- if (!feedback) return;
2183
- const { key } = feedback;
2184
- const before = state.ratings[key];
2185
- const text = comment?.trim().slice(0, MAX_COMMENT$1);
2186
- const commented = rating === "down" && Boolean(text);
2187
- const ratings = (value) => {
2188
- const { [key]: _previous, ...others } = state.ratings;
2189
- return value ? {
2190
- ...others,
2191
- [key]: value
2192
- } : others;
2193
- };
2194
- const entry = rated.get(key) ?? {
2195
- confirmed: before,
2196
- latest: 0,
2197
- queue: Promise.resolve()
2198
- };
2199
- rated.set(key, entry);
2200
- const request = ++entry.latest;
2201
- set({
2202
- ratings: ratings(rating),
2203
- error: void 0,
2204
- commenting: commented || rating === "down" && before !== "down" ? messageId : void 0
2205
- });
2206
- const sent = entry.queue.then(() => client.rate(feedback.handle, rating, rating === null ? void 0 : text));
2207
- entry.queue = sent;
2208
- const problem = await sent;
2209
- if (!problem) {
2210
- entry.confirmed = rating ?? void 0;
2211
- client.rememberRating(key, rating);
2212
- events.emit({
2213
- type: "feedback",
2214
- bot,
2215
- rating,
2216
- commented
2217
- });
2218
- }
2219
- if (entry.latest !== request) return;
2220
- if (problem) set({
2221
- ratings: ratings(entry.confirmed),
2222
- error: problem,
2223
- ...commented ? {} : { commenting: void 0 }
2224
- });
2225
- else if (commented && state.commenting === messageId) set({ commenting: void 0 });
2226
- },
2227
- dismissComment() {
2228
- if (state.commenting !== void 0) set({ commenting: void 0 });
2229
- },
2230
- focus() {
2231
- focus("input", true);
2232
- }
2233
- };
2234
- return {
2235
- config,
2236
- actions,
2237
- t,
2238
- subscribe(listener) {
2239
- listeners.add(listener);
2240
- return () => listeners.delete(listener);
2241
- },
2242
- getSnapshot: () => state,
2243
- getServerSnapshot: () => initial,
2244
- start(startOptions = {}) {
2245
- if (run) return;
2246
- const current = {};
2247
- run = current;
2248
- set({
2249
- ratings: client.ratings(),
2250
- canDictate: voice !== void 0 && recorder.canRecord(),
2251
- ...state.phase === "starting" && client.hasConversation() ? { phase: "loading" } : {}
2252
- });
2253
- document.addEventListener("visibilitychange", onVisibility);
2254
- (startOptions.handshake ?? Promise.resolve()).then(() => identities, () => identities).finally(() => {
2255
- if (run !== current) return;
2256
- identityReady = true;
2257
- if (!loaded) loadHistory();
2258
- else {
2259
- if (state.phase !== "ready") set({ phase: "ready" });
2260
- announce();
2261
- }
2262
- });
2263
- },
2264
- stop() {
2265
- if (!run) return;
2266
- run = void 0;
2267
- document.removeEventListener("visibilitychange", onVisibility);
2268
- history?.abort();
2269
- history = void 0;
2270
- endTurn?.("stopped");
2271
- turn?.abort();
2272
- turn = void 0;
2273
- discardRecording();
2274
- if (uploads.size > 0) {
2275
- cancelUploads(uploads.keys());
2276
- set({ files: state.files.filter((file) => file.status !== "uploading") });
2277
- }
2278
- },
2279
- identify(token) {
2280
- identities = identities.then(async () => {
2281
- if (!await client.identify(token)) return;
2282
- loaded = false;
2283
- set({
2284
- messages: [],
2285
- error: void 0,
2286
- commenting: void 0
2287
- });
2288
- if (identityReady && run) loadHistory();
2289
- });
2290
- },
2291
- configure(page) {
2292
- set({ page });
2293
- },
2294
- hide() {
2295
- discardRecording();
2296
- },
2297
- level: () => recording?.level(),
2298
- onFocus,
2299
- onEvent: (listener) => events.on("*", listener)
2300
- };
2301
- }
2302
- // src/react/root.tsx
2303
- /**
2304
- * Runs one bot's chat for the components inside it, without rendering any element. Its props
2305
- * take what `askdare('identify')` and `askdare('configure')` take, checked the same way.
2306
- */
2307
- function Root({ config, identity, context, greeting, starters, onEvent, children }) {
2308
- 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}".`);
2309
- 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}.`);
2310
- const page = pageOptions({
2311
- greeting,
2312
- starters,
2313
- context
2314
- });
2315
- const id = `${config.basePath} ${config.botId} ${config.widget.locale}`;
2316
- const [held, setHeld] = useState(() => ({
2317
- id,
2318
- store: createChatStore(config, { page })
2319
- }));
2320
- let { store } = held;
2321
- if (held.id !== id) {
2322
- store = createChatStore(config, { page });
2323
- setHeld({
2324
- id,
2325
- store
2326
- });
2327
- }
2328
- const listener = useRef(onEvent);
2329
- useLayoutEffect(() => {
2330
- listener.current = onEvent;
2331
- }, [onEvent]);
2332
- useEffect(() => {
2333
- if (identity === void 0) return;
2334
- const token = identityToken(identity);
2335
- if (token !== void 0) store.identify(token);
2336
- }, [identity, store]);
2337
- useEffect(() => {
2338
- const stopEvents = store.onEvent((event) => listener.current?.(event));
2339
- store.start();
2340
- return () => {
2341
- store.stop();
2342
- stopEvents();
2343
- };
2344
- }, [store]);
2345
- const key = JSON.stringify(page);
2346
- useEffect(() => {
2347
- if (JSON.stringify(store.getSnapshot().page) !== key) store.configure(page);
2348
- }, [key, store]);
2349
- return /* @__PURE__ */ jsx(ChatProvider, {
2350
- store,
2351
- children
2352
- });
2353
- }
2354
650
  // src/react/theme.tsx
2355
651
  /** React 19 hoists these into <head> and waits for them, in this order, before showing the chat. */
2356
652
  const PRECEDENCE = "askdare";
@@ -2533,15 +829,7 @@ function DefaultFooter() {
2533
829
  })] })
2534
830
  ] }) : /* @__PURE__ */ jsx(Recorder, { cancelIcon: /* @__PURE__ */ jsx(CloseIcon, {}) })
2535
831
  })] }),
2536
- bot.disclosure !== false && /* @__PURE__ */ jsxs("p", {
2537
- "data-ask-part": "disclosure",
2538
- children: [t("disclosure.text"), bot.disclosure.privacyUrl && /* @__PURE__ */ jsxs(Fragment, { children: [" ", /* @__PURE__ */ jsx("a", {
2539
- href: bot.disclosure.privacyUrl,
2540
- target: "_blank",
2541
- rel: "noopener noreferrer",
2542
- children: t("disclosure.privacy")
2543
- })] })]
2544
- })
832
+ /* @__PURE__ */ jsx(Disclosure, {})
2545
833
  ] });
2546
834
  }
2547
835
  // src/react/skin/avatar.tsx
@@ -2686,9 +974,9 @@ function Feedback() {
2686
974
  }
2687
975
  // src/react/skin/message.tsx
2688
976
  /**
2689
- * One message: the assistant's face beside its answers, then text, files, sources, rating and,
2690
- * under the latest answer, the options the visitor can click (unless the theme puts them above
2691
- * the message field).
977
+ * One message: the assistant's face beside its answers, then text, tool cards, files, sources,
978
+ * rating and, under the latest answer, the options the visitor can click (unless the theme puts
979
+ * them above the message field).
2692
980
  */
2693
981
  function DefaultMessage() {
2694
982
  const message = useMessage();
@@ -2697,6 +985,7 @@ function DefaultMessage() {
2697
985
  "data-ask-part": "message-body",
2698
986
  children: [
2699
987
  /* @__PURE__ */ jsx(MessageText, {}),
988
+ /* @__PURE__ */ jsx(ToolResults, {}),
2700
989
  /* @__PURE__ */ jsx(MessageFiles, {}),
2701
990
  /* @__PURE__ */ jsx(Citations, {}),
2702
991
  /* @__PURE__ */ jsx(Feedback, {}),
@@ -2791,7 +1080,11 @@ function DefaultWelcome() {
2791
1080
  }
2792
1081
  // src/react/skin/panel.tsx
2793
1082
  /** The default look of the chat inside its frame: header, conversation and message field. */
2794
- function DefaultPanel({ headingLevel = 2, onClose, components = {}, ownsDocument = false }) {
1083
+ function DefaultPanel({ headingLevel: level, onClose: close, components = {}, ownsDocument: owns = false }) {
1084
+ const frame = useFrame();
1085
+ const headingLevel = level ?? (frame ? 1 : 2);
1086
+ const onClose = close ?? frame?.close;
1087
+ const ownsDocument = owns || frame !== null;
2795
1088
  const { state, actions, bot, t } = useChat();
2796
1089
  const [confirming, setConfirming] = useState(false);
2797
1090
  /** Accepted, and the server is deleting the conversation: the question stays, busy, until then. */
@@ -2864,6 +1157,7 @@ function DefaultPanel({ headingLevel = 2, onClose, components = {}, ownsDocument
2864
1157
  /* @__PURE__ */ jsx(MessageList, { children: message }),
2865
1158
  /* @__PURE__ */ jsx(Status, {})
2866
1159
  ] }),
1160
+ /* @__PURE__ */ jsx(HumanCheck, {}),
2867
1161
  /* @__PURE__ */ jsx(ErrorMessage, {}),
2868
1162
  /* @__PURE__ */ jsx(Footer, {})
2869
1163
  ]
@@ -2888,4 +1182,4 @@ function DefaultChat({ className, colorScheme, ...panel }) {
2888
1182
  }), /* @__PURE__ */ jsx(DefaultPanel, { ...panel })]
2889
1183
  });
2890
1184
  }
2891
- export { AttachButton, Citations, Composer, DefaultChat, DictateButton, ErrorMessage, FeedbackButton, Files, Input, Markdown, Message, MessageFiles, MessageList, MessageText, Messages, Panel, QuickReplies, Recorder, Root, Send, Status, Theme, useChat, useChatState, useMessage };
1185
+ export { AttachButton, Citations, Composer, DefaultChat, DictateButton, Disclosure, ErrorMessage, FeedbackButton, Files, HumanCheck, Input, Link, Markdown, Message, MessageFiles, MessageList, MessageText, Messages, Panel, QuickReplies, Recorder, Root, Send, Status, Theme, ToolResults, useChat, useChatState, useFrame, useMessage };