@boldare/askdare 0.4.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 (48) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +14 -4
  3. package/dist/cli.js +19 -6
  4. package/dist/define-tool.js +677 -7
  5. package/dist/embed.d.ts +1 -1
  6. package/dist/embed.js +2 -1
  7. package/dist/{store.d.ts → events.d.ts} +127 -52
  8. package/dist/index.d.ts +28 -2
  9. package/dist/index.js +82 -1
  10. package/dist/next.d.ts +22 -11
  11. package/dist/next.js +537 -139
  12. package/dist/react.d.ts +24 -4
  13. package/dist/react.js +126 -18
  14. package/dist/root.js +169 -37
  15. package/dist/tool-results.d.ts +11 -1
  16. package/dist/ui/askdare.css +9 -1
  17. package/dist/ui/avatar.tsx +1 -1
  18. package/dist/ui/chat.tsx +1 -1
  19. package/dist/ui/confirm.tsx +1 -1
  20. package/dist/ui/context.ts +1 -1
  21. package/dist/ui/feedback.tsx +1 -1
  22. package/dist/ui/footer.tsx +3 -15
  23. package/dist/ui/header.tsx +1 -1
  24. package/dist/ui/icons.tsx +1 -1
  25. package/dist/ui/index.ts +1 -1
  26. package/dist/ui/message.tsx +1 -1
  27. package/dist/ui/panel.tsx +3 -1
  28. package/dist/ui/welcome.tsx +1 -1
  29. package/docs/accessibility.md +83 -0
  30. package/docs/cli.md +4 -3
  31. package/docs/compliance.md +160 -0
  32. package/docs/configuration.md +47 -2
  33. package/docs/costs.md +8 -1
  34. package/docs/custom-store.md +2 -0
  35. package/docs/embedding.md +2 -0
  36. package/docs/feedback.md +1 -1
  37. package/docs/going-public.md +15 -3
  38. package/docs/guardrails.md +128 -0
  39. package/docs/migrating-from-openai-assistant.md +1 -1
  40. package/docs/privacy.md +26 -2
  41. package/docs/react.md +7 -1
  42. package/docs/styling.md +2 -2
  43. package/docs/support.md +3 -3
  44. package/docs/texts.md +100 -96
  45. package/docs/troubleshooting.md +30 -3
  46. package/llms.txt +12 -9
  47. package/package.json +1 -1
  48. package/skills/askdare/SKILL.md +9 -2
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- import { a as ToolResults, c as ChatConfig, f as PresetName, i as ToolRenderers, l as ChatStyles, n as LinkProps, o as ToolResultsProps, p as ThemeVariants, r as ToolRendererProps, s as ChatAttachments, t as Link, u as ChatWidget } from "./tool-results.js";
2
+ import { a as ToolResults, c as ChatConfig, d as ChatWidget, i as ToolRenderers, l as ChatHumanCheck, m as ThemeVariants, n as LinkProps, o as ToolResultsProps, p as PresetName, r as ToolRendererProps, s as ChatAttachments, t as Link, u as ChatStyles } from "./tool-results.js";
3
3
  import { ComponentProps, ComponentType, NamedExoticComponent, ReactElement, ReactNode, Ref } from "react";
4
4
  /** One tool call's payload, as the `tool.ui` event and the history carry it. */
