@seclai/react 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,6 +41,7 @@ export function App() {
41
41
  - **`AgentChat`** sends each message as a run with a shared session id and streams the reply.
42
42
  - **`SeclaiAgent`** renders one of the two based on `mode`.
43
43
  - **`RunProgress`** shows a running run's steps and elapsed time. See [below](#runprogress).
44
+ - **`MarkdownContent`** renders the agent's replies, including while they stream. See [Markdown](#markdown).
44
45
 
45
46
  ### Files in `AgentChat`
46
47
 
@@ -252,28 +253,40 @@ import { MediaGallery, MediaPreview, MediaSkeleton, MediaViewer } from "@seclai/
252
253
  />
253
254
  ```
254
255
 
255
- - **`MediaPreview`** shows one attachment. An image gets a card: a fixed-ratio frame so the layout doesn't jump while it loads, an optional number badge and a download link. Files that aren't images are a download link.
256
- - **`MediaGallery`** lays out a run's images as numbered cards that open a full-size viewer, with "Download all" when there's more than one. It downloads the files one at a time, because browsers block a burst of simultaneous downloads. Other files follow the images as download links.
256
+ - **`MediaPreview`** shows one attachment as a card, chosen by its mime type (ignoring case and parameters such as `; codecs=…`). Every card has a download link, an optional number badge and an `actions` slot:
257
+ - **Images** (`image/*`, SVG included) sit in a fixed-ratio frame, so the layout doesn't jump while they load.
258
+ - **Audio** (`audio/*`) plays in the browser's own `<audio controls>`, under the file's name.
259
+ - **Video** (`video/*`) plays in the browser's own `<video controls playsinline>`, in a frame like an image's.
260
+ - **PDFs** (`application/pdf`) show in the browser's PDF viewer, in an `<object>`. Browsers without one, including most mobile browsers, show a download link in its place.
261
+ - **Anything else**, HTML included, is a download link.
262
+
263
+ Audio and video load only their metadata until played (`preload="metadata"`). A file that fails to load says so in its card, and keeps its download link.
264
+ - **`MediaGallery`** lays out a run's images, audio, video and PDFs as cards, numbered in the attachments' order so the numbers match the agent's numbered list. Images open a full-size viewer. "Download all" saves every card's file when there's more than one, one at a time, because browsers block a burst of simultaneous downloads. Other files follow the cards as download links.
257
265
  - **`MediaSkeleton`** is a placeholder card for an image that's still being generated. It pulses, unless the user prefers reduced motion.
258
- - **`MediaViewer`** is the gallery's full-size viewer, a modal `<dialog>` with previous and next (also on the arrow keys) and a download button. Escape, the close button or a click on the backdrop closes it, and focus goes back to where it was. It's controlled: pass the `index` to show, or `null` when closed.
259
- - **`attachmentFileName(attachment, number?)`** is the filename the components save a file as: its own name, or else `image-<number>` (or its id) with an extension from the mime type, such as `image-2.png`.
266
+ - **`MediaViewer`** is the gallery's full-size image viewer, a modal `<dialog>` with previous and next (also on the arrow keys) and a download button. Escape, the close button or a click on the backdrop closes it, and focus goes back to where it was. It's controlled: pass the `index` to show, or `null` when closed. Pass `numbers` to name each image by its card number rather than its position. Video and PDFs don't open in it: video has its own full-screen control, and a PDF its browser viewer.
267
+ - **`attachmentFileName(attachment, number?)`** is the filename the components save a file as: its own name, or else its kind and number (`image-2.png`, `audio-3.mp3`, `video-1.mp4`, `pdf-4.pdf`, `file-5.zip`), or its id without a number, with an extension from the mime type.
260
268
 
261
269
  | `MediaPreview` prop | |
262
270
  |---|---|
263
271
  | `attachment` | Required. The file to show |
264
- | `aspectRatio` | The frame's ratio, as a number (`16 / 9`) or a string (`"16 / 9"`). Without it the frame takes the image's own ratio once it loads, and `--seclai-media-aspect-ratio` (square) until then |
265
- | `number` | A badge on the image, matching the agent's numbered list. Also names an unnamed download `image-<number>` |
272
+ | `aspectRatio` | An image or video frame's ratio, as a number (`16 / 9`) or a string (`"16 / 9"`). Without it the frame takes the file's own ratio once it loads, and `--seclai-media-aspect-ratio` (square) until then. Audio and PDF cards don't use it |
273
+ | `number` | A badge on the card, matching the agent's numbered list. Also names an unnamed file, such as `image-<number>` or `audio-<number>`, for download and for screen readers ("Audio 2") |
266
274
  | `actions` | App-specific buttons after the download link: a node, or a function of the attachment |
267
- | `onOpen` | Makes the image a button, for opening a viewer |
275
+ | `onOpen` | Makes an image a button, for opening a viewer. Other files ignore it |
268
276
 
269
277
  | `MediaGallery` prop | |
270
278
  |---|---|
271
279
  | `attachments` | Required. A run's attachments |
272
- | `aspectRatio` | Every card's ratio. Without it each card takes its image's own ratio |
273
- | `pending` | How many skeleton cards to show after the images, numbered on from them |
274
- | `actions` | `(attachment, number) => ReactNode`, for each image card |
280
+ | `aspectRatio` | Every image and video card's ratio. Without it each takes its file's own ratio |
281
+ | `pending` | How many skeleton cards to show after the cards, numbered on from them |
282
+ | `actions` | `(attachment, number) => ReactNode`, for each card |
283
+
284
+ The stylesheet adds these variables for media: `--seclai-media-aspect-ratio` (a frame's ratio before its image or video loads, `1 / 1`), `--seclai-media-fit` (`object-fit` in the frame, `scale-down`, so small images keep their natural size), `--seclai-media-min-width` (a gallery column's minimum width, `220px`), `--seclai-media-max-width` (a card's width outside a gallery, `480px`) and `--seclai-media-pdf-aspect-ratio` (a PDF's frame, `3 / 4`). Each kind of card has a class: `.seclai-media-image`, `.seclai-media-audio`, `.seclai-media-video` and `.seclai-media-pdf`, all with `.seclai-media-card`. The viewer is dark in both colour schemes.
275
285
 
276
- The stylesheet adds these variables for media: `--seclai-media-aspect-ratio` (a frame's ratio before its image loads, `1 / 1`), `--seclai-media-fit` (`object-fit` in the frame, `scale-down`, so small images keep their natural size), `--seclai-media-min-width` (a gallery column's minimum width, `220px`) and `--seclai-media-max-width` (a card's width outside a gallery, `480px`). The viewer is dark in both colour schemes.
286
+ ### Audio, video and PDFs
287
+
288
+ - **Seeking doesn't work yet, and Safari may not play video.** The previews stream through the `download` handler, and the Seclai API doesn't answer HTTP `Range` requests for run attachments yet ([seclai/seclai#2556](https://github.com/seclai/seclai/issues/2556)), nor can `@seclai/sdk` send them ([seclai/seclai-javascript#21](https://github.com/seclai/seclai-javascript/issues/21)). So audio and video play from the start but can't skip ahead, and Safari, which wants `206 Partial Content` for video, may refuse to play it at all. The download link still works. The handler will forward `Range` once both land.
289
+ - **Your Content Security Policy** must let the page load media and objects from the handler's URL: if you set `media-src` or `object-src` (or `default-src`), they need `'self'`, or wherever you mount the handler. `object-src 'none'`, a common recommendation, stops PDFs from showing, as do `frame-ancestors 'none'` and `X-Frame-Options: DENY` on the handler's responses (`SAMEORIGIN` is fine). The handler's own `sandbox` policy on the files it serves doesn't stop `<audio>` and `<video>` from playing them: a response's policy only applies when it's opened as a page.
277
290
 
278
291
  ### Saving files
279
292
 
@@ -297,25 +310,137 @@ Here `toJpeg` is your own code that draws the image on a canvas and returns `can
297
310
  - **`saveFile(urlOrBlob, filename)`** saves a URL or a `Blob` through a temporary `<a download>`. A URL that isn't `http:`, `https:`, `blob:` or relative (such as `javascript:`) is skipped with a warning. For a `Blob` it makes an object URL and revokes it 40 seconds later, once the browser has had time to start the download. Without a `document`, as in server rendering, it does nothing.
298
311
  - **`saveFiles(files, { delayMs, signal })`** saves `{ source, filename }` files one at a time with `saveFile`, waiting `delayMs` (400 ms) between them, as "Download all" does. A `source` is a URL or a `Blob`. It stops when `signal` aborts.
299
312
 
300
- ## Placeholders
313
+ ## Markdown
314
+
315
+ `AgentRunForm` and `AgentChat` show the agent's replies, and the user's messages, with `MarkdownContent`. It's exported for your own UI too:
316
+
317
+ ```tsx
318
+ import { MarkdownContent } from "@seclai/react";
319
+
320
+ <MarkdownContent content={run.text} streaming={run.status === "running"} />
321
+ ```
322
+
323
+ | Prop | |
324
+ |---|---|
325
+ | `content` | Required. The Markdown |
326
+ | `streaming` | The text is still arriving. See [Streaming](#streaming) |
327
+ | `extensions` | Extensions such as `math()`, in place of the ones from `SeclaiMarkdownProvider` |
328
+
329
+ It renders [GitHub Flavored Markdown](https://github.github.com/gfm/):
330
+
331
+ - paragraphs, headings, **bold**, *emphasis*, ~~strikethrough~~, block quotes and rules;
332
+ - links, and bare URLs and emails, which become links;
333
+ - inline code and code blocks, fenced or indented, in a monospace font. Code blocks scroll sideways rather than wrap;
334
+ - lists, nested by indenting an item to the text of the item above, with paragraphs and code blocks inside items;
335
+ - tables, which scroll sideways when they're too wide;
336
+ - task lists (`- [ ]`, `- [x]`), as disabled checkboxes, and footnotes.
337
+
338
+ Agent replies get a few extras:
339
+
340
+ - **Numbered items keep the number the agent wrote.** Markdown only keeps a list's first number and counts on from it, so `1. 1. 1.` would read 1, 2, 3. Each number shows in a badge like `MediaPreview`'s, so "2." in the text matches image 2. The list is still an `<ol>` with `start` and `value` set.
341
+ - **A single newline is a line break**, as in chat apps, rather than a space. `<br>` is one too, as agents write it in table cells.
342
+ - **`•` works as a bullet**, as well as `-`, `*` and `+`.
343
+
344
+ Maths, Mermaid diagrams and HTML are opt-in: see [Extensions](#extensions).
345
+
346
+ ### Streaming
347
+
348
+ `MarkdownContent` re-renders on every token. To stay fast on long replies, it splits the text into top-level blocks, such as paragraphs, lists, tables and code blocks, and only parses the last one again: about 2 ms per token on a 50 KB reply, where parsing the whole reply takes over 100 ms. Blocks are split where the parser ended one, so a list with blank lines between its items, or a code block holding a blank line, stays whole. A reply with a link reference definition (`[docs]: https://…`) or a footnote is parsed whole, as those change text elsewhere in it.
349
+
350
+ Partial text renders as what it is so far, without errors or garbage:
351
+
352
+ - An unclosed code fence is a code block to the end.
353
+ - A table's header row is text until its delimiter row arrives.
354
+ - An unclosed `**`, `` ` `` or `[link](` is text until it closes.
355
+ - Maths and diagrams render once they're complete: see [Extensions](#extensions).
356
+
357
+ With `streaming` set (`AgentRunForm` and `AgentChat` set it while a reply streams), an unfinished last line that could still turn into something else is held back until more of it arrives: a bare list marker (`-`, `2.`), the start of a rule or heading underline (`-`, `--`, `* *`), a fence (```` ``` ````, `$$`), a table's delimiter row (`| --- |`) or a bare `#`. Shown as they are, these would flash as an empty list item, or turn the line above into a heading, for a token or two.
358
+
359
+ ### Extensions
360
+
361
+ HTML, maths and Mermaid diagrams are extensions, each in an entry of its own, so an app that doesn't use one doesn't bundle it. Pass them to every `MarkdownContent` at once, including the ones `AgentRunForm` and `AgentChat` render, with `SeclaiMarkdownProvider`:
362
+
363
+ ```tsx
364
+ import { AgentChat, SeclaiMarkdownProvider } from "@seclai/react";
365
+ import { html } from "@seclai/react/html";
366
+ import { math } from "@seclai/react/math";
367
+ import { mermaid } from "@seclai/react/mermaid";
368
+ import "katex/dist/katex.min.css"; // for math()
369
+
370
+ const extensions = [html(), math(), mermaid()];
371
+
372
+ export function App() {
373
+ return (
374
+ <SeclaiMarkdownProvider extensions={extensions}>
375
+ <AgentChat />
376
+ </SeclaiMarkdownProvider>
377
+ );
378
+ }
379
+ ```
301
380
 
302
- These are exported so the API is in place, but they're minimal until they're ported from the main Seclai app:
381
+ Or pass them to one `MarkdownContent` with its `extensions` prop, which replaces the provider's. Each factory returns the same extension every time, so calling them inline is fine.
303
382
 
304
- | Export | For now | Coming |
383
+ | Extension | Install | Renders |
305
384
  |---|---|---|
306
- | `MarkdownContent` | Paragraphs, lists, rules and bold (see below) | GFM tables, KaTeX, mermaid, sanitized SVG |
307
- | `MediaPreview` | Image cards (see [Media](#media)), a download link for everything else | Audio, video and PDF previews |
385
+ | `html()` from `@seclai/react/html` | Nothing more | HTML in the Markdown, such as `<sub>`, `<kbd>`, `<details>` and inline `<svg>` charts, sanitized (see [Security](#security)). Without it, HTML shows as the text it is. It bundles an HTML parser, about 50 KB gzipped |
386
+ | `math()` from `@seclai/react/math` | `katex` and `remark-math` | `$…$` and `\(…\)` inline, `$$…$$` and `\[…\]` as a block, and ```` ```math ```` fences, with [KaTeX](https://katex.org). Import KaTeX's stylesheet, `katex/dist/katex.min.css`, once in your app: without it the maths shows twice, as text and as MathML |
387
+ | `mermaid()` from `@seclai/react/mermaid` | `mermaid` | ```` ```mermaid ```` code blocks as [Mermaid](https://mermaid.js.org) diagrams. Mermaid is loaded on demand the first time a diagram shows, so bundlers split it into chunks of its own |
308
388
 
309
- `MarkdownContent` shows the agent's text in `AgentRunForm` and `AgentChat`. It renders:
389
+ **Before turning on `html()`:** with it, angle brackets in prose are read as HTML tags, and a tag that isn't on the allowlist is removed. Agents write such text all the time outside backticks, and the reader sees words go missing with no sign of why:
310
390
 
311
- - paragraphs, split by blank lines, with a single newline as a line break;
312
- - numbered lists (`1.` or `1)`), keeping the agent's own numbers. Each number is a badge like the one on `MediaPreview`, so "2." in the text matches image 2;
313
- - bulleted lists (`-`, `*` or `•`);
314
- - nested lists: an item indented at least 2 spaces more than the item above it (a tab counts as 4) is nested in that item, numbered or bulleted, at any depth;
315
- - horizontal rules: a line of three or more `-`, `*` or `_`, optionally spaced (`---`, `* * *`);
316
- - `**bold**`.
391
+ | The agent writes | Shows with `html()` |
392
+ |---|---|
393
+ | `Return a List<String> of names` | Return a List of names |
394
+ | `Pass the <filename> argument` | Pass the argument |
395
+ | `If a<b and c>d then swap.` | If a**d then swap.** (read as a `<b>` tag) |
396
+
397
+ Text in backticks, such as `` `List<String>` ``, is safe. So turn `html()` on only for agents that are meant to produce HTML or SVG, and prompt them to put code, types and placeholders in backticks. A tag left open also makes the rest of the reply re-parse whole on every streamed token, which slows long replies down.
398
+
399
+ `katex`, `remark-math` and `mermaid` are optional peer dependencies: install them only for the extensions you use.
400
+
401
+ ```sh
402
+ npm install katex remark-math # for math()
403
+ npm install mermaid # for mermaid()
404
+ ```
317
405
 
318
- Anything else, such as headings, links, code and tables, shows as the text it is. It never renders HTML. While the text streams in, a list item with nothing after its marker, a rule that's only partly there, or a `**` that isn't closed yet, shows as plain text until it's complete. The root element is a `div.seclai-markdown`, and the list numbers are `.seclai-markdown-number`.
406
+ How they handle partial and invalid input:
407
+
408
+ - **Maths** renders once its closing delimiter arrives. Until then, `$…` is text, and a `$$` block or ```` ```math ```` fence shows its source as a code block. Invalid LaTeX shows as its source in code, not as a KaTeX error. `\(…\)` and `\[…\]` are rewritten to `$…$` and `$$…$$` before parsing, except in code. As in most Markdown maths, `$5 and $10` on one line is read as maths.
409
+ - **A Mermaid diagram** is drawn once its closing fence arrives. Until then, while Mermaid loads, and if the diagram has a syntax error, its source shows as a code block. `mermaid({ theme: "dark" })` picks Mermaid's theme (`"default"`, on a white background, unless set). Mermaid has one configuration per page, so the first theme used applies to every diagram.
410
+
411
+ To write your own, a `MarkdownExtension` is an object with any of `remarkPlugins`, `rehypePluginsBeforeSanitize`, `rehypePlugins`, `components` and `transform`. `rehypePlugins` run after sanitizing, so they must only add HTML they built. `components` replace the built-in ones, as in [react-markdown](https://github.com/remarkjs/react-markdown#components). Create an extension once, outside your components, rather than on every render: a new object is a new set of plugins, which renders every block again. For example, to show images inline rather than as links (see [Security](#security)):
412
+
413
+ ```tsx
414
+ const images: MarkdownExtension = {
415
+ components: { img: ({ node: _, ...props }) => <img {...props} loading="lazy" /> },
416
+ };
417
+ ```
418
+
419
+ ### Security
420
+
421
+ Agent output is untrusted: a reply can be steered by whatever the agent read. So:
422
+
423
+ - **Links** keep only `http:`, `https:` and `mailto:` URLs, and relative ones (`/path`, `#id`). Anything else, such as `javascript:` or `data:`, is removed, and the link shows as its text. `http:` and `https:` links open in a new tab with `rel="noopener noreferrer"`.
424
+ - **Images show as links** to the image (with its alt text, or else its URL), rather than loading. A reply could otherwise use an image URL to send data from the conversation to another server, or to track that it was viewed. An image inside a link shows as its alt text. To show images anyway, replace the `img` component with an extension, as above; the URL rules still apply, so only `http:`, `https:` and relative image URLs load.
425
+ - **HTML shows as text** unless `html()` is on. With it, HTML is sanitized to an allowlist: [GitHub's](https://github.com/syntax-tree/hast-util-sanitize#defaultschema), plus SVG shapes, text, gradients, markers, masks and filters. `<script>`, `<style>`, `<iframe>`, `<foreignObject>`, `<template>` and `<noscript>` are removed with their content; other elements not on the list, such as `<form>` or `<object>`, are removed but keep their text. `on*` event handlers, `style`, `class`, `accesskey` and `tabindex` attributes are removed. Every `id` is prefixed with `user-content-`, so a reply can't clobber the app's own ids, and in-page links (`#id`) follow the prefix. In SVG, `href` and `url(…)` can only point at an id in the same reply.
426
+ - **KaTeX** runs with `trust: false`, so `\href`, `\url`, `\includegraphics` and the `\html…` commands don't produce links, images or attributes.
427
+ - **Mermaid** runs with `securityLevel: "strict"` and `startOnLoad: false`, and syntax errors show the source rather than Mermaid's error diagram. Labels can't hold images or `style` attributes, and a diagram's `%%{init: …}%%` directive can't set `themeCSS`, `fontFamily`, `altFontFamily` or the label sanitizing, which Mermaid copies into the diagram as they are, so a diagram can't load outside URLs or restyle the page.
428
+
429
+ ### Styling Markdown
430
+
431
+ The stylesheet styles Markdown with the same `--seclai-*` variables, in light and dark colour schemes. The root is a `div.seclai-markdown`, and its elements are plain HTML (`p`, `h1` to `h6`, `pre > code`, `table`, `blockquote` and so on), so `.seclai-markdown h2` and the like work for your own styles. It also uses:
432
+
433
+ | Class | |
434
+ |---|---|
435
+ | `.seclai-markdown-number` | A numbered item's badge, the first child of its `li`. The item's content is in a `div` after it |
436
+ | `.seclai-markdown-table` | The scrolling wrapper around a table |
437
+ | `.seclai-markdown-image` | The link an image shows as |
438
+ | `.seclai-markdown-math` | KaTeX's output: a `span` inline, a `div` for a block |
439
+ | `.seclai-markdown-mermaid` | A drawn diagram, with `data-theme` set to its Mermaid theme |
440
+ | `.task-list-item`, `.contains-task-list` | A task list's items, and the list |
441
+ | `section.footnotes` | The footnotes, at the end |
442
+
443
+ Two more variables: `--seclai-code-font` (the monospace font for code) and `--seclai-code-surface` (the background of code blocks and inline code).
319
444
 
320
445
  ## License
321
446
 
@@ -0,0 +1,117 @@
1
+ "use client";
2
+
3
+ // src/markdown/text.ts
4
+ function normalizeNewlines(text) {
5
+ return text.includes("\r") ? text.replace(/\r\n?/g, "\n") : text;
6
+ }
7
+ var CONTAINER_PREFIX = /^[\s>]*/;
8
+ var PENDING_LINE = /^(?:\d{1,9}[.)]?)?[-*+_=•|:`~$#\s]*$/;
9
+ function holdBackPendingLine(text) {
10
+ const start = text.lastIndexOf("\n") + 1;
11
+ const line = text.slice(start).replace(CONTAINER_PREFIX, "");
12
+ return PENDING_LINE.test(line) ? text.slice(0, start) : text;
13
+ }
14
+ var FENCE_OPEN = /^[ \t>]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*(`{3,}(?=[^`]*$)|~{3,})/;
15
+ var FENCE_CLOSE = /^[ \t>]*(`{3,}|~{3,})[ \t]*$/;
16
+ function codeRanges(text) {
17
+ const ranges = [];
18
+ let fence = null;
19
+ let runStart = -1;
20
+ const spans = (start, end) => {
21
+ let at = start;
22
+ while (at < end) {
23
+ const tick = text.indexOf("`", at);
24
+ if (tick === -1 || tick >= end) break;
25
+ let length = 1;
26
+ while (text[tick + length] === "`") length++;
27
+ let slashes = 0;
28
+ while (text[tick - 1 - slashes] === "\\") slashes++;
29
+ if (slashes % 2 === 1) {
30
+ at = tick + 1;
31
+ continue;
32
+ }
33
+ let close = tick + length;
34
+ let found = -1;
35
+ while (close < end) {
36
+ const next = text.indexOf("`", close);
37
+ if (next === -1 || next >= end) break;
38
+ let run = 1;
39
+ while (text[next + run] === "`") run++;
40
+ if (run === length) {
41
+ found = next;
42
+ break;
43
+ }
44
+ close = next + run;
45
+ }
46
+ if (found === -1) {
47
+ at = tick + length;
48
+ } else {
49
+ ranges.push([tick, found + length]);
50
+ at = found + length;
51
+ }
52
+ }
53
+ };
54
+ let lineStart = 0;
55
+ while (lineStart <= text.length) {
56
+ const newline = text.indexOf("\n", lineStart);
57
+ const lineEnd = newline === -1 ? text.length : newline;
58
+ const line = text.slice(lineStart, lineEnd);
59
+ if (fence) {
60
+ const closing = FENCE_CLOSE.exec(line)?.[1];
61
+ if (closing && closing[0] === fence.char && closing.length >= fence.length) {
62
+ ranges.push([fence.start, lineEnd]);
63
+ fence = null;
64
+ }
65
+ } else {
66
+ const opening = FENCE_OPEN.exec(line)?.[1];
67
+ const blank = !line.trim();
68
+ if (opening || blank) {
69
+ if (runStart !== -1) spans(runStart, lineStart);
70
+ runStart = -1;
71
+ } else if (runStart === -1) {
72
+ runStart = lineStart;
73
+ }
74
+ if (opening) fence = { char: opening[0], length: opening.length, start: lineStart };
75
+ }
76
+ if (newline === -1) break;
77
+ lineStart = newline + 1;
78
+ }
79
+ if (fence) ranges.push([fence.start, text.length]);
80
+ else if (runStart !== -1) spans(runStart, text.length);
81
+ return ranges.sort((a, b) => a[0] - b[0]);
82
+ }
83
+ function replaceOutsideCode(text, pattern, replace) {
84
+ const ranges = codeRanges(text);
85
+ if (ranges.length === 0) {
86
+ return text.replace(pattern, (match, ...rest) => replace(match, rest.at(-2), text));
87
+ }
88
+ let masked = "";
89
+ let at = 0;
90
+ for (const [start, end] of ranges) {
91
+ masked += text.slice(at, start) + "\0".repeat(end - start);
92
+ at = end;
93
+ }
94
+ masked += text.slice(at);
95
+ let out = "";
96
+ at = 0;
97
+ for (const match of masked.matchAll(pattern)) {
98
+ const start = match.index;
99
+ const end = start + match[0].length;
100
+ out += text.slice(at, start) + replace(text.slice(start, end), start, text);
101
+ at = end;
102
+ }
103
+ return out + text.slice(at);
104
+ }
105
+ var BULLET = /^([ \t>]*)•(?=[ \t])/gm;
106
+ function normalizeBullets(text) {
107
+ return text.includes("\u2022") ? replaceOutsideCode(text, BULLET, (match) => `${match.slice(0, -1)}-`) : text;
108
+ }
109
+ var MAY_DEFINE = /^[ \t]*(?:(?:>|(?:[-*+]|\d{1,9}[.)])[ \t])[ \t]*)*\[(?:[^\\\]]|\\[\s\S]){1,999}\]:/m;
110
+
111
+ export {
112
+ normalizeNewlines,
113
+ holdBackPendingLine,
114
+ replaceOutsideCode,
115
+ normalizeBullets,
116
+ MAY_DEFINE
117
+ };
@@ -0,0 +1,134 @@
1
+ "use client";
2
+
3
+ // src/markdown/plugins.ts
4
+ function visit(node, test, fn, parent) {
5
+ if (node.type === test) fn(node, parent);
6
+ if ("children" in node) for (const child of node.children) visit(child, test, fn, node);
7
+ }
8
+ function remarkListNumbers() {
9
+ return (tree, file) => {
10
+ const source = String(file.value);
11
+ visit(tree, "list", (list) => {
12
+ if (list.type !== "list" || !list.ordered) return;
13
+ for (const item of list.children) {
14
+ const offset = item.position?.start.offset;
15
+ if (offset === void 0) continue;
16
+ const number = /^[ \t]*(\d{1,9})[.)]/.exec(source.slice(offset, offset + 16))?.[1];
17
+ if (number === void 0) continue;
18
+ item.data = { ...item.data, hProperties: { ...item.data?.hProperties, value: number } };
19
+ }
20
+ });
21
+ };
22
+ }
23
+ var LINE_ENDING = /[ \t]*\n[ \t]*/;
24
+ function remarkLineBreaks() {
25
+ const split = (parent) => {
26
+ const children = [];
27
+ let changed = false;
28
+ for (const child of parent.children) {
29
+ if (child.type === "text" && child.value.includes("\n")) {
30
+ changed = true;
31
+ child.value.split(LINE_ENDING).forEach((value, i) => {
32
+ if (i > 0) children.push({ type: "break" });
33
+ if (value) children.push({ type: "text", value });
34
+ });
35
+ continue;
36
+ }
37
+ if ("children" in child) split(child);
38
+ children.push(child);
39
+ }
40
+ if (changed) parent.children = children;
41
+ };
42
+ return (tree) => split(tree);
43
+ }
44
+ var BR = /^<br\s*\/?>$/i;
45
+ function remarkHtmlBreaks() {
46
+ return (tree) => visit(tree, "html", (node, parent) => {
47
+ if (node.type !== "html" || !parent || parent.type === "root" || !BR.test(node.value)) return;
48
+ const index = parent.children.indexOf(node);
49
+ parent.children[index] = { type: "break" };
50
+ });
51
+ }
52
+ function isClosedFence(node, source) {
53
+ const start = node.position?.start.offset;
54
+ const end = node.position?.end.offset;
55
+ if (start === void 0 || end === void 0) return true;
56
+ const text = source.slice(start, end);
57
+ const opening = /^[ \t]*(`{3,}|~{3,}|\${2,})/.exec(text)?.[1];
58
+ if (!opening) return true;
59
+ const newline = text.lastIndexOf("\n");
60
+ if (newline === -1) return false;
61
+ const closing = /^[ \t>]*(`+|~+|\$+)[ \t]*$/.exec(text.slice(newline + 1))?.[1];
62
+ return !!closing && closing[0] === opening[0] && closing.length >= opening.length;
63
+ }
64
+ function remarkOpenFencesAsCode(languages) {
65
+ return () => (tree, file) => {
66
+ const source = String(file.value);
67
+ visit(tree, "code", (node) => {
68
+ const code = node;
69
+ if (code.lang && languages.includes(code.lang.toLowerCase()) && !isClosedFence(code, source)) {
70
+ code.lang = null;
71
+ code.meta = null;
72
+ }
73
+ });
74
+ };
75
+ }
76
+ var isElement = (node) => node.type === "element";
77
+ function rehypeRawAsText() {
78
+ const walk = (node) => {
79
+ node.children.forEach((child, index) => {
80
+ const raw = child;
81
+ if (raw.type === "raw") node.children[index] = { type: "text", value: raw.value };
82
+ else if (child.type === "element") walk(child);
83
+ });
84
+ };
85
+ return (tree) => walk(tree);
86
+ }
87
+ function rehypeTrimBlocks() {
88
+ return (tree) => {
89
+ tree.children = tree.children.filter((child) => child.type !== "text" || child.value.trim() !== "");
90
+ };
91
+ }
92
+ function rehypeListBadges() {
93
+ const walk = (node) => {
94
+ for (const child of node.children) {
95
+ if (child.type !== "element") continue;
96
+ walk(child);
97
+ if (child.tagName !== "ol") continue;
98
+ const start = Number(child.properties.start);
99
+ let next = Number.isInteger(start) ? start : 1;
100
+ let first;
101
+ for (const item of child.children) {
102
+ if (!isElement(item) || item.tagName !== "li") continue;
103
+ const value = Number(item.properties.value);
104
+ const number = Number.isInteger(value) && item.properties.value !== void 0 ? value : next;
105
+ first ??= number;
106
+ next = number + 1;
107
+ item.properties.value = number;
108
+ item.children = [
109
+ {
110
+ type: "element",
111
+ tagName: "span",
112
+ properties: { className: ["seclai-markdown-number"] },
113
+ children: [{ type: "text", value: String(number) }]
114
+ },
115
+ { type: "element", tagName: "div", properties: {}, children: item.children }
116
+ ];
117
+ }
118
+ if (first !== void 0) child.properties.start = first;
119
+ child.properties.role = "list";
120
+ }
121
+ };
122
+ return (tree) => walk(tree);
123
+ }
124
+
125
+ export {
126
+ remarkListNumbers,
127
+ remarkLineBreaks,
128
+ remarkHtmlBreaks,
129
+ isClosedFence,
130
+ remarkOpenFencesAsCode,
131
+ rehypeRawAsText,
132
+ rehypeTrimBlocks,
133
+ rehypeListBadges
134
+ };
@@ -0,0 +1,49 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { Options, Components } from 'react-markdown';
4
+
5
+ type PluggableList = NonNullable<Options["remarkPlugins"]>;
6
+ /**
7
+ * Adds to what `MarkdownContent` renders: HTML with `html()` from
8
+ * `@seclai/react/html`, maths with `math()` from `@seclai/react/math`, or
9
+ * diagrams with `mermaid()` from `@seclai/react/mermaid`.
10
+ */
11
+ interface MarkdownExtension {
12
+ /** remark plugins, run on the Markdown tree after the built-in syntax (GFM). */
13
+ remarkPlugins?: PluggableList;
14
+ /**
15
+ * rehype plugins, run on the HTML tree before it's sanitized, such as
16
+ * `rehype-raw` in `html()`. What they add is sanitized.
17
+ */
18
+ rehypePluginsBeforeSanitize?: PluggableList;
19
+ /**
20
+ * rehype plugins, run on the HTML tree after it's sanitized. What they add
21
+ * isn't sanitized, so they must only add HTML they built themselves.
22
+ */
23
+ rehypePlugins?: PluggableList;
24
+ /**
25
+ * Components for elements, as in `react-markdown`. They replace the built-in
26
+ * ones for the same element, such as `a`, `img` or `table`.
27
+ */
28
+ components?: Components;
29
+ /** Rewrites the whole text before it's parsed, for syntax Markdown doesn't have. */
30
+ transform?: (markdown: string) => string;
31
+ }
32
+ interface SeclaiMarkdownProviderProps {
33
+ /** The extensions for every `MarkdownContent` inside, including the ones `AgentChat` and `AgentRunForm` render. */
34
+ extensions: readonly MarkdownExtension[];
35
+ children?: ReactNode;
36
+ }
37
+ /**
38
+ * Sets the Markdown extensions for every `MarkdownContent` inside it, such as
39
+ * the ones `AgentChat` and `AgentRunForm` render:
40
+ *
41
+ * ```tsx
42
+ * <SeclaiMarkdownProvider extensions={[math(), mermaid()]}>
43
+ * <AgentChat />
44
+ * </SeclaiMarkdownProvider>
45
+ * ```
46
+ */
47
+ declare function SeclaiMarkdownProvider({ extensions, children }: SeclaiMarkdownProviderProps): react.JSX.Element;
48
+
49
+ export { type MarkdownExtension as M, SeclaiMarkdownProvider as S, type SeclaiMarkdownProviderProps as a };
package/dist/html.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { M as MarkdownExtension } from './extensions-D2MHwNt1.js';
2
+ import 'react';
3
+ import 'react-markdown';
4
+
5
+ /**
6
+ * HTML written in the Markdown, such as `<sub>`, `<kbd>`, `<details>` or an
7
+ * inline `<svg>` chart, rendered rather than shown as text. It's sanitized to
8
+ * an allowlist: GitHub's, plus SVG shapes, text, gradients and filters. Scripts,
9
+ * styles, event handlers, `<iframe>`, `<foreignObject>`, forms and URLs other
10
+ * than http, https and mailto are removed, and SVG can only reference ids in
11
+ * the same reply.
12
+ *
13
+ * ```tsx
14
+ * import { SeclaiMarkdownProvider } from "@seclai/react";
15
+ * import { html } from "@seclai/react/html";
16
+ *
17
+ * <SeclaiMarkdownProvider extensions={[html()]}>…</SeclaiMarkdownProvider>
18
+ * ```
19
+ */
20
+ declare function html(): MarkdownExtension;
21
+
22
+ export { html };
package/dist/html.js ADDED
@@ -0,0 +1,11 @@
1
+ "use client";
2
+
3
+ // src/html.ts
4
+ import rehypeRaw from "rehype-raw";
5
+ var extension = { rehypePluginsBeforeSanitize: [rehypeRaw] };
6
+ function html() {
7
+ return extension;
8
+ }
9
+ export {
10
+ html
11
+ };