@dudko.dev/agent-web-ui 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -4
- package/dist/canvas.cjs +0 -1
- package/dist/canvas.js +1 -2
- package/dist/{chunk-WFM6B7CL.js → chunk-627OXMFG.js} +2 -1
- package/dist/{chunk-EL2YCROY.js → chunk-D64VLIRY.js} +0 -1
- package/dist/{chunk-ZBHESK6V.js → chunk-G7LQTOA2.js} +0 -1
- package/dist/{chunk-SVYHDLAZ.js → chunk-S5AHUAFG.js} +0 -1
- package/dist/{chunk-7O64ZI6Z.js → chunk-TJBGZM6D.js} +0 -1
- package/dist/{chunk-VCR7LU7J.js → chunk-V33T6VX3.js} +0 -1
- package/dist/{chunk-WZ7K7JIP.js → chunk-VZCQXE3P.js} +0 -1
- package/dist/{chunk-GB7RZJMG.js → chunk-WEYQMUKY.js} +0 -1
- package/dist/{chunk-KZQB35LS.js → chunk-Y6QYUFSC.js} +0 -1
- package/dist/controller.cjs +560 -6
- package/dist/controller.d.cts +110 -3
- package/dist/controller.d.ts +110 -3
- package/dist/controller.js +556 -6
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/dist/{labels-DH1ESUtm.d.ts → labels-BJMtk5Fw.d.ts} +2 -0
- package/dist/{labels-CmiTBLWD.d.cts → labels-B_y8F1GW.d.cts} +2 -0
- package/dist/locales/be.cjs +2 -1
- package/dist/locales/be.js +1 -2
- package/dist/locales/bg.cjs +2 -1
- package/dist/locales/bg.js +1 -2
- package/dist/locales/ca.cjs +2 -1
- package/dist/locales/ca.js +1 -2
- package/dist/locales/cs.cjs +2 -1
- package/dist/locales/cs.js +1 -2
- package/dist/locales/da.cjs +2 -1
- package/dist/locales/da.js +1 -2
- package/dist/locales/de.cjs +2 -1
- package/dist/locales/de.js +1 -2
- package/dist/locales/el.cjs +2 -1
- package/dist/locales/el.js +1 -2
- package/dist/locales/en.cjs +2 -1
- package/dist/locales/en.js +1 -2
- package/dist/locales/es-419.cjs +2 -1
- package/dist/locales/es-419.js +2 -3
- package/dist/locales/es.cjs +2 -1
- package/dist/locales/es.js +2 -3
- package/dist/locales/fi.cjs +2 -1
- package/dist/locales/fi.js +1 -2
- package/dist/locales/fr-CA.cjs +2 -1
- package/dist/locales/fr-CA.js +2 -3
- package/dist/locales/fr.cjs +2 -1
- package/dist/locales/fr.js +2 -3
- package/dist/locales/gn.cjs +2 -1
- package/dist/locales/gn.js +1 -2
- package/dist/locales/hr.cjs +2 -1
- package/dist/locales/hr.js +1 -2
- package/dist/locales/ht.cjs +2 -1
- package/dist/locales/ht.js +1 -2
- package/dist/locales/hu.cjs +2 -1
- package/dist/locales/hu.js +1 -2
- package/dist/locales/index.cjs +2 -1
- package/dist/locales/index.js +1 -2
- package/dist/locales/it.cjs +2 -1
- package/dist/locales/it.js +1 -2
- package/dist/locales/nb.cjs +2 -1
- package/dist/locales/nb.js +1 -2
- package/dist/locales/nl.cjs +2 -1
- package/dist/locales/nl.js +1 -2
- package/dist/locales/pl.cjs +2 -1
- package/dist/locales/pl.js +1 -2
- package/dist/locales/pt-BR.cjs +2 -1
- package/dist/locales/pt-BR.js +1 -2
- package/dist/locales/pt.cjs +2 -1
- package/dist/locales/pt.js +1 -2
- package/dist/locales/qu.cjs +2 -1
- package/dist/locales/qu.js +1 -2
- package/dist/locales/ro.cjs +2 -1
- package/dist/locales/ro.js +1 -2
- package/dist/locales/ru.cjs +2 -1
- package/dist/locales/ru.js +1 -2
- package/dist/locales/sk.cjs +2 -1
- package/dist/locales/sk.js +1 -2
- package/dist/locales/sq.cjs +2 -1
- package/dist/locales/sq.js +1 -2
- package/dist/locales/sr-Latn.cjs +2 -1
- package/dist/locales/sr-Latn.js +2 -3
- package/dist/locales/sr.cjs +2 -1
- package/dist/locales/sr.js +2 -3
- package/dist/locales/sv.cjs +2 -1
- package/dist/locales/sv.js +1 -2
- package/dist/locales/tr.cjs +2 -1
- package/dist/locales/tr.js +1 -2
- package/dist/locales/uk.cjs +2 -1
- package/dist/locales/uk.js +1 -2
- package/dist/markdown.cjs +36 -1
- package/dist/markdown.d.cts +27 -1
- package/dist/markdown.d.ts +27 -1
- package/dist/markdown.js +34 -2
- package/dist/mcp-app-sandbox.cjs +0 -1
- package/dist/mcp-app-sandbox.js +1 -2
- package/dist/mcp-app.cjs +0 -1
- package/dist/mcp-app.js +2 -3
- package/dist/pipeline.cjs +0 -1
- package/dist/pipeline.js +1 -2
- package/package.json +3 -3
- package/dist/canvas.cjs.map +0 -1
- package/dist/canvas.js.map +0 -1
- package/dist/chunk-7O64ZI6Z.js.map +0 -1
- package/dist/chunk-EL2YCROY.js.map +0 -1
- package/dist/chunk-GB7RZJMG.js.map +0 -1
- package/dist/chunk-KZQB35LS.js.map +0 -1
- package/dist/chunk-SVYHDLAZ.js.map +0 -1
- package/dist/chunk-VCR7LU7J.js.map +0 -1
- package/dist/chunk-WFM6B7CL.js.map +0 -1
- package/dist/chunk-WZ7K7JIP.js.map +0 -1
- package/dist/chunk-ZBHESK6V.js.map +0 -1
- package/dist/controller.cjs.map +0 -1
- package/dist/controller.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/locales/be.cjs.map +0 -1
- package/dist/locales/be.js.map +0 -1
- package/dist/locales/bg.cjs.map +0 -1
- package/dist/locales/bg.js.map +0 -1
- package/dist/locales/ca.cjs.map +0 -1
- package/dist/locales/ca.js.map +0 -1
- package/dist/locales/cs.cjs.map +0 -1
- package/dist/locales/cs.js.map +0 -1
- package/dist/locales/da.cjs.map +0 -1
- package/dist/locales/da.js.map +0 -1
- package/dist/locales/de.cjs.map +0 -1
- package/dist/locales/de.js.map +0 -1
- package/dist/locales/el.cjs.map +0 -1
- package/dist/locales/el.js.map +0 -1
- package/dist/locales/en.cjs.map +0 -1
- package/dist/locales/en.js.map +0 -1
- package/dist/locales/es-419.cjs.map +0 -1
- package/dist/locales/es-419.js.map +0 -1
- package/dist/locales/es.cjs.map +0 -1
- package/dist/locales/es.js.map +0 -1
- package/dist/locales/fi.cjs.map +0 -1
- package/dist/locales/fi.js.map +0 -1
- package/dist/locales/fr-CA.cjs.map +0 -1
- package/dist/locales/fr-CA.js.map +0 -1
- package/dist/locales/fr.cjs.map +0 -1
- package/dist/locales/fr.js.map +0 -1
- package/dist/locales/gn.cjs.map +0 -1
- package/dist/locales/gn.js.map +0 -1
- package/dist/locales/hr.cjs.map +0 -1
- package/dist/locales/hr.js.map +0 -1
- package/dist/locales/ht.cjs.map +0 -1
- package/dist/locales/ht.js.map +0 -1
- package/dist/locales/hu.cjs.map +0 -1
- package/dist/locales/hu.js.map +0 -1
- package/dist/locales/index.cjs.map +0 -1
- package/dist/locales/index.js.map +0 -1
- package/dist/locales/it.cjs.map +0 -1
- package/dist/locales/it.js.map +0 -1
- package/dist/locales/nb.cjs.map +0 -1
- package/dist/locales/nb.js.map +0 -1
- package/dist/locales/nl.cjs.map +0 -1
- package/dist/locales/nl.js.map +0 -1
- package/dist/locales/pl.cjs.map +0 -1
- package/dist/locales/pl.js.map +0 -1
- package/dist/locales/pt-BR.cjs.map +0 -1
- package/dist/locales/pt-BR.js.map +0 -1
- package/dist/locales/pt.cjs.map +0 -1
- package/dist/locales/pt.js.map +0 -1
- package/dist/locales/qu.cjs.map +0 -1
- package/dist/locales/qu.js.map +0 -1
- package/dist/locales/ro.cjs.map +0 -1
- package/dist/locales/ro.js.map +0 -1
- package/dist/locales/ru.cjs.map +0 -1
- package/dist/locales/ru.js.map +0 -1
- package/dist/locales/sk.cjs.map +0 -1
- package/dist/locales/sk.js.map +0 -1
- package/dist/locales/sq.cjs.map +0 -1
- package/dist/locales/sq.js.map +0 -1
- package/dist/locales/sr-Latn.cjs.map +0 -1
- package/dist/locales/sr-Latn.js.map +0 -1
- package/dist/locales/sr.cjs.map +0 -1
- package/dist/locales/sr.js.map +0 -1
- package/dist/locales/sv.cjs.map +0 -1
- package/dist/locales/sv.js.map +0 -1
- package/dist/locales/tr.cjs.map +0 -1
- package/dist/locales/tr.js.map +0 -1
- package/dist/locales/uk.cjs.map +0 -1
- package/dist/locales/uk.js.map +0 -1
- package/dist/markdown.cjs.map +0 -1
- package/dist/markdown.js.map +0 -1
- package/dist/mcp-app-sandbox.cjs.map +0 -1
- package/dist/mcp-app-sandbox.js.map +0 -1
- package/dist/mcp-app.cjs.map +0 -1
- package/dist/mcp-app.js.map +0 -1
- package/dist/pipeline.cjs.map +0 -1
- package/dist/pipeline.js.map +0 -1
package/dist/markdown.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/markdown/index.ts","../src/named-files.ts","../src/markdown/parse.ts","../src/markdown/stream.ts","../src/markdown/render.ts"],"sourcesContent":["// `@dudko.dev/agent-web-ui/markdown`: the answers' Markdown as a tree any front end can draw -\n// the parser (`parse.ts`), the parser of a text still being written (`stream.ts`) and the helpers\n// every renderer needs (`render.ts`). Pure: no framework, no DOM, no import but this package's\n// own `workspacePathOf`. Not in the main entry: a host without Markdown does not carry it.\nexport * from './parse.js'\nexport * from './stream.js'\nexport * from './render.js'\n","/**\n * The workspace files an answer NAMES in its text (`<MessageList showNamedFiles>`): pure, no\n * React, no DOM, no import. What it reads as a path, exactly:\n *\n * - an inline code span whose whole content is an absolute path - `` `/attachments/a.png` ``\n * (one or more backticks, CommonMark's rule: closed by a run of the same length; the one space\n * inside each end is dropped);\n * - the destination of a Markdown link or image - `[a](/media/a.jpg)`, ``,\n * `[a](</notes/my notes.md>)` - percent-decoded.\n *\n * Nothing else: a path in plain words (`see /notes.md`), in a fenced code block (``` or ~~~ - a\n * listing, a command, an example: not something the answer hands over), in an indented block or\n * in a URL (`https://…`, `//host/…`) is not read. A path is absolute, one line, at most 512\n * characters, with no empty, `.` or `..` segment, no backslash or control character and no\n * trailing slash (a folder) - it is never normalised into another path: what is looked up is what\n * the answer wrote. Then {@link namedFilesOf} keeps only the paths that EXIST in the workspace's\n * listing - the one check that matters: a path that is not a file of the workspace is nothing.\n *\n * The scan is linear in the text, whatever the text holds (it runs while a message is drawn,\n * and the text is the model's - which a fetched page can steer): code spans by one pass over the\n * runs of backticks, links by a pattern that cannot backtrack across brackets, and no more than\n * {@link NAMED_FILES_TEXT_MAX} characters of it.\n */\n\n/** The most files an answer is shown with (see {@link namedFilesOf}). */\nexport const NAMED_FILES_MAX = 12\n\n/** The most distinct paths kept from one text (a bound on what is looked up, not on the scan). */\nexport const NAMED_FILES_SCAN_MAX = 200\n\n/**\n * The most of a text that is scanned: the first 100,000 characters. That is about 25,000 tokens -\n * more than an answer that hands files over is (above most models' default output limit for one\n * answer); past it, the text is a dump (a file pasted back, a runaway answer), whose paths are a\n * listing, not files handed over. It bounds the scan's (linear) work to a few milliseconds.\n */\nexport const NAMED_FILES_TEXT_MAX = 100_000\n\nconst PATH_MAX = 512\n\n/** `raw` as a workspace path, or `undefined` when it is not one (see the module's rules). */\nexport const workspacePathOf = (raw: string): string | undefined => {\n if (raw.length < 2 || raw.length > PATH_MAX) return undefined\n if (raw[0] !== '/' || raw[1] === '/') return undefined\n // Control characters (a line break among them), DEL, a backslash.\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f\\\\]/.test(raw)) return undefined\n const segments = raw.slice(1).split('/')\n for (const s of segments) {\n if (!s || s === '.' || s === '..' || s.trim() !== s) return undefined\n }\n return raw\n}\n\n/** The text with its fenced code blocks blanked out (the same length, line breaks kept). */\nconst withoutFences = (text: string): string => {\n const lines = text.split('\\n')\n let fence: { char: string; size: number } | undefined\n for (let i = 0; i < lines.length; i++) {\n const open = /^ {0,3}(`{3,}|~{3,})/.exec(lines[i])\n if (!fence) {\n if (open && !(open[1][0] === '`' && lines[i].slice(open[0].length).includes('`'))) {\n fence = { char: open[1][0], size: open[1].length }\n lines[i] = ' '.repeat(lines[i].length)\n }\n continue\n }\n const close = /^ {0,3}(`{3,}|~{3,})\\s*$/.exec(lines[i])\n if (close && close[1][0] === fence.char && close[1].length >= fence.size) fence = undefined\n lines[i] = ' '.repeat(lines[i].length)\n }\n return lines.join('\\n')\n}\n\nconst decoded = (s: string): string => {\n if (!s.includes('%')) return s\n try {\n return decodeURIComponent(s)\n } catch {\n return s\n }\n}\n\n/**\n * The code spans of a text, as CommonMark reads them: a run of backticks opens a span that the\n * next run of the SAME length closes (a run with no such run after it is just backticks). One\n * pass over the runs, and the closer of each found from a map of the next run of each length -\n * linear, where a regex with a back-reference tried every closer for every opener (a run of 300\n * backticks before 20,000 characters took seconds).\n */\nconst codeSpansOf = (text: string): { at: number; end: number; inner: string }[] => {\n const runs: { at: number; size: number }[] = []\n for (let i = text.indexOf('`'); i >= 0; i = text.indexOf('`', i)) {\n let j = i + 1\n while (j < text.length && text.charCodeAt(j) === 96) j++\n runs.push({ at: i, size: j - i })\n i = j\n }\n const next = new Array<number>(runs.length)\n const later = new Map<number, number>()\n for (let k = runs.length - 1; k >= 0; k--) {\n next[k] = later.get(runs[k].size) ?? -1\n later.set(runs[k].size, k)\n }\n const spans: { at: number; end: number; inner: string }[] = []\n for (let k = 0; k < runs.length;) {\n const close = next[k]\n if (close < 0) {\n k++\n continue\n }\n const open = runs[k]\n const end = runs[close].at + runs[close].size\n spans.push({ at: open.at, end, inner: text.slice(open.at + open.size, runs[close].at) })\n // The runs between the two are the span's content.\n k = close + 1\n }\n return spans\n}\n\n/**\n * A link or image: `[text](dest \"title\")`, the destination bare or in `<…>`. The text holds no\n * bracket at all - so a line of `[` is read once, not once from every `[` to the line's end.\n */\nconst LINK =\n /!?\\[[^[\\]\\n]*\\]\\(\\s*(<[^<>\\n]+>|[^\\s()<>]+)(?:\\s+(?:\"[^\"\\n]*\"|'[^'\\n]*'|\\([^()\\n]*\\)))?\\s*\\)/g\n\n/**\n * The workspace paths a text names, in the order they appear, each once, at most\n * {@link NAMED_FILES_SCAN_MAX}. Whether they exist is {@link namedFilesOf}'s question.\n */\nexport const pathsNamedIn = (text: string): string[] => {\n if (!text) return []\n const head = text.length > NAMED_FILES_TEXT_MAX ? text.slice(0, NAMED_FILES_TEXT_MAX) : text\n if (!head.includes('/')) return []\n const found: { at: number; path: string }[] = []\n let masked = withoutFences(head)\n // Code spans first, then blanked: a link written inside one is code, not a link.\n const spans = codeSpansOf(masked)\n const parts: string[] = []\n let from = 0\n for (const span of spans) {\n let inner = span.inner\n if (inner.length > 2 && inner.startsWith(' ') && inner.endsWith(' ')) inner = inner.slice(1, -1)\n const path = workspacePathOf(inner)\n if (path) found.push({ at: span.at, path })\n parts.push(masked.slice(from, span.at), ' '.repeat(span.end - span.at))\n from = span.end\n }\n masked = parts.join('') + masked.slice(from)\n for (const m of masked.matchAll(LINK)) {\n const dest = m[1].startsWith('<') ? m[1].slice(1, -1) : m[1]\n const path = workspacePathOf(decoded(dest))\n if (path) found.push({ at: m.index, path })\n }\n found.sort((a, b) => a.at - b.at)\n const out: string[] = []\n const seen = new Set<string>()\n for (const { path } of found) {\n if (seen.has(path)) continue\n seen.add(path)\n out.push(path)\n if (out.length >= NAMED_FILES_SCAN_MAX) break\n }\n return out\n}\n\nexport interface NamedFilesOptions {\n /** Paths left out - the files the answer wrote, the media it made: they have chips already. */\n exclude?: Iterable<string>\n /** At most this many (default {@link NAMED_FILES_MAX}). */\n max?: number\n}\n\n/**\n * The paths of `named` (from {@link pathsNamedIn}) that are files of the workspace - `exists`\n * answers from its listing, never by reading or fetching anything -, without `exclude`, in order,\n * at most `max` (default 12: each chip of a picture reads its bytes for the thumbnail, and an\n * answer that lists a folder of two hundred files would otherwise read them all - the chips are\n * for the files the answer hands over, not a second file browser; the Files panel has them all).\n */\nexport const namedFilesOf = (\n named: readonly string[],\n exists: (path: string) => boolean,\n { exclude, max = NAMED_FILES_MAX }: NamedFilesOptions = {},\n): string[] => {\n const skip = new Set(exclude ?? [])\n const out: string[] = []\n for (const path of named) {\n if (out.length >= max) break\n if (skip.has(path) || !exists(path)) continue\n skip.add(path)\n out.push(path)\n }\n return out\n}\n","/**\n * Markdown of an answer → blocks and inline runs (pure: no framework, no DOM). A renderer turns\n * them into elements - the React package's `<Markdown>` (`@dudko.dev/agent-web-react/markdown`),\n * or one of any other front end - never into HTML. What answers use: paragraphs with their line\n * breaks, headings, lists (nested), task boxes as text, code blocks, quotes, rules, GFM tables,\n * and inline **bold**, *italic*, ~~struck~~, `code`, links and bare URLs. Raw HTML stays text. A\n * link is a link only for http(s) and mailto ({@link safeHref}) - anything else (`javascript:`,\n * `data:`, `//host`) is its text -, or a FILE when its destination is a workspace path (bare or in\n * `<…>`, with an optional title; `workspacePathOf`, after percent-decoding): `{ t: 'file' }`,\n * which a renderer draws as a link-styled control that opens the file - only if the workspace has\n * it, else as the link's words. A code span whose whole content is such a path carries it too\n * (`path`), for the same control. A link's words hold no link of their own: no bare URL, no path.\n * An image (``) is its `!` and a link (or a file): no picture is ever loaded from an answer.\n *\n * An answer is drawn while it is written: `stream.ts` has the rules for a text that is not\n * finished (what is held back, what is drawn as if closed), so that nothing already on the\n * screen changes its kind or its height when the rest arrives.\n */\n\nimport { workspacePathOf } from '../named-files.js'\n\nexport type MarkdownInline =\n | { t: 'text'; v: string }\n | { t: 'br' }\n | { t: 'code'; v: string; path?: string }\n | { t: 'strong' | 'em' | 'del'; c: MarkdownInline[] }\n | { t: 'link'; href: string; c: MarkdownInline[] }\n | { t: 'file'; path: string; c: MarkdownInline[] }\n\nexport type MarkdownAlign = 'left' | 'center' | 'right' | undefined\n\nexport interface MarkdownListItem {\n c: MarkdownInline[]\n sub?: MarkdownListBlock\n}\nexport interface MarkdownListBlock {\n t: 'list'\n ordered: boolean\n start: number\n items: MarkdownListItem[]\n}\n\nexport type MarkdownBlock =\n | { t: 'p'; c: MarkdownInline[] }\n | { t: 'h'; level: 1 | 2 | 3 | 4 | 5 | 6; c: MarkdownInline[] }\n | { t: 'code'; lang: string; v: string }\n | { t: 'quote'; c: MarkdownBlock[] }\n | { t: 'hr' }\n | MarkdownListBlock\n | { t: 'table'; align: MarkdownAlign[]; head: MarkdownInline[][]; rows: MarkdownInline[][][] }\n\nconst decoded = (s: string): string => {\n if (!s.includes('%')) return s\n try {\n return decodeURIComponent(s)\n } catch {\n return s\n }\n}\n\n/** The longest workspace path (the React package's `workspacePathOf` refuses a longer one). */\nconst PATH_MAX = 512\n/**\n * The longest destination that can still name such a path: each of its characters written at\n * most as `%E2%80%AE` (nine characters for one). A longer one is refused before it is read.\n */\nconst DEST_MAX = 9 * PATH_MAX\n/** The longest title a link to a file may carry - as long as a path. */\nconst TITLE_MAX = PATH_MAX\n\n/**\n * The workspace path a link's destination (what is between its parentheses) names, or\n * `undefined` - read exactly as an answer's link is (`parseMarkdownInline`'s file links): bare or in\n * `<…>` (which may hold spaces and parentheses), with an optional `\"title\"` / `'title'` after\n * it, percent-decoded BEFORE the check - `%2e%2e` is `..`, `%2F%2Fhost` is `//host`, `%5C` a\n * backslash, all refused - and then the React package's `workspacePathOf`, the rules its file\n * chips use (absolute, no `..` / `.` / empty segment, no `//host`, no backslash or control\n * character, never normalised).\n */\nexport const workspaceLinkPath = (raw: string): string | undefined => {\n const runs = parseMarkdownInline(`[x](${raw})`)\n return runs.length === 1 && runs[0].t === 'file' ? runs[0].path : undefined\n}\n\n/**\n * The URL a link may point to, or `undefined`: `http://`, `https://` or `mailto:` (any case), then\n * no blank at all - as the text holds it, never decoded (`javascript:`, `java%73cript:` and\n * `java\\tscript:` are no scheme of these, so text). Nothing relative or protocol-relative\n * (`/a`, `//host`), no `javascript:`, `data:`, `vbscript:`, `file:` or any other scheme. Blanks\n * around it are dropped.\n */\nexport const safeHref = (url: string): string | undefined => {\n const u = url.trim()\n return /^(https?:\\/\\/|mailto:)[^\\s]+$/i.test(u) ? u : undefined\n}\n\n// ── inline ──────────────────────────────────────────────────────────────────\n\ntype Delim = '*' | '_' | '~'\ntype Token =\n | MarkdownInline\n | {\n t: 'delim'\n ch: Delim\n n: 1 | 2\n open: boolean\n close: boolean\n /** Not inside a word on its left (`2*3` is not the start of emphasis still to close). */\n lead?: boolean\n match?: number\n }\n\nconst spaceCode = (code: number) =>\n code === 32 || (code >= 9 && code <= 13) || (code > 127 && /\\s/.test(String.fromCharCode(code)))\nconst isSpace = (c: string | undefined) => c === undefined || spaceCode(c.charCodeAt(0))\nconst isWord = (c: string | undefined) => {\n if (c === undefined) return false\n const code = c.charCodeAt(0)\n if (code < 128)\n return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122)\n return /[\\p{L}\\p{N}]/u.test(c)\n}\nconst URL_START = /^https?:\\/\\//i\nconst URL_TAIL = /[.,;:!?'\")\\]]+$/\n\n/**\n * For each position, where the next `ch` is at or after it (`text.length` when none): built in\n * one pass from the end, so every \"find the closing bracket\" below is a lookup, not a scan.\n */\nconst nextOf = (text: string, test: (code: number) => boolean): Int32Array => {\n const next = new Int32Array(text.length + 1)\n next[text.length] = text.length\n for (let i = text.length - 1; i >= 0; i--) next[i] = test(text.charCodeAt(i)) ? i : next[i + 1]\n return next\n}\n\nconst pushText = (out: MarkdownInline[], v: string) => {\n if (!v) return\n const last = out[out.length - 1]\n if (last?.t === 'text') last.v += v\n else out.push({ t: 'text', v })\n}\n\n/**\n * Inline runs of one paragraph, heading, list item or table cell. A single scan, linear in the\n * text (no backtracking regex: a long line of unmatched `**`, `_`, backticks or brackets costs\n * the same as plain text): code spans first, then links and bare URLs, then emphasis matched\n * with one opener stack per kind of delimiter. `words`: the words of a link, where nothing is a\n * link again - a bare URL is text, a code span is no path.\n */\nexport const parseMarkdownInline = (\n source: string,\n depth = 0,\n tail = false,\n words = false,\n): MarkdownInline[] => {\n // The end of a text still being written: a run of markers there may be half of a longer one,\n // an opener or a closer. It waits for what follows (see `Parse.streaming`).\n const text = tail ? source.replace(/[*_~`]+$/, '') : source\n if (depth > 8) return text ? [{ t: 'text', v: text }] : []\n const n = text.length\n const closeBracket = nextOf(text, (c) => c === 93)\n const closeParen = nextOf(text, (c) => c === 41)\n const newline = nextOf(text, (c) => c === 10)\n const space = nextOf(text, spaceCode)\n // Backtick runs by length, in order: a code span closes at the next run of the same length.\n const runs = new Map<number, number[]>()\n for (let i = 0; i < n;) {\n if (text[i] !== '`') {\n i++\n continue\n }\n let j = i\n while (j < n && text[j] === '`') j++\n const list = runs.get(j - i) ?? []\n list.push(i)\n runs.set(j - i, list)\n i = j\n }\n const cursor = new Map<number, number>()\n\n // A link to a workspace file - `[words](/path)`, `(</my file (1).md>)`, `(/a.md \"title\")` -\n // read from the lookups below, never by a scan from each `[`. Only a destination that can be\n // one is read (sliced, decoded, checked): a bare one holds no `(` and a `<…>` one no `<` - so it\n // holds no other link's address of its kind, and no character is read for more than two links\n // -, it is no longer than a path can be written, and the `[`s before one `](` share one\n // reading. `'open'`: the text ends inside such a link, as it may still be.\n let lookups: Record<'lt' | 'gt' | 'openParen' | 'dq' | 'sq' | 'solid', Int32Array> | undefined\n const look = () =>\n (lookups ??= {\n lt: nextOf(text, (c) => c === 60),\n gt: nextOf(text, (c) => c === 62),\n openParen: nextOf(text, (c) => c === 40),\n dq: nextOf(text, (c) => c === 34),\n sq: nextOf(text, (c) => c === 39),\n solid: nextOf(text, (c) => !spaceCode(c)),\n })\n type FileLink = { path: string; end: number } | 'open' | undefined\n let readAt = -1\n let read: FileLink\n const fileLinkAt = (close: number): FileLink => {\n if (close !== readAt) {\n readAt = close\n read = readFileLink(close + 2)\n }\n return read\n }\n const readFileLink = (start: number): FileLink => {\n const x = look()\n const line = newline[start]\n const p = x.solid[start]\n if (p >= n || p > line) return undefined\n let from: number\n let to: number\n let after: number\n if (text[p] === '<') {\n from = p + 1\n if (from < n && text[from] !== '/') return undefined\n to = x.gt[from]\n const bad = Math.min(x.lt[from], line)\n if (to >= n) return bad >= n && n - from <= DEST_MAX ? 'open' : undefined\n if (bad < to || to - from > DEST_MAX) return undefined\n after = to + 1\n } else if (text[p] === '/') {\n from = p\n if (text[p + 1] === '/') return undefined\n to = Math.min(space[p], closeParen[p])\n const bad = Math.min(x.lt[p], x.gt[p], x.openParen[p])\n if (to >= n) return bad >= n && n - from <= DEST_MAX ? 'open' : undefined\n if (bad < to || to - from > DEST_MAX) return undefined\n after = to\n } else return undefined\n // The destination is whole: a path, or not a link to a file at all.\n const path = workspacePathOf(decoded(text.slice(from, to)))\n if (!path) return undefined\n // Then blanks, an optional title, blanks, and `)` - each found by a lookup.\n let q = x.solid[after]\n if (q > line) return undefined\n if (q >= n) return 'open'\n if ((text[q] === '\"' || text[q] === \"'\") && q > after) {\n const shut = (text[q] === '\"' ? x.dq : x.sq)[q + 1]\n if (shut >= n) return line >= n && n - q <= TITLE_MAX ? 'open' : undefined\n if (shut > line || shut - q > TITLE_MAX) return undefined\n q = x.solid[shut + 1]\n if (q > line) return undefined\n if (q >= n) return 'open'\n }\n return text[q] === ')' ? { path, end: q } : undefined\n }\n\n const tokens: Token[] = []\n const flush = (from: number, to: number) => {\n // Text, with its line breaks.\n let at = from\n while (at < to) {\n const nl = Math.min(newline[at], to)\n if (nl > at) tokens.push({ t: 'text', v: text.slice(at, nl) })\n if (nl < to) tokens.push({ t: 'br' })\n at = nl + 1\n }\n }\n let plain = 0\n let i = 0\n while (i < n) {\n const c = text[i]\n if (c === '`') {\n let j = i\n while (j < n && text[j] === '`') j++\n const len = j - i\n const list = runs.get(len)!\n let k = cursor.get(len) ?? 0\n while (k < list.length && list[k] <= i) k++\n cursor.set(len, k)\n if (k < list.length) {\n flush(plain, i)\n const end = list[k]\n cursor.set(len, k + 1)\n const body = text.slice(j, end).replace(/\\n/g, ' ')\n const v = /^ .* $/s.test(body) && body.trim() ? body.slice(1, -1) : body\n // A span that is a workspace path, whole: a file the answer hands over. Only a closed one\n // - one still being written is no path yet -, and not in a link's words.\n const path = !words && v.includes('/') ? workspacePathOf(v) : undefined\n tokens.push(path ? { t: 'code', v, path } : { t: 'code', v })\n i = plain = end + len\n } else if (tail) {\n // Still being written: code up to where the text ends, as it will be when it closes.\n flush(plain, i)\n const body = text.slice(j).replace(/\\n/g, ' ')\n tokens.push({ t: 'code', v: body.startsWith(' ') && body.trim() ? body.slice(1) : body })\n i = plain = n\n } else i = j\n continue\n }\n if (c === '[') {\n const close = closeBracket[i + 1]\n if (close < n && close > i + 1 && close < newline[i] && text[close + 1] === '(') {\n const end = closeParen[close + 2]\n const href =\n end < n && space[close + 2] >= end ? safeHref(text.slice(close + 2, end)) : undefined\n if (href) {\n flush(plain, i)\n tokens.push({\n t: 'link',\n href,\n c: parseMarkdownInline(text.slice(i + 1, close), depth + 1, false, true),\n })\n i = plain = end + 1\n continue\n }\n // A link with no words (`[](/a.png)`) is text, as for any link. The `!` of an image stays\n // text too: dropped when the link completes, it would be text taken off the screen while\n // the answer streams.\n const file = fileLinkAt(close)\n if (file !== undefined && file !== 'open') {\n flush(plain, i)\n tokens.push({\n t: 'file',\n path: file.path,\n c: parseMarkdownInline(text.slice(i + 1, close), depth + 1, false, true),\n })\n i = plain = file.end + 1\n continue\n }\n if (tail && (file === 'open' || (end >= n && space[close + 2] >= n))) {\n // A link whose address (or title) is still being written: its words, as they will\n // read - never its `](`, address or title.\n flush(plain, i)\n tokens.push(...parseMarkdownInline(text.slice(i + 1, close), depth + 1, false, true))\n i = plain = n\n continue\n }\n }\n if (tail && newline[i] >= n && (close >= n || close === n - 1)) {\n // A bracket still open, or closed by the last character: it may be a link's text, so it\n // is drawn without its brackets until what follows says (`(` - a link - or anything else).\n flush(plain, i)\n if (close >= n) {\n i = plain = i + 1\n continue\n }\n tokens.push(...parseMarkdownInline(text.slice(i + 1, close), depth + 1))\n i = plain = n\n continue\n }\n i++\n continue\n }\n if (\n !words &&\n (c === 'h' || c === 'H') &&\n URL_START.test(text.slice(i, i + 8)) &&\n !isWord(text[i - 1])\n ) {\n let end = space[i]\n for (let k = i; k < end; k++) {\n if ('<>()'.includes(text[k])) {\n end = k\n break\n }\n }\n const url = text.slice(i, end).replace(URL_TAIL, '')\n if (url.length > 8) {\n flush(plain, i)\n tokens.push({ t: 'link', href: url, c: [{ t: 'text', v: url }] })\n i = plain = i + url.length\n continue\n }\n i++\n continue\n }\n if (c === '*' || c === '_' || c === '~') {\n let j = i\n while (j < n && text[j] === c) j++\n const before = text[i - 1]\n const after = text[j]\n let open = !isSpace(after)\n let close = !isSpace(before)\n // An underscore inside a word (snake_case) is not emphasis.\n if (c === '_' && isWord(before) && isWord(after)) open = close = false\n const len = j - i\n if ((c === '~' && len !== 2) || (!open && !close)) {\n i = j\n continue\n }\n flush(plain, i)\n // A run of three opens strong then em, and closes em then strong.\n const sizes: (1 | 2)[] =\n c === '~' ? [2] : len === 1 ? [1] : len === 2 ? [2] : open && !close ? [2, 1] : [1, 2]\n let used = 0\n for (const size of sizes) {\n tokens.push({ t: 'delim', ch: c, n: size, open, close, lead: !isWord(before) })\n used += size\n }\n if (len > used) tokens.push({ t: 'text', v: c.repeat(len - used) })\n i = plain = j\n continue\n }\n i++\n }\n flush(plain, n)\n\n // Emphasis: a closer takes the nearest opener of its kind; openers of other kinds above that\n // one can no longer close and become text. Each opener is pushed and popped once.\n const stacks: number[][] = [[], [], [], [], [], []]\n const kindOf = (tok: { ch: Delim; n: 1 | 2 }) =>\n (tok.ch === '*' ? 0 : tok.ch === '_' ? 2 : 4) + tok.n - 1\n for (let idx = 0; idx < tokens.length; idx++) {\n const tok = tokens[idx]\n if (tok.t !== 'delim') continue\n const own = stacks[kindOf(tok)]\n const top = own.length ? own[own.length - 1] : -1\n if (tok.close && top >= 0 && top < idx - 1) {\n own.pop()\n ;(tokens[top] as { match?: number }).match = idx\n tok.match = top\n for (const st of stacks) while (st.length && st[st.length - 1] > top) st.pop()\n continue\n }\n if (tok.open) own.push(idx)\n }\n if (tail) {\n // Emphasis still open where the text ends is emphasis already: it closes there, the\n // innermost first. (Openers inside a matched pair were dropped above; these nest.)\n const open = stacks.flat().sort((a, b) => b - a)\n for (const idx of open) {\n const opener = tokens[idx] as Token & { t: 'delim' }\n if (!opener.lead) continue\n opener.match = tokens.length\n tokens.push({ t: 'delim', ch: opener.ch, n: opener.n, open: false, close: true, match: idx })\n }\n }\n\n const root: MarkdownInline[] = []\n const frames: {\n out: MarkdownInline[]\n node?: MarkdownInline & { c: MarkdownInline[] }\n until: number\n }[] = [{ out: root, until: -1 }]\n tokens.forEach((tok, idx) => {\n const frame = frames[frames.length - 1]\n if (tok.t !== 'delim') {\n if (tok.t === 'text') pushText(frame.out, tok.v)\n else frame.out.push(tok)\n return\n }\n if (tok.match !== undefined && tok.match > idx) {\n const node = {\n t: tok.ch === '~' ? 'del' : tok.n === 2 ? 'strong' : 'em',\n c: [],\n } as MarkdownInline & { c: MarkdownInline[] }\n frames.push({ out: node.c, node, until: tok.match })\n return\n }\n if (tok.match !== undefined && frame.until === idx && frame.node) {\n frames.pop()\n frames[frames.length - 1].out.push(frame.node)\n return\n }\n pushText(frame.out, tok.ch.repeat(tok.n))\n })\n return root\n}\n\n// ── blocks ──────────────────────────────────────────────────────────────────\n\n// Any indentation: a model puts a code block under a list item with the item's indent (Gemini:\n// 8 spaces), and this scanner has no indented code blocks for it to be instead.\nconst FENCE = /^([ \\t]*)(`{3,}|~{3,})\\s*([\\w+#.-]*)/\nconst HEADING = /^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$/\nconst HR = /^ {0,3}([-*_])(?:\\s*\\1){2,}\\s*$/\nconst BULLET = /^( *)([-*+])\\s+(.*)$/\nconst ORDERED = /^( *)(\\d{1,9})[.)]\\s+(.*)$/\nconst QUOTE = /^ {0,3}>\\s?(.*)$/\nconst TABLE_RULE = /^\\s*\\|?\\s*:?-{1,}:?\\s*(\\|\\s*:?-{1,}:?\\s*)*\\|?\\s*$/\n\n/**\n * The deepest a list nests (counting the quotes and lists around it): far past any answer's, and\n * the bound that keeps a text of ever-deeper items linear (`tests/markdown.test.ts`, \"time\").\n */\nconst LIST_NESTING_MAX = 8\n\nconst cells = (line: string): string[] => {\n let s = line.trim()\n if (s.startsWith('|')) s = s.slice(1)\n if (s.endsWith('|') && !s.endsWith('\\\\|')) s = s.slice(0, -1)\n const out: string[] = []\n let cur = ''\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '\\\\' && s[i + 1] === '|') {\n cur += '|'\n i++\n } else if (s[i] === '|') {\n out.push(cur.trim())\n cur = ''\n } else cur += s[i]\n }\n out.push(cur.trim())\n return out\n}\n\nconst alignOf = (cell: string): MarkdownAlign => {\n const c = cell.trim()\n const left = c.startsWith(':')\n const right = c.endsWith(':')\n return left && right ? 'center' : right ? 'right' : left ? 'left' : undefined\n}\n\nconst startsBlock = (line: string, next: string | undefined): boolean =>\n FENCE.test(line) ||\n HEADING.test(line) ||\n HR.test(line) ||\n BULLET.test(line) ||\n ORDERED.test(line) ||\n QUOTE.test(line) ||\n (line.includes('|') && next !== undefined && TABLE_RULE.test(next) && next.includes('-'))\n\n/**\n * The blocks of a Markdown text. `streaming`: the text is an answer still being written, so\n * what ends at its end is drawn as it will be when it is finished (an inline construct still\n * open - `parseMarkdownInline`'s `tail`); `stream.ts` decides what of the last line is drawn at all.\n */\nexport const parseMarkdown = (text: string, depth = 0, streaming = false): MarkdownBlock[] => {\n const lines = text.replace(/\\r\\n?/g, '\\n').split('\\n')\n const out: MarkdownBlock[] = []\n let i = 0\n /** Whether line `k` is the last of a text still being written. */\n const last = (k: number) => streaming && k >= lines.length - 1\n while (i < lines.length) {\n const line = lines[i]\n if (!line.trim()) {\n i++\n continue\n }\n const fence = FENCE.exec(line)\n if (fence) {\n const body: string[] = []\n // The code's own indentation is kept; the fence's is taken off every line.\n const indent = new RegExp(`^[ \\\\t]{0,${fence[1].length}}`)\n i++\n while (i < lines.length && !lines[i].trimStart().startsWith(fence[2])) {\n body.push(lines[i++].replace(indent, ''))\n }\n i++\n out.push({ t: 'code', lang: fence[3], v: body.join('\\n') })\n continue\n }\n const heading = HEADING.exec(line)\n if (heading) {\n out.push({\n t: 'h',\n level: heading[1].length as 1 | 2 | 3 | 4 | 5 | 6,\n c: parseMarkdownInline(heading[2], 0, last(i)),\n })\n i++\n continue\n }\n if (HR.test(line)) {\n out.push({ t: 'hr' })\n i++\n continue\n }\n if (QUOTE.test(line) && depth < 4) {\n const body: string[] = []\n while (i < lines.length && QUOTE.test(lines[i])) body.push(QUOTE.exec(lines[i++])![1])\n out.push({\n t: 'quote',\n c: parseMarkdown(body.join('\\n'), depth + 1, streaming && i >= lines.length),\n })\n continue\n }\n const next = lines[i + 1]\n if (line.includes('|') && next !== undefined && TABLE_RULE.test(next) && next.includes('-')) {\n const head = cells(line)\n const align = cells(next).map(alignOf)\n i += 2\n const rows: MarkdownInline[][][] = []\n while (i < lines.length && lines[i].trim() && lines[i].includes('|')) {\n const row = cells(lines[i])\n // The cell being written is the last one that has anything in it.\n let open = -1\n if (last(i)) for (let k = 0; k < row.length; k++) if (row[k] !== '') open = k\n i++\n rows.push(head.map((_, k) => parseMarkdownInline(row[k] ?? '', 0, k === open)))\n }\n out.push({ t: 'table', align, head: head.map((h) => parseMarkdownInline(h)), rows })\n continue\n }\n if (BULLET.test(line) || ORDERED.test(line)) {\n const ordered = !BULLET.test(line)\n const first = (ordered ? ORDERED : BULLET).exec(line)!\n const indent = first[1].length\n const list: MarkdownListBlock = {\n t: 'list',\n ordered,\n start: ordered ? Number(first[2]) : 1,\n items: [],\n }\n while (i < lines.length) {\n const l = lines[i]\n const m = (ordered ? ORDERED : BULLET).exec(l)\n if (m && m[1].length <= indent + 1) {\n list.items.push({ c: parseMarkdownInline(m[3], 0, last(i)) })\n i++\n continue\n }\n const nested = BULLET.exec(l) ?? ORDERED.exec(l)\n if (nested && nested[1].length > indent + 1 && list.items.length) {\n if (depth >= LIST_NESTING_MAX) {\n // As deep as lists go: a deeper item is one more item of this list (never dropped).\n list.items.push({ c: parseMarkdownInline(nested[3], 0, last(i)) })\n i++\n continue\n }\n // The deeper items go under the item before them, a level at a time. Each level reads\n // the lines under it again, so the levels are bounded (`LIST_NESTING_MAX`): linear on\n // any staircase of indents.\n const subLines: string[] = []\n while (i < lines.length) {\n const s = BULLET.exec(lines[i]) ?? ORDERED.exec(lines[i])\n if (!s || s[1].length <= indent + 1) break\n subLines.push(lines[i++].slice(nested[1].length))\n }\n const sub = parseMarkdown(\n subLines.join('\\n'),\n depth + 1,\n streaming && i >= lines.length,\n ).find((b): b is MarkdownListBlock => b.t === 'list')\n if (sub) list.items[list.items.length - 1].sub = sub\n continue\n }\n // A continuation line of the item (indented, not blank, not a new block).\n if (\n l.trim() &&\n /^\\s+/.test(l) &&\n !startsBlock(l.trim(), lines[i + 1]) &&\n list.items.length\n ) {\n const item = list.items[list.items.length - 1]\n item.c.push({ t: 'br' }, ...parseMarkdownInline(l.trim(), 0, last(i)))\n i++\n continue\n }\n break\n }\n out.push(list)\n continue\n }\n // A paragraph: up to a blank line or the start of another block; line breaks are kept.\n const body: string[] = [line]\n i++\n while (i < lines.length && lines[i].trim() && !startsBlock(lines[i], lines[i + 1])) {\n body.push(lines[i++])\n }\n out.push({\n t: 'p',\n c: parseMarkdownInline(\n body.map((l) => l.trim()).join('\\n'),\n 0,\n streaming && i >= lines.length,\n ),\n })\n }\n return out\n}\n","import { parseMarkdown, type MarkdownBlock } from './parse.js'\n\n/**\n * An answer's Markdown WHILE IT IS WRITTEN (pure). The text grows a few characters at a time and\n * is drawn each time; drawn naively, what is on the screen keeps changing its kind - a `##`\n * that is a paragraph until its space arrives, a table's first row that is a line of pipes until\n * the rule under it, a fence that closes one backtick at a time, `**` that shows until its pair -\n * and each change moves everything under it. The rules, each pinned by `tests/markdown-stream.test.ts`:\n *\n * 1. A finished line is drawn as it will stay. Only the LAST line can be held back, and only\n * while it cannot be told what it is:\n * - it is nothing but marker characters so far (`#`, `-`, `1.`, `>`, `` ` ``, `|`, `*`, `---`);\n * - inside a code block, it may be the closing fence (or, still blank, its indent);\n * - it starts with `|` and may be a table's header (held with the rule line under it, until\n * that line is complete: then it is a table, or two lines of text).\n * 2. An inline construct open where the text ends is drawn as if it closed there (`parseMarkdownInline`'s\n * `tail`): emphasis and code at once, a link as its text until its address is whole; a run of\n * markers at the very end waits.\n * 3. Blocks before the last blank line (outside a code block) are finished: they are parsed once\n * and kept, as the same objects - so each piece costs the size of the last block, not of the\n * answer, and React leaves the finished blocks alone.\n *\n * What is held back is at most one short line (or a table's two head lines), for as long as it\n * takes the model to write it. A finished answer is parsed whole, without any of this.\n */\n\n/** A fence at any indentation, as `parse.ts` reads it. */\nconst FENCE = /^[ \\t]*(`{3,}|~{3,})/\n/** A line of marker characters only: it can still become a heading, a list, a rule, a fence… */\nconst MARKERS_ONLY = /^[\\s#>*+\\-_|`~=:\\d.)]{0,16}$/\n/** What a table's rule line looks like, whole or in part. */\nconst RULE_SO_FAR = /^\\s*\\|?[\\s:|-]*$/\n\nconst pipes = (line: string | undefined): boolean => line !== undefined && line.includes('|')\nconst blank = (line: string | undefined): boolean => line === undefined || !line.trim()\n\n/**\n * The part of a text still being written that is drawn now: `text` without what its last line\n * cannot yet be told to be (rule 1). Never longer than `text`; equal to it when nothing is held.\n */\nexport const markdownSettled = (text: string): string => {\n const lines = text.split('\\n')\n const n = lines.length\n // The code block the last line is in, if any (its fence).\n let fence: string | undefined\n for (let i = 0; i < n - 1; i++) {\n const line = lines[i]\n if (fence) {\n if (line.trimStart().startsWith(fence)) fence = undefined\n } else {\n const m = FENCE.exec(line)\n if (m) fence = m[1]\n }\n }\n const lastLine = lines[n - 1]\n const cut = (count: number) => lines.slice(0, n - count).join('\\n') + (n > count ? '\\n' : '')\n if (fence) {\n // The closing fence, one character at a time, is not a line of code - nor is its indent\n // (a fence under a list item is written 8 spaces in), so a line of blanks waits too.\n const t = lastLine.trim()\n return !t || fence.startsWith(t) ? cut(1) : text\n }\n // A table's header, and the rule line being written under it.\n const inTable = (k: number) => pipes(lines[k]) && !blank(lines[k])\n if (\n n >= 2 &&\n lines[n - 2].trimStart().startsWith('|') &&\n RULE_SO_FAR.test(lastLine) &&\n !inTable(n - 3)\n )\n return cut(2)\n if (lastLine.trimStart().startsWith('|') && !inTable(n - 2)) return cut(1)\n if (lastLine && MARKERS_ONLY.test(lastLine)) return cut(1)\n return text\n}\n\n/** Where the finished blocks of `text` end, looking from `from` (a block boundary): rule 3. */\nconst finishedEnd = (text: string, from: number): number => {\n let fence: string | undefined\n let end = from\n let at = from\n while (at < text.length) {\n const nl = text.indexOf('\\n', at)\n if (nl < 0) break\n const line = text.slice(at, nl)\n if (fence) {\n if (line.trimStart().startsWith(fence)) fence = undefined\n } else {\n const m = FENCE.exec(line)\n if (m) fence = m[1]\n // A blank line outside a code block ends every block before it.\n else if (!line.trim()) end = nl + 1\n }\n at = nl + 1\n }\n return end\n}\n\n/** The parse of a growing text so far: what is finished, and what was drawn last. */\nexport interface MarkdownStream {\n /** The text the finished blocks came from (a prefix of every later text). */\n done: string\n finished: MarkdownBlock[]\n blocks: MarkdownBlock[]\n}\n\nexport const emptyMarkdownStream = (): MarkdownStream => ({ done: '', finished: [], blocks: [] })\n\n/**\n * The blocks of `text`, an answer still being written, given the parse of what it was before.\n * A text that is not a continuation (another answer) starts over.\n */\nexport const parseMarkdownStreaming = (prev: MarkdownStream, text: string): MarkdownStream => {\n const source = text.includes('\\r') ? text.replace(/\\r\\n?/g, '\\n') : text\n const base = source.startsWith(prev.done) ? prev : emptyMarkdownStream()\n const end = finishedEnd(source, base.done.length)\n const finished =\n end > base.done.length\n ? [...base.finished, ...parseMarkdown(source.slice(base.done.length, end))]\n : base.finished\n // One line break at the end ends no block: the last line is still the last line.\n const tail = parseMarkdown(markdownSettled(source.slice(end)).replace(/\\n$/, ''), 0, true)\n return {\n done: source.slice(0, end),\n finished,\n blocks: tail.length ? [...finished, ...tail] : finished,\n }\n}\n","import { parseMarkdown, type MarkdownBlock, type MarkdownInline } from './parse.js'\n\n/**\n * What every renderer of the parsed tree needs and is not React: the parses cached by text, the\n * words of inline runs, and which table cells wrap. The React package's `<Markdown>` uses these;\n * a renderer of another front end (a web component, Vue, Svelte) should too, so the same answer\n * looks and reads the same everywhere.\n */\n\n/** How many parses {@link parseMarkdownCached} keeps (the oldest go first). */\nexport const MARKDOWN_CACHE_MAX = 64\n\nconst parsed = new Map<string, MarkdownBlock[]>()\n\n/**\n * The blocks of a FINISHED text, cached by the text: a saved chat opened again, or a re-render,\n * does not parse again. Bounded ({@link MARKDOWN_CACHE_MAX}); the parse itself is linear. The\n * blocks are shared between callers - never change them. A text still being written goes through\n * `parseMarkdownStreaming` instead (each piece would be an entry here).\n */\nexport const parseMarkdownCached = (text: string): MarkdownBlock[] => {\n const hit = parsed.get(text)\n if (hit) return hit\n const blocks = parseMarkdown(text)\n parsed.set(text, blocks)\n if (parsed.size > MARKDOWN_CACHE_MAX) parsed.delete(parsed.keys().next().value!)\n return blocks\n}\n\n/** The words of inline runs, as a screen reader is to name them (a link's or a file's words). */\nexport const markdownPlainText = (runs: MarkdownInline[]): string =>\n runs\n .map((r) =>\n r.t === 'text' || r.t === 'code' ? r.v : r.t === 'br' ? ' ' : markdownPlainText(r.c),\n )\n .join('')\n\n/**\n * A table cell longer than this many characters wraps, in a column of its own width; every other\n * cell is one line, and a table wider than the screen scrolls in its box. So a table's rows keep\n * their height when another row arrives while the answer is written (columns that share the\n * width would re-wrap each other's cells).\n */\nexport const MARKDOWN_LONG_CELL = 48\n\nconst lengthOf = (runs: MarkdownInline[]): number =>\n runs.reduce(\n (n, r) =>\n n + (r.t === 'text' || r.t === 'code' ? r.v.length : r.t === 'br' ? 1 : lengthOf(r.c)),\n 0,\n )\n\n/** Whether a table cell wraps (see {@link MARKDOWN_LONG_CELL}). */\nexport const markdownCellIsLong = (runs: MarkdownInline[]): boolean =>\n lengthOf(runs) > MARKDOWN_LONG_CELL\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsCA,IAAM,WAAW;AAGV,IAAM,kBAAkB,CAAC,QAAoC;AAClE,MAAI,IAAI,SAAS,KAAK,IAAI,SAAS,SAAU,QAAO;AACpD,MAAI,IAAI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AW,CAAC,SAChB,KAAK;AAAA,EACH,CAAC,GAAG,MACF,KAAK,EAAE,MAAM,UAAU,EAAE,MAAM,SAAS,EAAE,EAAE,SAAS,EAAE,MAAM,OAAO,IAAI,SAAS,EAAE,CAAC;AAAA,EACtF;AACF;AAGK,IAAM,qBAAqB,CAAC,SACjC,SAAS,IAAI,IAAI;","names":["PATH_MAX","i","body","FENCE"]}
|
package/dist/markdown.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/markdown/parse.ts","../src/markdown/stream.ts","../src/markdown/render.ts"],"sourcesContent":["/**\n * Markdown of an answer → blocks and inline runs (pure: no framework, no DOM). A renderer turns\n * them into elements - the React package's `<Markdown>` (`@dudko.dev/agent-web-react/markdown`),\n * or one of any other front end - never into HTML. What answers use: paragraphs with their line\n * breaks, headings, lists (nested), task boxes as text, code blocks, quotes, rules, GFM tables,\n * and inline **bold**, *italic*, ~~struck~~, `code`, links and bare URLs. Raw HTML stays text. A\n * link is a link only for http(s) and mailto ({@link safeHref}) - anything else (`javascript:`,\n * `data:`, `//host`) is its text -, or a FILE when its destination is a workspace path (bare or in\n * `<…>`, with an optional title; `workspacePathOf`, after percent-decoding): `{ t: 'file' }`,\n * which a renderer draws as a link-styled control that opens the file - only if the workspace has\n * it, else as the link's words. A code span whose whole content is such a path carries it too\n * (`path`), for the same control. A link's words hold no link of their own: no bare URL, no path.\n * An image (``) is its `!` and a link (or a file): no picture is ever loaded from an answer.\n *\n * An answer is drawn while it is written: `stream.ts` has the rules for a text that is not\n * finished (what is held back, what is drawn as if closed), so that nothing already on the\n * screen changes its kind or its height when the rest arrives.\n */\n\nimport { workspacePathOf } from '../named-files.js'\n\nexport type MarkdownInline =\n | { t: 'text'; v: string }\n | { t: 'br' }\n | { t: 'code'; v: string; path?: string }\n | { t: 'strong' | 'em' | 'del'; c: MarkdownInline[] }\n | { t: 'link'; href: string; c: MarkdownInline[] }\n | { t: 'file'; path: string; c: MarkdownInline[] }\n\nexport type MarkdownAlign = 'left' | 'center' | 'right' | undefined\n\nexport interface MarkdownListItem {\n c: MarkdownInline[]\n sub?: MarkdownListBlock\n}\nexport interface MarkdownListBlock {\n t: 'list'\n ordered: boolean\n start: number\n items: MarkdownListItem[]\n}\n\nexport type MarkdownBlock =\n | { t: 'p'; c: MarkdownInline[] }\n | { t: 'h'; level: 1 | 2 | 3 | 4 | 5 | 6; c: MarkdownInline[] }\n | { t: 'code'; lang: string; v: string }\n | { t: 'quote'; c: MarkdownBlock[] }\n | { t: 'hr' }\n | MarkdownListBlock\n | { t: 'table'; align: MarkdownAlign[]; head: MarkdownInline[][]; rows: MarkdownInline[][][] }\n\nconst decoded = (s: string): string => {\n if (!s.includes('%')) return s\n try {\n return decodeURIComponent(s)\n } catch {\n return s\n }\n}\n\n/** The longest workspace path (the React package's `workspacePathOf` refuses a longer one). */\nconst PATH_MAX = 512\n/**\n * The longest destination that can still name such a path: each of its characters written at\n * most as `%E2%80%AE` (nine characters for one). A longer one is refused before it is read.\n */\nconst DEST_MAX = 9 * PATH_MAX\n/** The longest title a link to a file may carry - as long as a path. */\nconst TITLE_MAX = PATH_MAX\n\n/**\n * The workspace path a link's destination (what is between its parentheses) names, or\n * `undefined` - read exactly as an answer's link is (`parseMarkdownInline`'s file links): bare or in\n * `<…>` (which may hold spaces and parentheses), with an optional `\"title\"` / `'title'` after\n * it, percent-decoded BEFORE the check - `%2e%2e` is `..`, `%2F%2Fhost` is `//host`, `%5C` a\n * backslash, all refused - and then the React package's `workspacePathOf`, the rules its file\n * chips use (absolute, no `..` / `.` / empty segment, no `//host`, no backslash or control\n * character, never normalised).\n */\nexport const workspaceLinkPath = (raw: string): string | undefined => {\n const runs = parseMarkdownInline(`[x](${raw})`)\n return runs.length === 1 && runs[0].t === 'file' ? runs[0].path : undefined\n}\n\n/**\n * The URL a link may point to, or `undefined`: `http://`, `https://` or `mailto:` (any case), then\n * no blank at all - as the text holds it, never decoded (`javascript:`, `java%73cript:` and\n * `java\\tscript:` are no scheme of these, so text). Nothing relative or protocol-relative\n * (`/a`, `//host`), no `javascript:`, `data:`, `vbscript:`, `file:` or any other scheme. Blanks\n * around it are dropped.\n */\nexport const safeHref = (url: string): string | undefined => {\n const u = url.trim()\n return /^(https?:\\/\\/|mailto:)[^\\s]+$/i.test(u) ? u : undefined\n}\n\n// ── inline ──────────────────────────────────────────────────────────────────\n\ntype Delim = '*' | '_' | '~'\ntype Token =\n | MarkdownInline\n | {\n t: 'delim'\n ch: Delim\n n: 1 | 2\n open: boolean\n close: boolean\n /** Not inside a word on its left (`2*3` is not the start of emphasis still to close). */\n lead?: boolean\n match?: number\n }\n\nconst spaceCode = (code: number) =>\n code === 32 || (code >= 9 && code <= 13) || (code > 127 && /\\s/.test(String.fromCharCode(code)))\nconst isSpace = (c: string | undefined) => c === undefined || spaceCode(c.charCodeAt(0))\nconst isWord = (c: string | undefined) => {\n if (c === undefined) return false\n const code = c.charCodeAt(0)\n if (code < 128)\n return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122)\n return /[\\p{L}\\p{N}]/u.test(c)\n}\nconst URL_START = /^https?:\\/\\//i\nconst URL_TAIL = /[.,;:!?'\")\\]]+$/\n\n/**\n * For each position, where the next `ch` is at or after it (`text.length` when none): built in\n * one pass from the end, so every \"find the closing bracket\" below is a lookup, not a scan.\n */\nconst nextOf = (text: string, test: (code: number) => boolean): Int32Array => {\n const next = new Int32Array(text.length + 1)\n next[text.length] = text.length\n for (let i = text.length - 1; i >= 0; i--) next[i] = test(text.charCodeAt(i)) ? i : next[i + 1]\n return next\n}\n\nconst pushText = (out: MarkdownInline[], v: string) => {\n if (!v) return\n const last = out[out.length - 1]\n if (last?.t === 'text') last.v += v\n else out.push({ t: 'text', v })\n}\n\n/**\n * Inline runs of one paragraph, heading, list item or table cell. A single scan, linear in the\n * text (no backtracking regex: a long line of unmatched `**`, `_`, backticks or brackets costs\n * the same as plain text): code spans first, then links and bare URLs, then emphasis matched\n * with one opener stack per kind of delimiter. `words`: the words of a link, where nothing is a\n * link again - a bare URL is text, a code span is no path.\n */\nexport const parseMarkdownInline = (\n source: string,\n depth = 0,\n tail = false,\n words = false,\n): MarkdownInline[] => {\n // The end of a text still being written: a run of markers there may be half of a longer one,\n // an opener or a closer. It waits for what follows (see `Parse.streaming`).\n const text = tail ? source.replace(/[*_~`]+$/, '') : source\n if (depth > 8) return text ? [{ t: 'text', v: text }] : []\n const n = text.length\n const closeBracket = nextOf(text, (c) => c === 93)\n const closeParen = nextOf(text, (c) => c === 41)\n const newline = nextOf(text, (c) => c === 10)\n const space = nextOf(text, spaceCode)\n // Backtick runs by length, in order: a code span closes at the next run of the same length.\n const runs = new Map<number, number[]>()\n for (let i = 0; i < n;) {\n if (text[i] !== '`') {\n i++\n continue\n }\n let j = i\n while (j < n && text[j] === '`') j++\n const list = runs.get(j - i) ?? []\n list.push(i)\n runs.set(j - i, list)\n i = j\n }\n const cursor = new Map<number, number>()\n\n // A link to a workspace file - `[words](/path)`, `(</my file (1).md>)`, `(/a.md \"title\")` -\n // read from the lookups below, never by a scan from each `[`. Only a destination that can be\n // one is read (sliced, decoded, checked): a bare one holds no `(` and a `<…>` one no `<` - so it\n // holds no other link's address of its kind, and no character is read for more than two links\n // -, it is no longer than a path can be written, and the `[`s before one `](` share one\n // reading. `'open'`: the text ends inside such a link, as it may still be.\n let lookups: Record<'lt' | 'gt' | 'openParen' | 'dq' | 'sq' | 'solid', Int32Array> | undefined\n const look = () =>\n (lookups ??= {\n lt: nextOf(text, (c) => c === 60),\n gt: nextOf(text, (c) => c === 62),\n openParen: nextOf(text, (c) => c === 40),\n dq: nextOf(text, (c) => c === 34),\n sq: nextOf(text, (c) => c === 39),\n solid: nextOf(text, (c) => !spaceCode(c)),\n })\n type FileLink = { path: string; end: number } | 'open' | undefined\n let readAt = -1\n let read: FileLink\n const fileLinkAt = (close: number): FileLink => {\n if (close !== readAt) {\n readAt = close\n read = readFileLink(close + 2)\n }\n return read\n }\n const readFileLink = (start: number): FileLink => {\n const x = look()\n const line = newline[start]\n const p = x.solid[start]\n if (p >= n || p > line) return undefined\n let from: number\n let to: number\n let after: number\n if (text[p] === '<') {\n from = p + 1\n if (from < n && text[from] !== '/') return undefined\n to = x.gt[from]\n const bad = Math.min(x.lt[from], line)\n if (to >= n) return bad >= n && n - from <= DEST_MAX ? 'open' : undefined\n if (bad < to || to - from > DEST_MAX) return undefined\n after = to + 1\n } else if (text[p] === '/') {\n from = p\n if (text[p + 1] === '/') return undefined\n to = Math.min(space[p], closeParen[p])\n const bad = Math.min(x.lt[p], x.gt[p], x.openParen[p])\n if (to >= n) return bad >= n && n - from <= DEST_MAX ? 'open' : undefined\n if (bad < to || to - from > DEST_MAX) return undefined\n after = to\n } else return undefined\n // The destination is whole: a path, or not a link to a file at all.\n const path = workspacePathOf(decoded(text.slice(from, to)))\n if (!path) return undefined\n // Then blanks, an optional title, blanks, and `)` - each found by a lookup.\n let q = x.solid[after]\n if (q > line) return undefined\n if (q >= n) return 'open'\n if ((text[q] === '\"' || text[q] === \"'\") && q > after) {\n const shut = (text[q] === '\"' ? x.dq : x.sq)[q + 1]\n if (shut >= n) return line >= n && n - q <= TITLE_MAX ? 'open' : undefined\n if (shut > line || shut - q > TITLE_MAX) return undefined\n q = x.solid[shut + 1]\n if (q > line) return undefined\n if (q >= n) return 'open'\n }\n return text[q] === ')' ? { path, end: q } : undefined\n }\n\n const tokens: Token[] = []\n const flush = (from: number, to: number) => {\n // Text, with its line breaks.\n let at = from\n while (at < to) {\n const nl = Math.min(newline[at], to)\n if (nl > at) tokens.push({ t: 'text', v: text.slice(at, nl) })\n if (nl < to) tokens.push({ t: 'br' })\n at = nl + 1\n }\n }\n let plain = 0\n let i = 0\n while (i < n) {\n const c = text[i]\n if (c === '`') {\n let j = i\n while (j < n && text[j] === '`') j++\n const len = j - i\n const list = runs.get(len)!\n let k = cursor.get(len) ?? 0\n while (k < list.length && list[k] <= i) k++\n cursor.set(len, k)\n if (k < list.length) {\n flush(plain, i)\n const end = list[k]\n cursor.set(len, k + 1)\n const body = text.slice(j, end).replace(/\\n/g, ' ')\n const v = /^ .* $/s.test(body) && body.trim() ? body.slice(1, -1) : body\n // A span that is a workspace path, whole: a file the answer hands over. Only a closed one\n // - one still being written is no path yet -, and not in a link's words.\n const path = !words && v.includes('/') ? workspacePathOf(v) : undefined\n tokens.push(path ? { t: 'code', v, path } : { t: 'code', v })\n i = plain = end + len\n } else if (tail) {\n // Still being written: code up to where the text ends, as it will be when it closes.\n flush(plain, i)\n const body = text.slice(j).replace(/\\n/g, ' ')\n tokens.push({ t: 'code', v: body.startsWith(' ') && body.trim() ? body.slice(1) : body })\n i = plain = n\n } else i = j\n continue\n }\n if (c === '[') {\n const close = closeBracket[i + 1]\n if (close < n && close > i + 1 && close < newline[i] && text[close + 1] === '(') {\n const end = closeParen[close + 2]\n const href =\n end < n && space[close + 2] >= end ? safeHref(text.slice(close + 2, end)) : undefined\n if (href) {\n flush(plain, i)\n tokens.push({\n t: 'link',\n href,\n c: parseMarkdownInline(text.slice(i + 1, close), depth + 1, false, true),\n })\n i = plain = end + 1\n continue\n }\n // A link with no words (`[](/a.png)`) is text, as for any link. The `!` of an image stays\n // text too: dropped when the link completes, it would be text taken off the screen while\n // the answer streams.\n const file = fileLinkAt(close)\n if (file !== undefined && file !== 'open') {\n flush(plain, i)\n tokens.push({\n t: 'file',\n path: file.path,\n c: parseMarkdownInline(text.slice(i + 1, close), depth + 1, false, true),\n })\n i = plain = file.end + 1\n continue\n }\n if (tail && (file === 'open' || (end >= n && space[close + 2] >= n))) {\n // A link whose address (or title) is still being written: its words, as they will\n // read - never its `](`, address or title.\n flush(plain, i)\n tokens.push(...parseMarkdownInline(text.slice(i + 1, close), depth + 1, false, true))\n i = plain = n\n continue\n }\n }\n if (tail && newline[i] >= n && (close >= n || close === n - 1)) {\n // A bracket still open, or closed by the last character: it may be a link's text, so it\n // is drawn without its brackets until what follows says (`(` - a link - or anything else).\n flush(plain, i)\n if (close >= n) {\n i = plain = i + 1\n continue\n }\n tokens.push(...parseMarkdownInline(text.slice(i + 1, close), depth + 1))\n i = plain = n\n continue\n }\n i++\n continue\n }\n if (\n !words &&\n (c === 'h' || c === 'H') &&\n URL_START.test(text.slice(i, i + 8)) &&\n !isWord(text[i - 1])\n ) {\n let end = space[i]\n for (let k = i; k < end; k++) {\n if ('<>()'.includes(text[k])) {\n end = k\n break\n }\n }\n const url = text.slice(i, end).replace(URL_TAIL, '')\n if (url.length > 8) {\n flush(plain, i)\n tokens.push({ t: 'link', href: url, c: [{ t: 'text', v: url }] })\n i = plain = i + url.length\n continue\n }\n i++\n continue\n }\n if (c === '*' || c === '_' || c === '~') {\n let j = i\n while (j < n && text[j] === c) j++\n const before = text[i - 1]\n const after = text[j]\n let open = !isSpace(after)\n let close = !isSpace(before)\n // An underscore inside a word (snake_case) is not emphasis.\n if (c === '_' && isWord(before) && isWord(after)) open = close = false\n const len = j - i\n if ((c === '~' && len !== 2) || (!open && !close)) {\n i = j\n continue\n }\n flush(plain, i)\n // A run of three opens strong then em, and closes em then strong.\n const sizes: (1 | 2)[] =\n c === '~' ? [2] : len === 1 ? [1] : len === 2 ? [2] : open && !close ? [2, 1] : [1, 2]\n let used = 0\n for (const size of sizes) {\n tokens.push({ t: 'delim', ch: c, n: size, open, close, lead: !isWord(before) })\n used += size\n }\n if (len > used) tokens.push({ t: 'text', v: c.repeat(len - used) })\n i = plain = j\n continue\n }\n i++\n }\n flush(plain, n)\n\n // Emphasis: a closer takes the nearest opener of its kind; openers of other kinds above that\n // one can no longer close and become text. Each opener is pushed and popped once.\n const stacks: number[][] = [[], [], [], [], [], []]\n const kindOf = (tok: { ch: Delim; n: 1 | 2 }) =>\n (tok.ch === '*' ? 0 : tok.ch === '_' ? 2 : 4) + tok.n - 1\n for (let idx = 0; idx < tokens.length; idx++) {\n const tok = tokens[idx]\n if (tok.t !== 'delim') continue\n const own = stacks[kindOf(tok)]\n const top = own.length ? own[own.length - 1] : -1\n if (tok.close && top >= 0 && top < idx - 1) {\n own.pop()\n ;(tokens[top] as { match?: number }).match = idx\n tok.match = top\n for (const st of stacks) while (st.length && st[st.length - 1] > top) st.pop()\n continue\n }\n if (tok.open) own.push(idx)\n }\n if (tail) {\n // Emphasis still open where the text ends is emphasis already: it closes there, the\n // innermost first. (Openers inside a matched pair were dropped above; these nest.)\n const open = stacks.flat().sort((a, b) => b - a)\n for (const idx of open) {\n const opener = tokens[idx] as Token & { t: 'delim' }\n if (!opener.lead) continue\n opener.match = tokens.length\n tokens.push({ t: 'delim', ch: opener.ch, n: opener.n, open: false, close: true, match: idx })\n }\n }\n\n const root: MarkdownInline[] = []\n const frames: {\n out: MarkdownInline[]\n node?: MarkdownInline & { c: MarkdownInline[] }\n until: number\n }[] = [{ out: root, until: -1 }]\n tokens.forEach((tok, idx) => {\n const frame = frames[frames.length - 1]\n if (tok.t !== 'delim') {\n if (tok.t === 'text') pushText(frame.out, tok.v)\n else frame.out.push(tok)\n return\n }\n if (tok.match !== undefined && tok.match > idx) {\n const node = {\n t: tok.ch === '~' ? 'del' : tok.n === 2 ? 'strong' : 'em',\n c: [],\n } as MarkdownInline & { c: MarkdownInline[] }\n frames.push({ out: node.c, node, until: tok.match })\n return\n }\n if (tok.match !== undefined && frame.until === idx && frame.node) {\n frames.pop()\n frames[frames.length - 1].out.push(frame.node)\n return\n }\n pushText(frame.out, tok.ch.repeat(tok.n))\n })\n return root\n}\n\n// ── blocks ──────────────────────────────────────────────────────────────────\n\n// Any indentation: a model puts a code block under a list item with the item's indent (Gemini:\n// 8 spaces), and this scanner has no indented code blocks for it to be instead.\nconst FENCE = /^([ \\t]*)(`{3,}|~{3,})\\s*([\\w+#.-]*)/\nconst HEADING = /^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$/\nconst HR = /^ {0,3}([-*_])(?:\\s*\\1){2,}\\s*$/\nconst BULLET = /^( *)([-*+])\\s+(.*)$/\nconst ORDERED = /^( *)(\\d{1,9})[.)]\\s+(.*)$/\nconst QUOTE = /^ {0,3}>\\s?(.*)$/\nconst TABLE_RULE = /^\\s*\\|?\\s*:?-{1,}:?\\s*(\\|\\s*:?-{1,}:?\\s*)*\\|?\\s*$/\n\n/**\n * The deepest a list nests (counting the quotes and lists around it): far past any answer's, and\n * the bound that keeps a text of ever-deeper items linear (`tests/markdown.test.ts`, \"time\").\n */\nconst LIST_NESTING_MAX = 8\n\nconst cells = (line: string): string[] => {\n let s = line.trim()\n if (s.startsWith('|')) s = s.slice(1)\n if (s.endsWith('|') && !s.endsWith('\\\\|')) s = s.slice(0, -1)\n const out: string[] = []\n let cur = ''\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '\\\\' && s[i + 1] === '|') {\n cur += '|'\n i++\n } else if (s[i] === '|') {\n out.push(cur.trim())\n cur = ''\n } else cur += s[i]\n }\n out.push(cur.trim())\n return out\n}\n\nconst alignOf = (cell: string): MarkdownAlign => {\n const c = cell.trim()\n const left = c.startsWith(':')\n const right = c.endsWith(':')\n return left && right ? 'center' : right ? 'right' : left ? 'left' : undefined\n}\n\nconst startsBlock = (line: string, next: string | undefined): boolean =>\n FENCE.test(line) ||\n HEADING.test(line) ||\n HR.test(line) ||\n BULLET.test(line) ||\n ORDERED.test(line) ||\n QUOTE.test(line) ||\n (line.includes('|') && next !== undefined && TABLE_RULE.test(next) && next.includes('-'))\n\n/**\n * The blocks of a Markdown text. `streaming`: the text is an answer still being written, so\n * what ends at its end is drawn as it will be when it is finished (an inline construct still\n * open - `parseMarkdownInline`'s `tail`); `stream.ts` decides what of the last line is drawn at all.\n */\nexport const parseMarkdown = (text: string, depth = 0, streaming = false): MarkdownBlock[] => {\n const lines = text.replace(/\\r\\n?/g, '\\n').split('\\n')\n const out: MarkdownBlock[] = []\n let i = 0\n /** Whether line `k` is the last of a text still being written. */\n const last = (k: number) => streaming && k >= lines.length - 1\n while (i < lines.length) {\n const line = lines[i]\n if (!line.trim()) {\n i++\n continue\n }\n const fence = FENCE.exec(line)\n if (fence) {\n const body: string[] = []\n // The code's own indentation is kept; the fence's is taken off every line.\n const indent = new RegExp(`^[ \\\\t]{0,${fence[1].length}}`)\n i++\n while (i < lines.length && !lines[i].trimStart().startsWith(fence[2])) {\n body.push(lines[i++].replace(indent, ''))\n }\n i++\n out.push({ t: 'code', lang: fence[3], v: body.join('\\n') })\n continue\n }\n const heading = HEADING.exec(line)\n if (heading) {\n out.push({\n t: 'h',\n level: heading[1].length as 1 | 2 | 3 | 4 | 5 | 6,\n c: parseMarkdownInline(heading[2], 0, last(i)),\n })\n i++\n continue\n }\n if (HR.test(line)) {\n out.push({ t: 'hr' })\n i++\n continue\n }\n if (QUOTE.test(line) && depth < 4) {\n const body: string[] = []\n while (i < lines.length && QUOTE.test(lines[i])) body.push(QUOTE.exec(lines[i++])![1])\n out.push({\n t: 'quote',\n c: parseMarkdown(body.join('\\n'), depth + 1, streaming && i >= lines.length),\n })\n continue\n }\n const next = lines[i + 1]\n if (line.includes('|') && next !== undefined && TABLE_RULE.test(next) && next.includes('-')) {\n const head = cells(line)\n const align = cells(next).map(alignOf)\n i += 2\n const rows: MarkdownInline[][][] = []\n while (i < lines.length && lines[i].trim() && lines[i].includes('|')) {\n const row = cells(lines[i])\n // The cell being written is the last one that has anything in it.\n let open = -1\n if (last(i)) for (let k = 0; k < row.length; k++) if (row[k] !== '') open = k\n i++\n rows.push(head.map((_, k) => parseMarkdownInline(row[k] ?? '', 0, k === open)))\n }\n out.push({ t: 'table', align, head: head.map((h) => parseMarkdownInline(h)), rows })\n continue\n }\n if (BULLET.test(line) || ORDERED.test(line)) {\n const ordered = !BULLET.test(line)\n const first = (ordered ? ORDERED : BULLET).exec(line)!\n const indent = first[1].length\n const list: MarkdownListBlock = {\n t: 'list',\n ordered,\n start: ordered ? Number(first[2]) : 1,\n items: [],\n }\n while (i < lines.length) {\n const l = lines[i]\n const m = (ordered ? ORDERED : BULLET).exec(l)\n if (m && m[1].length <= indent + 1) {\n list.items.push({ c: parseMarkdownInline(m[3], 0, last(i)) })\n i++\n continue\n }\n const nested = BULLET.exec(l) ?? ORDERED.exec(l)\n if (nested && nested[1].length > indent + 1 && list.items.length) {\n if (depth >= LIST_NESTING_MAX) {\n // As deep as lists go: a deeper item is one more item of this list (never dropped).\n list.items.push({ c: parseMarkdownInline(nested[3], 0, last(i)) })\n i++\n continue\n }\n // The deeper items go under the item before them, a level at a time. Each level reads\n // the lines under it again, so the levels are bounded (`LIST_NESTING_MAX`): linear on\n // any staircase of indents.\n const subLines: string[] = []\n while (i < lines.length) {\n const s = BULLET.exec(lines[i]) ?? ORDERED.exec(lines[i])\n if (!s || s[1].length <= indent + 1) break\n subLines.push(lines[i++].slice(nested[1].length))\n }\n const sub = parseMarkdown(\n subLines.join('\\n'),\n depth + 1,\n streaming && i >= lines.length,\n ).find((b): b is MarkdownListBlock => b.t === 'list')\n if (sub) list.items[list.items.length - 1].sub = sub\n continue\n }\n // A continuation line of the item (indented, not blank, not a new block).\n if (\n l.trim() &&\n /^\\s+/.test(l) &&\n !startsBlock(l.trim(), lines[i + 1]) &&\n list.items.length\n ) {\n const item = list.items[list.items.length - 1]\n item.c.push({ t: 'br' }, ...parseMarkdownInline(l.trim(), 0, last(i)))\n i++\n continue\n }\n break\n }\n out.push(list)\n continue\n }\n // A paragraph: up to a blank line or the start of another block; line breaks are kept.\n const body: string[] = [line]\n i++\n while (i < lines.length && lines[i].trim() && !startsBlock(lines[i], lines[i + 1])) {\n body.push(lines[i++])\n }\n out.push({\n t: 'p',\n c: parseMarkdownInline(\n body.map((l) => l.trim()).join('\\n'),\n 0,\n streaming && i >= lines.length,\n ),\n })\n }\n return out\n}\n","import { parseMarkdown, type MarkdownBlock } from './parse.js'\n\n/**\n * An answer's Markdown WHILE IT IS WRITTEN (pure). The text grows a few characters at a time and\n * is drawn each time; drawn naively, what is on the screen keeps changing its kind - a `##`\n * that is a paragraph until its space arrives, a table's first row that is a line of pipes until\n * the rule under it, a fence that closes one backtick at a time, `**` that shows until its pair -\n * and each change moves everything under it. The rules, each pinned by `tests/markdown-stream.test.ts`:\n *\n * 1. A finished line is drawn as it will stay. Only the LAST line can be held back, and only\n * while it cannot be told what it is:\n * - it is nothing but marker characters so far (`#`, `-`, `1.`, `>`, `` ` ``, `|`, `*`, `---`);\n * - inside a code block, it may be the closing fence (or, still blank, its indent);\n * - it starts with `|` and may be a table's header (held with the rule line under it, until\n * that line is complete: then it is a table, or two lines of text).\n * 2. An inline construct open where the text ends is drawn as if it closed there (`parseMarkdownInline`'s\n * `tail`): emphasis and code at once, a link as its text until its address is whole; a run of\n * markers at the very end waits.\n * 3. Blocks before the last blank line (outside a code block) are finished: they are parsed once\n * and kept, as the same objects - so each piece costs the size of the last block, not of the\n * answer, and React leaves the finished blocks alone.\n *\n * What is held back is at most one short line (or a table's two head lines), for as long as it\n * takes the model to write it. A finished answer is parsed whole, without any of this.\n */\n\n/** A fence at any indentation, as `parse.ts` reads it. */\nconst FENCE = /^[ \\t]*(`{3,}|~{3,})/\n/** A line of marker characters only: it can still become a heading, a list, a rule, a fence… */\nconst MARKERS_ONLY = /^[\\s#>*+\\-_|`~=:\\d.)]{0,16}$/\n/** What a table's rule line looks like, whole or in part. */\nconst RULE_SO_FAR = /^\\s*\\|?[\\s:|-]*$/\n\nconst pipes = (line: string | undefined): boolean => line !== undefined && line.includes('|')\nconst blank = (line: string | undefined): boolean => line === undefined || !line.trim()\n\n/**\n * The part of a text still being written that is drawn now: `text` without what its last line\n * cannot yet be told to be (rule 1). Never longer than `text`; equal to it when nothing is held.\n */\nexport const markdownSettled = (text: string): string => {\n const lines = text.split('\\n')\n const n = lines.length\n // The code block the last line is in, if any (its fence).\n let fence: string | undefined\n for (let i = 0; i < n - 1; i++) {\n const line = lines[i]\n if (fence) {\n if (line.trimStart().startsWith(fence)) fence = undefined\n } else {\n const m = FENCE.exec(line)\n if (m) fence = m[1]\n }\n }\n const lastLine = lines[n - 1]\n const cut = (count: number) => lines.slice(0, n - count).join('\\n') + (n > count ? '\\n' : '')\n if (fence) {\n // The closing fence, one character at a time, is not a line of code - nor is its indent\n // (a fence under a list item is written 8 spaces in), so a line of blanks waits too.\n const t = lastLine.trim()\n return !t || fence.startsWith(t) ? cut(1) : text\n }\n // A table's header, and the rule line being written under it.\n const inTable = (k: number) => pipes(lines[k]) && !blank(lines[k])\n if (\n n >= 2 &&\n lines[n - 2].trimStart().startsWith('|') &&\n RULE_SO_FAR.test(lastLine) &&\n !inTable(n - 3)\n )\n return cut(2)\n if (lastLine.trimStart().startsWith('|') && !inTable(n - 2)) return cut(1)\n if (lastLine && MARKERS_ONLY.test(lastLine)) return cut(1)\n return text\n}\n\n/** Where the finished blocks of `text` end, looking from `from` (a block boundary): rule 3. */\nconst finishedEnd = (text: string, from: number): number => {\n let fence: string | undefined\n let end = from\n let at = from\n while (at < text.length) {\n const nl = text.indexOf('\\n', at)\n if (nl < 0) break\n const line = text.slice(at, nl)\n if (fence) {\n if (line.trimStart().startsWith(fence)) fence = undefined\n } else {\n const m = FENCE.exec(line)\n if (m) fence = m[1]\n // A blank line outside a code block ends every block before it.\n else if (!line.trim()) end = nl + 1\n }\n at = nl + 1\n }\n return end\n}\n\n/** The parse of a growing text so far: what is finished, and what was drawn last. */\nexport interface MarkdownStream {\n /** The text the finished blocks came from (a prefix of every later text). */\n done: string\n finished: MarkdownBlock[]\n blocks: MarkdownBlock[]\n}\n\nexport const emptyMarkdownStream = (): MarkdownStream => ({ done: '', finished: [], blocks: [] })\n\n/**\n * The blocks of `text`, an answer still being written, given the parse of what it was before.\n * A text that is not a continuation (another answer) starts over.\n */\nexport const parseMarkdownStreaming = (prev: MarkdownStream, text: string): MarkdownStream => {\n const source = text.includes('\\r') ? text.replace(/\\r\\n?/g, '\\n') : text\n const base = source.startsWith(prev.done) ? prev : emptyMarkdownStream()\n const end = finishedEnd(source, base.done.length)\n const finished =\n end > base.done.length\n ? [...base.finished, ...parseMarkdown(source.slice(base.done.length, end))]\n : base.finished\n // One line break at the end ends no block: the last line is still the last line.\n const tail = parseMarkdown(markdownSettled(source.slice(end)).replace(/\\n$/, ''), 0, true)\n return {\n done: source.slice(0, end),\n finished,\n blocks: tail.length ? [...finished, ...tail] : finished,\n }\n}\n","import { parseMarkdown, type MarkdownBlock, type MarkdownInline } from './parse.js'\n\n/**\n * What every renderer of the parsed tree needs and is not React: the parses cached by text, the\n * words of inline runs, and which table cells wrap. The React package's `<Markdown>` uses these;\n * a renderer of another front end (a web component, Vue, Svelte) should too, so the same answer\n * looks and reads the same everywhere.\n */\n\n/** How many parses {@link parseMarkdownCached} keeps (the oldest go first). */\nexport const MARKDOWN_CACHE_MAX = 64\n\nconst parsed = new Map<string, MarkdownBlock[]>()\n\n/**\n * The blocks of a FINISHED text, cached by the text: a saved chat opened again, or a re-render,\n * does not parse again. Bounded ({@link MARKDOWN_CACHE_MAX}); the parse itself is linear. The\n * blocks are shared between callers - never change them. A text still being written goes through\n * `parseMarkdownStreaming` instead (each piece would be an entry here).\n */\nexport const parseMarkdownCached = (text: string): MarkdownBlock[] => {\n const hit = parsed.get(text)\n if (hit) return hit\n const blocks = parseMarkdown(text)\n parsed.set(text, blocks)\n if (parsed.size > MARKDOWN_CACHE_MAX) parsed.delete(parsed.keys().next().value!)\n return blocks\n}\n\n/** The words of inline runs, as a screen reader is to name them (a link's or a file's words). */\nexport const markdownPlainText = (runs: MarkdownInline[]): string =>\n runs\n .map((r) =>\n r.t === 'text' || r.t === 'code' ? r.v : r.t === 'br' ? ' ' : markdownPlainText(r.c),\n )\n .join('')\n\n/**\n * A table cell longer than this many characters wraps, in a column of its own width; every other\n * cell is one line, and a table wider than the screen scrolls in its box. So a table's rows keep\n * their height when another row arrives while the answer is written (columns that share the\n * width would re-wrap each other's cells).\n */\nexport const MARKDOWN_LONG_CELL = 48\n\nconst lengthOf = (runs: MarkdownInline[]): number =>\n runs.reduce(\n (n, r) =>\n n + (r.t === 'text' || r.t === 'code' ? r.v.length : r.t === 'br' ? 1 : lengthOf(r.c)),\n 0,\n )\n\n/** Whether a table cell wra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;AAGK,IAAM,qBAAqB,CAAC,SACjC,SAAS,IAAI,IAAI;","names":["i","body","FENCE"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp-app-sandbox.ts","../src/mcp-app-policy.ts"],"sourcesContent":["import {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n type McpAppColorScheme,\n type McpAppPolicyOrigins,\n} from './mcp-app-policy.js'\n\n/**\n * The `./mcp-app-sandbox` entry: the MCP Apps sandbox proxy - the page a host serves on ANOTHER\n * origin, so that an app runs on an origin of its own (storage, cookies, a real `Origin`) and not\n * in an opaque one. Framework-free, no imports but `mcp-app-policy.ts`: a Cloudflare Worker, Deno,\n * Bun or Node (18+) serves it with `mcpAppSandboxResponse` (Request in, Response out).\n *\n * The page, `<base>/<policy>` (`<policy>` = `mcpAppPolicyToken`):\n *\n * 1. Its response carries the app's policy as a HEADER, built from the path (`mcpAppPolicy`), plus\n * `frame-ancestors` = the allowed host origins. The app's document is written into a frame\n * the page creates (`about:blank`, `document.write`), which INHERITS that policy - nothing the\n * app's markup says comes before it, and every document the app can reach on this origin\n * (this page, a reload of it, a frame of it) has a policy some host chose for that frame.\n * 2. Its script binds to the first ANCESTOR window on an allowed host origin that sends it\n * `ui/notifications/sandbox-resource-ready`, once; after that it relays the extension's\n * messages between that window (to its exact origin) and the app's window (to this origin),\n * never the `ui/notifications/sandbox-*` ones, and creates nothing else. It asks for\n * `ui/notifications/sandbox-proxy-ready` with a content-free message to every ancestor.\n * 3. The app's frame: `sandbox=\"allow-scripts allow-same-origin\"`, no `allow` attribute. The app\n * is same-origin with this page and can reach it - which is why the boundary is not here but\n * in what the HOST draws around it (the frame's sandbox, the shell's `frame-src` pinned to\n * this URL) and in the policy header above. A `sandbox`, `csp` or `permissions` the host sends\n * is ignored: the header is the policy, and no permission is ever granted.\n */\n\nexport {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n}\nexport type { McpAppColorScheme, McpAppPolicyOrigins }\n\n/** A host origin pattern: `https://<prefix>*<suffix>.<rest>`, `*` one run of `[a-z0-9-]`. */\nexport interface McpAppSandboxHostPattern {\n prefix: string\n suffix: string\n /** The rest of the host name after the first label: two labels at least. */\n rest: string\n}\n\n/** The host origins a sandbox page answers, as `parseMcpAppSandboxHosts` reads them. */\nexport interface McpAppSandboxHosts {\n /** Exact origins (`https://agent.example.com`, `http://127.0.0.1:4173`). */\n origins: string[]\n /** One-label patterns (`https://*-agents.example.workers.dev`). */\n patterns: McpAppSandboxHostPattern[]\n /** The same as `frame-ancestors` sources (a pattern widened to `https://*.<rest>`). */\n frameAncestors: string[]\n /** Entries that are neither: a sandbox with any of these refuses to serve (503). */\n invalid: string[]\n}\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst NAME = `${LABEL}(?:\\\\.${LABEL})+`\nconst EXACT_HTTPS = new RegExp(`^https://${LABEL}(?:\\\\.${LABEL})*(?::\\\\d{1,5})?$`)\nconst EXACT_LOOPBACK = /^http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::\\d{1,5})?$/\nconst PATTERN = new RegExp(`^https://([a-z0-9-]{0,40})\\\\*([a-z0-9-]{0,40})\\\\.(${NAME})$`)\n\n/**\n * The allowed host origins, from a list or a space / comma separated string (a deploy-time\n * setting, e.g. `ALLOWED_HOST_ORIGINS=\"https://agent.example.com https://*-agents.example.workers.dev\"`).\n * An entry is an exact origin - `https://`, or `http://` on `localhost` / `127.0.0.1` - or a\n * pattern with ONE `*` inside the first label of an `https://` host. The page's script holds the\n * pattern to one label (`[a-z0-9-]+`, no dot); `frame-ancestors` cannot say that, so there the\n * pattern is widened to `https://*.<rest>` (every subdomain of `<rest>`). Anything else is\n * `invalid`.\n */\nexport const parseMcpAppSandboxHosts = (\n value: string | readonly string[] | undefined,\n): McpAppSandboxHosts => {\n const entries = (typeof value === 'string' ? value.split(/[\\s,]+/) : [...(value ?? [])])\n .map((e) => (typeof e === 'string' ? e.trim() : ''))\n .filter(Boolean)\n const hosts: McpAppSandboxHosts = { origins: [], patterns: [], frameAncestors: [], invalid: [] }\n const ancestor = (source: string) => {\n if (!hosts.frameAncestors.includes(source)) hosts.frameAncestors.push(source)\n }\n for (const raw of entries) {\n const entry = raw.toLowerCase().replace(/\\/$/, '')\n const pattern = PATTERN.exec(entry)\n if (pattern) {\n const [, prefix, suffix, rest] = pattern\n if (\n !hosts.patterns.some((p) => p.prefix === prefix && p.suffix === suffix && p.rest === rest)\n ) {\n hosts.patterns.push({ prefix, suffix, rest })\n }\n ancestor(`https://*.${rest}`)\n } else if (EXACT_HTTPS.test(entry) || EXACT_LOOPBACK.test(entry)) {\n if (!hosts.origins.includes(entry)) hosts.origins.push(entry)\n ancestor(entry)\n } else {\n hosts.invalid.push(raw.slice(0, 120))\n }\n }\n return hosts\n}\n\n/** Whether an origin is one of the hosts (the same rule the page's script applies). */\nexport const isMcpAppSandboxHost = (hosts: McpAppSandboxHosts, origin: string): boolean => {\n if (hosts.origins.includes(origin)) return true\n const head = 'https://'\n for (const p of hosts.patterns) {\n const tail = `.${p.rest}`\n if (!origin.startsWith(head) || !origin.endsWith(tail)) continue\n const label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || !label.startsWith(p.prefix) || !label.endsWith(p.suffix)) continue\n const middle = label.slice(p.prefix.length, label.length - p.suffix.length)\n if (/^[a-z0-9-]+$/.test(middle)) return true\n }\n return false\n}\n\n/**\n * The page's script (inline; it runs under the app's own policy, which allows inline scripts).\n * It reads the hosts from `#mcp-app-sandbox-hosts`, binds to the first allowed ancestor that sends\n * the resource, writes the app into its frame, and relays - see the entry's comment.\n */\nexport const MCP_APP_SANDBOX_SCRIPT = `(function () {\n 'use strict'\n var READY = ${JSON.stringify(MCP_APP_SANDBOX_PROXY_READY)}\n var RESOURCE = ${JSON.stringify(MCP_APP_SANDBOX_RESOURCE_READY)}\n var RESERVED = 'ui/notifications/sandbox-'\n var me = window\n if (me.parent === me) return\n var cfg\n try {\n cfg = JSON.parse(document.getElementById('mcp-app-sandbox-hosts').textContent)\n } catch (e) {\n return\n }\n var origins = cfg && Array.isArray(cfg.origins) ? cfg.origins : []\n var patterns = cfg && Array.isArray(cfg.patterns) ? cfg.patterns : []\n function allowed(origin) {\n if (typeof origin !== 'string') return false\n if (origins.indexOf(origin) >= 0) return true\n for (var i = 0; i < patterns.length; i++) {\n var p = patterns[i]\n var head = 'https://'\n var tail = '.' + p.rest\n if (origin.indexOf(head) !== 0 || origin.length <= head.length + tail.length) continue\n if (origin.slice(origin.length - tail.length) !== tail) continue\n var label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || label.indexOf(p.prefix) !== 0) continue\n if (label.slice(label.length - p.suffix.length) !== p.suffix) continue\n if (/^[a-z0-9-]+$/.test(label.slice(p.prefix.length, label.length - p.suffix.length))) return true\n }\n return false\n }\n var ancestors = []\n for (var w = me.parent; ancestors.length < 32; w = w.parent) {\n ancestors.push(w)\n if (w === w.parent) break\n }\n function ancestor(source) {\n for (var i = 0; i < ancestors.length; i++) if (ancestors[i] === source) return true\n return false\n }\n function reserved(d) {\n return !!d && typeof d === 'object' && typeof d.method === 'string' && d.method.indexOf(RESERVED) === 0\n }\n var OWN = me.origin\n var host = null\n var hostOrigin = ''\n var app = null\n me.addEventListener('message', function (e) {\n var d = e.data\n if (app && e.source === app) {\n if (e.origin !== OWN || reserved(d)) return\n host.postMessage(d, hostOrigin)\n return\n }\n if (host) {\n if (e.source !== host || e.origin !== hostOrigin || reserved(d) || !app) return\n app.postMessage(d, OWN)\n return\n }\n if (!d || typeof d !== 'object' || d.jsonrpc !== '2.0' || d.method !== RESOURCE) return\n if (!ancestor(e.source) || !allowed(e.origin)) return\n var p = d.params\n if (!p || typeof p !== 'object' || typeof p.html !== 'string') return\n host = e.source\n hostOrigin = e.origin\n var frame = document.createElement('iframe')\n frame.id = 'app'\n frame.setAttribute('sandbox', 'allow-scripts allow-same-origin')\n frame.setAttribute('referrerpolicy', 'no-referrer')\n frame.setAttribute('title', 'MCP App')\n document.body.appendChild(frame)\n app = frame.contentWindow\n var doc = frame.contentDocument\n doc.open()\n doc.write(p.html)\n doc.close()\n })\n var ready = { jsonrpc: '2.0', method: READY, params: {} }\n for (var i = 0; i < ancestors.length; i++) ancestors[i].postMessage(ready, '*')\n})()`\n\nconst json = (value: unknown): string =>\n JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026')\n\n/**\n * The page: the hosts as data, the script. Serve it with `mcpAppSandboxHeaders`. `scheme` (the\n * frame's colour scheme, `?scheme=` of the page's URL) is declared by the page and on the app's\n * frame - only `light` / `dark`; without one the page declares nothing.\n */\nexport const mcpAppSandboxPage = (\n hosts: McpAppSandboxHosts,\n scheme?: McpAppColorScheme,\n): string => {\n const s = mcpAppColorScheme(scheme)\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex\">' +\n (s ? `<meta name=\"color-scheme\" content=\"${s}\">` : '') +\n '<title>MCP App sandbox</title>' +\n `<style>${s ? `:root{color-scheme:${s}}` : ''}` +\n 'html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n `iframe{display:block;border:0;width:100%;height:100%${s ? `;color-scheme:${s}` : ''}}` +\n '</style></head><body>' +\n `<script type=\"application/json\" id=\"mcp-app-sandbox-hosts\">${json({\n origins: hosts.origins,\n patterns: hosts.patterns,\n })}</script>` +\n `<script>${MCP_APP_SANDBOX_SCRIPT}</script></body></html>`\n )\n}\n\n/** Browser features the page and the app may never use, whatever an app asks for. */\nexport const MCP_APP_SANDBOX_PERMISSIONS_POLICY =\n 'camera=(), microphone=(), geolocation=(), display-capture=(), payment=(), usb=(), serial=(), midi=()'\n\nconst COMMON = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Robots-Tag': 'noindex, nofollow',\n 'Referrer-Policy': 'no-referrer',\n 'Cache-Control': 'no-store',\n}\n\n/**\n * The page's response headers: the app's policy AND `frame-ancestors` (the hosts; `'none'` when\n * there are none), `nosniff`, `no-store` (a policy is never served from a stale copy), no referrer,\n * `noindex`, and a Permissions-Policy that grants nothing.\n */\nexport const mcpAppSandboxHeaders = (\n policy: McpAppPolicyOrigins,\n hosts: McpAppSandboxHosts,\n): Record<string, string> => ({\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Security-Policy': `${mcpAppPolicy(policy)}; frame-ancestors ${\n hosts.frameAncestors.length > 0 ? hosts.frameAncestors.join(' ') : \"'none'\"\n }`,\n 'Permissions-Policy': MCP_APP_SANDBOX_PERMISSIONS_POLICY,\n ...COMMON,\n})\n\nexport interface McpAppSandboxServeOptions {\n /** Where the pages are: `'/sandbox/v1'` serves `/sandbox/v1/<policy>`. */\n path: string\n /** The host origins that may frame the page and send it an app (see `parseMcpAppSandboxHosts`). */\n hosts: string | readonly string[] | undefined\n}\n\nconst plain = (status: number, text: string, extra: Record<string, string> = {}): Response =>\n new Response(text, {\n status,\n headers: {\n 'Content-Type': 'text/plain; charset=utf-8',\n 'Content-Security-Policy': \"default-src 'none'; frame-ancestors 'none'\",\n ...COMMON,\n ...extra,\n },\n })\n\n/**\n * A fetch handler for the sandbox page: `GET` / `HEAD` of `<path>/<policy>` is the page, with its\n * headers (and `?scheme=light|dark`, the frame's colour scheme - anything else is none); a token\n * that is not exactly what `mcpAppPolicyToken` writes is 400; another method 405;\n * any other path 404; no valid host origin (or an invalid entry in the setting) 503 - a sandbox\n * nobody may frame is a configuration error, not a page.\n */\nexport const mcpAppSandboxResponse = (\n request: Request,\n options: McpAppSandboxServeOptions,\n): Response => {\n const { pathname, searchParams } = new URL(request.url)\n const base = options.path.replace(/\\/+$/, '')\n if (!pathname.startsWith(`${base}/`)) return plain(404, 'Not found')\n const token = pathname.slice(base.length + 1)\n if (token.length === 0 || token.includes('/')) return plain(404, 'Not found')\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n return plain(405, 'Method not allowed', { Allow: 'GET, HEAD' })\n }\n const policy = mcpAppPolicyOfToken(token)\n if (!policy) return plain(400, 'Not a policy this sandbox serves')\n const hosts = parseMcpAppSandboxHosts(options.hosts)\n if (hosts.invalid.length > 0 || hosts.frameAncestors.length === 0) {\n return plain(503, 'This sandbox has no valid allowed host origins')\n }\n const scheme = mcpAppColorScheme(searchParams.get(MCP_APP_SCHEME_PARAM))\n return new Response(request.method === 'HEAD' ? null : mcpAppSandboxPage(hosts, scheme), {\n status: 200,\n headers: mcpAppSandboxHeaders(policy, hosts),\n })\n}\n","/**\n * MCP Apps: what the host (the page, `mcp-app.ts`) and the sandbox proxy (a page on ANOTHER\n * origin, `mcp-app-sandbox.ts`) must agree on - the app's Content-Security-Policy, the policy as a\n * path segment of the proxy's URL, and the names of the sandbox messages. Pure code with NO\n * imports at all: the proxy's server bundles it without React or the core (a Worker), so the\n * origin rule below is a copy of the core's `mcpAppOrigin`, and `tests/apps-sandbox.test.ts`\n * holds the two to the same answers.\n */\n\n/** The proxy tells the host it can take the app (Sandbox → Host; content-free). */\nexport const MCP_APP_SANDBOX_PROXY_READY = 'ui/notifications/sandbox-proxy-ready'\n/** The host hands the proxy the app's HTML (Host → Sandbox), once. */\nexport const MCP_APP_SANDBOX_RESOURCE_READY = 'ui/notifications/sandbox-resource-ready'\n\n/** The specification reserves these between a host and its proxy: never relayed to or from an app. */\nexport const isMcpAppSandboxMessage = (data: unknown): boolean =>\n typeof data === 'object' &&\n data !== null &&\n typeof (data as { method?: unknown }).method === 'string' &&\n (data as { method: string }).method.startsWith('ui/notifications/sandbox-')\n\n/**\n * The colour scheme of an app's frame: the theme the app is told when its frame is drawn. Every\n * document between the page and the app declares it (the frame element, the shell, the sandbox\n * page and its frame), because a browser paints an OPAQUE canvas - the canvas colour of the\n * embedded document's own scheme - behind a document whose scheme differs from its frame\n * element's: an app that is dark with a transparent body was drawn on white.\n */\nexport type McpAppColorScheme = 'light' | 'dark'\n\n/** The query parameter of the sandbox page that carries the scheme (`?scheme=dark`). */\nexport const MCP_APP_SCHEME_PARAM = 'scheme'\n\n/** `light` or `dark` exactly; anything else is no scheme (nothing is declared). */\nexport const mcpAppColorScheme = (value: unknown): McpAppColorScheme | undefined =>\n value === 'light' || value === 'dark' ? value : undefined\n\n/** The origins an app's policy grants, each already an origin (`mcpAppPolicyOrigin`). */\nexport interface McpAppPolicyOrigins {\n /** `fetch` / XHR / WebSocket (`connect-src`). */\n connect: string[]\n /** Scripts, styles, images, fonts, media. */\n resources: string[]\n}\n\n/**\n * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the\n * network ONLY where the resource declared it. Nested frames, workers, plugins, forms and `<base>`\n * are refused whatever was declared (a frame the app may embed would also be a place it may\n * navigate itself to). The lists must already be checked origins: nothing here re-checks them.\n *\n * `'wasm-unsafe-eval'` lets the app compile WebAssembly (a tracer, a codec, a parser), which the\n * specification's default policy leaves out and a server cannot ask for (it declares origins, not\n * keywords). It adds no reach: a module only calls what the app's own script hands it, and the\n * network stays `connect-src`. `eval`, `new Function` and string timers stay refused - that is\n * `'unsafe-eval'`, which is never granted.\n */\nexport const mcpAppPolicy = ({ connect, resources }: McpAppPolicyOrigins): string => {\n const from = resources.length > 0 ? ` ${resources.join(' ')}` : ''\n return [\n \"default-src 'none'\",\n `script-src 'unsafe-inline' 'wasm-unsafe-eval'${from}`,\n `style-src 'unsafe-inline'${from}`,\n `img-src data: blob:${from}`,\n `font-src data:${from}`,\n `media-src data: blob:${from}`,\n connect.length > 0 ? `connect-src ${connect.join(' ')}` : \"connect-src 'none'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n \"webrtc 'block'\",\n ].join('; ')\n}\n\n// ── The origin rule: a COPY of the core's `mcpAppOrigin` (src/mcp/apps.ts) ──────────────────\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst HOST = `(?:\\\\*\\\\.)?${LABEL}(?:\\\\.${LABEL})*`\nconst PORT = '(?::\\\\d{1,5})?'\nconst SECURE_ORIGIN = new RegExp(`^(?:https|wss)://${HOST}${PORT}$`)\nconst LOOPBACK_ORIGIN = new RegExp(`^(?:http|ws)://(?:localhost|127\\\\.0\\\\.0\\\\.1|\\\\[::1\\\\])${PORT}$`)\n\n/**\n * One declared CSP entry as a source expression a policy may carry, or `undefined`: only an\n * origin (`https://` / `wss://`, a `*.` wildcard over at least two labels, or `http://` /\n * `ws://` on loopback). The same answers as the core's `mcpAppOrigin`, for the proxy's server.\n */\nexport const mcpAppPolicyOrigin = (entry: unknown): string | undefined => {\n if (typeof entry !== 'string' || entry.length > 300) return undefined\n const value = entry.trim().toLowerCase().replace(/\\/$/, '')\n if (SECURE_ORIGIN.test(value)) {\n const host = value.replace(/^[a-z]+:\\/\\//, '').replace(/:\\d+$/, '')\n if (host.startsWith('*.') && !host.slice(2).includes('.')) return undefined\n return value\n }\n return LOOPBACK_ORIGIN.test(value) ? value : undefined\n}\n\n// ── The policy in the proxy's URL ────────────────────────────────────────────────────────────\n\n/** At most this many origins per list (the core's `MCP_APP_MAX_DOMAINS`). */\nexport const MCP_APP_POLICY_MAX_ORIGINS = 32\n/** A policy token longer than this is not put in a URL: the app runs without its own origin. */\nexport const MCP_APP_POLICY_TOKEN_MAX_CHARS = 4096\n\nconst B64URL = /^[A-Za-z0-9_-]+$/\n\n/**\n * The policy as one path segment (base64url of `{\"c\":[…],\"r\":[…]}`), or `undefined` when it does\n * not fit. It is in the PATH, not the query, because a `frame-src` source expression matches a\n * path exactly and ignores the query: the host pins the proxy's frame to this one URL, so nothing\n * inside the frame can load the proxy page with a policy of its choosing.\n */\nexport const mcpAppPolicyToken = ({\n connect,\n resources,\n}: McpAppPolicyOrigins): string | undefined => {\n const json = JSON.stringify({ c: connect, r: resources })\n // Origins are ASCII; anything else is not a list of checked origins.\n if (/[^\\x20-\\x7e]/.test(json)) return undefined\n const token = btoa(json).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n return token.length <= MCP_APP_POLICY_TOKEN_MAX_CHARS ? token : undefined\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst originList = (value: unknown): string[] | undefined => {\n if (!Array.isArray(value) || value.length > MCP_APP_POLICY_MAX_ORIGINS) return undefined\n const out: string[] = []\n for (const entry of value) {\n // Exactly an origin as the host writes it: checked, canonical, once.\n if (typeof entry !== 'string' || mcpAppPolicyOrigin(entry) !== entry || out.includes(entry)) {\n return undefined\n }\n out.push(entry)\n }\n return out\n}\n\n/**\n * The policy a token stands for, or `undefined` for anything that is not exactly what\n * `mcpAppPolicyToken` writes: base64url of an object with the two lists and nothing else, every\n * entry an origin by the rule above, no more than `MCP_APP_POLICY_MAX_ORIGINS` each, the\n * canonical encoding (one URL per policy).\n */\nexport const mcpAppPolicyOfToken = (token: unknown): McpAppPolicyOrigins | undefined => {\n if (\n typeof token !== 'string' ||\n token.length === 0 ||\n token.length > MCP_APP_POLICY_TOKEN_MAX_CHARS ||\n !B64URL.test(token)\n ) {\n return undefined\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(atob(token.replace(/-/g, '+').replace(/_/g, '/')))\n } catch {\n return undefined\n }\n if (!isObject(parsed)) return undefined\n const keys = Object.keys(parsed)\n if (keys.length !== 2 || !keys.includes('c') || !keys.includes('r')) return undefined\n const connect = originList(parsed.c)\n const resources = originList(parsed.r)\n if (!connect || !resources) return undefined\n const policy = { connect, resources }\n return mcpAppPolicyToken(policy) === token ? policy : undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUO,IAAM,8BAA8B;AAEpC,IAAM,iCAAiC;AAGvC,IAAM,yBAAyB,CAAC,SACrC,OAAO,SAAS,YAChB,SAAS,QACT,OAAQ,KAA8B,WAAW,YAChD,KAA4B,OAAO,WAAW,2BAA2B;AAYrE,IAAM,uBAAuB;AAG7B,IAAM,oBAAoB,CAAC,UAChC,UAAU,WAAW,UAAU,SAAS,QAAQ;AAsB3C,IAAM,eAAe,CAAC,EAAE,SAAS,UAAU,MAAmC;AACnF,QAAM,OAAO,UAAU,SAAS,IAAI,IAAI,UAAU,KAAK,GAAG,CAAC,KAAK;AAChE,SAAO;AAAA,IACL;AAAA,IACA,gDAAgD,IAAI;AAAA,IACpD,4BAA4B,IAAI;AAAA,IAChC,sBAAsB,IAAI;AAAA,IAC1B,iBAAiB,IAAI;AAAA,IACrB,wBAAwB,IAAI;AAAA,IAC5B,QAAQ,SAAS,IAAI,eAAe,QAAQ,KAAK,GAAG,CAAC,KAAK;AAAA,IAC1D;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAIA,IAAM,QAAQ;AACd,IAAM,OAAO,cAAc,KAAK,SAAS,KAAK;AAC9C,IAAM,OAAO;AACb,IAAM,gBAAgB,IAAI,OAAO,oBAAoB,IAAI,GAAG,IAAI,GAAG;AACnE,IAAM,kBAAkB,IAAI,OAAO,yDAAyD,IAAI,GAAG;AAO5F,IAAM,qB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AQ,KAAK;AAAA,EAC7C,CAAC;AACH;","names":["json","LABEL"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp-app-sandbox.ts"],"sourcesContent":["import {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n type McpAppColorScheme,\n type McpAppPolicyOrigins,\n} from './mcp-app-policy.js'\n\n/**\n * The `./mcp-app-sandbox` entry: the MCP Apps sandbox proxy - the page a host serves on ANOTHER\n * origin, so that an app runs on an origin of its own (storage, cookies, a real `Origin`) and not\n * in an opaque one. Framework-free, no imports but `mcp-app-policy.ts`: a Cloudflare Worker, Deno,\n * Bun or Node (18+) serves it with `mcpAppSandboxResponse` (Request in, Response out).\n *\n * The page, `<base>/<policy>` (`<policy>` = `mcpAppPolicyToken`):\n *\n * 1. Its response carries the app's policy as a HEADER, built from the path (`mcpAppPolicy`), plus\n * `frame-ancestors` = the allowed host origins. The app's document is written into a frame\n * the page creates (`about:blank`, `document.write`), which INHERITS that policy - nothing the\n * app's markup says comes before it, and every document the app can reach on this origin\n * (this page, a reload of it, a frame of it) has a policy some host chose for that frame.\n * 2. Its script binds to the first ANCESTOR window on an allowed host origin that sends it\n * `ui/notifications/sandbox-resource-ready`, once; after that it relays the extension's\n * messages between that window (to its exact origin) and the app's window (to this origin),\n * never the `ui/notifications/sandbox-*` ones, and creates nothing else. It asks for\n * `ui/notifications/sandbox-proxy-ready` with a content-free message to every ancestor.\n * 3. The app's frame: `sandbox=\"allow-scripts allow-same-origin\"`, no `allow` attribute. The app\n * is same-origin with this page and can reach it - which is why the boundary is not here but\n * in what the HOST draws around it (the frame's sandbox, the shell's `frame-src` pinned to\n * this URL) and in the policy header above. A `sandbox`, `csp` or `permissions` the host sends\n * is ignored: the header is the policy, and no permission is ever granted.\n */\n\nexport {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n}\nexport type { McpAppColorScheme, McpAppPolicyOrigins }\n\n/** A host origin pattern: `https://<prefix>*<suffix>.<rest>`, `*` one run of `[a-z0-9-]`. */\nexport interface McpAppSandboxHostPattern {\n prefix: string\n suffix: string\n /** The rest of the host name after the first label: two labels at least. */\n rest: string\n}\n\n/** The host origins a sandbox page answers, as `parseMcpAppSandboxHosts` reads them. */\nexport interface McpAppSandboxHosts {\n /** Exact origins (`https://agent.example.com`, `http://127.0.0.1:4173`). */\n origins: string[]\n /** One-label patterns (`https://*-agents.example.workers.dev`). */\n patterns: McpAppSandboxHostPattern[]\n /** The same as `frame-ancestors` sources (a pattern widened to `https://*.<rest>`). */\n frameAncestors: string[]\n /** Entries that are neither: a sandbox with any of these refuses to serve (503). */\n invalid: string[]\n}\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst NAME = `${LABEL}(?:\\\\.${LABEL})+`\nconst EXACT_HTTPS = new RegExp(`^https://${LABEL}(?:\\\\.${LABEL})*(?::\\\\d{1,5})?$`)\nconst EXACT_LOOPBACK = /^http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::\\d{1,5})?$/\nconst PATTERN = new RegExp(`^https://([a-z0-9-]{0,40})\\\\*([a-z0-9-]{0,40})\\\\.(${NAME})$`)\n\n/**\n * The allowed host origins, from a list or a space / comma separated string (a deploy-time\n * setting, e.g. `ALLOWED_HOST_ORIGINS=\"https://agent.example.com https://*-agents.example.workers.dev\"`).\n * An entry is an exact origin - `https://`, or `http://` on `localhost` / `127.0.0.1` - or a\n * pattern with ONE `*` inside the first label of an `https://` host. The page's script holds the\n * pattern to one label (`[a-z0-9-]+`, no dot); `frame-ancestors` cannot say that, so there the\n * pattern is widened to `https://*.<rest>` (every subdomain of `<rest>`). Anything else is\n * `invalid`.\n */\nexport const parseMcpAppSandboxHosts = (\n value: string | readonly string[] | undefined,\n): McpAppSandboxHosts => {\n const entries = (typeof value === 'string' ? value.split(/[\\s,]+/) : [...(value ?? [])])\n .map((e) => (typeof e === 'string' ? e.trim() : ''))\n .filter(Boolean)\n const hosts: McpAppSandboxHosts = { origins: [], patterns: [], frameAncestors: [], invalid: [] }\n const ancestor = (source: string) => {\n if (!hosts.frameAncestors.includes(source)) hosts.frameAncestors.push(source)\n }\n for (const raw of entries) {\n const entry = raw.toLowerCase().replace(/\\/$/, '')\n const pattern = PATTERN.exec(entry)\n if (pattern) {\n const [, prefix, suffix, rest] = pattern\n if (\n !hosts.patterns.some((p) => p.prefix === prefix && p.suffix === suffix && p.rest === rest)\n ) {\n hosts.patterns.push({ prefix, suffix, rest })\n }\n ancestor(`https://*.${rest}`)\n } else if (EXACT_HTTPS.test(entry) || EXACT_LOOPBACK.test(entry)) {\n if (!hosts.origins.includes(entry)) hosts.origins.push(entry)\n ancestor(entry)\n } else {\n hosts.invalid.push(raw.slice(0, 120))\n }\n }\n return hosts\n}\n\n/** Whether an origin is one of the hosts (the same rule the page's script applies). */\nexport const isMcpAppSandboxHost = (hosts: McpAppSandboxHosts, origin: string): boolean => {\n if (hosts.origins.includes(origin)) return true\n const head = 'https://'\n for (const p of hosts.patterns) {\n const tail = `.${p.rest}`\n if (!origin.startsWith(head) || !origin.endsWith(tail)) continue\n const label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || !label.startsWith(p.prefix) || !label.endsWith(p.suffix)) continue\n const middle = label.slice(p.prefix.length, label.length - p.suffix.length)\n if (/^[a-z0-9-]+$/.test(middle)) return true\n }\n return false\n}\n\n/**\n * The page's script (inline; it runs under the app's own policy, which allows inline scripts).\n * It reads the hosts from `#mcp-app-sandbox-hosts`, binds to the first allowed ancestor that sends\n * the resource, writes the app into its frame, and relays - see the entry's comment.\n */\nexport const MCP_APP_SANDBOX_SCRIPT = `(function () {\n 'use strict'\n var READY = ${JSON.stringify(MCP_APP_SANDBOX_PROXY_READY)}\n var RESOURCE = ${JSON.stringify(MCP_APP_SANDBOX_RESOURCE_READY)}\n var RESERVED = 'ui/notifications/sandbox-'\n var me = window\n if (me.parent === me) return\n var cfg\n try {\n cfg = JSON.parse(document.getElementById('mcp-app-sandbox-hosts').textContent)\n } catch (e) {\n return\n }\n var origins = cfg && Array.isArray(cfg.origins) ? cfg.origins : []\n var patterns = cfg && Array.isArray(cfg.patterns) ? cfg.patterns : []\n function allowed(origin) {\n if (typeof origin !== 'string') return false\n if (origins.indexOf(origin) >= 0) return true\n for (var i = 0; i < patterns.length; i++) {\n var p = patterns[i]\n var head = 'https://'\n var tail = '.' + p.rest\n if (origin.indexOf(head) !== 0 || origin.length <= head.length + tail.length) continue\n if (origin.slice(origin.length - tail.length) !== tail) continue\n var label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || label.indexOf(p.prefix) !== 0) continue\n if (label.slice(label.length - p.suffix.length) !== p.suffix) continue\n if (/^[a-z0-9-]+$/.test(label.slice(p.prefix.length, label.length - p.suffix.length))) return true\n }\n return false\n }\n var ancestors = []\n for (var w = me.parent; ancestors.length < 32; w = w.parent) {\n ancestors.push(w)\n if (w === w.parent) break\n }\n function ancestor(source) {\n for (var i = 0; i < ancestors.length; i++) if (ancestors[i] === source) return true\n return false\n }\n function reserved(d) {\n return !!d && typeof d === 'object' && typeof d.method === 'string' && d.method.indexOf(RESERVED) === 0\n }\n var OWN = me.origin\n var host = null\n var hostOrigin = ''\n var app = null\n me.addEventListener('message', function (e) {\n var d = e.data\n if (app && e.source === app) {\n if (e.origin !== OWN || reserved(d)) return\n host.postMessage(d, hostOrigin)\n return\n }\n if (host) {\n if (e.source !== host || e.origin !== hostOrigin || reserved(d) || !app) return\n app.postMessage(d, OWN)\n return\n }\n if (!d || typeof d !== 'object' || d.jsonrpc !== '2.0' || d.method !== RESOURCE) return\n if (!ancestor(e.source) || !allowed(e.origin)) return\n var p = d.params\n if (!p || typeof p !== 'object' || typeof p.html !== 'string') return\n host = e.source\n hostOrigin = e.origin\n var frame = document.createElement('iframe')\n frame.id = 'app'\n frame.setAttribute('sandbox', 'allow-scripts allow-same-origin')\n frame.setAttribute('referrerpolicy', 'no-referrer')\n frame.setAttribute('title', 'MCP App')\n document.body.appendChild(frame)\n app = frame.contentWindow\n var doc = frame.contentDocument\n doc.open()\n doc.write(p.html)\n doc.close()\n })\n var ready = { jsonrpc: '2.0', method: READY, params: {} }\n for (var i = 0; i < ancestors.length; i++) ancestors[i].postMessage(ready, '*')\n})()`\n\nconst json = (value: unknown): string =>\n JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026')\n\n/**\n * The page: the hosts as data, the script. Serve it with `mcpAppSandboxHeaders`. `scheme` (the\n * frame's colour scheme, `?scheme=` of the page's URL) is declared by the page and on the app's\n * frame - only `light` / `dark`; without one the page declares nothing.\n */\nexport const mcpAppSandboxPage = (\n hosts: McpAppSandboxHosts,\n scheme?: McpAppColorScheme,\n): string => {\n const s = mcpAppColorScheme(scheme)\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex\">' +\n (s ? `<meta name=\"color-scheme\" content=\"${s}\">` : '') +\n '<title>MCP App sandbox</title>' +\n `<style>${s ? `:root{color-scheme:${s}}` : ''}` +\n 'html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n `iframe{display:block;border:0;width:100%;height:100%${s ? `;color-scheme:${s}` : ''}}` +\n '</style></head><body>' +\n `<script type=\"application/json\" id=\"mcp-app-sandbox-hosts\">${json({\n origins: hosts.origins,\n patterns: hosts.patterns,\n })}</script>` +\n `<script>${MCP_APP_SANDBOX_SCRIPT}</script></body></html>`\n )\n}\n\n/** Browser features the page and the app may never use, whatever an app asks for. */\nexport const MCP_APP_SANDBOX_PERMISSIONS_POLICY =\n 'camera=(), microphone=(), geolocation=(), display-capture=(), payment=(), usb=(), serial=(), midi=()'\n\nconst COMMON = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Robots-Tag': 'noindex, nofollow',\n 'Referrer-Policy': 'no-referrer',\n 'Cache-Control': 'no-store',\n}\n\n/**\n * The page's response headers: the app's policy AND `frame-ancestors` (the hosts; `'none'` when\n * there are none), `nosniff`, `no-store` (a policy is never served from a stale copy), no referrer,\n * `noindex`, and a Permissions-Policy that grants nothing.\n */\nexport const mcpAppSandboxHeaders = (\n policy: McpAppPolicyOrigins,\n hosts: McpAppSandboxHosts,\n): Record<string, string> => ({\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Security-Policy': `${mcpAppPolicy(policy)}; frame-ancestors ${\n hosts.frameAncestors.length > 0 ? hosts.frameAncestors.join(' ') : \"'none'\"\n }`,\n 'Permissions-Policy': MCP_APP_SANDBOX_PERMISSIONS_POLICY,\n ...COMMON,\n})\n\nexport interface McpAppSandboxServeOptions {\n /** Where the pages are: `'/sandbox/v1'` serves `/sandbox/v1/<policy>`. */\n path: string\n /** The host origins that may frame the page and send it an app (see `parseMcpAppSandboxHosts`). */\n hosts: string | readonly string[] | undefined\n}\n\nconst plain = (status: number, text: string, extra: Record<string, string> = {}): Response =>\n new Response(text, {\n status,\n headers: {\n 'Content-Type': 'text/plain; charset=utf-8',\n 'Content-Security-Policy': \"default-src 'none'; frame-ancestors 'none'\",\n ...COMMON,\n ...extra,\n },\n })\n\n/**\n * A fetch handler for the sandbox page: `GET` / `HEAD` of `<path>/<policy>` is the page, with its\n * headers (and `?scheme=light|dark`, the frame's colour scheme - anything else is none); a token\n * that is not exactly what `mcpAppPolicyToken` writes is 400; another method 405;\n * any other path 404; no valid host origin (or an invalid entry in the setting) 503 - a sandbox\n * nobody may frame is a configuration error, not a page.\n */\nexport const mcpAppSandboxResponse = (\n request: Request,\n options: McpAppSandboxServeOptions,\n): Response => {\n const { pathname, searchParams } = new URL(request.url)\n const base = options.path.replace(/\\/+$/, '')\n if (!pathname.startsWith(`${base}/`)) return plain(404, 'Not found')\n const token = pathname.slice(base.length + 1)\n if (token.length === 0 || token.includes('/')) return plain(404, 'Not found')\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n return plain(405, 'Method not allowed', { Allow: 'GET, HEAD' })\n }\n const policy = mcpAppPolicyOfToken(token)\n if (!policy) return plain(400, 'Not a policy this sandbox serves')\n const hosts = parseMcpAppSandboxHosts(options.hosts)\n if (hosts.invalid.length > 0 || hosts.frameAncestors.length === 0) {\n return plain(503, 'This sandbox has no valid allowed host origins')\n }\n const scheme = mcpAppColorScheme(searchParams.get(MCP_APP_SCHEME_PARAM))\n return new Response(request.method === 'HEAD' ? null : mcpAppSandboxPage(hosts, scheme), {\n status: 200,\n headers: mcpAppSandboxHeaders(policy, hosts),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4EA,IAAM,QAAQ;AACd,IAAM,OAAO,GAAG,KAAK,SAAS,KAAK;AACnC,IAAM,cAAc,IAAI,OAAO,YAAY,KAAK,SAAS,KAAK,mBAAmB;AACjF,IAAM,iBAAiB;AACvB,IAAM,UAAU,IAAI,OAAO,qDAAqD,IAAI,IAAI;AAWjF,IAAM,0BAA0B,CACrC,UACuB;AACvB,QAAM,WAAW,OAAO,UAAU,WAAW,MAAM,MAAM,QAAQ,IAAI,CAAC,GAAI,SAAS,CAAC,CAAE,GACnF,IAAI,CAAC,MAAO,OAAO,MAAM,WAAW,EAAE,KAAK,IAAI,EAAG,EAClD,OAAO,OAAO;AACjB,QAAM,QAA4B,EAAE,SAAS,CAAC,GAAG,UAAU,CAAC,GAAG,gBAAgB,CAAC,GAAG,SAAS,CAAC,EAAE;AAC/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