5
5
  interface ToolUi {
@@ -141,6 +141,8 @@ interface ChatState {
141
141
  readonly ratings: Readonly<Record<string, Rating>>;
142
142
  /** The id of the answer just rated 👎, while the chat asks what went wrong. */
143
143
  readonly commenting: string | undefined;
144
+ /** The chat waits for the visitor to pass the bot's human check before it connects. */
145
+ readonly humanCheck: boolean;
144
146
  }
145
147
  /**
146
148
  * What happened in the chat, for the page's analytics and reactions (ADR-0013). Metadata only:
@@ -231,6 +233,8 @@ declare const EN: {
231
233
  readonly "launcher.open": "Open chat";
232
234
  readonly "launcher.close": "Close chat";
233
235
  readonly "launcher.unavailable": "The chat couldn’t load. Please try again later.";
236
+ readonly "humanCheck.label": "Checking that you’re human";
237
+ readonly "error.humanCheck": "We couldn’t confirm you’re human. Please try again.";
234
238
  readonly "error.connection": "Connection problem. Please try again.";
235
239
  readonly "error.history": "Could not load the previous conversation.";
236
240
  readonly "error.updated": "The assistant was updated. Please reload the page.";
@@ -385,6 +389,13 @@ export declare function useChat(): Chat;
385
389
  export declare function useChatState<T>(select: (state: ChatState) => T): T;
386
390
  /** The message being rendered, inside `MessageList`. */
387
391
  export declare function useMessage(): ChatMessage;
392
+ type DisclosureProps = ComponentProps<"p">;
393
+ /**
394
+ * The AI notice (EU AI Act, art. 50): `disclosure.text`, with a link to the bot's
395
+ * `widget.disclosure.privacyUrl` when it has one. Children replace the text with your own notice.
396
+ * Renders nothing when the bot sets `disclosure: false`.
397
+ */
398
+ export declare function Disclosure({ children, ...props }: DisclosureProps): ReactElement | null;
388
399
  interface FeedbackButtonProps extends ComponentProps<"button"> {
389
400
  /** What a click rates the answer: 👍 `up` or 👎 `down`. A second click takes the rating back. */
390
401
  readonly rating: Rating;
@@ -395,6 +406,13 @@ interface FeedbackButtonProps extends ComponentProps<"button"> {
395
406
  * be rated. After 👎 the chat's `state.commenting` names the answer to ask about.
396
407
  */
397
408
  export declare function FeedbackButton({ rating, onClick, ...props }: FeedbackButtonProps): ReactElement | null;
409
+ type HumanCheckProps = Omit<ComponentProps<"div">, "children">;
410
+ /**
411
+ * The bot's human check (`security.humanVerifier`), shown while the chat waits for it before it
412
+ * connects; nothing otherwise. The default look includes it; a headless chat whose bot has a check
413
+ * must render it, or it can't connect.
414
+ */
415
+ export declare function HumanCheck(props: HumanCheckProps): ReactElement | null;
398
416
  /**
399
417
  * Renders model output as markdown (GFM) without ever producing raw HTML: marked only tokenizes,
400
418
  * and each token becomes an element here. HTML in the source is dropped, links are limited to
@@ -407,8 +425,10 @@ interface MarkdownProps {
407
425
  export declare const Markdown: NamedExoticComponent<MarkdownProps>;
408
426
  type MessagesProps = ComponentProps<"div">;
409
427
  /**
410
- * The conversation: a live region that follows the latest message as it streams. Holds the
411
- * welcome, the `MessageList` and the `Status`.
428
+ * The conversation, following the latest message as it streams. Holds the welcome, the
429
+ * `MessageList` and the `Status`. It is a log but not a live region: text growing inside a node is
430
+ * read in fragments or not at all, so a finished answer is announced once, through a status region
431
+ * next to it.
412
432
  */
413
433
  export declare function Messages({ ref, ...props }: MessagesProps): ReactElement;
414
434
  interface MessageListProps {
@@ -500,4 +520,4 @@ interface RootProps {
500
520
  * take what `askdare('identify')` and `askdare('configure')` take, checked the same way.
501
521
  */
502
522
  export declare function Root({ config, identity, context, greeting, starters, onEvent, toolRenderers, children }: RootProps): ReactElement;
503
- export { type AttachButtonProps, type Chat, type ChatActions, type ChatAttachments, type ChatBot, type ChatConfig, type ChatEvent, type ChatEventListener, type ChatEventType, type ChatMessage, type ChatPhase, type ChatState, type ChatStyles, type ChatWidget, type Citation, type CitationsProps, type ComposerProps, type DefaultChatComponents, type DefaultChatProps, type DictateButtonProps, type Dictation, type ErrorMessageProps, type FeedbackButtonProps, type FilesProps, type Frame, type InputProps, Link, type LinkProps, type MarkdownProps, type MessageFilesProps, type MessageListProps, type MessageProps, type MessageTextProps, type MessagesProps, type PanelProps, type PendingFile, type QuickRepliesProps, type Rating, type RecorderProps, type RootProps, type SendProps, type SentFile, type StatusProps, type ThemeProps, type ToolRendererProps, type ToolRenderers, ToolResults, type ToolResultsProps, type ToolUi, type Translate };
523
+ export { type AttachButtonProps, type Chat, type ChatActions, type ChatAttachments, type ChatBot, type ChatConfig, type ChatEvent, type ChatEventListener, type ChatEventType, type ChatHumanCheck, type ChatMessage, type ChatPhase, type ChatState, type ChatStyles, type ChatWidget, type Citation, type CitationsProps, type ComposerProps, type DefaultChatComponents, type DefaultChatProps, type DictateButtonProps, type Dictation, type DisclosureProps, type ErrorMessageProps, type FeedbackButtonProps, type FilesProps, type Frame, type HumanCheckProps, type InputProps, Link, type LinkProps, type MarkdownProps, type MessageFilesProps, type MessageListProps, type MessageProps, type MessageTextProps, type MessagesProps, type PanelProps, type PendingFile, type QuickRepliesProps, type Rating, type RecorderProps, type RootProps, type SendProps, type SentFile, type StatusProps, type ThemeProps, type ToolRendererProps, type ToolRenderers, ToolResults, type ToolResultsProps, type ToolUi, type Translate };
package/dist/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  'use client';
2
- import { C as useOptionalMessage, S as useMessage, T as useTexts, _ as MessageProvider, a as ToolResults, b as useChatState, d as safeUrl, f as pluralText, m as acceptTypes, p as canSend, r as Link, t as Root, u as Markdown, v as useChat, w as useStore, x as useFrame, y as useChatConfig } from "./root.js";
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
3
  import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  // src/react/refs.ts
@@ -37,28 +37,55 @@ function focusElement(ref, explicit = false) {
37
37
  // src/react/messages.tsx
38
38
  /** False for an answer that ended (or failed) before any text or sources, or options to show. */
39
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
+ };
40
49
  /**
41
- * The conversation: a live region that follows the latest message as it streams. Holds the
42
- * 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.
43
54
  */
44
55
  function Messages({ ref, ...props }) {
45
56
  const own = useRef(null);
57
+ const streaming = useRef(void 0);
58
+ const [finished, setFinished] = useState("");
46
59
  const loading = useChatState((state) => state.phase === "loading");
47
60
  const latest = useChatState((state) => state.messages.at(-1));
48
61
  const commenting = useChatState((state) => state.commenting);
49
62
  useEffect(() => {
50
63
  const log = own.current;
51
- 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
+ }
52
75
  }, [latest, commenting]);
53
- return /* @__PURE__ */ jsx("div", {
76
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
54
77
  "data-ask-part": "messages",
55
78
  role: "log",
56
- "aria-live": "polite",
57
- "aria-relevant": "additions",
79
+ "aria-live": "off",
58
80
  "aria-busy": loading,
59
81
  ...props,
60
82
  ref: useMergedRef(own, ref)
61
- });
83
+ }), /* @__PURE__ */ jsx("div", {
84
+ "data-ask-part": "announcement",
85
+ role: "status",
86
+ style: hidden,
87
+ children: finished
88
+ })] });
62
89
  }
