@supersolutions/super-chat-ui-core 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,7 +9,7 @@ binding does not have to reimplement them:
9
9
  - `export.ts` — `threadToMarkdown`, `downloadThread`.
10
10
 
11
11
  No React, no DOM framework. Part of the [superchat](../../README.md) monorepo. The React
12
- components live in [`@supersolutions/super-chat-ui`](../ui/README.md); the shared stylesheet still
12
+ components live in [`@supersolutions/super-chat-ui`](../bindings/react-ui/README.md); the shared stylesheet still
13
13
  ships with that package for now.
14
14
 
15
15
  ## Install
package/dist/index.d.ts CHANGED
@@ -31,29 +31,72 @@ declare function threadToMarkdown(messages: readonly Message[], title?: string):
31
31
  /** Trigger a download of the thread as a `.md` file. */
32
32
  declare function downloadThread(messages: readonly Message[], filename?: string, title?: string): void;
33
33
 
34
+ /**
35
+ * What a host can change about how Markdown becomes HTML. Everything is optional, and the
36
+ * defaults are the safe ones: no image is fetched, no maths is guessed at, code is coloured by
37
+ * a small built-in highlighter.
38
+ */
39
+ type MarkdownOptions = {
40
+ /**
41
+ * Colour fenced code: `(code, lang) => html` for the inside of `<code>`, or `undefined` to
42
+ * leave that block plain. The default knows JS/TS, JSON, Python, shell, SQL, HTML/CSS, YAML
43
+ * and diffs; pass highlight.js or Shiki here for the rest, or `false` for none. The returned
44
+ * HTML is inserted as it is, so it must come from code you trust.
45
+ */
46
+ highlight?: ((code: string, lang: string) => string | undefined) | false;
47
+ /**
48
+ * Typeset `$…$` and `$$…$$`: `(tex, display) => html`, or `undefined` to leave the source as
49
+ * text. Without this, `$` is an ordinary character, so a price is never mistaken for maths.
50
+ * The returned HTML is inserted as it is, so it must come from code you trust (KaTeX, Temml).
51
+ */
52
+ math?: (tex: string, display: boolean) => string | undefined;
53
+ /**
54
+ * What `![alt](https://…)` becomes. `"link"` (the default) is a link to the image: nothing is
55
+ * fetched until the reader follows it, so a model cannot make a page load a URL it chose.
56
+ * `"embed"` draws the picture, with lazy loading and no referrer.
57
+ */
58
+ images?: "link" | "embed";
59
+ /**
60
+ * Draw the buttons for code blocks and tables (copy, wrap, show all) as markup. They carry
61
+ * `data-sc-act` and no words; `ProseHtml` in `super-chat-ui` gives them their labels and
62
+ * answers them. Off by default so a plain `renderMarkdown` string has no dead buttons in it.
63
+ */
64
+ actions?: boolean;
65
+ };
34
66
  type AnchoredMarkdown = {
35
67
  html: string;
36
68
  /** Index-aligned with the `data-sc-block` attribute on the rendered HTML. */
37
69
  blocks: MarkdownBlock[];
38
70
  };
71
+ /** A heading's hashes and text, by one linear pass; null when the line is not a heading. */
72
+ declare function atxHeading(line: string): {
73
+ hashes: number;
74
+ text: string;
75
+ } | null;
39
76
  /** Render for the transcript: no anchors, because chat prose is not addressed. */
40
- declare function renderMarkdown(src: string): string;
77
+ declare function renderMarkdown(src: string, options?: MarkdownOptions): string;
41
78
  /** What renderMarkdownStream keeps between calls. Start from newMarkdownStream(). */
42
79
  type MarkdownStream = {
43
80
  /** The source the cached blocks were decided on; valid while the text starts with it. */
44
81
  settled: string;
45
- /** Rendered HTML of those blocks. */
46
- html: string;
82
+ /** Rendered HTML of those blocks, one string each, in order. They never change once here. */
83
+ parts: string[];
47
84
  /** Where the block after them starts looking: the line after the last one. */
48
85
  resume: number;
86
+ /** The options the cache was rendered with; a different set starts it over. */
87
+ options: MarkdownOptions | undefined;
49
88
  };
50
89
  declare const newMarkdownStream: () => MarkdownStream;
51
90
  /**
52
91
  * renderMarkdown for text that grows while it is shown — always the same
53
- * string renderMarkdown(src) returns, but blocks that can no longer change are
92
+ * HTML renderMarkdown(src) returns, but blocks that can no longer change are
54
93
  * rendered once and reused, so a streamed answer costs its open tail per
55
94
  * frame instead of its whole length.
56
95
  *
96
+ * Returned block by block: the strings of blocks that cannot change again are the very same
97
+ * strings from one call to the next, which is what lets `ProseHtml` leave their DOM alone
98
+ * (and a selection inside them standing) while the tail grows.
99
+ *
57
100
  * Every block renders from its own source slice alone, so the only question
58
101
  * is which blocks later text can still move. splitBlocks decides a block's
59
102
  * extent from its own lines and, at most, the first line of the block after
@@ -73,7 +116,9 @@ declare const newMarkdownStream: () => MarkdownStream;
73
116
  * Text that does not start with `stream.settled` — a new run, an edit — drops
74
117
  * the cache and renders from scratch.
75
118
  */
76
- declare function renderMarkdownStream(src: string, stream: MarkdownStream): string;
119
+ declare function renderMarkdownBlocks(src: string, stream: MarkdownStream, options?: MarkdownOptions): string[];
120
+ /** `renderMarkdownBlocks`, joined: the string `renderMarkdown(src, options)` would give. */
121
+ declare function renderMarkdownStream(src: string, stream: MarkdownStream, options?: MarkdownOptions): string;
77
122
  /**
78
123
  * Render for a document previewer: every block carries `data-sc-block`, so a
79
124
  * DOM selection resolves to a source span by walking up to the nearest one.
@@ -82,6 +127,19 @@ declare function renderMarkdownStream(src: string, stream: MarkdownStream): stri
82
127
  * assistant prose has nothing to address and the extra attributes would be
83
128
  * noise in every message bubble.
84
129
  */
85
- declare function renderMarkdownWithAnchors(src: string): AnchoredMarkdown;
130
+ declare function renderMarkdownWithAnchors(src: string, options?: MarkdownOptions): AnchoredMarkdown;
131
+
132
+ /** The languages the built-in highlighter knows, by every name it answers to. */
133
+ declare const HIGHLIGHT_LANGUAGES: readonly string[];
134
+ /**
135
+ * Highlight `code` written in `lang`, as HTML for the inside of `<code>`.
136
+ * Returns `undefined` for a language it does not know, which leaves the code as plain text.
137
+ */
138
+ declare function highlightCode(code: string, lang: string): string | undefined;
139
+
140
+ /** Header row and data rows, tab-separated — what a spreadsheet pastes into cells. */
141
+ declare function tableToTsv(header: readonly string[], rows: readonly (readonly string[])[]): string;
142
+ /** A GitHub-flavoured Markdown table. A pipe in a cell is escaped; a line break becomes a space. */
143
+ declare function tableToMarkdown(header: readonly string[], rows: readonly (readonly string[])[], align?: readonly ("left" | "center" | "right" | null)[]): string;
86
144
 
87
- export { type AnchoredMarkdown, type FormatOptions, type MarkdownStream, STABLE_FORMAT, deltaTone, downloadThread, formatDelta, formatValue, newMarkdownStream, renderMarkdown, renderMarkdownStream, renderMarkdownWithAnchors, safeHref, threadToMarkdown, toneClass };
145
+ export { type AnchoredMarkdown, type FormatOptions, HIGHLIGHT_LANGUAGES, type MarkdownOptions, type MarkdownStream, STABLE_FORMAT, atxHeading, deltaTone, downloadThread, formatDelta, formatValue, highlightCode, newMarkdownStream, renderMarkdown, renderMarkdownBlocks, renderMarkdownStream, renderMarkdownWithAnchors, safeHref, tableToMarkdown, tableToTsv, threadToMarkdown, toneClass };
package/dist/index.js CHANGED
@@ -18,32 +18,49 @@ function numbersFor(locale) {
18
18
  }
19
19
  return formats;
20
20
  }
