Open History to see the last commit
1import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts";
2import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";
3import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
4import { type PluggableList, type Processor, type Transformer, unified } from "unified";
5import remarkParse from "remark-parse";
6import remarkRehype from "remark-rehype";
7import { find, html } from "property-information";
8import rehypeRaw from "rehype-raw";
9import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
10import remarkBreaks from "remark-breaks";
11import remarkGfm from "remark-gfm";
12import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
13import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
14import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
15import {
16 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
17 remarkCodexDirectives,
18} from "./codexMarkdownDirectives.ts";
19import {
20 absoluteFilePathMatches,
21 isWindowsDrivePathHref,
22 normalizeMarkdownLinkDestination,
23} from "./markdownLinks.ts";
24import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
25
26export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
27
28type MarkdownImageHastNode = {
29 type?: string;
30 value?: string;
31 tagName?: string;
32 properties?: Record<string, unknown>;
33 children?: MarkdownImageHastNode[];
34};
35
36function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
37 return (node.children ?? []).filter(
38 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
39 );
40}
41
42const STANDALONE_IMAGE_BLOCKS = new Set([
43 "p",
44 "div",
45 "li",
46 "td",
47 "th",
48 "figure",
49 "center",
50 "blockquote",
51]);
52
53function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
54 const children = meaningfulHastChildren(node);
55 if (children.length !== 1) return undefined;
56 const only = children[0];
57 if (only?.type !== "element") return undefined;
58 if (only.tagName === "img") return only;
59 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
60 ? soleImageDescendant(only)
61 : undefined;
62}
63
64function markStandaloneImages(node: MarkdownImageHastNode) {
65 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
66 const image = soleImageDescendant(node);
67 if (image) image.properties = { ...image.properties, dataStandalone: true };
68 }
69 node.children?.forEach((child) => {
70 if (child.type === "element") markStandaloneImages(child);
71 });
72}
73
74// Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag.
75const RAW_HTML_TAG_PATTERN = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
76
77function rehypePreserveBareAnchorPlaceholders() {
78 return (tree: MarkdownImageHastNode) => {
79 const anchors: Array<MarkdownImageHastNode | null> = [];
80 let rawTextTag: string | undefined;
81 const visit = (node: MarkdownImageHastNode) => {
82 if (node.type === "raw" && typeof node.value === "string") {
83 const tags = new RegExp(RAW_HTML_TAG_PATTERN);
84 let offset = 0;
85 while (rawTextTag !== "plaintext") {
86 // Raw text ends at its closing tag even inside comment-looking text.
87 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
88 matcher.lastIndex = offset;
89 const match = matcher.exec(node.value);
90 if (!match) break;
91 const [tag] = match;
92 offset = matcher.lastIndex;
93 if (rawTextTag) {
94 rawTextTag = undefined;
95 continue;
96 }
97 if (tag.startsWith("<!--")) continue;
98 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
99 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
100 if (
101 opening &&
102 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
103 ) {
104 rawTextTag = opening;
105 } else if (opening === "a") {
106 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
107 } else if (closing === "a") {
108 anchors.pop();
109 }
110 }
111 }
112 node.children?.forEach(visit);
113 };
114
115 visit(tree);
116 for (const anchor of anchors) {
117 if (anchor) anchor.type = "text";
118 }
119 };
120}
121
122const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;
123
124/**
125 * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
126 * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
127 * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
128 */
129function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
130 if (!picture.children) return;
131 const image = picture.children.find((child) => child.tagName === "img");
132 for (const source of picture.children) {
133 if (source.tagName !== "source" || !image) continue;
134 const media = source.properties?.media;
135 const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
136 const srcSet = source.properties?.srcSet;
137 const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
138 // A candidate's URL runs to the first space (a descriptor such as `2x` may follow).
139 const url =
140 typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";
141 const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
142 // As in a browser, the first source that matches a scheme is the one shown.
143 if (scheme && url && image.properties?.[key] === undefined) {
144 // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
145 const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
146 image.properties = { ...image.properties, [key]: value };
147 }
148 }
149 picture.children = picture.children.filter((child) => child.tagName !== "source");
150}
151
152function rehypePreserveImageSourceMeta() {
153 return (tree: MarkdownImageHastNode) => {
154 const visit = (node: MarkdownImageHastNode) => {
155 const src = node.properties?.src;
156 const title = node.properties?.title;
157 if (node.type === "element" && node.tagName === "picture") {
158 moveColorSchemeSourcesToImage(node);
159 }
160 if (node.type === "element" && node.tagName === "img") {
161 node.properties = {
162 ...node.properties,
163 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
164 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
165 };
166 }
167 node.children?.forEach(visit);
168 };
169
170 visit(tree);
171 markStandaloneImages(tree);
172 };
173}
174
175const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
176
177// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first.
178function rehypeNormalizeLocalEditorLinks() {
179 return (tree: MarkdownImageHastNode) => {
180 const visit = (node: MarkdownImageHastNode) => {
181 const href = node.properties?.href;
182 if (node.type === "element" && node.tagName === "a" && typeof href === "string") {
183 try {
184 const url = new URL(href);
185 if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href };
186 } catch {
187 // Not an absolute URL; the sanitizer decides.
188 }
189 }
190 node.children?.forEach(visit);
191 };
192
193 visit(tree);
194 };
195}
196
197const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
198 ...defaultSchema,
199 attributes: {
200 ...defaultSchema.attributes,
201 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
202 // Fence languages plus the two math classes the web chat's math plugin emits.
203 code: [
204 ["className", /^language-./, "math-inline", "math-display"],
205 "dataCodeMeta",
206 "dataInlineCode",
207 ],
208 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
209 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
210 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
211 img: [
212 ...(defaultSchema.attributes?.img ?? []),
213 "dataDarkSrc",
214 "dataLightSrc",
215 "dataLocalSrc",
216 "dataMarkdownTitle",
217 "dataStandalone",
218 ],
219 },
220 protocols: {
221 ...defaultSchema.protocols,
222 href: [
223 ...(defaultSchema.protocols?.href ?? []),
224 "file",
225 "t3-citation",
226 "t3-context",
227 THREAD_LINK_PROTOCOL,
228 // Scheme only: the renderer's URL transform checks the rest of the link shape.
229 ...LOCAL_FILE_LINK_SCHEMES,
230 ],
231 src: IMAGE_SRC_PROTOCOLS,
232 dataDarkSrc: IMAGE_SRC_PROTOCOLS,
233 dataLightSrc: IMAGE_SRC_PROTOCOLS,
234 },
235} satisfies Parameters<typeof rehypeSanitize>[0];
236
237export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
238 remarkGfm,
239 remarkKeepAutolinkSuffixes,
240 remarkLinkAbsoluteFilePaths,
241 remarkKeepWindowsPaths,
242 remarkGithubAlerts,
243 remarkKeepOrderedListNumbers,
244 remarkNormalizeListItemIndentation,
245 remarkCodexDirectives,
246 remarkBreakAroundImageLines,
247 remarkPreserveCodeMeta,
248 remarkNormalizeLinksAndTagInlineCode,
249];
250
251export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
252 remarkGfm,
253 remarkKeepAutolinkSuffixes,
254 remarkLinkAbsoluteFilePaths,
255 remarkKeepWindowsPaths,
256 remarkGithubAlerts,
257 remarkKeepOrderedListNumbers,
258 remarkNormalizeListItemIndentation,
259 remarkCodexDirectives,
260 remarkBreakAroundImageLines,
261 remarkBreaks,
262 remarkPreserveCodeMeta,
263 remarkNormalizeLinksAndTagInlineCode,
264];
265
266// Start tags an HTML parser closes an open `<p>` for.
267const CLOSES_PARAGRAPH = new Set(
268 "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split(
269 " ",
270 ),
271);
272const HEADING = /^h[1-6]$/;
273
274interface HtmlScope {
275 readonly anchor: boolean;
276 readonly paragraph: boolean;
277 readonly heading: boolean;
278}
279
280/**
281 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
282 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
283 * drops `data`, both repeated here, and moves blank text that renders the same.
284 */
285function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
286 if (node.type === "raw") return true;
287 let inner = scope;
288 if (node.type === "element" && node.tagName) {
289 const { tagName } = node;
290 const heading = HEADING.test(tagName);
291 if (
292 (tagName === "a" && scope.anchor) ||
293 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
294 (heading && scope.heading)
295 ) {
296 return true;
297 }
298 inner = {
299 anchor: scope.anchor || tagName === "a",
300 paragraph: scope.paragraph || tagName === "p",
301 heading: scope.heading || heading,
302 };
303 const properties = node.properties ?? {};
304 for (const key of Object.keys(properties)) {
305 const value = properties[key];
306 const info = find(html, key);
307 if (
308 value === false ||
309 value === null ||
310 value === undefined ||
311 Number.isNaN(value) ||
312 (!value && info.boolean)
313 ) {
314 delete properties[key];
315 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
316 properties[key] = "";
317 }
318 }
319 delete (node as { data?: unknown }).data;
320 }
321 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
322}
323
324const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
325
326/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
327function rehypeRawWhenPresent(this: Processor) {
328 const transform = rehypeRaw.call(this) as unknown as (
329 tree: MarkdownImageHastNode,
330 file: unknown,
331 ) => unknown;
332 return (tree: MarkdownImageHastNode, file: unknown) =>
333 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
334}
335
336export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
337 rehypePreserveBareAnchorPlaceholders,
338 rehypeRawWhenPresent,
339 rehypePreserveImageSourceMeta,
340 rehypeNormalizeLocalEditorLinks,
341 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
342];
343
344const isImageNode = (node: PhrasingContent | undefined): boolean =>
345 node?.type === "image" ||
346 node?.type === "imageReference" ||
347 ((node?.type === "link" || node?.type === "linkReference") &&
348 node.children.length === 1 &&
349 isImageNode(node.children[0]));
350const endsLine = (node: PhrasingContent | undefined) =>
351 node === undefined ||
352 node.type === "break" ||
353 (node.type === "text" && /\n[ \t]*$/.test(node.value));
354const startsLine = (node: PhrasingContent | undefined) =>
355 node === undefined ||
356 node.type === "break" ||
357 (node.type === "text" && /^[ \t]*\n/.test(node.value));
358
359function breakLinesAroundImages(paragraph: Paragraph) {
360 const children = paragraph.children;
361 if (!children.some(isImageNode)) return;
362 const ownsLine = (index: number) =>
363 isImageNode(children[index]) &&
364 endsLine(children[index - 1]) &&
365 startsLine(children[index + 1]);
366 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
367 if (child.type !== "text") return [child];
368 const afterImage = ownsLine(index - 1);
369 const beforeImage = ownsLine(index + 1);
370 if (!afterImage && !beforeImage) return [child];
371 const parts: PhrasingContent[] = [];
372 let value = child.value;
373 if (afterImage) {
374 value = value.replace(/^[ \t]*\n/, "");
375 parts.push({ type: "break" });
376 }
377 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
378 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
379 if (value) parts.push({ type: "text", value });
380 if (breakAfter) parts.push({ type: "break" });
381 return parts;
382 });
383}
384
385/**
386 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
387 * joins those lines into one paragraph, which puts the image inline beside its label. An
388 * image alone on its source line keeps that line; prose and inline badges still wrap.
389 */
390function remarkBreakAroundImageLines() {
391 return (tree: Root) => {
392 const visit = (node: Root | RootContent) => {
393 if (node.type === "paragraph") breakLinesAroundImages(node);
394 else if ("children" in node) node.children.forEach(visit);
395 };
396 visit(tree);
397 };
398}
399
400type MarkdownAstNode = {
401 type?: string;
402 meta?: unknown;
403 url?: string;
404 data?: {
405 hProperties?: Record<string, unknown>;
406 };
407 children?: MarkdownAstNode[];
408};
409
410function remarkKeepAutolinkSuffixes(): Transformer<Root> {
411 return (tree, file) => {
412 const source = String(file);
413 const visit = (node: Root | RootContent) => {
414 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
415 for (let index = 0; index < node.children.length; index++) {
416 const child = node.children[index];
417 const next = node.children[index + 1];
418 if (child?.type === "link" && /^https?:\/\//i.test(child.url) && next?.type === "text") {
419 const suffix = /^[_~]+/.exec(next.value)?.[0];
420 if (!suffix) continue;
421 const label = child.children.length === 1 ? child.children[0] : undefined;
422 if (label?.type !== "text") continue;
423 if (label.value !== child.url && `http://${label.value}` !== child.url) continue;
424 const start = child.position?.start.offset;
425 const end = child.position?.end.offset;
426 const bare =
427 !child.position ||
428 (start !== undefined &&
429 end !== undefined &&
430 source.slice(start, end) === label.value &&
431 source.slice(end, end + suffix.length) === suffix);
432 if (bare) {
433 child.url += suffix;
434 label.value += suffix;
435 next.value = next.value.slice(suffix.length);
436 if (child.position && end !== undefined) {
437 const boundary = {
438 ...child.position.end,
439 column: child.position.end.column + suffix.length,
440 offset: end + suffix.length,
441 };
442 child.position.end = boundary;
443 if (label.position) label.position.end = boundary;
444 if (next.position) next.position.start = boundary;
445 }
446 if (!next.value) node.children.splice(index + 1, 1);
447 }
448 }
449 if (child) visit(child);
450 }
451 };
452 visit(tree);
453 };
454}
455
456function remarkLinkAbsoluteFilePaths(): Transformer<Root> {
457 return (tree) => {
458 // Raw `<a>` tags are sibling html nodes, so text inside one is not under a link node.
459 let rawAnchorDepth = 0;
460 const visit = (node: Root | RootContent) => {
461 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
462 node.children = node.children.flatMap((child): typeof node.children => {
463 if (child.type === "html") {
464 for (const [tag] of child.value.matchAll(RAW_HTML_TAG_PATTERN)) {
465 if (/^<a[\s/>]/i.test(tag)) rawAnchorDepth += 1;
466 else if (/^<\/a[\s>]/i.test(tag)) rawAnchorDepth = Math.max(0, rawAnchorDepth - 1);
467 }
468 }
469 if (child.type !== "text" || rawAnchorDepth > 0) {
470 visit(child);
471 return [child];
472 }
473 const parts: PhrasingContent[] = [];
474 let offset = 0;
475 for (const { index, path } of absoluteFilePathMatches(child.value)) {
476 if (index > offset) parts.push({ type: "text", value: child.value.slice(offset, index) });
477 parts.push({ type: "link", url: path, children: [{ type: "text", value: path }] });
478 offset = index + path.length;
479 }
480 if (offset === 0) return [child];
481 if (offset < child.value.length)
482 parts.push({ type: "text", value: child.value.slice(offset) });
483 return parts;
484 });
485 };
486 visit(tree);
487 };
488}
489
490function remarkPreserveCodeMeta() {
491 return (tree: MarkdownAstNode) => {
492 const visit = (node: MarkdownAstNode) => {
493 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
494 node.data = {
495 ...node.data,
496 hProperties: {
497 ...node.data?.hProperties,
498 dataCodeMeta: node.meta.trim(),
499 },
500 };
501 }
502 node.children?.forEach(visit);
503 };
504
505 visit(tree);
506 };
507}
508
509function remarkNormalizeLinksAndTagInlineCode() {
510 return (tree: MarkdownAstNode) => {
511 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
512 if (
513 (node.type === "link" || node.type === "definition") &&
514 typeof node.url === "string" &&
515 /^[A-Za-z]:[\\/]/.test(node.url)
516 ) {
517 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
518 }
519 if (node.type === "inlineCode" && !insideLink) {
520 node.data = {
521 ...node.data,
522 hProperties: {
523 ...node.data?.hProperties,
524 dataInlineCode: "",
525 },
526 };
527 }
528 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
529 node.children?.forEach((child) => visit(child, childInsideLink));
530 };
531
532 visit(tree, false);
533 };
534}
535
536export function shouldPreserveAssistantLineBreaks(text: string): boolean {
537 return /^★ Insight(?:\s|─)/mu.test(text);
538}
539
540export function remarkAssistantInsights(this: Processor) {
541 return (tree: Root, file: { value: unknown }) => {
542 const source = String(file.value);
543 if (!source.includes("★ Insight")) return;
544 const protectedRanges: { start: number; end: number; code: boolean }[] = [];
545 const inspect = (node: RootContent | PhrasingContent) => {
546 const start = node.position?.start.offset;
547 const end = node.position?.end.offset;
548 if (start !== undefined && end !== undefined) {
549 const code =
550 node.type === "code" ||
551 node.type === "html" ||
552 (node.type === "inlineCode" && node.position?.start.line !== node.position?.end.line);
553 if (code || node.type === "list" || node.type === "blockquote")
554 protectedRanges.push({ start, end, code });
555 }
556 if ("children" in node) node.children.forEach(inspect);
557 };
558 tree.children.forEach(inspect);
559 const starts = new Set<number>();
560 const offsets: { original: number; rewritten: number; prefix: number }[] = [];
561 let indent: string | undefined;
562 let original = 0;
563 let rewritten = 0;
564 const lines = source.split(/(?<=\n)|(?<=\r)(?!\n)/u).map((line, index) => {
565 const value = line.replace(/[\r\n]+$/u, "");
566 const blocked = protectedRanges.some(
567 (range) =>
568 original >= range.start && original < range.end && (indent === undefined || range.code),
569 );
570 const opening =
571 indent === undefined && !blocked
572 ? /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u.exec(value)
573 : null;
574 const closing =
575 indent !== undefined && !blocked ? /^( {0,3})(`?)─{3,}\2[ \t]*$/u.exec(value) : null;
576 let prefix = 0;
577 let output = line;
578 if (opening) {
579 indent = opening[1] ?? "";
580 starts.add(index + 1);
581 output = ">" + line.slice(value.length);
582 } else if (closing && closing[1] === indent) {
583 indent = undefined;
584 output = line.slice(value.length);
585 } else if (indent !== undefined) {
586 prefix = 2;
587 output = "> " + line;
588 }
589 offsets.push({ original, rewritten, prefix });
590 original += line.length;
591 rewritten += output.length;
592 return output;
593 });
594 if (starts.size === 0) return;
595 const parsed = this.parse(lines.join("")) as Root;
596 const restorePosition = (node: RootContent | PhrasingContent) => {
597 if (node.position) {
598 for (const point of [node.position.start, node.position.end]) {
599 const offset = offsets[point.line - 1];
600 if (!offset) continue;
601 point.column = Math.max(1, point.column - offset.prefix);
602 if (point.offset !== undefined)
603 point.offset += offset.original - offset.rewritten - offset.prefix;
604 }
605 }
606 if ("children" in node) node.children.forEach(restorePosition);
607 };
608 for (const node of parsed.children) {
609 if (node.type === "blockquote" && starts.has(node.position?.start.line ?? 0)) {
610 node.data = { ...node.data, hProperties: { dataAlert: "insight" } };
611 }
612 restorePosition(node);
613 }
614 tree.children = parsed.children;
615 };
616}
617
618const imageSourceProcessor = unified()
619 .use(remarkParse)
620 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
621 .use(remarkRehype, { allowDangerousHtml: true })
622 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
623
624interface ImageSourceNode {
625 readonly type: string;
626 readonly tagName?: string;
627 readonly properties?: {
628 readonly src?: unknown;
629 readonly dataLocalSrc?: unknown;
630 readonly dataDarkSrc?: unknown;
631 readonly dataLightSrc?: unknown;
632 };
633 readonly children?: ReadonlyArray<ImageSourceNode>;
634}
635
636/**
637 * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads
638 * them. Code, comments, and plain links show no image, so they add none.
639 */
640export function chatMarkdownImageSources(markdown: string): Array<string> {
641 const sources: Array<string> = [];
642 const visit = (node: ImageSourceNode) => {
643 if (node.type === "element" && node.tagName === "img") {
644 const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};
645 // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
646 if (typeof dataLocalSrc === "string") {
647 sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
648 } else if (typeof src === "string") {
649 sources.push(normalizeMarkdownLinkDestination(src));
650 }
651 // A `<picture>` shows one of these instead, by the viewer's theme.
652 for (const variant of [dataDarkSrc, dataLightSrc]) {
653 if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));
654 }
655 }
656 node.children?.forEach(visit);
657 };
658 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
659 return sources;
660}