63
90
  /** Renders its children for every message worth showing. Has no element of its own. */
64
91
  function MessageList({ children }) {
@@ -434,6 +461,94 @@ function FeedbackButton({ rating, onClick, ...props }) {
434
461
  ...props
435
462
  });
436
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
+ }
437
552
  // src/react/notices.tsx
438
553
  /** What the chat is doing: loading a conversation, or what the assistant does before it writes. */
439
554
  function Status(props) {
@@ -714,15 +829,7 @@ function DefaultFooter() {
714
829
  })] })
715
830
  ] }) : /* @__PURE__ */ jsx(Recorder, { cancelIcon: /* @__PURE__ */ jsx(CloseIcon, {}) })
716
831
  })] }),
717
- bot.disclosure !== false && /* @__PURE__ */ jsxs("p", {
718
- "data-ask-part": "disclosure",
719
- children: [t("disclosure.text"), bot.disclosure.privacyUrl && /* @__PURE__ */ jsxs(Fragment, { children: [" ", /* @__PURE__ */ jsx("a", {
720
- href: bot.disclosure.privacyUrl,
721
- target: "_blank",
722
- rel: "noopener noreferrer",
723
- children: t("disclosure.privacy")
724
- })] })]
725
- })
832
+ /* @__PURE__ */ jsx(Disclosure, {})
726
833
  ] });
727
834
  }
728
835
  // src/react/skin/avatar.tsx
@@ -1050,6 +1157,7 @@ function DefaultPanel({ headingLevel: level, onClose: close, components = {}, ow
1050
1157
  /* @__PURE__ */ jsx(MessageList, { children: message }),
1051
1158
  /* @__PURE__ */ jsx(Status, {})
1052
1159
  ] }),
1160
+ /* @__PURE__ */ jsx(HumanCheck, {}),
1053
1161
  /* @__PURE__ */ jsx(ErrorMessage, {}),
1054
1162
  /* @__PURE__ */ jsx(Footer, {})
