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