21
+ function numeric(value) {
22
+ if (typeof value === "number") return value;
23
+ if (typeof value === "bigint") return Number(value);
24
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
25
+ return Number.NaN;
26
+ }
27
+ function plain(value) {
28
+ if (typeof value === "string" && value.trim() === "") return "\u2014";
29
+ if (typeof value === "object") {
30
+ try {
31
+ return JSON.stringify(value) ?? String(value);
32
+ } catch {
33
+ return String(value);
34
+ }
35
+ }
36
+ return String(value);
37
+ }
21
38
  function formatValue(value, format = "text", options = {}) {
22
39
  if (value == null) return "\u2014";
23
40
  const { locale, timeZone } = options;
24
41
  const numbers = numbersFor(locale);
25
42
  switch (format) {
26
43
  case "number": {
27
- const n = Number(value);
28
- if (!Number.isFinite(n)) return String(value);
44
+ const n = numeric(value);
45
+ if (!Number.isFinite(n)) return plain(value);
29
46
  return Math.abs(n) >= 1e5 ? numbers.compact.format(n) : numbers.plain.format(n);
30
47
  }
31
48
  case "currency": {
32
- const n = Number(value);
33
- if (!Number.isFinite(n)) return String(value);
49
+ const n = numeric(value);
50
+ if (!Number.isFinite(n)) return plain(value);
34
51
  const abs = Math.abs(n);
35
52
  const digits = abs >= 1 ? 2 : abs >= 0.01 ? 4 : 8;
36
53
  const min = abs >= 1e3 && Number.isInteger(n) ? 0 : 2;
37
54
  return `$${n.toLocaleString(locale, { minimumFractionDigits: min, maximumFractionDigits: Math.max(min, digits) })}`;
38
55
  }
39
56
  case "percent": {
40
- const n = Number(value);
41
- if (!Number.isFinite(n)) return String(value);
57
+ const n = numeric(value);
58
+ if (!Number.isFinite(n)) return plain(value);
42
59
  return `${(Math.abs(n) < 1 ? numbers.pctNarrow : numbers.pctWide).format(n)}%`;
43
60
  }
44
61
  case "bytes": {
45
- const n = Number(value);
46
- if (!Number.isFinite(n)) return String(value);
62
+ const n = numeric(value);
63
+ if (!Number.isFinite(n)) return plain(value);
47
64
  const units = ["B", "KB", "MB", "GB", "TB"];
48
65
  let i = 0;
49
66
  let v = n;
@@ -54,22 +71,22 @@ function formatValue(value, format = "text", options = {}) {
54
71
  return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
55
72
  }
56
73
  case "duration": {
57
- const ms = Number(value);
58
- if (!Number.isFinite(ms)) return String(value);
74
+ const ms = numeric(value);
75
+ if (!Number.isFinite(ms)) return plain(value);
59
76
  if (ms < 1e3) return `${Math.round(ms)}ms`;
60
77
  if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
61
78
  if (ms < 36e5) return `${Math.floor(ms / 6e4)}m ${Math.round(ms % 6e4 / 1e3)}s`;
62
79
  return `${(ms / 36e5).toFixed(1)}h`;
63
80
  }
64
81
  case "datetime": {
65
- const d = typeof value === "number" ? new Date(value) : new Date(String(value));
66
- if (Number.isNaN(d.getTime())) return String(value);
82
+ const d = typeof value === "number" ? new Date(value) : typeof value === "string" ? new Date(value) : new Date(Number.NaN);
83
+ if (Number.isNaN(d.getTime())) return plain(value);
67
84
  return d.toLocaleString(locale, timeZone ? { timeZone, timeZoneName: "short" } : void 0);
68
85
  }
69
86
  case "code":
70
87
  case "text":
71
88
  default:
72
- return typeof value === "object" ? JSON.stringify(value) : String(value);
89
+ return typeof value === "object" ? plain(value) : String(value);
73
90
  }
74
91
  }
75
92
  function formatDelta(delta, format = "number", options = {}) {
@@ -86,31 +103,56 @@ function safeHref(url) {
86
103
  }
87
104
 
88
105
  // src/export.ts
106
+ function fence(text) {
107
+ let longest = 0;
108
+ for (const run2 of text.match(/`+/g) ?? []) longest = Math.max(longest, run2.length);
109
+ return "`".repeat(Math.max(3, longest + 1));
110
+ }
111
+ function fenced(info, text) {
112
+ const f = fence(text);
113
+ return `${f}${info}
114
+ ${text}
115
+ ${f}`;
116
+ }
117
+ function cell(value) {
118
+ let text;
119
+ if (value === null || value === void 0) text = "";
120
+ else if (typeof value === "object") {
121
+ try {
122
+ text = JSON.stringify(value);
123
+ } catch {
124
+ text = String(value);
125
+ }
126
+ } else text = String(value);
127
+ return text.replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
128
+ }
89
129
  function cardToMarkdown(spec) {
90
130
  const kind = String(spec.kind ?? "unknown");
91
131
  const title = spec.title ? `**${spec.title}**
92
132
 
93
133
  ` : "";
94
134
  if (kind === "table" && Array.isArray(spec.columns) && Array.isArray(spec.rows)) {
95
- const cols = spec.columns;
96
- const rows = spec.rows;
97
- const head = `| ${cols.map((c) => c.label).join(" | ")} |`;
135
+ const cols = spec.columns.filter((c) => typeof c === "object" && c !== null);
136
+ const rows = spec.rows.filter((r) => typeof r === "object" && r !== null);
137
+ const head = `| ${cols.map((c) => cell(c.label)).join(" | ")} |`;
98
138
  const rule = `| ${cols.map(() => "---").join(" | ")} |`;
99
- const body = rows.map((r) => `| ${cols.map((c) => String(r[c.key] ?? "")).join(" | ")} |`).join("\n");
139
+ const body = rows.map((r) => `| ${cols.map((c) => cell(r[c.key])).join(" | ")} |`).join("\n");
100
140
  return `${title}${head}
101
141
  ${rule}
102
142
  ${body}`;
103
143
  }
104
144
  if (kind === "markdown" && typeof spec.body === "string") return `${title}${spec.body}`;
105
145
  if (kind === "code" && typeof spec.code === "string") {
106
- return `${title}\`\`\`${spec.language ?? ""}
107
- ${spec.code}
108
- \`\`\``;
146
+ return `${title}${fenced(typeof spec.language === "string" ? spec.language : "", spec.code)}`;
109
147
  }
110
148
  if (kind === "callout" && typeof spec.body === "string") return `> ${title}${spec.body}`;
111
- return `${title}\`\`\`json
112
- ${JSON.stringify(spec, null, 2)}
113
- \`\`\``;
149
+ let json;
150
+ try {
151
+ json = JSON.stringify(spec, null, 2) ?? "null";
152
+ } catch {
153
+ json = "(data that cannot be shown as JSON)";
154
+ }
155
+ return `${title}${fenced("json", json)}`;
114
156
  }
115
157
  function partToMarkdown(part) {
116
158
  switch (part.type) {
@@ -122,8 +164,15 @@ function partToMarkdown(part) {
122
164
  ${part.text}
123
165
 
124
166
  </details>`;
125
- case "tool-call":
126
- return `- \`${part.name}(${JSON.stringify(part.input ?? {})})\``;
167
+ case "tool-call": {
168
+ let args;
169
+ try {
170
+ args = JSON.stringify(part.input ?? {}) ?? "{}";
171
+ } catch {
172
+ args = "\u2026";
173
+ }
174
+ return `- \`${part.name}(${args})\``;
175
+ }
127
176
  case "tool-result":
128
177
  return part.failure ? `- \`${part.name}\` failed: ${part.failure}` : null;
129
178
  case "image":
@@ -131,7 +180,12 @@ ${part.text}
131
180
  case "file":
132
181
  return `_(file: ${part.filename ?? "attachment"})_`;
133
182
  case "artifact":
134
- return part.kind.startsWith("card:") ? cardToMarkdown(part.data.spec ?? part.data) : null;
183
+ if (!part.kind.startsWith("card:")) return null;
184
+ {
185
+ const data = part.data;
186
+ const spec = data?.spec ?? data;
187
+ return typeof spec === "object" && spec !== null && !Array.isArray(spec) ? cardToMarkdown(spec) : null;
188
+ }
135
189
  default:
136
190
  return null;
137
191
  }
@@ -143,7 +197,8 @@ function threadToMarkdown(messages, title) {
143
197
  const body = m.parts.map(partToMarkdown).filter(Boolean).join("\n\n");
144
198
  if (!body) continue;
145
199
  const who = m.role === "user" ? "You" : m.role === "tool" ? "Tools" : "Assistant";
146
- const when = m.createdAt ? ` \xB7 ${new Date(m.createdAt).toISOString().slice(0, 16).replace("T", " ")}` : "";
200
+ const at = typeof m.createdAt === "number" ? new Date(m.createdAt) : void 0;
201
+ const when = at && Number.isFinite(at.getTime()) ? ` \xB7 ${at.toISOString().slice(0, 16).replace("T", " ")}` : "";
147
202
  out.push(`## ${who}${when}`, "", body, "");
148
203
  }
149
204
  return out.join("\n").trimEnd() + "\n";
@@ -160,15 +215,218 @@ function downloadThread(messages, filename = "conversation.md", title) {
160
215
 
161
216
  // src/markdown.ts
162
217
  import { splitBlocks } from "@supersolutions/super-chat-core";
218
+
219
+ // src/highlight.ts
220
+ var escape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
221
+ var words = (list) => `\\b(?:${list.trim().split(/\s+/).join("|")})\\b`;
222
+ var STRING = `"(?:[^"\\\\\\n]|\\\\.)*"?|'(?:[^'\\\\\\n]|\\\\.)*'?`;
223
+ var NUMBER = `\\b(?:0x[\\da-fA-F]+|\\d+(?:\\.\\d+)?(?:e[+-]?\\d+)?)\\b`;
224
+ var lexer = (groups, flags = "g") => ({
225
+ re: new RegExp(groups.map(([, source]) => `(${source})`).join("|"), flags),
226
+ classes: groups.map(([cls]) => cls)
227
+ });
228
+ var JS_WORDS = /* @__PURE__ */ words(`
229
+ as async await break case catch class const continue debugger default delete do else enum export
230
+ extends finally for from function if implements import in instanceof interface let new of package
231
+ private protected public readonly return static super switch this throw try type typeof var void
232
+ while with yield satisfies declare namespace abstract keyof
233
+ `);
234
+ var LITERALS = /* @__PURE__ */ words("true false null undefined NaN Infinity None True False nil");
235
+ var SOURCES = {
236
+ js: () => lexer([
237
+ ["c", "\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)"],
238
+ ["s", `${STRING}|\`(?:[^\`\\\\]|\\\\[\\s\\S])*\`?`],
239
+ ["k", JS_WORDS],
240
+ ["l", LITERALS],
241
+ ["n", NUMBER],
242
+ ["f", "\\b[A-Za-z_$][\\w$]*(?=\\s*\\()"]
243
+ ]),
244
+ py: () => lexer([
245
+ ["c", "#[^\\n]*"],
246
+ ["s", `(?:[rbfRBF]{0,2})(?:"""[\\s\\S]*?(?:"""|$)|'''[\\s\\S]*?(?:'''|$))|(?:[rbfRBF]{0,2})(?:${STRING})`],
247
+ [
248
+ "k",
249
+ words(`
250
+ and as assert async await break class continue def del elif else except finally for from global
251
+ if import in is lambda nonlocal not or pass raise return try while with yield match case
252
+ `)
253
+ ],
254
+ ["l", LITERALS],
255
+ ["n", NUMBER],
256
+ ["f", "\\b[A-Za-z_]\\w*(?=\\s*\\()"]
257
+ ]),
258
+ json: () => lexer([
259
+ ["p", `"(?:[^"\\\\\\n]|\\\\.)*"(?=\\s*:)`],
260
+ ["s", `"(?:[^"\\\\\\n]|\\\\.)*"?`],
261
+ ["l", words("true false null")],
262
+ ["n", "-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"]
263
+ ]),
264
+ sh: () => lexer([
265
+ ["c", "(?:^|(?<=\\s))#[^\\n]*"],
266
+ ["s", STRING],
267
+ ["v", "\\$(?:\\{[^}\\n]*\\}|[A-Za-z_]\\w*|[0-9?!#@*$])"],
268
+ ["f", "(?:^|(?<=[;|&(]))[ \\t]*(?:sudo\\s+)?[A-Za-z_.\\/-][\\w./-]*"],
269
+ ["a", "(?<=\\s)--?[A-Za-z][\\w-]*"],
270
+ ["k", words("if then else elif fi for while do done case esac function in export return exit")],
271
+ ["n", NUMBER]
272
+ ], "gm"),
273
+ sql: () => lexer(
274
+ [
275
+ ["c", "--[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)"],
276
+ ["s", "'(?:[^']|'')*'?"],
277
+ [
278
+ "k",
279
+ words(`
280
+ select from where and or not null is in as on join left right inner outer full cross group by
281
+ order having limit offset insert into values update set delete create alter drop table index
282
+ view distinct union all case when then else end exists between like ilike asc desc primary key
283
+ foreign references default returning with
284
+ `)
285
+ ],
286
+ ["n", NUMBER],
287
+ ["f", "\\b[A-Za-z_]\\w*(?=\\s*\\()"]
288
+ ],
289
+ "gi"
290
+ ),
291
+ markup: () => lexer([
292
+ ["c", "<!--[\\s\\S]*?(?:-->|$)|\\/\\*[\\s\\S]*?(?:\\*\\/|$)"],
293
+ ["s", STRING],
294
+ ["k", "<\\/?[A-Za-z][\\w:-]*|\\/?>|@[A-Za-z-]+"],
295
+ ["a", "\\b[A-Za-z-]+(?==)"],
296
+ ["p", "(?<=[{;\\s])[a-z-]+(?=\\s*:)"],
297
+ ["n", "#[\\da-fA-F]{3,8}\\b|\\b\\d+(?:\\.\\d+)?(?:px|em|rem|%|vh|vw|s|ms)?\\b"]
298
+ ]),
299
+ yaml: () => lexer([
300
+ ["c", "(?:^|(?<=\\s))#[^\\n]*"],
301
+ ["p", `^[ \\t-]*[\\w."'/-]+(?=\\s*:(?:\\s|$))`],
302
+ ["s", STRING],
303
+ ["l", words("true false null yes no on off")],
304
+ ["n", NUMBER]
305
+ ], "gm")
306
+ };
307
+ var ALIASES = {
308
+ js: "js",
309
+ jsx: "js",
310
+ mjs: "js",
311
+ cjs: "js",
312
+ javascript: "js",
313
+ ts: "js",
314
+ tsx: "js",
315
+ typescript: "js",
316
+ py: "py",
317
+ python: "py",
318
+ json: "json",
319
+ jsonc: "json",
320
+ json5: "json",
321
+ sh: "sh",
322
+ bash: "sh",
323
+ zsh: "sh",
324
+ shell: "sh",
325
+ console: "sh",
326
+ shellsession: "sh",
327
+ sql: "sql",
328
+ psql: "sql",
329
+ postgres: "sql",
330
+ mysql: "sql",
331
+ sqlite: "sql",
332
+ html: "markup",
333
+ xml: "markup",
334
+ svg: "markup",
335
+ css: "markup",
336
+ scss: "markup",
337
+ vue: "markup",
338
+ yaml: "yaml",
339
+ yml: "yaml",
340
+ toml: "yaml"
341
+ };
342
+ var built = /* @__PURE__ */ new Map();
343
+ function lexerFor(key) {
344
+ if (!built.has(key)) {
345
+ try {
346
+ built.set(key, SOURCES[key]());
347
+ } catch {
348
+ built.set(key, null);
349
+ }
350
+ }
351
+ return built.get(key);
352
+ }
353
+ function run({ re, classes }, code) {
354
+ let out = "";
355
+ let last = 0;
356
+ re.lastIndex = 0;
357
+ for (let m = re.exec(code); m; m = re.exec(code)) {
358
+ if (m[0] === "") {
359
+ re.lastIndex += 1;
360
+ continue;
361
+ }
362
+ let group = 1;
363
+ while (group < m.length && m[group] === void 0) group += 1;
364
+ const cls = classes[group - 1];
365
+ out += escape(code.slice(last, m.index));
366
+ out += cls ? `<span class="sc-tok-${cls}">${escape(m[0])}</span>` : escape(m[0]);
367
+ last = m.index + m[0].length;
368
+ }
369
+ return out + escape(code.slice(last));
370
+ }
371
+ function diff(code) {
372
+ return code.split("\n").map((line) => {
373
+ const cls = /^(?:\+\+\+|---)/.test(line) ? "k" : line.startsWith("+") ? "add" : line.startsWith("-") ? "del" : line.startsWith("@@") ? "k" : "";
374
+ return cls ? `<span class="sc-tok-${cls}">${escape(line)}</span>` : escape(line);
375
+ }).join("\n");
376
+ }
377
+ var HIGHLIGHT_LANGUAGES = /* @__PURE__ */ (() => [...Object.keys(ALIASES), "diff", "patch"])();
378
+ function highlightCode(code, lang) {
379
+ const name = lang.toLowerCase();
380
+ if (name === "diff" || name === "patch") return diff(code);
381
+ const key = Object.hasOwn(ALIASES, name) ? ALIASES[name] : void 0;
382
+ const lex = key ? lexerFor(key) : null;
383
+ return lex ? run(lex, code) : void 0;
384
+ }
385
+
386
+ // src/markdown.ts
387
+ var contextOf = (o) => ({
388
+ highlight: o?.highlight === void 0 ? highlightCode : o.highlight,
389
+ math: o?.math,
390
+ embed: o?.images === "embed",
391
+ actions: o?.actions === true
392
+ });
163
393
  var MARKDOWN_SIGNIFICANT = /[`*_#[\]>~|-]/;
164
394
  var ORDERED_ITEM = /^ {0,3}\d{1,9}[.)]\s/m;
165
395
  var SETEXT_EQUALS = /\n {0,3}=+[ \t]*$/;
166
- var isPlainProse = (raw) => !MARKDOWN_SIGNIFICANT.test(raw) && !ORDERED_ITEM.test(raw) && !SETEXT_EQUALS.test(raw);
396
+ var AUTOLINKABLE = /https?:\/\//;
397
+ var ENTITY = /&(?:[a-z][a-z\d]{1,31}|#\d{1,7}|#x[\da-f]{1,6});/i;
398
+ var isPlainProse = (raw, ctx) => !MARKDOWN_SIGNIFICANT.test(raw) && !ORDERED_ITEM.test(raw) && !SETEXT_EQUALS.test(raw) && !AUTOLINKABLE.test(raw) && !ENTITY.test(raw) && !(ctx.math && raw.includes("$"));
167
399
  var MAX_DEPTH = 4;
168
400
  var escapeHtml = (s) => s.replace(/\0/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
169
- var LINK = /\[([^\]]+)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\)/g;
170
- var emphasize = (s) => s.replace(/~~([^~\n]+)~~/g, "<del>$1</del>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/(^|[^*])\*([^*\n]+)\*/g, "$1<em>$2</em>");
171
- function inline(raw) {
401
+ var LINK = /\[((?:[^\[\]]|\[[^\[\]]*\])+)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\)/g;
402
+ var IMAGE = /!\[([^\]]*)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+)\)/g;
403
+ var URL_BODY = String.raw`(?:(?!&(?:quot|lt|gt);)[^\s\0()]|\([^\s\0()]*\))+`;
404
+ var ANGLE_URL = /* @__PURE__ */ new RegExp(String.raw`&lt;(https?:\/\/${URL_BODY})&gt;`, "g");
405
+ var BARE_URL = /* @__PURE__ */ new RegExp(String.raw`(?<![\w/=@])https?:\/\/${URL_BODY}`, "g");
406
+ var URL_TAIL_CHARS = ".,;:!?*_~";
407
+ var ESCAPED_ENTITY = /&amp;([a-z][a-z\d]{1,31}|#\d{1,7}|#x[\da-f]{1,6});/gi;
408
+ var MATH_DISPLAY = /\$\$([^\0]+?)\$\$/g;
409
+ var MATH_INLINE = /(?<![\\$\w])\$(?=[^\s$])((?:[^$\n\\]|\\.)+?)(?<=[^\s\\])\$(?![\d\w$])/g;
410
+ var INLINE_TAG = /<(\/?)(strong|em|del)>/g;
411
+ function nest(html) {
412
+ const open = [];
413
+ const out = html.replace(INLINE_TAG, (_all, close, tag) => {
414
+ if (!close) {
415
+ open.push(tag);
416
+ return `<${tag}>`;
417
+ }
418
+ const at = open.lastIndexOf(tag);
419
+ if (at < 0) return "";
420
+ const inner = open.splice(at);
421
+ inner.shift();
422
+ open.push(...inner);
423
+ return inner.reverse().map((t) => `</${t}>`).join("") + `</${tag}>` + [...inner].reverse().map((t) => `<${t}>`).join("");
424
+ });
425
+ return out + open.reverse().map((t) => `</${t}>`).join("");
426
+ }
427
+ var emphasize = (s) => nest(s.replace(/~~([^~\n]+)~~/g, "<del>$1</del>").replace(/\*\*\*(?=[^\s*])([^*\n]+?)\*\*\*/g, "<strong><em>$1</em></strong>").replace(/\*\*(?=\S)((?:[^*]|\*(?!\*))+?)\*\*/g, "<strong>$1</strong>").replace(/(^|[^\w])__(?=\S)((?:[^_]|_(?!_))+?)__(?!\w)/g, "$1<strong>$2</strong>").replace(/(^|[^*])\*(?=[^\s*])([^*\n]*[^\s*])\*(?!\*)/g, "$1<em>$2</em>").replace(/(^|[^\w])_(?=[^\s_])([^_\n]*[^\s_])_(?![\w])/g, "$1<em>$2</em>"));
428
+ var unescapeHtml = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
429
+ function inline(raw, ctx) {
172
430
  const spans = [];
173
431
  const spanSource = [];
174
432
  let s = escapeHtml(raw);
@@ -177,61 +435,113 @@ function inline(raw) {
177
435
  spanSource.push(all);
178
436
  return `\0${spans.length - 1}\0`;
179
437
  });
438
+ const maths = [];
439
+ const mathSource = [];
440
+ if (ctx.math) {
441
+ const typeset = (tex, display, whole) => {
442
+ const out = ctx.math(unescapeHtml(tex).trim(), display);
443
+ if (out === void 0) return whole;
444
+ maths.push(out);
445
+ mathSource.push(whole);
446
+ return `\0M${maths.length - 1}\0`;
447
+ };
448
+ s = s.replace(MATH_DISPLAY, (all, tex) => typeset(tex, true, all));
449
+ s = s.replace(MATH_INLINE, (all, tex) => typeset(tex, false, all));
450
+ }
180
451
  const links = [];
181
- s = s.replace(LINK, (_all, text, url) => {
182
- const literal = url.replace(/\0(\d+)\0/g, (_m, i) => spanSource[Number(i)]);
183
- links.push({ text, url: literal, ref: literal.startsWith("ref:") });
452
+ const lift = (link) => {
453
+ links.push(link);
184
454
  return `\0L${links.length - 1}\0`;
455
+ };
456
+ const literalUrl = (url) => url.replace(/\0M(\d+)\0/g, (_m, i) => mathSource[Number(i)]).replace(/\0(\d+)\0/g, (_m, i) => spanSource[Number(i)]);
457
+ s = s.replace(
458
+ IMAGE,
459
+ (_all, alt, url) => lift({ text: literalUrl(alt), url: literalUrl(url), ref: false, plain: true, image: true })
460
+ );
461
+ s = s.replace(LINK, (_all, text, url) => {
462
+ const literal = literalUrl(url);
463
+ return lift({ text, url: literal, ref: literal.startsWith("ref:"), plain: false });
185
464
  });
186
- s = emphasize(s).replace(
187
- /\0L(\d+)\0/g,
188
- (_all, i) => {
189
- const link = links[Number(i)];
190
- if (link.ref) return `<span class="sc-ref" data-ref="${link.url}">${emphasize(link.text)}</span>`;
191
- return `<a href="${link.url}" target="_blank" rel="noopener noreferrer">${emphasize(link.text)}</a>`;
465
+ s = s.replace(ANGLE_URL, (_all, url) => lift({ text: url, url, ref: false, plain: true }));
466
+ s = s.replace(BARE_URL, (all) => {
467
+ let end = all.length;
468
+ while (end > 0 && URL_TAIL_CHARS.includes(all[end - 1])) end -= 1;
469
+ const url = all.slice(0, end);
470
+ return lift({ text: url, url, ref: false, plain: true }) + all.slice(url.length);
471
+ });
472
+ s = emphasize(s.replace(ESCAPED_ENTITY, "&$1;"));
473
+ const draw = (index, inside) => {
474
+ const link = links[index];
475
+ const nest2 = (text) => text.replace(/\0L(\d+)\0/g, (_all, j) => draw(Number(j), true));
476
+ if (link.image) {
477
+ const alt = link.text;
478
+ if (ctx.embed) {
479
+ return `<img class="sc-md-img" src="${link.url}" alt="${alt}" loading="lazy" decoding="async" referrerpolicy="no-referrer">`;
480
+ }
481
+ if (inside) return alt || link.url;
482
+ return `<a class="sc-md-image" href="${link.url}" target="_blank" rel="noopener noreferrer">${alt || link.url}</a>`;
192
483
  }
193
- );
194
- return s.replace(/\0(\d+)\0/g, (_all, i) => `<code>${spans[Number(i)]}</code>`);
484
+ if (link.ref) return `<span class="sc-ref" data-ref="${link.url}">${nest2(emphasize(link.text))}</span>`;
485
+ return `<a href="${link.url}" target="_blank" rel="noopener noreferrer">${nest2(link.plain ? link.text : emphasize(link.text))}</a>`;
486
+ };
487
+ s = s.replace(/\0L(\d+)\0/g, (_all, i) => draw(Number(i), false));
488
+ return s.replace(/\0M(\d+)\0/g, (_all, i) => maths[Number(i)]).replace(/\0(\d+)\0/g, (_all, i) => `<code>${spans[Number(i)]}</code>`);
195
489
  }
196
490
  var CLOSING_FENCE = /^ {0,3}(?:`{3,}|~{3,})\s*$/;
197
- function renderFence(raw) {
198
- const lines = raw.split("\n").slice(1);
491
+ var FENCE_LANG = /^ {0,3}(?:`{3,}|~{3,})[ \t]*([A-Za-z0-9][A-Za-z0-9_+#.-]{0,31})(?:[ \t{].*)?$/;
492
+ var WRAP_ICON = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M2 4h12M2 8h8.5a2.5 2.5 0 0 1 0 5H8m0 0 1.6-1.6M8 13l1.6 1.6M2 12h2.5" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
493
+ function codeBox(source, lang, ctx) {
494
+ const code = source.replace(/\0/g, "");
495
+ const colored = lang && ctx.highlight ? ctx.highlight(code, lang) : void 0;
496
+ const body = colored ?? escapeHtml(code);
497
+ const attr = lang ? ` data-lang="${lang}"` : "";
498
+ const pre = `<pre${attr} tabindex="0"><code${lang ? ` class="language-${lang}"` : ""}>${body}</code></pre>`;
499
+ if (!ctx.actions) return pre;
500
+ return `<div class="sc-mdcode"${attr}><div class="sc-mdcode__bar"><span class="sc-mdcode__lang">${lang}</span><span class="sc-mdcode__tools"><button type="button" class="sc-mdcode__btn" data-sc-act="wrap">${WRAP_ICON}</button><button type="button" class="sc-mdcode__btn" data-sc-act="copy"></button></span></div>${pre}<button type="button" class="sc-mdcode__more" data-sc-act="more"></button></div>`;
501
+ }
502
+ function renderFence(raw, ctx) {
503
+ const lines = raw.split("\n");
504
+ const lang = (FENCE_LANG.exec(lines[0])?.[1] ?? "").toLowerCase();
505
+ lines.shift();
199
506
  if (lines.length && CLOSING_FENCE.test(lines[lines.length - 1])) lines.pop();
200
- return `<pre><code>${escapeHtml(lines.join("\n"))}</code></pre>`;
507
+ return codeBox(lines.join("\n"), lang, ctx);
201
508
  }
202
- function renderIndentedCode(raw) {
509
+ function renderIndentedCode(raw, ctx) {
203
510
  const body = raw.split("\n").map((l) => l.replace(/^(?: {4}|\t)/, "")).join("\n");
204
- return `<pre><code>${escapeHtml(body)}</code></pre>`;
511
+ return codeBox(body, "", ctx);
205
512
  }
206
513
  var DELIMITER_CELL = /^:?-+:?$/;
207
514
  function cellsOf(line) {
208
515
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
209
516
  return trimmed.split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|"));
210
517
  }
211
- var alignOf = (cell) => {
212
- const left = cell.startsWith(":");
213
- const right = cell.endsWith(":");
518
+ var alignOf = (cell2) => {
519
+ const left = cell2.startsWith(":");
520
+ const right = cell2.endsWith(":");
214
521
  return left && right ? "center" : right ? "right" : left ? "left" : null;
215
522
  };
216
- function renderTable(lines) {
523
+ function renderTable(lines, ctx) {
217
524
  if (lines.length < 2 || !lines[0].includes("|")) return null;
218
525
  const delimiter = cellsOf(lines[1]);
219
526
  if (!delimiter.length || !delimiter.every((c) => DELIMITER_CELL.test(c))) return null;
220
527
  const head = cellsOf(lines[0]);
221
528
  if (head.length !== delimiter.length) return null;
222
529
  const align = delimiter.map(alignOf);
223
- const cell = (tag, text, i) => {
530
+ const cell2 = (tag, text, i) => {
224
531
  const a = align[i];
225
- return `<${tag}${a ? ` class="sc-md-${a}"` : ""}>${inline(text)}</${tag}>`;
532
+ return `<${tag}${a ? ` class="sc-md-${a}"` : ""}>${inline(text, ctx)}</${tag}>`;
226
533
  };
227
534
  const body = lines.slice(2).filter((l) => l.trim() !== "").map((l) => {
228
535
  const row = cellsOf(l);
229
- const cells = Array.from({ length: head.length }, (_, i) => cell("td", row[i] ?? "", i));
536
+ const cells = Array.from({ length: head.length }, (_, i) => cell2("td", row[i] ?? "", i));
230
537
  return `<tr>${cells.join("")}</tr>`;
231
538
  }).join("");
232
- return `<table class="sc-md-table"><thead><tr>${head.map((h, i) => cell("th", h, i)).join("")}</tr></thead><tbody>${body}</tbody></table>`;
539
+ const table = `<div class="sc-md-scroll" tabindex="0"><table class="sc-md-table"><thead><tr>${head.map((h, i) => cell2("th", h, i)).join("")}</tr></thead><tbody>${body}</tbody></table></div>`;
540
+ if (!ctx.actions) return table;
541
+ return `<div class="sc-md-tablebox"><div class="sc-md-tablebar"><button type="button" class="sc-md-tablebtn" data-sc-act="copy-tsv"></button><button type="button" class="sc-md-tablebtn" data-sc-act="copy-md"></button></div>${table}</div>`;
233
542
  }
234
543
  var LIST_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])[ \t]+(.*)$/;
544
+ var TASK_MARK = /^\[([ xX])\][ \t]+/;
235
545
  function parseList(lines) {
236
546
  const first = LIST_ITEM.exec(lines[0] ?? "");
237
547
  if (!first) return null;
@@ -251,40 +561,79 @@ function parseList(lines) {
251
561
  }
252
562
  return { ordered, start: ordered ? Number.parseInt(marker, 10) : 1, items: items.map((l) => l.join("\n")) };
253
563
  }
254
- function renderItem(item, depth) {
255
- const lines = item.replace(/\s+$/, "").split("\n");
564
+ function renderItem(item, depth, ctx) {
565
+ const mark = TASK_MARK.exec(item);
566
+ const body = mark ? item.slice(mark[0].length) : item;
567
+ const lines = body.trimEnd().split("\n");
256
568
  const nestedAt = lines.findIndex((l, i) => i > 0 && LIST_ITEM.test(l));
257
569
  const head = (nestedAt === -1 ? lines : lines.slice(0, nestedAt)).filter((l) => l.trim() !== "");
258
570
  const rest = nestedAt === -1 ? [] : lines.slice(nestedAt);
259
- const loose = /\n[ \t]*\n/.test(item.trim());
260
- const headHtml = head.length ? loose ? renderSource(head.join("\n"), depth + 1) : inline(head.join(" ").trim()) : "";
261
- return headHtml + (rest.length ? renderSource(rest.join("\n"), depth + 1) : "");
571
+ const loose = /\n[ \t]*\n/.test(body.trim());
572
+ const headHtml = head.length ? loose ? renderSource(head.join("\n"), depth + 1, ctx) : inline(head.join(" ").trim(), ctx) : "";
573
+ const nested = rest.length ? renderSource(rest.join("\n"), depth + 1, ctx) : "";
574
+ if (!mark) return { html: headHtml + nested, task: false };
575
+ const checked = mark[1] !== " " ? " checked" : "";
576
+ const box = `<input type="checkbox" disabled${checked}`;
577
+ return {
578
+ html: (loose ? `${box} aria-label="[${mark[1]}]">${headHtml}` : `<label>${box}> ${headHtml}</label>`) + nested,
579
+ task: true
580
+ };
262
581
  }
263
- function renderList(lines, depth) {
582
+ function renderList(lines, depth, ctx) {
264
583
  const parsed = parseList(lines);
265
584
  if (!parsed) return null;
266
- const items = parsed.items.map((item) => `<li>${renderItem(item, depth)}</li>`).join("");
585
+ const items = parsed.items.map((item) => {
586
+ const { html, task } = renderItem(item, depth, ctx);
587
+ return `<li${task ? ' class="sc-md-task"' : ""}>${html}</li>`;
588
+ }).join("");
267
589
  if (!parsed.ordered) return `<ul>${items}</ul>`;
268
590
  return `<ol${parsed.start !== 1 ? ` start="${parsed.start}"` : ""}>${items}</ol>`;
269
591
  }
270
592
  var QUOTE_MARK = /^ {0,3}> ?/;
271
593
  var THEMATIC_BREAK = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
272
594
  var SETEXT = /^ {0,3}(=+|-+)\s*$/;
273
- var ATX = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
274
- function renderProse(lines) {
595
+ var ATX_HEAD = /^ {0,3}(#{1,6})\s+/;
596
+ var ATX_SLOW = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
597
+ var ATX_SLOW_MAX = 2e3;
598
+ var ODD_TERMINATOR = /[\r\u2028\u2029]/;
599
+ function atxHeading(line) {
600
+ if (ODD_TERMINATOR.test(line)) {
601
+ if (line.length > ATX_SLOW_MAX) return null;
602
+ const m = ATX_SLOW.exec(line);
603
+ return m ? { hashes: m[1].length, text: m[2] } : null;
604
+ }
605
+ const head = ATX_HEAD.exec(line);
606
+ if (!head) return null;
607
+ let end = line.length;
608
+ const floor = head[0].length;
609
+ const skip = (test) => {
610
+ while (end > floor && test(line[end - 1])) end -= 1;
611
+ };
612
+ const space = (c) => /\s/.test(c);
613
+ skip(space);
614
+ skip((c) => c === "#");
615
+ skip(space);
616
+ return { hashes: head[1].length, text: line.slice(floor, end) };
617
+ }
618
+ var DISPLAY_MATH = /^\s*\$\$([\s\S]+?)\$\$\s*$/;
619
+ function renderProse(lines, ctx) {
275
620
  const out = [];
276
621
  let para = [];
277
622
  const flush = () => {
278
623
  if (!para.length) return;
279
- out.push(`<p>${para.map(inline).join("<br/>")}</p>`);
624
+ const display = ctx.math ? DISPLAY_MATH.exec(para.join("\n")) : null;
625
+ const typeset = display ? ctx.math(display[1].trim(), true) : void 0;
626
+ out.push(
627
+ typeset !== void 0 ? `<div class="sc-math-block">${typeset}</div>` : `<p>${para.map((l) => inline(l, ctx)).join("<br/>")}</p>`
628
+ );
280
629
  para = [];
281
630
  };
282
631
  for (const line of lines) {
283
- const h = ATX.exec(line);
632
+ const h = atxHeading(line);
284
633
  if (h) {
285
634
  flush();
286
- const level = Math.min(h[1].length + 1, 6);
287
- out.push(`<h${level}>${inline(h[2])}</h${level}>`);
635
+ const level = Math.min(h.hashes + 1, 6);
636
+ out.push(`<h${level}>${inline(h.text, ctx)}</h${level}>`);
288
637
  continue;
289
638
  }
290
639
  para.push(line);
@@ -292,19 +641,19 @@ function renderProse(lines) {
292
641
  flush();
293
642
  return out.join("");
294
643
  }
295
- function renderTextBlock(raw, depth) {
296
- if (isPlainProse(raw)) {
644
+ function renderTextBlock(raw, depth, ctx) {
645
+ if (isPlainProse(raw, ctx)) {
297
646
  return `<p>${escapeHtml(raw).replace(/\n/g, "<br/>")}</p>`;
298
647
  }
299
648
  const lines = raw.split("\n");
300
- const table = renderTable(lines);
649
+ const table = renderTable(lines, ctx);
301
650
  if (table) return table;
302
651
  if (depth < MAX_DEPTH && QUOTE_MARK.test(lines[0])) {
303
652
  const inner = lines.map((l) => l.replace(QUOTE_MARK, "")).join("\n");
304
- return `<blockquote>${renderSource(inner, depth + 1)}</blockquote>`;
653
+ return `<blockquote>${renderSource(inner, depth + 1, ctx)}</blockquote>`;
305
654
  }
306
655
  if (depth < MAX_DEPTH) {
307
- const list = renderList(lines, depth);
656
+ const list = renderList(lines, depth, ctx);
308
657
  if (list) return list;
309
658
  }
310
659
  if (lines.length === 1 && THEMATIC_BREAK.test(lines[0])) return "<hr/>";
@@ -312,60 +661,90 @@ function renderTextBlock(raw, depth) {
312
661
  if (lines.length >= 2 && SETEXT.test(last)) {
313
662
  const level = last.trim().startsWith("=") ? 2 : 3;
314
663
  const text = lines.slice(0, -1).join(" ").trim();
315
- return `<h${level}>${inline(text)}</h${level}>`;
664
+ return `<h${level}>${inline(text, ctx)}</h${level}>`;
316
665
  }
317
- return renderProse(lines);
666
+ return renderProse(lines, ctx);
318
667
  }
319
- function renderBlock(src, block, depth) {
668
+ function renderBlock(src, block, depth, ctx) {
320
669
  const raw = src.slice(block.start, block.end);
321
- if (block.kind === "fence") return renderFence(raw);
322
- if (block.kind === "code") return renderIndentedCode(raw);
323
- return renderTextBlock(raw, depth);
670
+ if (block.kind === "fence") return renderFence(raw, ctx);
671
+ if (block.kind === "code") return renderIndentedCode(raw, ctx);
672
+ return renderTextBlock(raw, depth, ctx);
324
673
  }
325
- function renderSource(src, depth) {
326
- return splitBlocks(src).map((b) => renderBlock(src, b, depth)).join("");
674
+ function renderSource(src, depth, ctx) {
675
+ return splitBlocks(src).map((b) => renderBlock(src, b, depth, ctx)).join("");
327
676
  }
328
- function renderMarkdown(src) {
329
- return renderSource(src, 0);
677
+ function renderMarkdown(src, options) {
678
+ return renderSource(src, 0, contextOf(options));
330
679
  }
331
- var newMarkdownStream = () => ({ settled: "", html: "", resume: 0 });
332
- function renderMarkdownStream(src, stream) {
333
- if (!src.startsWith(stream.settled)) Object.assign(stream, newMarkdownStream());
680
+ var newMarkdownStream = () => ({ settled: "", parts: [], resume: 0, options: void 0 });
681
+ function renderMarkdownBlocks(src, stream, options) {
682
+ if (!src.startsWith(stream.settled) || stream.options !== options) {
683
+ Object.assign(stream, newMarkdownStream());
684
+ stream.options = options;
685
+ }
686
+ const ctx = contextOf(options);
334
687
  const from = stream.resume;
335
688
  const tail = src.slice(from);
336
689
  const blocks = splitBlocks(tail);
337
690
  const lastLine = src.lastIndexOf("\n") + 1 - from;
338
- let html = stream.html;
691
+ const shown = stream.parts.slice();
339
692
  for (let i = 0; i < blocks.length; i += 1) {
340
- const rendered = renderBlock(tail, blocks[i], 0);
341
- html += rendered;
693
+ const rendered = renderBlock(tail, blocks[i], 0, ctx);
694
+ shown.push(rendered);
342
695
  if (i + 1 < blocks.length && blocks[i + 1].start < lastLine) {
343
- stream.html += rendered;
696
+ stream.parts.push(rendered);
344
697
  stream.resume = from + blocks[i].end + 1;
345
698
  }
346
699
  }
347
700
  stream.settled = src.slice(0, lastLine + from);
348
- return html;
701
+ return shown;
349
702
  }
350
- function renderMarkdownWithAnchors(src) {
703
+ function renderMarkdownStream(src, stream, options) {
704
+ return renderMarkdownBlocks(src, stream, options).join("");
705
+ }
706
+ function renderMarkdownWithAnchors(src, options) {
707
+ const ctx = contextOf(options);
351
708
  const blocks = splitBlocks(src);
352
709
  const html = blocks.map((block, i) => {
353
- const rendered = renderBlock(src, block, 0);
710
+ const rendered = renderBlock(src, block, 0, ctx);
354
711
  return rendered.replace(/^(\s*<[a-z][a-z0-9]*)/i, `$1 data-sc-block="${i}"`);
355
712
  }).join("");
356
713
  return { html, blocks };
357
714
  }
715
+
716
+ // src/table.ts
717
+ var flatten = (cell2) => cell2.replace(/[\t\r\n]+/g, " ");
718
+ function tableToTsv(header, rows) {
719
+ const line = (cells) => cells.map(flatten).join(" ");
720
+ return [line(header), ...rows.map(line)].join("\n");
721
+ }
722
+ function tableToMarkdown(header, rows, align = []) {
723
+ const cell2 = (c) => flatten(c).replace(/\|/g, "\\|").trim();
724
+ const rule = header.map((_, i) => {
725
+ const a = align[i];
726
+ return a === "center" ? ":---:" : a === "right" ? "---:" : a === "left" ? ":---" : "---";
727
+ });
728
+ const line = (cells) => `| ${header.map((_, i) => cell2(cells[i] ?? "")).join(" | ")} |`;
729
+ return [line(header), `| ${rule.join(" | ")} |`, ...rows.map(line)].join("\n");
730
+ }
358
731
  export {
732
+ HIGHLIGHT_LANGUAGES,
359
733
  STABLE_FORMAT,
734
+ atxHeading,
360
735
  deltaTone,
361
736
  downloadThread,
362
737
  formatDelta,
363
738
  formatValue,
739
+ highlightCode,
364
740
  newMarkdownStream,
365
741
  renderMarkdown,
742
+ renderMarkdownBlocks,
366
743
  renderMarkdownStream,
367
744
  renderMarkdownWithAnchors,
368
745
  safeHref,
746
+ tableToMarkdown,
747
+ tableToTsv,
369
748
  threadToMarkdown,
370
749
  toneClass
371
750
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/format.ts","../src/export.ts","../src/markdown.ts"],"sourcesContent":["// Value formatting shared by every card renderer.\n//\n// Centralised because a table cell and a stat tile showing the same number in\n// different formats is the fastest way to make an interface look untrustworthy.\n\nimport type { CardValueFormat } from \"@supersolutions/super-chat-core\";\n\nexport type FormatOptions = {\n /** BCP 47 locale. Omitted means the viewer's own. */\n locale?: string;\n /** IANA time zone for `datetime` values. Omitted means the viewer's own. */\n timeZone?: string;\n};\n\n/**\n * Fixed settings for HTML rendered ahead of the browser. A build server and a\n * viewer rarely share a locale or time zone, so server output and the first\n * client render must both use these or hydration fails.\n */\nexport const STABLE_FORMAT: FormatOptions = { locale: \"en-US\", timeZone: \"UTC\" };\n\nfunction createNumberFormats(locale?: string) {\n return {\n compact: new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 2 }),\n plain: new Intl.NumberFormat(locale, { maximumFractionDigits: 6 }),\n pctWide: new Intl.NumberFormat(locale, { maximumFractionDigits: 1, useGrouping: false }),\n pctNarrow: new Intl.NumberFormat(locale, { maximumFractionDigits: 2, useGrouping: false }),\n };\n}\n\nconst numberFormats = new Map<string, ReturnType<typeof createNumberFormats>>();\n\nfunction numbersFor(locale?: string) {\n const key = locale ?? \"\";\n let formats = numberFormats.get(key);\n if (!formats) {\n formats = createNumberFormats(locale);\n numberFormats.set(key, formats);\n }\n return formats;\n}\n\nexport function formatValue(value: unknown, format: CardValueFormat = \"text\", options: FormatOptions = {}): string {\n if (value == null) return \"—\";\n const { locale, timeZone } = options;\n const numbers = numbersFor(locale);\n\n switch (format) {\n case \"number\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n // Compact only above 5 digits: \"12.3K\" is helpful, \"1.2K\" hides precision\n // people expect to see on small counts.\n return Math.abs(n) >= 100_000 ? numbers.compact.format(n) : numbers.plain.format(n);\n }\n case \"currency\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n const abs = Math.abs(n);\n // Sub-cent values are common in crypto; fixed 2dp would render them as $0.00.\n const digits = abs >= 1 ? 2 : abs >= 0.01 ? 4 : 8;\n // A whole amount in the thousands reads as \"$48,200\". Forcing \".00\" onto\n // it is the machine-printed look; amounts with cents keep them.\n const min = abs >= 1000 && Number.isInteger(n) ? 0 : 2;\n return `$${n.toLocaleString(locale, { minimumFractionDigits: min, maximumFractionDigits: Math.max(min, digits) })}`;\n }\n case \"percent\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n // One decimal at most (\"8.2%\", \"12%\"), two only below 1% where the\n // second digit is the signal (\"0.04%\"). A fixed \"8.20%\" is false precision.\n return `${(Math.abs(n) < 1 ? numbers.pctNarrow : numbers.pctWide).format(n)}%`;\n }\n case \"bytes\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"];\n let i = 0;\n let v = n;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i += 1;\n }\n return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;\n }\n case \"duration\": {\n const ms = Number(value);\n if (!Number.isFinite(ms)) return String(value);\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n return `${(ms / 3_600_000).toFixed(1)}h`;\n }\n case \"datetime\": {\n const d = typeof value === \"number\" ? new Date(value) : new Date(String(value));\n if (Number.isNaN(d.getTime())) return String(value);\n return d.toLocaleString(locale, timeZone ? { timeZone, timeZoneName: \"short\" } : undefined);\n }\n case \"code\":\n case \"text\":\n default:\n return typeof value === \"object\" ? JSON.stringify(value) : String(value);\n }\n}\n\nexport function formatDelta(delta: number, format: CardValueFormat = \"number\", options: FormatOptions = {}): string {\n // A true minus sign: the hyphen-minus is narrower and misaligns a column of\n // signed deltas against the plus signs above it.\n const sign = delta > 0 ? \"+\" : delta < 0 ? \"−\" : \"\";\n return `${sign}${formatValue(Math.abs(delta), format, options)}`;\n}\n\nexport const toneClass = (tone?: string): string => (tone && tone !== \"neutral\" ? ` sc-tone--${tone}` : \"\");\n\n/** Positive is not always good — but for a delta with no stated tone it is the useful default. */\nexport const deltaTone = (delta: number): \"positive\" | \"negative\" | \"neutral\" =>\n delta > 0 ? \"positive\" : delta < 0 ? \"negative\" : \"neutral\";\n\n/**\n * A URL that came from a model or a tool, made safe to put in an `href`: only http(s) links\n * pass, anything else (`javascript:`, `data:`, `vbscript:`, a relative path that could be read\n * as a scheme after whitespace tricks) comes back as `undefined` and the caller renders plain\n * text. React 19 refuses `javascript:` hrefs itself, but this package supports React 18, which\n * only warns and then navigates.\n */\nexport function safeHref(url: string | undefined | null): string | undefined {\n if (typeof url !== \"string\") return undefined;\n const trimmed = url.trim();\n // Browsers strip tab and newline characters inside a URL before parsing it, so\n // `java\\tscript:` is a javascript: URL; reject anything with control characters outright.\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(trimmed)) return undefined;\n return /^https?:\\/\\/[^\\s]+$/i.test(trimmed) ? trimmed : undefined;\n}\n","// Thread export.\n//\n// Markdown rather than JSON: the point of exporting a conversation is to read it\n// somewhere else or paste it into a ticket, and JSON serves neither. Cards are\n// rendered as their data, not as their markup — a table exported as HTML is\n// useless in a text file, but as a markdown table it survives.\n//\n// Sharing (a hosted link) is deliberately NOT here: it needs a backend the kit\n// does not have, and faking it with a data: URL would produce links that break\n// the moment they leave the browser.\n\nimport type { Card, ContentPart, Message } from \"@supersolutions/super-chat-core\";\n\nfunction cardToMarkdown(spec: Record<string, unknown>): string {\n const kind = String(spec.kind ?? \"unknown\");\n const title = spec.title ? `**${spec.title}**\\n\\n` : \"\";\n\n if (kind === \"table\" && Array.isArray(spec.columns) && Array.isArray(spec.rows)) {\n const cols = spec.columns as { key: string; label: string }[];\n const rows = spec.rows as Record<string, unknown>[];\n const head = `| ${cols.map((c) => c.label).join(\" | \")} |`;\n const rule = `| ${cols.map(() => \"---\").join(\" | \")} |`;\n const body = rows.map((r) => `| ${cols.map((c) => String(r[c.key] ?? \"\")).join(\" | \")} |`).join(\"\\n\");\n return `${title}${head}\\n${rule}\\n${body}`;\n }\n\n if (kind === \"markdown\" && typeof spec.body === \"string\") return `${title}${spec.body}`;\n if (kind === \"code\" && typeof spec.code === \"string\") {\n return `${title}\\`\\`\\`${spec.language ?? \"\"}\\n${spec.code}\\n\\`\\`\\``;\n }\n if (kind === \"callout\" && typeof spec.body === \"string\") return `> ${title}${spec.body}`;\n\n // Everything else keeps its data rather than being dropped — an export that\n // silently omits a card is worse than one that is a little verbose.\n return `${title}\\`\\`\\`json\\n${JSON.stringify(spec, null, 2)}\\n\\`\\`\\``;\n}\n\nfunction partToMarkdown(part: ContentPart): string | null {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"reasoning\":\n return `<details><summary>Reasoning</summary>\\n\\n${part.text}\\n\\n</details>`;\n case \"tool-call\":\n return `- \\`${part.name}(${JSON.stringify(part.input ?? {})})\\``;\n case \"tool-result\":\n return part.failure ? `- \\`${part.name}\\` failed: ${part.failure}` : null;\n case \"image\":\n return \"_(image)_\";\n case \"file\":\n return `_(file: ${part.filename ?? \"attachment\"})_`;\n case \"artifact\":\n return part.kind.startsWith(\"card:\")\n ? cardToMarkdown(((part.data as { spec?: Card[\"spec\"] }).spec ?? part.data) as Record<string, unknown>)\n : null;\n default:\n return null;\n }\n}\n\n/** Render a thread as markdown. `title` becomes the H1 when given. */\nexport function threadToMarkdown(messages: readonly Message[], title?: string): string {\n const out: string[] = title ? [`# ${title}`, \"\"] : [];\n\n for (const m of messages) {\n if (m.role === \"system\") continue;\n const body = m.parts.map(partToMarkdown).filter(Boolean).join(\"\\n\\n\");\n if (!body) continue;\n const who = m.role === \"user\" ? \"You\" : m.role === \"tool\" ? \"Tools\" : \"Assistant\";\n const when = m.createdAt ? ` · ${new Date(m.createdAt).toISOString().slice(0, 16).replace(\"T\", \" \")}` : \"\";\n out.push(`## ${who}${when}`, \"\", body, \"\");\n }\n\n return out.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\n/** Trigger a download of the thread as a `.md` file. */\nexport function downloadThread(messages: readonly Message[], filename = \"conversation.md\", title?: string): void {\n const blob = new Blob([threadToMarkdown(messages, title)], { type: \"text/markdown;charset=utf-8\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n // Revoking immediately can race the download in some browsers; one frame is\n // enough for the click to have been consumed.\n requestAnimationFrame(() => URL.revokeObjectURL(url));\n}\n","// Minimal markdown renderer for assistant text, markdown cards and document\n// artifacts.\n//\n// Deliberately not a full parser — a chat message or card body is short, and\n// pulling in a markdown library plus a sanitizer for this is disproportionate.\n//\n// It does now split into blocks before rendering, and that is not a stylistic\n// change. A document previewer has to answer \"the user selected this on screen;\n// where is it in the source?\", because that span is both what gets quoted into\n// the next request and what an edit has to anchor against. The previous shape —\n// escape the whole string, pull fences out into placeholders, then run a chain\n// of global regexes — destroyed source positions in its first statement.\n//\n// So the order is inverted: split on the RAW source and record offsets, then\n// escape and transform each block independently. Escaping per block rather than\n// up front is load-bearing, not tidiness: `&` → `&amp;` changes the string\n// length, so escaping first would shift every offset recorded afterwards. That\n// failure is invisible on screen — the page renders perfectly and the anchors\n// silently point at the wrong text — which is why markdown.test.ts asserts the\n// offsets round-trip rather than trusting the output to look right.\n//\n// ── Why it grew ──────────────────────────────────────────────────────────────\n//\n// The block set used to be headings, emphasis, code, links and bullet lists,\n// and for a chat bubble that is the right amount of renderer. A document\n// artifact changed the requirement under it: a document is a thing the user\n// KEEPS, reads in a previewer and downloads as `.md`, and a report whose table\n// renders as a column of literal pipes is not a document — it is the source of\n// one. Tables, quotes, ordered lists and indented code are not exotic; they are\n// what anyone writing a report reaches for in the first paragraph.\n//\n// The structure changed with the scope. A chain of global regexes over one\n// escaped string cannot tell a table from a paragraph, so each block is now\n// CLASSIFIED first and rendered by shape, and only the leaves run inline\n// transforms. Nesting (a list inside a quote, a quote inside a list) falls out\n// of rendering a block's interior through the same splitter, with a depth cap\n// so a pathological `> > > > …` cannot recurse without end.\n\nimport { splitBlocks, type MarkdownBlock } from \"@supersolutions/super-chat-core\";\n\nexport type AnchoredMarkdown = {\n html: string;\n /** Index-aligned with the `data-sc-block` attribute on the rendered HTML. */\n blocks: MarkdownBlock[];\n};\n\n// Cheap pre-check carried over from main: with none of these characters\n// present, no heading, emphasis, code, link, list, quote or table rule below\n// could match, so the whole chain is skippable. Applied per BLOCK rather than\n// per document — one fenced snippet in an otherwise plain artifact should not\n// cost the other forty paragraphs their shortcut.\nconst MARKDOWN_SIGNIFICANT = /[`*_#[\\]>~|-]/;\n// Two constructs carry no character the test above would catch: an ordered\n// item, and a setext heading underlined with `=`. Adding `=` and the digits to\n// MARKDOWN_SIGNIFICANT would cost the shortcut on most prose, so they get their\n// own (equally cheap) look instead.\nconst ORDERED_ITEM = /^ {0,3}\\d{1,9}[.)]\\s/m;\nconst SETEXT_EQUALS = /\\n {0,3}=+[ \\t]*$/;\n\nconst isPlainProse = (raw: string) =>\n !MARKDOWN_SIGNIFICANT.test(raw) && !ORDERED_ITEM.test(raw) && !SETEXT_EQUALS.test(raw);\n\n/** How deep a quote or list may nest before its interior is rendered flat. */\nconst MAX_DEPTH = 4;\n\n// Quotes are escaped because link URLs are interpolated into href=\"…\" — an\n// unescaped quote in a URL would close the attribute and open a new one\n// (browsers recover from the missing-whitespace parse error by reading\n// `\"onmouseover=\"…` as a fresh attribute).\n//\n// NUL is dropped here, at the one place every leaf is escaped, rather than only in\n// `inline`: the inline placeholders below are built from it, so it must never come from\n// the source, and code blocks and the plain-prose shortcut would otherwise let a raw\n// U+0000 through into the output. (Block offsets are computed on the raw source, so\n// removing it from the output moves no anchor.)\nconst escapeHtml = (s: string) =>\n s.replace(/\\0/g, \"\").replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n// ── Inline ───────────────────────────────────────────────────────────────────\n\n/**\n * Escape, then transform. Every leaf goes through here and nothing else does.\n *\n * Code spans are lifted out FIRST and put back last, so `**not bold**` inside\n * backticks stays literal — the same protection fenced blocks get, which the\n * old chain gave only to fences. NUL is stripped from the input because the\n * placeholders are built from it; without that, text could forge one.\n */\n// Only http(s) links — a javascript: URL must never survive. The destination may\n// contain one level of balanced parentheses (`…/wiki/Foo_(bar)`), as CommonMark\n// allows; the two alternatives cannot match the same character, so there is no\n// backtracking blow-up on a hostile string.\n//\n// The other destination is a card reference, `ref:<card>?key=value&…` (super-protocol\n// docs/CARD-REFS.md). It is not a link: it becomes a span the host wires to a card, and it\n// stays plain text where no host does. The character set is the envelope's own, plus the `;`\n// that escaping gives `&`, so nothing in it can close an attribute or open a tag. The limits\n// are the parser's to enforce (a ref that breaks them degrades where it is used), not this\n// regex's; the bound here only keeps a hostile string from costing a long scan.\nconst LINK = /\\[([^\\]]+)\\]\\((https?:\\/\\/(?:[^()\\s]|\\([^()\\s]*\\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\\)/g;\n\n/** Strike-through, strong, emphasis. Runs on already-escaped text. */\nconst emphasize = (s: string) =>\n s\n .replace(/~~([^~\\n]+)~~/g, \"<del>$1</del>\")\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/(^|[^*])\\*([^*\\n]+)\\*/g, \"$1<em>$2</em>\");\n\nfunction inline(raw: string): string {\n const spans: string[] = [];\n const spanSource: string[] = []; // what each code span looked like, for where it must stay literal\n let s = escapeHtml(raw);\n\n s = s.replace(/(`+)([\\s\\S]+?)\\1(?!`)/g, (all, _ticks, body: string) => {\n spans.push(body);\n spanSource.push(all);\n return `\\0${spans.length - 1}\\0`;\n });\n\n // Links are lifted out the same way, BEFORE emphasis. Otherwise the emphasis rules\n // run over the destination too, and `…/a*b*c` becomes `href=\"…/a<em>b</em>c\"`: the\n // link silently points somewhere else. Only the link's text is emphasised.\n const links: { text: string; url: string; ref: boolean }[] = [];\n s = s.replace(LINK, (_all, text: string, url: string) => {\n // A backtick pair inside a URL is part of the URL, not a code span.\n const literal = url.replace(/\\0(\\d+)\\0/g, (_m, i: string) => spanSource[Number(i)]!);\n links.push({ text, url: literal, ref: literal.startsWith(\"ref:\") });\n return `\\0L${links.length - 1}\\0`;\n });\n\n s = emphasize(s).replace(\n /\\0L(\\d+)\\0/g,\n (_all, i: string) => {\n const link = links[Number(i)]!;\n if (link.ref) return `<span class=\"sc-ref\" data-ref=\"${link.url}\">${emphasize(link.text)}</span>`;\n return `<a href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${emphasize(link.text)}</a>`;\n },\n );\n\n return s.replace(/\\0(\\d+)\\0/g, (_all, i: string) => `<code>${spans[Number(i)]}</code>`);\n}\n\n// ── Verbatim blocks ──────────────────────────────────────────────────────────\n\nconst CLOSING_FENCE = /^ {0,3}(?:`{3,}|~{3,})\\s*$/;\n\nfunction renderFence(raw: string): string {\n // Drop the opening fence line (which may carry a language) and the closing\n // one if it is there — an unterminated fence has none. Content is escaped but\n // never sees an inline transform.\n const lines = raw.split(\"\\n\").slice(1);\n if (lines.length && CLOSING_FENCE.test(lines[lines.length - 1]!)) lines.pop();\n return `<pre><code>${escapeHtml(lines.join(\"\\n\"))}</code></pre>`;\n}\n\nfunction renderIndentedCode(raw: string): string {\n const body = raw.split(\"\\n\").map((l) => l.replace(/^(?: {4}|\\t)/, \"\")).join(\"\\n\");\n return `<pre><code>${escapeHtml(body)}</code></pre>`;\n}\n\n// ── Tables ───────────────────────────────────────────────────────────────────\n\ntype Align = \"left\" | \"center\" | \"right\" | null;\n\nconst DELIMITER_CELL = /^:?-+:?$/;\n\n/** Split a pipe row into cells, honouring `\\|` as a literal pipe. */\nfunction cellsOf(line: string): string[] {\n const trimmed = line.trim().replace(/^\\|/, \"\").replace(/\\|$/, \"\");\n return trimmed\n .split(/(?<!\\\\)\\|/)\n .map((c) => c.trim().replace(/\\\\\\|/g, \"|\"));\n}\n\nconst alignOf = (cell: string): Align => {\n const left = cell.startsWith(\":\");\n const right = cell.endsWith(\":\");\n return left && right ? \"center\" : right ? \"right\" : left ? \"left\" : null;\n};\n\nfunction renderTable(lines: string[]): string | null {\n if (lines.length < 2 || !lines[0]!.includes(\"|\")) return null;\n const delimiter = cellsOf(lines[1]!);\n if (!delimiter.length || !delimiter.every((c) => DELIMITER_CELL.test(c))) return null;\n\n const head = cellsOf(lines[0]!);\n if (head.length !== delimiter.length) return null;\n const align = delimiter.map(alignOf);\n\n // Alignment rides on a class rather than a style attribute: a host with a\n // strict CSP can ship this without allowing inline styles.\n const cell = (tag: \"th\" | \"td\", text: string, i: number) => {\n const a = align[i];\n return `<${tag}${a ? ` class=\"sc-md-${a}\"` : \"\"}>${inline(text)}</${tag}>`;\n };\n\n const body = lines\n .slice(2)\n .filter((l) => l.trim() !== \"\")\n .map((l) => {\n const row = cellsOf(l);\n // Short rows are padded and long ones cut, so a ragged table still lines\n // up under its header instead of leaking cells into a new column.\n const cells = Array.from({ length: head.length }, (_, i) => cell(\"td\", row[i] ?? \"\", i));\n return `<tr>${cells.join(\"\")}</tr>`;\n })\n .join(\"\");\n\n return `<table class=\"sc-md-table\"><thead><tr>${head\n .map((h, i) => cell(\"th\", h, i))\n .join(\"\")}</tr></thead><tbody>${body}</tbody></table>`;\n}\n\n// ── Lists ────────────────────────────────────────────────────────────────────\n\nconst LIST_ITEM = /^(\\s*)([-*+]|\\d{1,9}[.)])[ \\t]+(.*)$/;\n\ntype ParsedList = { ordered: boolean; start: number; items: string[] };\n\nfunction parseList(lines: string[]): ParsedList | null {\n const first = LIST_ITEM.exec(lines[0] ?? \"\");\n if (!first) return null;\n const base = first[1]!.length;\n const marker = first[2]!;\n const ordered = /^\\d/.test(marker);\n // Everything indented at least as far as the first item's text belongs to\n // that item — its wrapped lines, its paragraphs, and any list nested under it.\n const strip = new RegExp(`^ {0,${base + marker.length + 1}}`);\n\n const items: string[][] = [];\n for (const line of lines) {\n const m = LIST_ITEM.exec(line);\n if (m && m[1]!.length <= base) {\n items.push([m[3]!]);\n continue;\n }\n if (!items.length) return null;\n items[items.length - 1]!.push(line.replace(strip, \"\"));\n }\n\n return { ordered, start: ordered ? Number.parseInt(marker, 10) : 1, items: items.map((l) => l.join(\"\\n\")) };\n}\n\n/**\n * One item's interior.\n *\n * A single-paragraph item stays tight — `<li>text</li>`, not\n * `<li><p>text</p></li>` — because the paragraph margin inside a list item is\n * the classic \"why is my list double-spaced\" bug. Anything with a blank line or\n * a nested list goes back through the block pipeline, which is where nesting\n * comes from.\n */\nfunction renderItem(item: string, depth: number): string {\n const lines = item.replace(/\\s+$/, \"\").split(\"\\n\");\n const nestedAt = lines.findIndex((l, i) => i > 0 && LIST_ITEM.test(l));\n const head = (nestedAt === -1 ? lines : lines.slice(0, nestedAt)).filter((l) => l.trim() !== \"\");\n const rest = nestedAt === -1 ? [] : lines.slice(nestedAt);\n const loose = /\\n[ \\t]*\\n/.test(item.trim());\n\n const headHtml = head.length\n ? loose\n ? renderSource(head.join(\"\\n\"), depth + 1)\n : inline(head.join(\" \").trim())\n : \"\";\n return headHtml + (rest.length ? renderSource(rest.join(\"\\n\"), depth + 1) : \"\");\n}\n\nfunction renderList(lines: string[], depth: number): string | null {\n const parsed = parseList(lines);\n if (!parsed) return null;\n const items = parsed.items.map((item) => `<li>${renderItem(item, depth)}</li>`).join(\"\");\n if (!parsed.ordered) return `<ul>${items}</ul>`;\n return `<ol${parsed.start !== 1 ? ` start=\"${parsed.start}\"` : \"\"}>${items}</ol>`;\n}\n\n// ── Prose ────────────────────────────────────────────────────────────────────\n\nconst QUOTE_MARK = /^ {0,3}> ?/;\nconst THEMATIC_BREAK = /^ {0,3}(?:-{3,}|\\*{3,}|_{3,})\\s*$/;\nconst SETEXT = /^ {0,3}(=+|-+)\\s*$/;\n// Headings shift down one: the card or page owns the h1, so a document's own\n// `#` must not compete with it for the document outline a screen reader builds.\nconst ATX = /^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$/;\n\nfunction renderProse(lines: string[]): string {\n const out: string[] = [];\n let para: string[] = [];\n const flush = () => {\n if (!para.length) return;\n out.push(`<p>${para.map(inline).join(\"<br/>\")}</p>`);\n para = [];\n };\n\n for (const line of lines) {\n const h = ATX.exec(line);\n if (h) {\n flush();\n const level = Math.min(h[1]!.length + 1, 6);\n out.push(`<h${level}>${inline(h[2]!)}</h${level}>`);\n continue;\n }\n para.push(line);\n }\n flush();\n return out.join(\"\");\n}\n\nfunction renderTextBlock(raw: string, depth: number): string {\n if (isPlainProse(raw)) {\n // Escaping still happens — safety is not what the shortcut skips.\n return `<p>${escapeHtml(raw).replace(/\\n/g, \"<br/>\")}</p>`;\n }\n\n const lines = raw.split(\"\\n\");\n\n const table = renderTable(lines);\n if (table) return table;\n\n if (depth < MAX_DEPTH && QUOTE_MARK.test(lines[0]!)) {\n const inner = lines.map((l) => l.replace(QUOTE_MARK, \"\")).join(\"\\n\");\n return `<blockquote>${renderSource(inner, depth + 1)}</blockquote>`;\n }\n\n if (depth < MAX_DEPTH) {\n const list = renderList(lines, depth);\n if (list) return list;\n }\n\n if (lines.length === 1 && THEMATIC_BREAK.test(lines[0]!)) return \"<hr/>\";\n\n // Setext: the underline belongs to the lines above it, and reading it as a\n // paragraph followed by a rule is the wrong document — the title stops being\n // a heading, which is exactly what the outline is built from.\n const last = lines[lines.length - 1]!;\n if (lines.length >= 2 && SETEXT.test(last)) {\n const level = last.trim().startsWith(\"=\") ? 2 : 3;\n const text = lines.slice(0, -1).join(\" \").trim();\n return `<h${level}>${inline(text)}</h${level}>`;\n }\n\n return renderProse(lines);\n}\n\n// ── Assembly ─────────────────────────────────────────────────────────────────\n\nfunction renderBlock(src: string, block: MarkdownBlock, depth: number): string {\n const raw = src.slice(block.start, block.end);\n if (block.kind === \"fence\") return renderFence(raw);\n if (block.kind === \"code\") return renderIndentedCode(raw);\n return renderTextBlock(raw, depth);\n}\n\n/** Split and render a source, with no anchors. Also the recursion step. */\nfunction renderSource(src: string, depth: number): string {\n return splitBlocks(src)\n .map((b) => renderBlock(src, b, depth))\n .join(\"\");\n}\n\n/** Render for the transcript: no anchors, because chat prose is not addressed. */\nexport function renderMarkdown(src: string): string {\n return renderSource(src, 0);\n}\n\n/** What renderMarkdownStream keeps between calls. Start from newMarkdownStream(). */\nexport type MarkdownStream = {\n /** The source the cached blocks were decided on; valid while the text starts with it. */\n settled: string;\n /** Rendered HTML of those blocks. */\n html: string;\n /** Where the block after them starts looking: the line after the last one. */\n resume: number;\n};\n\nexport const newMarkdownStream = (): MarkdownStream => ({ settled: \"\", html: \"\", resume: 0 });\n\n/**\n * renderMarkdown for text that grows while it is shown — always the same\n * string renderMarkdown(src) returns, but blocks that can no longer change are\n * rendered once and reused, so a streamed answer costs its open tail per\n * frame instead of its whole length.\n *\n * Every block renders from its own source slice alone, so the only question\n * is which blocks later text can still move. splitBlocks decides a block's\n * extent from its own lines and, at most, the first line of the block after\n * it: the blank line or fence opener that ends it, and for a list or quote the\n * next non-blank line, which may continue it. Whether a line is blank, a fence\n * opener or closer, a list item or a quote can change while it is the last,\n * unterminated line — `1` becomes `1.`, a closing ``` becomes ```js, ``` gains\n * a backtick and stops opening a fence, a blank line gets text. Every line\n * before the last is final. So a block is settled once the block after it\n * starts before the last line: a setext underline, a loose list's next item,\n * a table's delimiter row or the rest of an open fence all belong to the\n * block that is still open. (This renderer has no reference definitions,\n * footnotes or raw HTML blocks, the other constructs that reach back.) And\n * splitBlocks never looks behind the line it stands on, so splitting from the\n * line after the settled blocks yields the same blocks the whole text would.\n *\n * Text that does not start with `stream.settled` — a new run, an edit — drops\n * the cache and renders from scratch.\n */\nexport function renderMarkdownStream(src: string, stream: MarkdownStream): string {\n if (!src.startsWith(stream.settled)) Object.assign(stream, newMarkdownStream());\n\n const from = stream.resume;\n const tail = src.slice(from);\n const blocks = splitBlocks(tail);\n const lastLine = src.lastIndexOf(\"\\n\") + 1 - from;\n let html = stream.html;\n for (let i = 0; i < blocks.length; i += 1) {\n const rendered = renderBlock(tail, blocks[i]!, 0);\n html += rendered;\n if (i + 1 < blocks.length && blocks[i + 1]!.start < lastLine) {\n stream.html += rendered;\n stream.resume = from + blocks[i]!.end + 1;\n }\n }\n stream.settled = src.slice(0, lastLine + from);\n return html;\n}\n\n/**\n * Render for a document previewer: every block carries `data-sc-block`, so a\n * DOM selection resolves to a source span by walking up to the nearest one.\n *\n * Kept separate from renderMarkdown rather than added as an option, because\n * assistant prose has nothing to address and the extra attributes would be\n * noise in every message bubble.\n */\nexport function renderMarkdownWithAnchors(src: string): AnchoredMarkdown {\n const blocks = splitBlocks(src);\n const html = blocks\n .map((block, i) => {\n const rendered = renderBlock(src, block, 0);\n // Every branch of renderBlock returns markup, so the first tag always\n // exists; the anchor rides on it instead of an extra wrapper element,\n // which keeps the DOM (and therefore .sc-prose's spacing rules) unchanged.\n return rendered.replace(/^(\\s*<[a-z][a-z0-9]*)/i, `$1 data-sc-block=\"${i}\"`);\n })\n .join(\"\");\n return { html, blocks };\n}\n"],"mappings":";AAmBO,IAAM,gBAA+B,EAAE,QAAQ,SAAS,UAAU,MAAM;AAE/E,SAAS,oBAAoB,QAAiB;AAC5C,SAAO;AAAA,IACL,SAAS,IAAI,KAAK,aAAa,QAAQ,EAAE,UAAU,WAAW,uBAAuB,EAAE,CAAC;AAAA,IACxF,OAAO,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,EAAE,CAAC;AAAA,IACjE,SAAS,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,GAAG,aAAa,MAAM,CAAC;AAAA,IACvF,WAAW,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,GAAG,aAAa,MAAM,CAAC;AAAA,EAC3F;AACF;AAEA,IAAM,gBAAgB,oBAAI,IAAoD;AAE9E,SAAS,WAAW,QAAiB;AACnC,QAAM,MAAM,UAAU;AACtB,MAAI,UAAU,cAAc,IAAI,GAAG;AACnC,MAAI,CAAC,SAAS;AACZ,cAAU,oBAAoB,MAAM;AACpC,kBAAc,IAAI,KAAK,OAAO;AAAA,EAChC;AACA,SAAO;AACT;AAEO,SAAS,YAAY,OAAgB,SAA0B,QAAQ,UAAyB,CAAC,GAAW;AACjH,MAAI,SAAS,KAAM,QAAO;AAC1B,QAAM,EAAE,QAAQ,SAAS,IAAI;AAC7B,QAAM,UAAU,WAAW,MAAM;AAEjC,UAAQ,QAAQ;AAAA,IACd,KAAK,UAAU;AACb,YAAM,IAAI,OAAO,KAAK;AACtB,UAA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AkB,CAAC;AAE9E,QAAM,OAAO,OAAO;AACpB,QAAM,OAAO,IAAI,MAAM,IAAI;AAC3B,QAAM,SAAS,YAAY,IAAI;AAC/B,QAAM,WAAW,IAAI,YAAY,IAAI,IAAI,IAAI;AAC7C,MAAI,OAAO,OAAO;AAClB,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,GAAG;AACzC,UAAM,WAAW,YAAY,MAAM,OAAO,CAAC,GAAI,CAAC;AAChD,YAAQ;AACR,QAAI,IAAI,IAAI,OAAO,UAAU,OAAO,IAAI,CAAC,EAAG,QAAQ,UAAU;AAC5D,aAAO,QAAQ;AACf,aAAO,SAAS,OAAO,OAAO,CAAC,EAAG,MAAM;AAAA,IAC1C;AAAA,EACF;AACA,SAAO,UAAU,IAAI,MAAM,GAAG,WAAW,IAAI;AAC7C,SAAO;AACT;AAUO,SAAS,0BAA0B,KAA+B;AACvE,QAAM,SAAS,YAAY,GAAG;AAC9B,QAAM,OAAO,OACV,IAAI,CAAC,OAAO,MAAM;AACjB,UAAM,WAAW,YAAY,KAAK,OAAO,CAAC;AAI1C,WAAO,SAAS,QAAQ,0BAA0B,qBAAqB,CAAC,GAAG;AAAA,EAC7E,CAAC,EACA,KAAK,EAAE;AACV,SAAO,EAAE,MAAM,OAAO;AACxB;","names":[]}
1
+ {"version":3,"sources":["../src/format.ts","../src/export.ts","../src/markdown.ts","../src/highlight.ts","../src/table.ts"],"sourcesContent":["// Value formatting shared by every card renderer.\n//\n// Centralised because a table cell and a stat tile showing the same number in\n// different formats is the fastest way to make an interface look untrustworthy.\n\nimport type { CardValueFormat } from \"@supersolutions/super-chat-core\";\n\nexport type FormatOptions = {\n /** BCP 47 locale. Omitted means the viewer's own. */\n locale?: string;\n /** IANA time zone for `datetime` values. Omitted means the viewer's own. */\n timeZone?: string;\n};\n\n/**\n * Fixed settings for HTML rendered ahead of the browser. A build server and a\n * viewer rarely share a locale or time zone, so server output and the first\n * client render must both use these or hydration fails.\n */\nexport const STABLE_FORMAT: FormatOptions = { locale: \"en-US\", timeZone: \"UTC\" };\n\nfunction createNumberFormats(locale?: string) {\n return {\n compact: new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 2 }),\n plain: new Intl.NumberFormat(locale, { maximumFractionDigits: 6 }),\n pctWide: new Intl.NumberFormat(locale, { maximumFractionDigits: 1, useGrouping: false }),\n pctNarrow: new Intl.NumberFormat(locale, { maximumFractionDigits: 2, useGrouping: false }),\n };\n}\n\nconst numberFormats = new Map<string, ReturnType<typeof createNumberFormats>>();\n\nfunction numbersFor(locale?: string) {\n const key = locale ?? \"\";\n let formats = numberFormats.get(key);\n if (!formats) {\n formats = createNumberFormats(locale);\n numberFormats.set(key, formats);\n }\n return formats;\n}\n\n/**\n * A value as a number, or NaN. `Number(\"\")` is 0, `Number(true)` is 1 and `Number([5])` is 5: an empty cell, a flag or a list is\n * not a count, and showing it as \"0\" or \"$0.00\" tells the reader something the data does not.\n */\nfunction numeric(value: unknown): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"bigint\") return Number(value);\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n return Number.NaN;\n}\n\n/** What to show for a value that is not the kind the format needs: the text of it, never `[object Object]`. */\nfunction plain(value: unknown): string {\n if (typeof value === \"string\" && value.trim() === \"\") return \"—\";\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n }\n return String(value);\n}\n\nexport function formatValue(value: unknown, format: CardValueFormat = \"text\", options: FormatOptions = {}): string {\n if (value == null) return \"—\";\n const { locale, timeZone } = options;\n const numbers = numbersFor(locale);\n\n switch (format) {\n case \"number\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n // Compact only above 5 digits: \"12.3K\" is helpful, \"1.2K\" hides precision\n // people expect to see on small counts.\n return Math.abs(n) >= 100_000 ? numbers.compact.format(n) : numbers.plain.format(n);\n }\n case \"currency\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n const abs = Math.abs(n);\n // Sub-cent values are common in crypto; fixed 2dp would render them as $0.00.\n const digits = abs >= 1 ? 2 : abs >= 0.01 ? 4 : 8;\n // A whole amount in the thousands reads as \"$48,200\". Forcing \".00\" onto\n // it is the machine-printed look; amounts with cents keep them.\n const min = abs >= 1000 && Number.isInteger(n) ? 0 : 2;\n return `$${n.toLocaleString(locale, { minimumFractionDigits: min, maximumFractionDigits: Math.max(min, digits) })}`;\n }\n case \"percent\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n // One decimal at most (\"8.2%\", \"12%\"), two only below 1% where the\n // second digit is the signal (\"0.04%\"). A fixed \"8.20%\" is false precision.\n return `${(Math.abs(n) < 1 ? numbers.pctNarrow : numbers.pctWide).format(n)}%`;\n }\n case \"bytes\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"];\n let i = 0;\n let v = n;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i += 1;\n }\n return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;\n }\n case \"duration\": {\n const ms = numeric(value);\n if (!Number.isFinite(ms)) return plain(value);\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n return `${(ms / 3_600_000).toFixed(1)}h`;\n }\n case \"datetime\": {\n const d = typeof value === \"number\" ? new Date(value) : typeof value === \"string\" ? new Date(value) : new Date(Number.NaN);\n if (Number.isNaN(d.getTime())) return plain(value);\n return d.toLocaleString(locale, timeZone ? { timeZone, timeZoneName: \"short\" } : undefined);\n }\n case \"code\":\n case \"text\":\n default:\n return typeof value === \"object\" ? plain(value) : String(value);\n }\n}\n\nexport function formatDelta(delta: number, format: CardValueFormat = \"number\", options: FormatOptions = {}): string {\n // A true minus sign: the hyphen-minus is narrower and misaligns a column of\n // signed deltas against the plus signs above it.\n const sign = delta > 0 ? \"+\" : delta < 0 ? \"−\" : \"\";\n return `${sign}${formatValue(Math.abs(delta), format, options)}`;\n}\n\nexport const toneClass = (tone?: string): string => (tone && tone !== \"neutral\" ? ` sc-tone--${tone}` : \"\");\n\n/** Positive is not always good — but for a delta with no stated tone it is the useful default. */\nexport const deltaTone = (delta: number): \"positive\" | \"negative\" | \"neutral\" =>\n delta > 0 ? \"positive\" : delta < 0 ? \"negative\" : \"neutral\";\n\n/**\n * A URL that came from a model or a tool, made safe to put in an `href`: only http(s) links\n * pass, anything else (`javascript:`, `data:`, `vbscript:`, a relative path that could be read\n * as a scheme after whitespace tricks) comes back as `undefined` and the caller renders plain\n * text. React 19 refuses `javascript:` hrefs itself, but this package supports React 18, which\n * only warns and then navigates.\n */\nexport function safeHref(url: string | undefined | null): string | undefined {\n if (typeof url !== \"string\") return undefined;\n const trimmed = url.trim();\n // Browsers strip tab and newline characters inside a URL before parsing it, so\n // `java\\tscript:` is a javascript: URL; reject anything with control characters outright.\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(trimmed)) return undefined;\n return /^https?:\\/\\/[^\\s]+$/i.test(trimmed) ? trimmed : undefined;\n}\n","// Thread export.\n//\n// Markdown rather than JSON: the point of exporting a conversation is to read it\n// somewhere else or paste it into a ticket, and JSON serves neither. Cards are\n// rendered as their data, not as their markup — a table exported as HTML is\n// useless in a text file, but as a markdown table it survives.\n//\n// Sharing (a hosted link) is deliberately NOT here: it needs a backend the kit\n// does not have, and faking it with a data: URL would produce links that break\n// the moment they leave the browser.\n\nimport type { Card, ContentPart, Message } from \"@supersolutions/super-chat-core\";\n\n/** A code fence that the text inside cannot close: longer than any run of backticks in it. */\nfunction fence(text: string): string {\n let longest = 0;\n for (const run of text.match(/`+/g) ?? []) longest = Math.max(longest, run.length);\n return \"`\".repeat(Math.max(3, longest + 1));\n}\n\nfunction fenced(info: string, text: string): string {\n const f = fence(text);\n return `${f}${info}\\n${text}\\n${f}`;\n}\n\n/** One table cell: a `|` or a line break inside it would end the cell or the row. */\nfunction cell(value: unknown): string {\n let text: string;\n if (value === null || value === undefined) text = \"\";\n else if (typeof value === \"object\") {\n try {\n text = JSON.stringify(value);\n } catch {\n text = String(value);\n }\n } else text = String(value);\n return text.replace(/\\|/g, \"\\\\|\").replace(/\\r\\n|\\r|\\n/g, \"<br>\");\n}\n\nfunction cardToMarkdown(spec: Record<string, unknown>): string {\n const kind = String(spec.kind ?? \"unknown\");\n const title = spec.title ? `**${spec.title}**\\n\\n` : \"\";\n\n if (kind === \"table\" && Array.isArray(spec.columns) && Array.isArray(spec.rows)) {\n const cols = (spec.columns as unknown[]).filter((c): c is { key: string; label: string } => typeof c === \"object\" && c !== null);\n const rows = (spec.rows as unknown[]).filter((r): r is Record<string, unknown> => typeof r === \"object\" && r !== null);\n const head = `| ${cols.map((c) => cell(c.label)).join(\" | \")} |`;\n const rule = `| ${cols.map(() => \"---\").join(\" | \")} |`;\n const body = rows.map((r) => `| ${cols.map((c) => cell(r[c.key])).join(\" | \")} |`).join(\"\\n\");\n return `${title}${head}\\n${rule}\\n${body}`;\n }\n\n if (kind === \"markdown\" && typeof spec.body === \"string\") return `${title}${spec.body}`;\n if (kind === \"code\" && typeof spec.code === \"string\") {\n return `${title}${fenced(typeof spec.language === \"string\" ? spec.language : \"\", spec.code)}`;\n }\n if (kind === \"callout\" && typeof spec.body === \"string\") return `> ${title}${spec.body}`;\n\n // Everything else keeps its data rather than being dropped — an export that\n // silently omits a card is worse than one that is a little verbose.\n let json: string;\n try {\n json = JSON.stringify(spec, null, 2) ?? \"null\";\n } catch {\n json = \"(data that cannot be shown as JSON)\";\n }\n return `${title}${fenced(\"json\", json)}`;\n}\n\nfunction partToMarkdown(part: ContentPart): string | null {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"reasoning\":\n return `<details><summary>Reasoning</summary>\\n\\n${part.text}\\n\\n</details>`;\n case \"tool-call\":\n {\n let args: string;\n try {\n args = JSON.stringify(part.input ?? {}) ?? \"{}\";\n } catch {\n args = \"…\";\n }\n return `- \\`${part.name}(${args})\\``;\n }\n case \"tool-result\":\n return part.failure ? `- \\`${part.name}\\` failed: ${part.failure}` : null;\n case \"image\":\n return \"_(image)_\";\n case \"file\":\n return `_(file: ${part.filename ?? \"attachment\"})_`;\n case \"artifact\":\n if (!part.kind.startsWith(\"card:\")) return null;\n {\n const data = part.data as { spec?: Card[\"spec\"] } | null | undefined;\n const spec = (data?.spec ?? data) as unknown;\n return typeof spec === \"object\" && spec !== null && !Array.isArray(spec) ? cardToMarkdown(spec as Record<string, unknown>) : null;\n }\n default:\n return null;\n }\n}\n\n/** Render a thread as markdown. `title` becomes the H1 when given. */\nexport function threadToMarkdown(messages: readonly Message[], title?: string): string {\n const out: string[] = title ? [`# ${title}`, \"\"] : [];\n\n for (const m of messages) {\n if (m.role === \"system\") continue;\n const body = m.parts.map(partToMarkdown).filter(Boolean).join(\"\\n\\n\");\n if (!body) continue;\n const who = m.role === \"user\" ? \"You\" : m.role === \"tool\" ? \"Tools\" : \"Assistant\";\n // A stored `createdAt` that is not a time (a hand edit, a string, 1e21) would make `toISOString` throw a RangeError.\n const at = typeof m.createdAt === \"number\" ? new Date(m.createdAt) : undefined;\n const when = at && Number.isFinite(at.getTime()) ? ` · ${at.toISOString().slice(0, 16).replace(\"T\", \" \")}` : \"\";\n out.push(`## ${who}${when}`, \"\", body, \"\");\n }\n\n return out.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\n/** Trigger a download of the thread as a `.md` file. */\nexport function downloadThread(messages: readonly Message[], filename = \"conversation.md\", title?: string): void {\n const blob = new Blob([threadToMarkdown(messages, title)], { type: \"text/markdown;charset=utf-8\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n // Revoking immediately can race the download in some browsers; one frame is\n // enough for the click to have been consumed.\n requestAnimationFrame(() => URL.revokeObjectURL(url));\n}\n","// Minimal markdown renderer for assistant text, markdown cards and document\n// artifacts.\n//\n// Deliberately not a full parser — a chat message or card body is short, and\n// pulling in a markdown library plus a sanitizer for this is disproportionate.\n//\n// It does now split into blocks before rendering, and that is not a stylistic\n// change. A document previewer has to answer \"the user selected this on screen;\n// where is it in the source?\", because that span is both what gets quoted into\n// the next request and what an edit has to anchor against. The previous shape —\n// escape the whole string, pull fences out into placeholders, then run a chain\n// of global regexes — destroyed source positions in its first statement.\n//\n// So the order is inverted: split on the RAW source and record offsets, then\n// escape and transform each block independently. Escaping per block rather than\n// up front is load-bearing, not tidiness: `&` → `&amp;` changes the string\n// length, so escaping first would shift every offset recorded afterwards. That\n// failure is invisible on screen — the page renders perfectly and the anchors\n// silently point at the wrong text — which is why markdown.test.ts asserts the\n// offsets round-trip rather than trusting the output to look right.\n//\n// ── Why it grew ──────────────────────────────────────────────────────────────\n//\n// The block set used to be headings, emphasis, code, links and bullet lists,\n// and for a chat bubble that is the right amount of renderer. A document\n// artifact changed the requirement under it: a document is a thing the user\n// KEEPS, reads in a previewer and downloads as `.md`, and a report whose table\n// renders as a column of literal pipes is not a document — it is the source of\n// one. Tables, quotes, ordered lists and indented code are not exotic; they are\n// what anyone writing a report reaches for in the first paragraph.\n//\n// The structure changed with the scope. A chain of global regexes over one\n// escaped string cannot tell a table from a paragraph, so each block is now\n// CLASSIFIED first and rendered by shape, and only the leaves run inline\n// transforms. Nesting (a list inside a quote, a quote inside a list) falls out\n// of rendering a block's interior through the same splitter, with a depth cap\n// so a pathological `> > > > …` cannot recurse without end.\n\nimport { splitBlocks, type MarkdownBlock } from \"@supersolutions/super-chat-core\";\nimport { highlightCode } from \"./highlight.js\";\n\n/**\n * What a host can change about how Markdown becomes HTML. Everything is optional, and the\n * defaults are the safe ones: no image is fetched, no maths is guessed at, code is coloured by\n * a small built-in highlighter.\n */\nexport type MarkdownOptions = {\n /**\n * Colour fenced code: `(code, lang) => html` for the inside of `<code>`, or `undefined` to\n * leave that block plain. The default knows JS/TS, JSON, Python, shell, SQL, HTML/CSS, YAML\n * and diffs; pass highlight.js or Shiki here for the rest, or `false` for none. The returned\n * HTML is inserted as it is, so it must come from code you trust.\n */\n highlight?: ((code: string, lang: string) => string | undefined) | false;\n /**\n * Typeset `$…$` and `$$…$$`: `(tex, display) => html`, or `undefined` to leave the source as\n * text. Without this, `$` is an ordinary character, so a price is never mistaken for maths.\n * The returned HTML is inserted as it is, so it must come from code you trust (KaTeX, Temml).\n */\n math?: (tex: string, display: boolean) => string | undefined;\n /**\n * What `![alt](https://…)` becomes. `\"link\"` (the default) is a link to the image: nothing is\n * fetched until the reader follows it, so a model cannot make a page load a URL it chose.\n * `\"embed\"` draws the picture, with lazy loading and no referrer.\n */\n images?: \"link\" | \"embed\";\n /**\n * Draw the buttons for code blocks and tables (copy, wrap, show all) as markup. They carry\n * `data-sc-act` and no words; `ProseHtml` in `super-chat-ui` gives them their labels and\n * answers them. Off by default so a plain `renderMarkdown` string has no dead buttons in it.\n */\n actions?: boolean;\n};\n\ntype Ctx = {\n highlight: ((code: string, lang: string) => string | undefined) | false;\n math: MarkdownOptions[\"math\"];\n embed: boolean;\n actions: boolean;\n};\n\nconst contextOf = (o: MarkdownOptions | undefined): Ctx => ({\n highlight: o?.highlight === undefined ? highlightCode : o.highlight,\n math: o?.math,\n embed: o?.images === \"embed\",\n actions: o?.actions === true,\n});\n\nexport type AnchoredMarkdown = {\n html: string;\n /** Index-aligned with the `data-sc-block` attribute on the rendered HTML. */\n blocks: MarkdownBlock[];\n};\n\n// Cheap pre-check carried over from main: with none of these characters\n// present, no heading, emphasis, code, link, list, quote or table rule below\n// could match, so the whole chain is skippable. Applied per BLOCK rather than\n// per document — one fenced snippet in an otherwise plain artifact should not\n// cost the other forty paragraphs their shortcut.\nconst MARKDOWN_SIGNIFICANT = /[`*_#[\\]>~|-]/;\n// Two constructs carry no character the test above would catch: an ordered\n// item, and a setext heading underlined with `=`. Adding `=` and the digits to\n// MARKDOWN_SIGNIFICANT would cost the shortcut on most prose, so they get their\n// own (equally cheap) look instead.\nconst ORDERED_ITEM = /^ {0,3}\\d{1,9}[.)]\\s/m;\nconst SETEXT_EQUALS = /\\n {0,3}=+[ \\t]*$/;\n\n// A bare URL and a character reference also have to be seen, and they carry none of the above.\nconst AUTOLINKABLE = /https?:\\/\\//;\nconst ENTITY = /&(?:[a-z][a-z\\d]{1,31}|#\\d{1,7}|#x[\\da-f]{1,6});/i;\n\nconst isPlainProse = (raw: string, ctx: Ctx) =>\n !MARKDOWN_SIGNIFICANT.test(raw) &&\n !ORDERED_ITEM.test(raw) &&\n !SETEXT_EQUALS.test(raw) &&\n !AUTOLINKABLE.test(raw) &&\n !ENTITY.test(raw) &&\n !(ctx.math && raw.includes(\"$\"));\n\n/** How deep a quote or list may nest before its interior is rendered flat. */\nconst MAX_DEPTH = 4;\n\n// Quotes are escaped because link URLs are interpolated into href=\"…\" — an\n// unescaped quote in a URL would close the attribute and open a new one\n// (browsers recover from the missing-whitespace parse error by reading\n// `\"onmouseover=\"…` as a fresh attribute).\n//\n// NUL is dropped here, at the one place every leaf is escaped, rather than only in\n// `inline`: the inline placeholders below are built from it, so it must never come from\n// the source, and code blocks and the plain-prose shortcut would otherwise let a raw\n// U+0000 through into the output. (Block offsets are computed on the raw source, so\n// removing it from the output moves no anchor.)\nconst escapeHtml = (s: string) =>\n s.replace(/\\0/g, \"\").replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n// ── Inline ───────────────────────────────────────────────────────────────────\n\n/**\n * Escape, then transform. Every leaf goes through here and nothing else does.\n *\n * Code spans are lifted out FIRST and put back last, so `**not bold**` inside\n * backticks stays literal — the same protection fenced blocks get, which the\n * old chain gave only to fences. NUL is stripped from the input because the\n * placeholders are built from it; without that, text could forge one.\n */\n// Only http(s) links — a javascript: URL must never survive. The destination may\n// contain one level of balanced parentheses (`…/wiki/Foo_(bar)`), as CommonMark\n// allows; the two alternatives cannot match the same character, so there is no\n// backtracking blow-up on a hostile string.\n//\n// The other destination is a card reference, `ref:<card>?key=value&…` (super-protocol\n// docs/CARD-REFS.md). It is not a link: it becomes a span the host wires to a card, and it\n// stays plain text where no host does. The character set is the envelope's own, plus the `;`\n// that escaping gives `&`, so nothing in it can close an attribute or open a tag. The limits\n// are the parser's to enforce (a ref that breaks them degrades where it is used), not this\n// regex's; the bound here only keeps a hostile string from costing a long scan.\nconst LINK = /\\[((?:[^\\[\\]]|\\[[^\\[\\]]*\\])+)\\]\\((https?:\\/\\/(?:[^()\\s]|\\([^()\\s]*\\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\\)/g;\n\n// An image: the destination follows the same rules as a link's, and only http(s) is one.\nconst IMAGE = /!\\[([^\\]]*)\\]\\((https?:\\/\\/(?:[^()\\s]|\\([^()\\s]*\\))+)\\)/g;\n// `<https://…>` (escaped, by now) and a bare URL. A URL stops at whitespace, at an escaped quote\n// or angle bracket, and at a parenthesis that is not part of a balanced pair, so a sentence\n// that ends with \"(see https://example.com)\" does not take the bracket with it.\nconst URL_BODY = String.raw`(?:(?!&(?:quot|lt|gt);)[^\\s\\0()]|\\([^\\s\\0()]*\\))+`;\nconst ANGLE_URL = /* @__PURE__ */ new RegExp(String.raw`&lt;(https?:\\/\\/${URL_BODY})&gt;`, \"g\");\nconst BARE_URL = /* @__PURE__ */ new RegExp(String.raw`(?<![\\w/=@])https?:\\/\\/${URL_BODY}`, \"g\");\n// Punctuation that ends a sentence, or the emphasis around a URL, is not part of it.\nconst URL_TAIL_CHARS = \".,;:!?*_~\";\n// A character reference in text stays one (`&amp;` shows `&`), and everything it can name is text.\nconst ESCAPED_ENTITY = /&amp;([a-z][a-z\\d]{1,31}|#\\d{1,7}|#x[\\da-f]{1,6});/gi;\n// `$$…$$`, then `$…$` where the opening `$` is followed and the closing one preceded by\n// something that is not a space, and the closing one is not followed by a digit or letter, so\n// \"costs $5 and $10\" is two prices and not a formula.\nconst MATH_DISPLAY = /\\$\\$([^\\0]+?)\\$\\$/g;\nconst MATH_INLINE = /(?<![\\\\$\\w])\\$(?=[^\\s$])((?:[^$\\n\\\\]|\\\\.)+?)(?<=[^\\s\\\\])\\$(?![\\d\\w$])/g;\n\n/**\n * The replacements below run one after another, so `*a **b* c**` comes out as `<em>a <strong>b</em> c</strong>`: tags that\n * cross. A browser repairs that when it parses the string, but the string itself is what tests, copy-as-HTML and anything\n * that walks it see. Where a closing tag is not the innermost open one, close the ones inside it first and open them again\n * after it, which is also what the browser's repair gives.\n */\nconst INLINE_TAG = /<(\\/?)(strong|em|del)>/g;\nfunction nest(html: string): string {\n const open: string[] = [];\n const out = html.replace(INLINE_TAG, (_all, close: string, tag: string) => {\n if (!close) {\n open.push(tag);\n return `<${tag}>`;\n }\n const at = open.lastIndexOf(tag);\n if (at < 0) return \"\";\n const inner = open.splice(at);\n inner.shift();\n open.push(...inner);\n return inner.reverse().map((t) => `</${t}>`).join(\"\") + `</${tag}>` + [...inner].reverse().map((t) => `<${t}>`).join(\"\");\n });\n return out + open.reverse().map((t) => `</${t}>`).join(\"\");\n}\n\n/** Strike-through, strong, emphasis. Runs on already-escaped text. */\nconst emphasize = (s: string) =>\n nest(s\n .replace(/~~([^~\\n]+)~~/g, \"<del>$1</del>\")\n .replace(/\\*\\*\\*(?=[^\\s*])([^*\\n]+?)\\*\\*\\*/g, \"<strong><em>$1</em></strong>\")\n .replace(/\\*\\*(?=\\S)((?:[^*]|\\*(?!\\*))+?)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/(^|[^\\w])__(?=\\S)((?:[^_]|_(?!_))+?)__(?!\\w)/g, \"$1<strong>$2</strong>\")\n .replace(/(^|[^*])\\*(?=[^\\s*])([^*\\n]*[^\\s*])\\*(?!\\*)/g, \"$1<em>$2</em>\")\n .replace(/(^|[^\\w])_(?=[^\\s_])([^_\\n]*[^\\s_])_(?![\\w])/g, \"$1<em>$2</em>\"));\n\nconst unescapeHtml = (s: string) =>\n s.replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").replace(/&quot;/g, '\"').replace(/&amp;/g, \"&\");\n\ntype Link = { text: string; url: string; ref: boolean; plain: boolean; image?: boolean };\n\nfunction inline(raw: string, ctx: Ctx): string {\n const spans: string[] = [];\n const spanSource: string[] = []; // what each code span looked like, for where it must stay literal\n let s = escapeHtml(raw);\n\n s = s.replace(/(`+)([\\s\\S]+?)\\1(?!`)/g, (all, _ticks, body: string) => {\n spans.push(body);\n spanSource.push(all);\n return `\\0${spans.length - 1}\\0`;\n });\n\n // Maths is lifted next, so its underscores and asterisks are not read as emphasis, and only\n // when the host supplied the typesetter: otherwise a `$` is a dollar sign.\n const maths: string[] = [];\n const mathSource: string[] = [];\n if (ctx.math) {\n const typeset = (tex: string, display: boolean, whole: string) => {\n const out = ctx.math!(unescapeHtml(tex).trim(), display);\n if (out === undefined) return whole;\n maths.push(out);\n mathSource.push(whole);\n return `\\0M${maths.length - 1}\\0`;\n };\n s = s.replace(MATH_DISPLAY, (all, tex: string) => typeset(tex, true, all));\n s = s.replace(MATH_INLINE, (all, tex: string) => typeset(tex, false, all));\n }\n\n // Links are lifted out the same way, BEFORE emphasis. Otherwise the emphasis rules\n // run over the destination too, and `…/a*b*c` becomes `href=\"…/a<em>b</em>c\"`: the\n // link silently points somewhere else. Only the link's text is emphasised.\n const links: Link[] = [];\n const lift = (link: Link) => {\n links.push(link);\n return `\\0L${links.length - 1}\\0`;\n };\n // A backtick pair inside a URL (or an image's alt text, which lands in an attribute) is part of\n // it, not a code span.\n const literalUrl = (url: string) =>\n url\n .replace(/\\0M(\\d+)\\0/g, (_m, i: string) => mathSource[Number(i)]!)\n .replace(/\\0(\\d+)\\0/g, (_m, i: string) => spanSource[Number(i)]!);\n\n s = s.replace(IMAGE, (_all, alt: string, url: string) =>\n lift({ text: literalUrl(alt), url: literalUrl(url), ref: false, plain: true, image: true }),\n );\n s = s.replace(LINK, (_all, text: string, url: string) => {\n const literal = literalUrl(url);\n return lift({ text, url: literal, ref: literal.startsWith(\"ref:\"), plain: false });\n });\n s = s.replace(ANGLE_URL, (_all, url: string) => lift({ text: url, url, ref: false, plain: true }));\n s = s.replace(BARE_URL, (all: string) => {\n let end = all.length;\n while (end > 0 && URL_TAIL_CHARS.includes(all[end - 1]!)) end -= 1; // a regex `[…]+$` is quadratic on \"a....x\"\n const url = all.slice(0, end);\n return lift({ text: url, url, ref: false, plain: true }) + all.slice(url.length);\n });\n\n s = emphasize(s.replace(ESCAPED_ENTITY, \"&$1;\"));\n\n // A link's text may hold another lifted construct (an image inside a link). Drawn from the\n // outside in, so the image can know it is inside one: an anchor never holds an anchor.\n const draw = (index: number, inside: boolean): string => {\n const link = links[index]!;\n const nest = (text: string) => text.replace(/\\0L(\\d+)\\0/g, (_all, j: string) => draw(Number(j), true));\n if (link.image) {\n const alt = link.text;\n if (ctx.embed) {\n return `<img class=\"sc-md-img\" src=\"${link.url}\" alt=\"${alt}\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\">`;\n }\n // A link to the picture, not the picture: the model chose this URL, and fetching it is\n // how a conversation leaks to a third party. The words stay readable and the `!` is gone.\n if (inside) return alt || link.url;\n return `<a class=\"sc-md-image\" href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${alt || link.url}</a>`;\n }\n if (link.ref) return `<span class=\"sc-ref\" data-ref=\"${link.url}\">${nest(emphasize(link.text))}</span>`;\n return `<a href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${nest(link.plain ? link.text : emphasize(link.text))}</a>`;\n };\n s = s.replace(/\\0L(\\d+)\\0/g, (_all, i: string) => draw(Number(i), false));\n\n return s\n .replace(/\\0M(\\d+)\\0/g, (_all, i: string) => maths[Number(i)]!)\n .replace(/\\0(\\d+)\\0/g, (_all, i: string) => `<code>${spans[Number(i)]}</code>`);\n}\n\n// ── Verbatim blocks ──────────────────────────────────────────────────────────\n\nconst CLOSING_FENCE = /^ {0,3}(?:`{3,}|~{3,})\\s*$/;\n// The first word of the info string, if it is a name and not prose: `js`, `c++`, `c#`, `shell-session`.\nconst FENCE_LANG = /^ {0,3}(?:`{3,}|~{3,})[ \\t]*([A-Za-z0-9][A-Za-z0-9_+#.-]{0,31})(?:[ \\t{].*)?$/;\n\n// Lines running on to a second row. Part of the markup, not a mask image or a decoration pass, so\n// it needs no stylesheet request and survives the page's strictest content security policy.\nconst WRAP_ICON =\n '<svg viewBox=\"0 0 16 16\" width=\"14\" height=\"14\" aria-hidden=\"true\"><path d=\"M2 4h12M2 8h8.5a2.5 2.5 0 0 1 0 5H8m0 0 1.6-1.6M8 13l1.6 1.6M2 12h2.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>';\n\n/** The code, its language, and the buttons a host may wire, in one box. */\nfunction codeBox(source: string, lang: string, ctx: Ctx): string {\n // NUL never reaches a highlighter or the page, whichever of them writes the markup.\n const code = source.replace(/\\0/g, \"\");\n const colored = lang && ctx.highlight ? ctx.highlight(code, lang) : undefined;\n const body = colored ?? escapeHtml(code);\n const attr = lang ? ` data-lang=\"${lang}\"` : \"\";\n const pre = `<pre${attr} tabindex=\"0\"><code${lang ? ` class=\"language-${lang}\"` : \"\"}>${body}</code></pre>`;\n if (!ctx.actions) return pre;\n return (\n `<div class=\"sc-mdcode\"${attr}><div class=\"sc-mdcode__bar\"><span class=\"sc-mdcode__lang\">${lang}</span>` +\n `<span class=\"sc-mdcode__tools\"><button type=\"button\" class=\"sc-mdcode__btn\" data-sc-act=\"wrap\">${WRAP_ICON}</button>` +\n `<button type=\"button\" class=\"sc-mdcode__btn\" data-sc-act=\"copy\"></button></span></div>${pre}` +\n `<button type=\"button\" class=\"sc-mdcode__more\" data-sc-act=\"more\"></button></div>`\n );\n}\n\nfunction renderFence(raw: string, ctx: Ctx): string {\n // Drop the opening fence line (which may carry a language) and the closing\n // one if it is there — an unterminated fence has none. Content is escaped but\n // never sees an inline transform.\n const lines = raw.split(\"\\n\");\n const lang = (FENCE_LANG.exec(lines[0]!)?.[1] ?? \"\").toLowerCase();\n lines.shift();\n if (lines.length && CLOSING_FENCE.test(lines[lines.length - 1]!)) lines.pop();\n return codeBox(lines.join(\"\\n\"), lang, ctx);\n}\n\nfunction renderIndentedCode(raw: string, ctx: Ctx): string {\n const body = raw.split(\"\\n\").map((l) => l.replace(/^(?: {4}|\\t)/, \"\")).join(\"\\n\");\n return codeBox(body, \"\", ctx);\n}\n\n// ── Tables ───────────────────────────────────────────────────────────────────\n\ntype Align = \"left\" | \"center\" | \"right\" | null;\n\nconst DELIMITER_CELL = /^:?-+:?$/;\n\n/** Split a pipe row into cells, honouring `\\|` as a literal pipe. */\nfunction cellsOf(line: string): string[] {\n const trimmed = line.trim().replace(/^\\|/, \"\").replace(/\\|$/, \"\");\n return trimmed\n .split(/(?<!\\\\)\\|/)\n .map((c) => c.trim().replace(/\\\\\\|/g, \"|\"));\n}\n\nconst alignOf = (cell: string): Align => {\n const left = cell.startsWith(\":\");\n const right = cell.endsWith(\":\");\n return left && right ? \"center\" : right ? \"right\" : left ? \"left\" : null;\n};\n\nfunction renderTable(lines: string[], ctx: Ctx): string | null {\n if (lines.length < 2 || !lines[0]!.includes(\"|\")) return null;\n const delimiter = cellsOf(lines[1]!);\n if (!delimiter.length || !delimiter.every((c) => DELIMITER_CELL.test(c))) return null;\n\n const head = cellsOf(lines[0]!);\n if (head.length !== delimiter.length) return null;\n const align = delimiter.map(alignOf);\n\n // Alignment rides on a class rather than a style attribute: a host with a\n // strict CSP can ship this without allowing inline styles.\n const cell = (tag: \"th\" | \"td\", text: string, i: number) => {\n const a = align[i];\n return `<${tag}${a ? ` class=\"sc-md-${a}\"` : \"\"}>${inline(text, ctx)}</${tag}>`;\n };\n\n const body = lines\n .slice(2)\n .filter((l) => l.trim() !== \"\")\n .map((l) => {\n const row = cellsOf(l);\n // Short rows are padded and long ones cut, so a ragged table still lines\n // up under its header instead of leaking cells into a new column.\n const cells = Array.from({ length: head.length }, (_, i) => cell(\"td\", row[i] ?? \"\", i));\n return `<tr>${cells.join(\"\")}</tr>`;\n })\n .join(\"\");\n\n // The table scrolls inside a box of its own, and the box takes focus: a wide table is\n // otherwise unreachable by keyboard. (A `display:block` table would scroll without the box,\n // but a block table is no longer a table to some assistive technology.)\n const table =\n `<div class=\"sc-md-scroll\" tabindex=\"0\"><table class=\"sc-md-table\"><thead><tr>${head\n .map((h, i) => cell(\"th\", h, i))\n .join(\"\")}</tr></thead><tbody>${body}</tbody></table></div>`;\n if (!ctx.actions) return table;\n return (\n `<div class=\"sc-md-tablebox\"><div class=\"sc-md-tablebar\">` +\n `<button type=\"button\" class=\"sc-md-tablebtn\" data-sc-act=\"copy-tsv\"></button>` +\n `<button type=\"button\" class=\"sc-md-tablebtn\" data-sc-act=\"copy-md\"></button></div>${table}</div>`\n );\n}\n\n// ── Lists ────────────────────────────────────────────────────────────────────\n\nconst LIST_ITEM = /^(\\s*)([-*+]|\\d{1,9}[.)])[ \\t]+(.*)$/;\nconst TASK_MARK = /^\\[([ xX])\\][ \\t]+/;\n\ntype ParsedList = { ordered: boolean; start: number; items: string[] };\n\nfunction parseList(lines: string[]): ParsedList | null {\n const first = LIST_ITEM.exec(lines[0] ?? \"\");\n if (!first) return null;\n const base = first[1]!.length;\n const marker = first[2]!;\n const ordered = /^\\d/.test(marker);\n // Everything indented at least as far as the first item's text belongs to\n // that item — its wrapped lines, its paragraphs, and any list nested under it.\n const strip = new RegExp(`^ {0,${base + marker.length + 1}}`);\n\n const items: string[][] = [];\n for (const line of lines) {\n const m = LIST_ITEM.exec(line);\n if (m && m[1]!.length <= base) {\n items.push([m[3]!]);\n continue;\n }\n if (!items.length) return null;\n items[items.length - 1]!.push(line.replace(strip, \"\"));\n }\n\n return { ordered, start: ordered ? Number.parseInt(marker, 10) : 1, items: items.map((l) => l.join(\"\\n\")) };\n}\n\n/**\n * One item's interior.\n *\n * A single-paragraph item stays tight — `<li>text</li>`, not\n * `<li><p>text</p></li>` — because the paragraph margin inside a list item is\n * the classic \"why is my list double-spaced\" bug. Anything with a blank line or\n * a nested list goes back through the block pipeline, which is where nesting\n * comes from.\n *\n * A task item (`[ ] todo`, `[x] done`) gets a checkbox that is shown and cannot be changed:\n * the reader is looking at an answer, not filling in a form. In a tight item the checkbox and\n * the text share a `<label>`, which is what names the box for a screen reader.\n */\nfunction renderItem(item: string, depth: number, ctx: Ctx): { html: string; task: boolean } {\n const mark = TASK_MARK.exec(item);\n const body = mark ? item.slice(mark[0].length) : item;\n const lines = body.trimEnd().split(\"\\n\");\n const nestedAt = lines.findIndex((l, i) => i > 0 && LIST_ITEM.test(l));\n const head = (nestedAt === -1 ? lines : lines.slice(0, nestedAt)).filter((l) => l.trim() !== \"\");\n const rest = nestedAt === -1 ? [] : lines.slice(nestedAt);\n const loose = /\\n[ \\t]*\\n/.test(body.trim());\n\n const headHtml = head.length\n ? loose\n ? renderSource(head.join(\"\\n\"), depth + 1, ctx)\n : inline(head.join(\" \").trim(), ctx)\n : \"\";\n const nested = rest.length ? renderSource(rest.join(\"\\n\"), depth + 1, ctx) : \"\";\n if (!mark) return { html: headHtml + nested, task: false };\n\n const checked = mark[1] !== \" \" ? \" checked\" : \"\";\n const box = `<input type=\"checkbox\" disabled${checked}`;\n return {\n html: (loose ? `${box} aria-label=\"[${mark[1]}]\">${headHtml}` : `<label>${box}> ${headHtml}</label>`) + nested,\n task: true,\n };\n}\n\nfunction renderList(lines: string[], depth: number, ctx: Ctx): string | null {\n const parsed = parseList(lines);\n if (!parsed) return null;\n const items = parsed.items\n .map((item) => {\n const { html, task } = renderItem(item, depth, ctx);\n return `<li${task ? ' class=\"sc-md-task\"' : \"\"}>${html}</li>`;\n })\n .join(\"\");\n if (!parsed.ordered) return `<ul>${items}</ul>`;\n return `<ol${parsed.start !== 1 ? ` start=\"${parsed.start}\"` : \"\"}>${items}</ol>`;\n}\n\n// ── Prose ────────────────────────────────────────────────────────────────────\n\nconst QUOTE_MARK = /^ {0,3}> ?/;\nconst THEMATIC_BREAK = /^ {0,3}(?:-{3,}|\\*{3,}|_{3,})\\s*$/;\nconst SETEXT = /^ {0,3}(=+|-+)\\s*$/;\n// Headings shift down one: the card or page owns the h1, so a document's own\n// `#` must not compete with it for the document outline a screen reader builds.\nconst ATX_HEAD = /^ {0,3}(#{1,6})\\s+/;\n// The one-regex form of a heading, `^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$`, backtracks without end on a line with a long run of\n// whitespace (20 000 spaces in a heading froze the page for minutes). It is kept only for the lines whose line terminators\n// make `.` stop early, which are rare, and bounded.\nconst ATX_SLOW = /^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$/;\nconst ATX_SLOW_MAX = 2000;\nconst ODD_TERMINATOR = /[\\r\\u2028\\u2029]/;\n\n/** A heading's hashes and text, by one linear pass; null when the line is not a heading. */\nexport function atxHeading(line: string): { hashes: number; text: string } | null {\n if (ODD_TERMINATOR.test(line)) {\n if (line.length > ATX_SLOW_MAX) return null;\n const m = ATX_SLOW.exec(line);\n return m ? { hashes: m[1]!.length, text: m[2]! } : null;\n }\n const head = ATX_HEAD.exec(line);\n if (!head) return null;\n // The text ends before any whitespace, then any closing hashes, then any whitespace, at the end of the line.\n let end = line.length;\n const floor = head[0].length;\n const skip = (test: (c: string) => boolean) => {\n while (end > floor && test(line[end - 1]!)) end -= 1;\n };\n const space = (c: string) => /\\s/.test(c);\n skip(space);\n skip((c) => c === \"#\");\n skip(space);\n return { hashes: head[1]!.length, text: line.slice(floor, end) };\n}\n// A paragraph that is nothing but `$$ … $$`, which may span lines.\nconst DISPLAY_MATH = /^\\s*\\$\\$([\\s\\S]+?)\\$\\$\\s*$/;\n\nfunction renderProse(lines: string[], ctx: Ctx): string {\n const out: string[] = [];\n let para: string[] = [];\n const flush = () => {\n if (!para.length) return;\n const display = ctx.math ? DISPLAY_MATH.exec(para.join(\"\\n\")) : null;\n const typeset = display ? ctx.math!(display[1]!.trim(), true) : undefined;\n out.push(\n typeset !== undefined\n ? `<div class=\"sc-math-block\">${typeset}</div>`\n : `<p>${para.map((l) => inline(l, ctx)).join(\"<br/>\")}</p>`,\n );\n para = [];\n };\n\n for (const line of lines) {\n const h = atxHeading(line);\n if (h) {\n flush();\n const level = Math.min(h.hashes + 1, 6);\n out.push(`<h${level}>${inline(h.text, ctx)}</h${level}>`);\n continue;\n }\n para.push(line);\n }\n flush();\n return out.join(\"\");\n}\n\nfunction renderTextBlock(raw: string, depth: number, ctx: Ctx): string {\n if (isPlainProse(raw, ctx)) {\n // Escaping still happens — safety is not what the shortcut skips.\n return `<p>${escapeHtml(raw).replace(/\\n/g, \"<br/>\")}</p>`;\n }\n\n const lines = raw.split(\"\\n\");\n\n const table = renderTable(lines, ctx);\n if (table) return table;\n\n if (depth < MAX_DEPTH && QUOTE_MARK.test(lines[0]!)) {\n const inner = lines.map((l) => l.replace(QUOTE_MARK, \"\")).join(\"\\n\");\n return `<blockquote>${renderSource(inner, depth + 1, ctx)}</blockquote>`;\n }\n\n if (depth < MAX_DEPTH) {\n const list = renderList(lines, depth, ctx);\n if (list) return list;\n }\n\n if (lines.length === 1 && THEMATIC_BREAK.test(lines[0]!)) return \"<hr/>\";\n\n // Setext: the underline belongs to the lines above it, and reading it as a\n // paragraph followed by a rule is the wrong document — the title stops being\n // a heading, which is exactly what the outline is built from.\n const last = lines[lines.length - 1]!;\n if (lines.length >= 2 && SETEXT.test(last)) {\n const level = last.trim().startsWith(\"=\") ? 2 : 3;\n const text = lines.slice(0, -1).join(\" \").trim();\n return `<h${level}>${inline(text, ctx)}</h${level}>`;\n }\n\n return renderProse(lines, ctx);\n}\n\n// ── Assembly ─────────────────────────────────────────────────────────────────\n\nfunction renderBlock(src: string, block: MarkdownBlock, depth: number, ctx: Ctx): string {\n const raw = src.slice(block.start, block.end);\n if (block.kind === \"fence\") return renderFence(raw, ctx);\n if (block.kind === \"code\") return renderIndentedCode(raw, ctx);\n return renderTextBlock(raw, depth, ctx);\n}\n\n/** Split and render a source, with no anchors. Also the recursion step. */\nfunction renderSource(src: string, depth: number, ctx: Ctx): string {\n return splitBlocks(src)\n .map((b) => renderBlock(src, b, depth, ctx))\n .join(\"\");\n}\n\n/** Render for the transcript: no anchors, because chat prose is not addressed. */\nexport function renderMarkdown(src: string, options?: MarkdownOptions): string {\n return renderSource(src, 0, contextOf(options));\n}\n\n/** What renderMarkdownStream keeps between calls. Start from newMarkdownStream(). */\nexport type MarkdownStream = {\n /** The source the cached blocks were decided on; valid while the text starts with it. */\n settled: string;\n /** Rendered HTML of those blocks, one string each, in order. They never change once here. */\n parts: string[];\n /** Where the block after them starts looking: the line after the last one. */\n resume: number;\n /** The options the cache was rendered with; a different set starts it over. */\n options: MarkdownOptions | undefined;\n};\n\nexport const newMarkdownStream = (): MarkdownStream => ({ settled: \"\", parts: [], resume: 0, options: undefined });\n\n/**\n * renderMarkdown for text that grows while it is shown — always the same\n * HTML renderMarkdown(src) returns, but blocks that can no longer change are\n * rendered once and reused, so a streamed answer costs its open tail per\n * frame instead of its whole length.\n *\n * Returned block by block: the strings of blocks that cannot change again are the very same\n * strings from one call to the next, which is what lets `ProseHtml` leave their DOM alone\n * (and a selection inside them standing) while the tail grows.\n *\n * Every block renders from its own source slice alone, so the only question\n * is which blocks later text can still move. splitBlocks decides a block's\n * extent from its own lines and, at most, the first line of the block after\n * it: the blank line or fence opener that ends it, and for a list or quote the\n * next non-blank line, which may continue it. Whether a line is blank, a fence\n * opener or closer, a list item or a quote can change while it is the last,\n * unterminated line — `1` becomes `1.`, a closing ``` becomes ```js, ``` gains\n * a backtick and stops opening a fence, a blank line gets text. Every line\n * before the last is final. So a block is settled once the block after it\n * starts before the last line: a setext underline, a loose list's next item,\n * a table's delimiter row or the rest of an open fence all belong to the\n * block that is still open. (This renderer has no reference definitions,\n * footnotes or raw HTML blocks, the other constructs that reach back.) And\n * splitBlocks never looks behind the line it stands on, so splitting from the\n * line after the settled blocks yields the same blocks the whole text would.\n *\n * Text that does not start with `stream.settled` — a new run, an edit — drops\n * the cache and renders from scratch.\n */\nexport function renderMarkdownBlocks(src: string, stream: MarkdownStream, options?: MarkdownOptions): string[] {\n if (!src.startsWith(stream.settled) || stream.options !== options) {\n Object.assign(stream, newMarkdownStream());\n stream.options = options;\n }\n const ctx = contextOf(options);\n\n const from = stream.resume;\n const tail = src.slice(from);\n const blocks = splitBlocks(tail);\n const lastLine = src.lastIndexOf(\"\\n\") + 1 - from;\n const shown = stream.parts.slice();\n for (let i = 0; i < blocks.length; i += 1) {\n const rendered = renderBlock(tail, blocks[i]!, 0, ctx);\n shown.push(rendered);\n if (i + 1 < blocks.length && blocks[i + 1]!.start < lastLine) {\n stream.parts.push(rendered);\n stream.resume = from + blocks[i]!.end + 1;\n }\n }\n stream.settled = src.slice(0, lastLine + from);\n return shown;\n}\n\n/** `renderMarkdownBlocks`, joined: the string `renderMarkdown(src, options)` would give. */\nexport function renderMarkdownStream(src: string, stream: MarkdownStream, options?: MarkdownOptions): string {\n return renderMarkdownBlocks(src, stream, options).join(\"\");\n}\n\n/**\n * Render for a document previewer: every block carries `data-sc-block`, so a\n * DOM selection resolves to a source span by walking up to the nearest one.\n *\n * Kept separate from renderMarkdown rather than added as an option, because\n * assistant prose has nothing to address and the extra attributes would be\n * noise in every message bubble.\n */\nexport function renderMarkdownWithAnchors(src: string, options?: MarkdownOptions): AnchoredMarkdown {\n const ctx = contextOf(options);\n const blocks = splitBlocks(src);\n const html = blocks\n .map((block, i) => {\n const rendered = renderBlock(src, block, 0, ctx);\n // Every branch of renderBlock returns markup, so the first tag always\n // exists; the anchor rides on it instead of an extra wrapper element,\n // which keeps the DOM (and therefore .sc-prose's spacing rules) unchanged.\n return rendered.replace(/^(\\s*<[a-z][a-z0-9]*)/i, `$1 data-sc-block=\"${i}\"`);\n })\n .join(\"\");\n return { html, blocks };\n}\n","// A small syntax highlighter for the code a chat answer is most likely to contain.\n//\n// This is the default for fenced code, and it is deliberately modest: one lexer per language\n// family, no grammar, no scopes, a couple of kilobytes. A host that wants more (every language,\n// theme-grade accuracy) passes its own `highlight` to the Markdown renderer — highlight.js,\n// Shiki, anything that turns code into HTML — and this is not used at all. Bundling a real\n// highlighter would cost more than the whole Markdown renderer (highlight.js with seven\n// languages is about three times its size), which is why the choice is the host's.\n//\n// Input is code; output is HTML for the inside of `<code>`. Every character of the code is\n// escaped, and a token is a `<span class=\"sc-tok-X\">` around escaped text, so nothing the model\n// wrote can become markup. Each lexer is a single alternation tried left to right, with no\n// nested quantifiers, so a hostile string costs a linear scan.\n\nconst escape = (s: string) =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n/** One alternation, and the token class each of its groups stands for (undefined = plain). */\ntype Lexer = { re: RegExp; classes: (string | undefined)[] };\n\nconst words = (list: string) => `\\\\b(?:${list.trim().split(/\\s+/).join(\"|\")})\\\\b`;\n\nconst STRING = `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"?|'(?:[^'\\\\\\\\\\\\n]|\\\\\\\\.)*'?`;\nconst NUMBER = `\\\\b(?:0x[\\\\da-fA-F]+|\\\\d+(?:\\\\.\\\\d+)?(?:e[+-]?\\\\d+)?)\\\\b`;\n\nconst lexer = (groups: [cls: string | undefined, source: string][], flags = \"g\"): Lexer => ({\n re: new RegExp(groups.map(([, source]) => `(${source})`).join(\"|\"), flags),\n classes: groups.map(([cls]) => cls),\n});\n\nconst JS_WORDS = /* @__PURE__ */ words(`\n as async await break case catch class const continue debugger default delete do else enum export\n extends finally for from function if implements import in instanceof interface let new of package\n private protected public readonly return static super switch this throw try type typeof var void\n while with yield satisfies declare namespace abstract keyof\n`);\nconst LITERALS = /* @__PURE__ */ words(\"true false null undefined NaN Infinity None True False nil\");\n\nconst SOURCES: Record<string, () => Lexer> = {\n js: () => lexer([\n [\"c\", \"\\\\/\\\\/[^\\\\n]*|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", `${STRING}|\\`(?:[^\\`\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*\\`?`],\n [\"k\", JS_WORDS],\n [\"l\", LITERALS],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_$][\\\\w$]*(?=\\\\s*\\\\()\"],\n ]),\n py: () => lexer([\n [\"c\", \"#[^\\\\n]*\"],\n [\"s\", `(?:[rbfRBF]{0,2})(?:\"\"\"[\\\\s\\\\S]*?(?:\"\"\"|$)|'''[\\\\s\\\\S]*?(?:'''|$))|(?:[rbfRBF]{0,2})(?:${STRING})`],\n [\n \"k\",\n words(`\n and as assert async await break class continue def del elif else except finally for from global\n if import in is lambda nonlocal not or pass raise return try while with yield match case\n `),\n ],\n [\"l\", LITERALS],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_]\\\\w*(?=\\\\s*\\\\()\"],\n ]),\n json: () => lexer([\n [\"p\", `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"(?=\\\\s*:)`],\n [\"s\", `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"?`],\n [\"l\", words(\"true false null\")],\n [\"n\", \"-?\\\\d+(?:\\\\.\\\\d+)?(?:[eE][+-]?\\\\d+)?\"],\n ]),\n sh: () => lexer([\n [\"c\", \"(?:^|(?<=\\\\s))#[^\\\\n]*\"],\n [\"s\", STRING],\n [\"v\", \"\\\\$(?:\\\\{[^}\\\\n]*\\\\}|[A-Za-z_]\\\\w*|[0-9?!#@*$])\"],\n [\"f\", \"(?:^|(?<=[;|&(]))[ \\\\t]*(?:sudo\\\\s+)?[A-Za-z_.\\\\/-][\\\\w./-]*\"],\n [\"a\", \"(?<=\\\\s)--?[A-Za-z][\\\\w-]*\"],\n [\"k\", words(\"if then else elif fi for while do done case esac function in export return exit\")],\n [\"n\", NUMBER],\n ], \"gm\"),\n sql: () => lexer(\n [\n [\"c\", \"--[^\\\\n]*|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", \"'(?:[^']|'')*'?\"],\n [\n \"k\",\n words(`\n select from where and or not null is in as on join left right inner outer full cross group by\n order having limit offset insert into values update set delete create alter drop table index\n view distinct union all case when then else end exists between like ilike asc desc primary key\n foreign references default returning with\n `),\n ],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_]\\\\w*(?=\\\\s*\\\\()\"],\n ],\n \"gi\",\n ),\n markup: () => lexer([\n [\"c\", \"<!--[\\\\s\\\\S]*?(?:-->|$)|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", STRING],\n [\"k\", \"<\\\\/?[A-Za-z][\\\\w:-]*|\\\\/?>|@[A-Za-z-]+\"],\n [\"a\", \"\\\\b[A-Za-z-]+(?==)\"],\n [\"p\", \"(?<=[{;\\\\s])[a-z-]+(?=\\\\s*:)\"],\n [\"n\", \"#[\\\\da-fA-F]{3,8}\\\\b|\\\\b\\\\d+(?:\\\\.\\\\d+)?(?:px|em|rem|%|vh|vw|s|ms)?\\\\b\"],\n ]),\n yaml: () => lexer([\n [\"c\", \"(?:^|(?<=\\\\s))#[^\\\\n]*\"],\n [\"p\", \"^[ \\\\t-]*[\\\\w.\\\"'/-]+(?=\\\\s*:(?:\\\\s|$))\"],\n [\"s\", STRING],\n [\"l\", words(\"true false null yes no on off\")],\n [\"n\", NUMBER],\n ], \"gm\"),\n};\n\nconst ALIASES: Record<string, string> = {\n js: \"js\", jsx: \"js\", mjs: \"js\", cjs: \"js\", javascript: \"js\", ts: \"js\", tsx: \"js\", typescript: \"js\",\n py: \"py\", python: \"py\",\n json: \"json\", jsonc: \"json\", json5: \"json\",\n sh: \"sh\", bash: \"sh\", zsh: \"sh\", shell: \"sh\", console: \"sh\", shellsession: \"sh\",\n sql: \"sql\", psql: \"sql\", postgres: \"sql\", mysql: \"sql\", sqlite: \"sql\",\n html: \"markup\", xml: \"markup\", svg: \"markup\", css: \"markup\", scss: \"markup\", vue: \"markup\",\n yaml: \"yaml\", yml: \"yaml\", toml: \"yaml\",\n};\n\nconst built = new Map<string, Lexer | null>();\n/** Built on first use: a lexer with a lookbehind must not be able to stop the module loading. */\nfunction lexerFor(key: string): Lexer | null {\n if (!built.has(key)) {\n try {\n built.set(key, SOURCES[key]!());\n } catch {\n built.set(key, null);\n }\n }\n return built.get(key)!;\n}\n\nfunction run({ re, classes }: Lexer, code: string): string {\n let out = \"\";\n let last = 0;\n re.lastIndex = 0;\n for (let m = re.exec(code); m; m = re.exec(code)) {\n if (m[0] === \"\") {\n re.lastIndex += 1;\n continue;\n }\n let group = 1;\n while (group < m.length && m[group] === undefined) group += 1;\n const cls = classes[group - 1];\n out += escape(code.slice(last, m.index));\n out += cls ? `<span class=\"sc-tok-${cls}\">${escape(m[0])}</span>` : escape(m[0]);\n last = m.index + m[0].length;\n }\n return out + escape(code.slice(last));\n}\n\n/** A diff is read line by line: what was added, what was taken out, where the hunk is. */\nfunction diff(code: string): string {\n return code\n .split(\"\\n\")\n .map((line) => {\n const cls = /^(?:\\+\\+\\+|---)/.test(line) ? \"k\" : line.startsWith(\"+\") ? \"add\" : line.startsWith(\"-\") ? \"del\" : line.startsWith(\"@@\") ? \"k\" : \"\";\n return cls ? `<span class=\"sc-tok-${cls}\">${escape(line)}</span>` : escape(line);\n })\n .join(\"\\n\");\n}\n\n/** The languages the built-in highlighter knows, by every name it answers to. */\nexport const HIGHLIGHT_LANGUAGES: readonly string[] = /* @__PURE__ */ (() => [...Object.keys(ALIASES), \"diff\", \"patch\"])();\n\n/**\n * Highlight `code` written in `lang`, as HTML for the inside of `<code>`.\n * Returns `undefined` for a language it does not know, which leaves the code as plain text.\n */\nexport function highlightCode(code: string, lang: string): string | undefined {\n const name = lang.toLowerCase();\n if (name === \"diff\" || name === \"patch\") return diff(code);\n const key = Object.hasOwn(ALIASES, name) ? ALIASES[name] : undefined;\n const lex = key ? lexerFor(key) : null;\n return lex ? run(lex, code) : undefined;\n}\n","// Tables as text, for the clipboard.\n//\n// One implementation for every table the kit shows: the `table` card hands it formatted cells,\n// and a table inside rendered Markdown hands it the text of its cells. Cells arrive already as\n// the strings a reader sees; nothing here formats a value.\n\n/** Tabs and line breaks inside a cell become a space: TSV has no way to escape them. */\nconst flatten = (cell: string) => cell.replace(/[\\t\\r\\n]+/g, \" \");\n\n/** Header row and data rows, tab-separated — what a spreadsheet pastes into cells. */\nexport function tableToTsv(header: readonly string[], rows: readonly (readonly string[])[]): string {\n const line = (cells: readonly string[]) => cells.map(flatten).join(\"\\t\");\n return [line(header), ...rows.map(line)].join(\"\\n\");\n}\n\n/** A GitHub-flavoured Markdown table. A pipe in a cell is escaped; a line break becomes a space. */\nexport function tableToMarkdown(\n header: readonly string[],\n rows: readonly (readonly string[])[],\n align: readonly (\"left\" | \"center\" | \"right\" | null)[] = [],\n): string {\n const cell = (c: string) => flatten(c).replace(/\\|/g, \"\\\\|\").trim();\n const rule = header.map((_, i) => {\n const a = align[i];\n return a === \"center\" ? \":---:\" : a === \"right\" ? \"---:\" : a === \"left\" ? \":---\" : \"---\";\n });\n const line = (cells: readonly string[]) => `| ${header.map((_, i) => cell(cells[i] ?? \"\")).join(\" | \")} |`;\n return [line(header), `| ${rule.join(\" | \")} |`, ...rows.map(line)].join(\"\\n\");\n}\n"],"mappings":";AAmBO,IAAM,gBAA+B,EAAE,QAAQ,SAAS,UAAU,MAAM;AAE/E,SAAS,oBAAoB,QAAiB;AAC5C,SAAO;AAAA,IACL,SAAS,IAAI,KAAK,aAAa,QAAQ,EAAE,UAAU,WAAW,uBAAuB,EAAE,CAAC;AAAA,IACxF,OAAO,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,EAAE,CAAC;AAAA,IACjE,SAAS,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,GAAG,aAAa,MAAM,CAAC;AAAA,IACvF,WAAW,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,GAAG,aAAa,MAAM,CAAC;AAAA,EAC3F;AACF;AAEA,I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AW,QAA2B,MAA8C;AAClG,QAAM,OAAO,CAAC,UAA6B,MAAM,IAAI,OAAO,EAAE,KAAK,GAAI;AACvE,SAAO,CAAC,KAAK,MAAM,GAAG,GAAG,KAAK,IAAI,IAAI,CAAC,EAAE,KAAK,IAAI;AACpD;AAGO,SAAS,gBACd,QACA,MACA,QAAyD,CAAC,GAClD;AACR,QAAMA,QAAO,CAAC,MAAc,QAAQ,CAAC,EAAE,QAAQ,OAAO,KAAK,EAAE,KAAK;AAClE,QAAM,OAAO,OAAO,IAAI,CAAC,GAAG,MAAM;AAChC,UAAM,IAAI,MAAM,CAAC;AACjB,WAAO,MAAM,WAAW,UAAU,MAAM,UAAU,SAAS,MAAM,SAAS,SAAS;AAAA,EACrF,CAAC;AACD,QAAM,OAAO,CAAC,UAA6B,KAAK,OAAO,IAAI,CAAC,GAAG,MAAMA,MAAK,MAAM,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,KAAK,CAAC;AACtG,SAAO,CAAC,KAAK,MAAM,GAAG,KAAK,KAAK,KAAK,KAAK,CAAC,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,EAAE,KAAK,IAAI;AAC/E;","names":["run","nest","cell","cell"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supersolutions/super-chat-ui-core",
3
- "version": "0.4.4",
3
+ "version": "0.5.1",
4
4
  "description": "Framework-free helpers shared by superchat UI bindings: markdown rendering (incl. streaming), value formatting and thread export.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SUPER SOLUTION LABS INC",
@@ -44,7 +44,7 @@
44
44
  "access": "public"
45
45
  },
46
46
  "dependencies": {
47
- "@supersolutions/super-chat-core": "0.4.4"
47
+ "@supersolutions/super-chat-core": "0.5.1"
48
48
  },
49
49
  "devDependencies": {
50
50
  "tsup": "^8.3.5",