1055
1163
  ]
@@ -1074,4 +1182,4 @@ function DefaultChat({ className, colorScheme, ...panel }) {
1074
1182
  }), /* @__PURE__ */ jsx(DefaultPanel, { ...panel })]
1075
1183
  });
1076
1184
  }
1077
- export { AttachButton, Citations, Composer, DefaultChat, DictateButton, ErrorMessage, FeedbackButton, Files, Input, Link, Markdown, Message, MessageFiles, MessageList, MessageText, Messages, Panel, QuickReplies, Recorder, Root, Send, Status, Theme, ToolResults, useChat, useChatState, useFrame, 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 };
package/dist/root.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
  import { t as O } from "./react-marked.js";
3
3
  import { Component, createContext, memo, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
- import { jsx, jsxs } from "react/jsx-runtime";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  // src/react/context.tsx
6
6
  const StoreContext = createContext(null);
7
7
  /** Set by `EmbedRoot`; null in a chat inside a page. */
@@ -289,42 +289,83 @@ function cells(row, header, depth) {
289
289
  }
290
290
  function blocks(tokens, depth) {
291
291
  if (depth > MAX_DEPTH) return [tokens.map((token) => token.raw).join("")];
292
- return tokens.map((token, key) => {
293
- switch (token.type) {
294
- case "paragraph": return /* @__PURE__ */ jsx("p", { children: inline(token.tokens, depth + 1) }, key);
295
- case "text": return token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
296
- case "heading": {
297
- const Heading = `h${Math.min(Math.max(token.depth, 1), 6)}`;
298
- return /* @__PURE__ */ jsx(Heading, { children: inline(token.tokens, depth + 1) }, key);
299
- }
300
- case "code": return /* @__PURE__ */ jsx("pre", { children: /* @__PURE__ */ jsx("code", { children: token.text }) }, key);
301
- case "blockquote": return /* @__PURE__ */ jsx("blockquote", { children: blocks(token.tokens ?? [], depth + 1) }, key);
302
- case "hr": return /* @__PURE__ */ jsx("hr", {}, key);
303
- case "list": {
304
- const items = token.items.map((item, index) => /* @__PURE__ */ jsxs("li", { children: [item.task && /* @__PURE__ */ jsx("input", {
305
- type: "checkbox",
306
- checked: item.checked ?? false,
307
- disabled: true
308
- }), blocks(item.tokens.filter((child) => child.type !== "checkbox"), depth + 1)] }, index));
309
- return token.ordered ? /* @__PURE__ */ jsx("ol", {
310
- start: typeof token.start === "number" ? token.start : void 0,
311
- children: items
312
- }, key) : /* @__PURE__ */ jsx("ul", { children: items }, key);
313
- }
314
- 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);
315
- default: return null;
292
+ return tokens.map((token, key) => block(token, key, depth));
293
+ }
294
+ function block(token, key, depth) {
295
+ switch (token.type) {
296
+ case "paragraph": return /* @__PURE__ */ jsx("p", { children: inline(token.tokens, depth + 1) }, key);
297
+ case "text": return token.tokens ? inline(token.tokens, depth + 1) : decodeEntities(token.text);
298
+ case "heading": {
299
+ const Heading = `h${Math.min(Math.max(token.depth, 1), 6)}`;
300
+ return /* @__PURE__ */ jsx(Heading, { children: inline(token.tokens, depth + 1) }, key);
316
301
  }
317
- });
302
+ case "code": return /* @__PURE__ */ jsx("pre", { children: /* @__PURE__ */ jsx("code", { children: token.text }) }, key);
303
+ case "blockquote": return /* @__PURE__ */ jsx("blockquote", { children: blocks(token.tokens ?? [], depth + 1) }, key);
304
+ case "hr": return /* @__PURE__ */ jsx("hr", {}, key);
305
+ case "list": {
306
+ const items = token.items.map((item, index) => /* @__PURE__ */ jsxs("li", { children: [item.task && /* @__PURE__ */ jsx("input", {
307
+ type: "checkbox",
308
+ checked: item.checked ?? false,
309
+ disabled: true
310
+ }), blocks(item.tokens.filter((child) => child.type !== "checkbox"), depth + 1)] }, index));
311
+ return token.ordered ? /* @__PURE__ */ jsx("ol", {
312
+ start: typeof token.start === "number" ? token.start : void 0,
313
+ children: items
314
+ }, key) : /* @__PURE__ */ jsx("ul", { children: items }, key);
315
+ }
316
+ 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);
317
+ default: return null;
318
+ }
318
319
  }
319
320
  /** The text as paragraphs, when markdown can't be had. */
320
321
  const plain = (text) => text.split(/\n{2,}/).map((paragraph, key) => /* @__PURE__ */ jsx("p", { children: paragraph }, key));
321
- function render(text) {
322
+ function lexAll(text) {
323
+ const tokens = O.lex(text, { gfm: true });
324
+ return {
325
+ text,
326
+ tokens,
327
+ extensible: Object.keys(tokens.links).length === 0 && tokens.reduce((length, token) => length + token.raw.length, 0) === text.length
328
+ };
329
+ }
330
+ /**
331
+ * Lexes `text`, reusing the tokens of `previous` when `text` only appends to it (a stream). Blocks
332
+ * before the last one are finished: text appended after a block can't change it, with two
333
+ * exceptions that stay on a full lex. A setext underline or a lazy continuation only reaches back
334
+ * to the last block, which is re-lexed; a link definition applies to the whole text, so an answer
335
+ * with one is lexed whole every time. Kept tokens stay the same objects, so their memoized
336
+ * `Block`s don't re-render.
337
+ */
338
+ function lex(text, previous) {
339
+ if (!previous?.extensible || !text.startsWith(previous.text)) return lexAll(text);
340
+ const { tokens } = previous;
341
+ let last = tokens.length - 1;
342
+ while (last > 0 && tokens[last]?.type === "space") last--;
343
+ let blank = false;
344
+ while (last > 0) {
345
+ const before = tokens[last - 1];
346
+ if (before.type === "space") blank = true;
347
+ else if (before.type !== "list" && !(before.type === "code" && before.codeBlockStyle === "indented") && (blank || before.raw.endsWith("\n\n"))) break;
348
+ else blank = false;
349
+ last--;
350
+ }
351
+ let offset = 0;
352
+ for (let index = 0; index < last; index++) offset += tokens[index]?.raw.length ?? 0;
353
+ const tail = lexAll(text.slice(offset));
354
+ if (!tail.extensible) return lexAll(text);
355
+ return {
356
+ text,
357
+ tokens: [...tokens.slice(0, Math.max(last, 0)), ...tail.tokens],
358
+ extensible: true
359
+ };
360
+ }
361
+ /** One top-level block. Memoized: while an answer streams, only its last block re-renders. */
362
+ const Block = memo(function Block({ token }) {
322
363
  try {
323
- return blocks(O.lex(text, { gfm: true }), 0);
364
+ return block(token, 0, 0);
324
365
  } catch {
325
- return plain(text);
366
+ return plain(token.raw);
326
367
  }
327
- }
368
+ });
328
369
  /** Shows the plain text if rendering a message ever fails, so one answer can't break the chat. */
329
370
  var Fallback = class extends Component {
330
371
  state = { failed: false };
@@ -336,11 +377,54 @@ var Fallback = class extends Component {
336
377
  }
337
378
  };
338
379
  const Markdown = /* @__PURE__ */ memo(function Markdown({ text }) {
380
+ const lexed = useRef(void 0);
381
+ let content;
382
+ try {
383
+ lexed.current = lex(text, lexed.current);
384
+ content = lexed.current.tokens.map((token, key) => /* @__PURE__ */ jsx(Block, { token }, key));
385
+ } catch {
386
+ lexed.current = void 0;
387
+ content = plain(text);
388
+ }
339
389
  return /* @__PURE__ */ jsx(Fallback, {
340
390
  text,
341
- children: render(text)
391
+ children: content
342
392
  });
343
393
  });
394
+ // src/react/disclosure.tsx
395
+ /** Chats that rendered a `Disclosure`, or were already told they don't. Development only. */
396
+ const disclosed = /* @__PURE__ */ new WeakSet();
397
+ /**
398
+ * The AI notice (EU AI Act, art. 50): `disclosure.text`, with a link to the bot's
399
+ * `widget.disclosure.privacyUrl` when it has one. Children replace the text with your own notice.
400
+ * Renders nothing when the bot sets `disclosure: false`.
401
+ */
402
+ function Disclosure({ children, ...props }) {
403
+ const store = useStore();
404
+ const { disclosure } = useChatConfig().widget;
405
+ const t = useTexts();
406
+ if (process.env.NODE_ENV !== "production") disclosed.add(store);
407
+ if (disclosure === false) return null;
408
+ return /* @__PURE__ */ jsx("p", {
409
+ "data-ask-part": "disclosure",
410
+ ...props,
411
+ children: children ?? /* @__PURE__ */ jsxs(Fragment, { children: [t("disclosure.text"), disclosure.privacyUrl && /* @__PURE__ */ jsxs(Fragment, { children: [" ", /* @__PURE__ */ jsx("a", {
412
+ href: disclosure.privacyUrl,
413
+ target: "_blank",
414
+ rel: "noopener noreferrer",
415
+ children: t("disclosure.privacy")
416
+ })] })] })
417
+ });
418
+ }
419
+ /**
420
+ * In development, after the chat's first render: notes once when it rendered no `Disclosure` while
421
+ * the bot keeps the notice on (ADR-0019). `disclosure: false` silences it.
422
+ */
423
+ function noteMissingDisclosure(store) {
424
+ if (store.config.widget.disclosure === false || disclosed.has(store)) return;
425
+ disclosed.add(store);
426
+ console.warn("[askdare] This chat renders no <Disclosure />, so visitors aren't told they are talking to an AI (EU AI Act, art. 50). Add <Disclosure /> from @boldare/askdare/react (children replace its text), or set widget.disclosure: false in defineBot if your page already says so.");
427
+ }
344
428
  // src/base-path.ts
345
429
  /**
346
430
  * Whether a chat route's `basePath` is a path on the app itself, like `/api/chat`: never another
@@ -850,6 +934,7 @@ var ChatClient = class {
850
934
  async identify(token) {
851
935
  if (token === this.#identity) return false;
852
936
  this.#identity = token;
937
+ if (token === null && this.#options.humanToken && !this.#session && !this.#opening && !this.#renewal && !this.#identityKey) return false;
853
938
  this.#identityChanged = true;
854
939
  await this.#opening?.catch(() => void 0);
855
940
  const before = this.#resumeKey();
@@ -1067,11 +1152,12 @@ var ChatClient = class {
1067
1152
  return this.#opening;
1068
1153
  }
1069
1154
  /** Not tied to one caller's signal, because other callers may be waiting for the same session. */
1070
- async #openSession() {
1155
+ async #openSession(stale) {
1071
1156
  const resumeToken = this.#options.storage.get(this.#resumeKey());
1072
- const accessToken = this.#session?.accessToken ?? this.#renewal;
1157
+ const accessToken = stale ?? this.#session?.accessToken ?? this.#renewal;
1073
1158
  const identityToken = this.#identity;
1074
1159
  const sentFrom = this.#resumeKey();
1160
+ const humanToken = accessToken && !stale ? void 0 : await this.#humanToken();
1075
1161
  const response = await this.#fetch(`${this.#options.basePath}/session`, {
1076
1162
  method: "POST",
1077
1163
  headers: { "content-type": "application/json" },
@@ -1079,9 +1165,15 @@ var ChatClient = class {
1079
1165
  botId: this.#options.botId,
1080
1166
  ...resumeToken ? { resumeToken } : {},
1081
1167
  ...accessToken ? { accessToken } : {},
1082
- ...identityToken === void 0 ? {} : { identityToken }
1168
+ ...identityToken === void 0 ? {} : { identityToken },
1169
+ ...humanToken ? { humanToken } : {}
1083
1170
  })
1084
1171
  });
1172
+ if (response.status === 401 && accessToken && !stale && this.#options.humanToken) {
1173
+ this.#session = void 0;
1174
+ this.#renewal = void 0;
1175
+ return this.#openSession(accessToken);
1176
+ }
1085
1177
  if (!response.ok) throw new SessionRefused(await this.#errorFromResponse(response, false));
1086
1178
  const body = await response.json();
1087
1179
  if (this.#identity === identityToken) this.#identityChanged = false;
@@ -1101,6 +1193,15 @@ var ChatClient = class {
1101
1193
  };
1102
1194
  return this.#session;
1103
1195
  }
1196
+ /** A token from the bot's human check, or undefined for a bot without one. */
1197
+ async #humanToken() {
1198
+ if (!this.#options.humanToken) return void 0;
1199
+ try {
1200
+ return await this.#options.humanToken();
1201
+ } catch {
1202
+ throw new SessionRefused(this.#error("unauthorized", "error.humanCheck", "We couldn’t confirm you’re human. Please try again."));
1203
+ }
1204
+ }
1104
1205
  /** What to show for a request that threw: the server's reason for refusing a session, if any. */
1105
1206
  #failure(error, code) {
1106
1207
  return error instanceof SessionRefused ? error.event : this.#connectionError(code);
@@ -1444,12 +1545,33 @@ function revokePreviews(files) {
1444
1545
  function createChatStore(initialConfig, options = {}) {
1445
1546
  let config = initialConfig;
1446
1547
  let t = translator(config.widget.texts);
1548
+ /** The session waiting for the visitor to pass the human check, if any (ADR-0019). */
1549
+ let humanCheck;
1550
+ /** Mounted `HumanCheck` components; without one, the check can never be passed. */
1551
+ let checkers = 0;
1552
+ const requestHumanCheck = () => new Promise((resolve, reject) => {
1553
+ humanCheck?.reject(/* @__PURE__ */ new Error("replaced"));
1554
+ humanCheck = {
1555
+ resolve,
1556
+ reject
1557
+ };
1558
+ if (checkers === 0) console.warn("[askdare] Render <HumanCheck />: this bot needs a human check to connect.");
1559
+ set({ humanCheck: true });
1560
+ });
1561
+ const answerHumanCheck = (token) => {
1562
+ const waiting = humanCheck;
1563
+ humanCheck = void 0;
1564
+ if (state.humanCheck) set({ humanCheck: false });
1565
+ if (token) waiting?.resolve(token);
1566
+ else waiting?.reject(/* @__PURE__ */ new Error("The human check failed."));
1567
+ };
1447
1568
  const client = options.client ?? new ChatClient({
1448
1569
  basePath: config.basePath,
1449
1570
  botId: config.botId,
1450
1571
  locale: config.widget.locale,
1451
1572
  storage: browserStorage(),
1452
- translate: (key, params) => config.widget.texts[key] === void 0 ? void 0 : t(key, params)
1573
+ translate: (key, params) => config.widget.texts[key] === void 0 ? void 0 : t(key, params),
1574
+ ...config.humanCheck ? { humanToken: requestHumanCheck } : {}
1453
1575
  });
1454
1576
  const recorder = options.recorder ?? {
1455
1577
  canRecord,
@@ -1470,7 +1592,8 @@ function createChatStore(initialConfig, options = {}) {
1470
1592
  canDictate: false,
1471
1593
  page: options.page ?? {},
1472
1594
  ratings: {},
1473
- commenting: void 0
1595
+ commenting: void 0,
1596
+ humanCheck: false
1474
1597
  };
1475
1598
  let state = initial;
1476
1599
  const listeners = /* @__PURE__ */ new Set();
@@ -1910,6 +2033,7 @@ function createChatStore(initialConfig, options = {}) {
1910
2033
  turn?.abort();
1911
2034
  turn = void 0;
1912
2035
  discardRecording();
2036
+ answerHumanCheck(null);
1913
2037
  if (uploads.size > 0) {
1914
2038
  cancelUploads(uploads.keys());
1915
2039
  set({ files: state.files.filter((file) => file.status !== "uploading") });
@@ -1960,6 +2084,13 @@ function createChatStore(initialConfig, options = {}) {
1960
2084
  hide() {
1961
2085
  discardRecording();
1962
2086
  },
2087
+ answerHumanCheck,
2088
+ attachHumanCheck() {
2089
+ checkers += 1;
2090
+ return () => {
2091
+ checkers -= 1;
2092
+ };
2093
+ },
1963
2094
  level: () => recording?.level(),
1964
2095
  onFocus,
1965
2096
  onEvent: (listener) => events.on("*", listener)
@@ -2094,6 +2225,7 @@ function Root({ config, identity, context, greeting, starters, onEvent, toolRend
2094
2225
  useEffect(() => {
2095
2226
  const stopEvents = store.onEvent((event) => listener.current?.(event));
2096
2227
  store.start();
2228
+ if (process.env.NODE_ENV !== "production") noteMissingDisclosure(store);
2097
2229
  return () => {
2098
2230
  store.stop();
2099
2231
  stopEvents();
@@ -2119,4 +2251,4 @@ function Root({ config, identity, context, greeting, starters, onEvent, toolRend
2119
2251
  })
2120
2252
  });
2121
2253
  }
2122
- export { useOptionalMessage as C, useMessage as S, useTexts as T, MessageProvider as _, ToolResults as a, useChatState as b, pageLocale as c, safeUrl as d, pluralText as f, FrameContext as g, ChatProvider as h, ToolRenderersProvider as i, pageOptions as l, acceptTypes as m, checkConfig as n, createChatStore as o, canSend as p, Link as r, identityToken as s, Root as t, Markdown as u, useChat as v, useStore as w, useFrame as x, useChatConfig as y };
2254
+ export { useFrame as C, useTexts as D, useStore as E, useChatState as S, useOptionalMessage as T, ChatProvider as _, ToolResults as a, useChat as b, pageLocale as c, noteMissingDisclosure as d, Markdown as f, acceptTypes as g, canSend as h, ToolRenderersProvider as i, pageOptions as l, pluralText as m, checkConfig as n, createChatStore as o, safeUrl as p, Link as r, identityToken as s, Root as t, Disclosure as u, FrameContext as v, useMessage as w, useChatConfig as x, MessageProvider as y };
@@ -71,6 +71,16 @@ interface ChatConfig {
71
71
  };
72
72
  /** From `getChatConfig`, for a chat inside a page. The iframe links its own stylesheets. */
73
73
  readonly styles?: ChatStyles;
74
+ /**
75
+ * Absent unless the bot has `security.humanVerifier`: the challenge the chat shows before a new
76
+ * session starts, rendered by `HumanCheck`.
77
+ */
78
+ readonly humanCheck?: ChatHumanCheck;
79
+ }
80
+ /** A human check the chat must pass before it connects; public, the site key only. */
81
+ interface ChatHumanCheck {
82
+ readonly provider: "turnstile";
83
+ readonly siteKey: string;
74
84
  }
75
85
  /** What `EmbedRoot` from `@boldare/askdare/embed` needs; `getEmbedConfig` builds it (ADR-0018). */
76
86
  interface EmbedChatConfig extends ChatConfig {
@@ -127,4 +137,4 @@ type LinkProps = Omit<ComponentProps<"a">, "href" | "target" | "rel"> & {
127
137
  * the text alone.
128
138
  */
129
139
  declare function Link({ href, children, ...props }: LinkProps): ReactElement;
130
- export { ToolResults as a, ChatConfig as c, EmbedChatConfig as d, PresetName as f, ToolRenderers as i, ChatStyles as l, LinkProps as n, ToolResultsProps as o, ThemeVariants as p, ToolRendererProps as r, ChatAttachments as s, Link as t, ChatWidget as u };
140
+ export { ToolResults as a, ChatConfig as c, ChatWidget as d, EmbedChatConfig as f, ToolRenderers as i, ChatHumanCheck as l, ThemeVariants as m, LinkProps as n, ToolResultsProps as o, PresetName as p, ToolRendererProps as r, ChatAttachments as s, Link as t, ChatStyles as u };
@@ -1,4 +1,4 @@
1
- /* Ejected from @boldare/askdare@0.4.0 with `npx @boldare/askdare add ui`. This copy is yours to change. */
1
+ /* Ejected from @boldare/askdare@0.5.0 with `npx @boldare/askdare add ui`. This copy is yours to change. */
2
2
  /*
3
3
  * Default skin of the chat (ADR-0008, ADR-0011), in the iframe and inside a page. Everything is
4
4
  * built on the public styling API: the --ask-* tokens (set per bot by the theme stylesheet), the
@@ -1091,6 +1091,14 @@
1091
1091
  }
1092
1092
  }
1093
1093
 
1094
+ /* ---------- Human check (Turnstile draws its own frame inside) ---------- */
1095
+
1096
+ [data-ask-part="human-check"]:where([data-ask-skin] *) {
1097
+ display: flex;
1098
+ justify-content: center;
1099
+ margin: 0 calc(var(--ask-space) * 1.5) var(--ask-space);
1100
+ }
1101
+
1094
1102
  /* ---------- Errors ---------- */
1095
1103
 
1096
1104
  [data-ask-part="error"]:where([data-ask-skin] *) {
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.4.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import type { ReactElement } from 'react';
3
3
  import { useSkin } from './context';
4
4
  import { SparkIcon } from './icons';
package/dist/ui/chat.tsx CHANGED
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.4.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  'use client';
3
3
 
4
4
  // The entry of an ejected copy (`npx @boldare/askdare add ui`): the same DefaultChat as in
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.4.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import { useChat } from '@boldare/askdare/react';
3
3
  import { type KeyboardEvent, type ReactElement, useEffect, useId, useRef } from 'react';
4
4
  import { RestartIcon } from './icons';
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.4.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.0 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import type { ChatBot, Translate } from '@boldare/askdare/react';
3
3
  import { type Context, createContext, type RefObject, useContext } from 'react';
4
4