Open History to see the last commit
1import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";
2import type { Processor } from "unified";
3import { isWindowsAbsolutePath } from "./path.ts";
4import type { PluggableList } from "unified";
5import rehypeRaw from "rehype-raw";
6import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
7import remarkBreaks from "remark-breaks";
8import remarkGfm from "remark-gfm";
9import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
10import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
11import {
12 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
13 remarkCodexDirectives,
14} from "./codexMarkdownDirectives.ts";
15import { isWindowsDrivePathHref } from "./markdownLinks.ts";
16import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
17
18type MarkdownImageHastNode = {
19 type?: string;
20 value?: string;
21 tagName?: string;
22 properties?: Record<string, unknown>;
23 children?: MarkdownImageHastNode[];
24};
25
26function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
27 return (node.children ?? []).filter(
28 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
29 );
30}
31
32const STANDALONE_IMAGE_BLOCKS = new Set([
33 "p",
34 "div",
35 "li",
36 "td",
37 "th",
38 "figure",
39 "center",
40 "blockquote",
41]);
42
43function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
44 const children = meaningfulHastChildren(node);
45 if (children.length !== 1) return undefined;
46 const only = children[0];
47 if (only?.type !== "element") return undefined;
48 if (only.tagName === "img") return only;
49 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
50 ? soleImageDescendant(only)
51 : undefined;
52}
53
54function markStandaloneImages(node: MarkdownImageHastNode) {
55 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
56 const image = soleImageDescendant(node);
57 if (image) image.properties = { ...image.properties, dataStandalone: true };
58 }
59 node.children?.forEach((child) => {
60 if (child.type === "element") markStandaloneImages(child);
61 });
62}
63
64function rehypePreserveBareAnchorPlaceholders() {
65 return (tree: MarkdownImageHastNode) => {
66 const anchors: Array<MarkdownImageHastNode | null> = [];
67 let rawTextTag: string | undefined;
68 const visit = (node: MarkdownImageHastNode) => {
69 if (node.type === "raw" && typeof node.value === "string") {
70 // Scan whole tags, attributes, and comments so embedded closing-anchor text cannot match a placeholder.
71 const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
72 let offset = 0;
73 while (rawTextTag !== "plaintext") {
74 // Raw text ends at its closing tag even inside comment-looking text.
75 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
76 matcher.lastIndex = offset;
77 const match = matcher.exec(node.value);
78 if (!match) break;
79 const [tag] = match;
80 offset = matcher.lastIndex;
81 if (rawTextTag) {
82 rawTextTag = undefined;
83 continue;
84 }
85 if (tag.startsWith("<!--")) continue;
86 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
87 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
88 if (
89 opening &&
90 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
91 ) {
92 rawTextTag = opening;
93 } else if (opening === "a") {
94 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
95 } else if (closing === "a") {
96 anchors.pop();
97 }
98 }
99 }
100 node.children?.forEach(visit);
101 };
102
103 visit(tree);
104 for (const anchor of anchors) {
105 if (anchor) anchor.type = "text";
106 }
107 };
108}
109
110function rehypePreserveImageSourceMeta() {
111 return (tree: MarkdownImageHastNode) => {
112 const visit = (node: MarkdownImageHastNode) => {
113 const src = node.properties?.src;
114 const title = node.properties?.title;
115 if (node.type === "element" && node.tagName === "img") {
116 node.properties = {
117 ...node.properties,
118 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
119 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
120 };
121 }
122 node.children?.forEach(visit);
123 };
124
125 visit(tree);
126 markStandaloneImages(tree);
127 };
128}
129
130const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
131 ...defaultSchema,
132 attributes: {
133 ...defaultSchema.attributes,
134 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
135 // Fence languages plus the two math classes the web chat's math plugin emits.
136 code: [
137 ["className", /^language-./, "math-inline", "math-display"],
138 "dataCodeMeta",
139 "dataInlineCode",
140 ],
141 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
142 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
143 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
144 img: [
145 ...(defaultSchema.attributes?.img ?? []),
146 "dataLocalSrc",
147 "dataMarkdownTitle",
148 "dataStandalone",
149 ],
150 },
151 protocols: {
152 ...defaultSchema.protocols,
153 href: [
154 ...(defaultSchema.protocols?.href ?? []),
155 "file",
156 "t3-citation",
157 "t3-context",
158 THREAD_LINK_PROTOCOL,
159 ],
160 src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
161 },
162} satisfies Parameters<typeof rehypeSanitize>[0];
163
164export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
165 remarkGfm,
166 remarkKeepWindowsPaths,
167 remarkGithubAlerts,
168 remarkNormalizeListItemIndentation,
169 remarkCodexDirectives,
170 remarkBreakAroundImageLines,
171 remarkPreserveCodeMeta,
172 remarkNormalizeLinksAndTagInlineCode,
173];
174
175export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
176 remarkGfm,
177 remarkKeepWindowsPaths,
178 remarkGithubAlerts,
179 remarkNormalizeListItemIndentation,
180 remarkCodexDirectives,
181 remarkBreakAroundImageLines,
182 remarkBreaks,
183 remarkPreserveCodeMeta,
184 remarkNormalizeLinksAndTagInlineCode,
185];
186
187export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
188 rehypePreserveBareAnchorPlaceholders,
189 rehypeRaw,
190 rehypePreserveImageSourceMeta,
191 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
192];
193
194const isImageNode = (node: PhrasingContent | undefined): boolean =>
195 node?.type === "image" ||
196 node?.type === "imageReference" ||
197 ((node?.type === "link" || node?.type === "linkReference") &&
198 node.children.length === 1 &&
199 isImageNode(node.children[0]));
200const endsLine = (node: PhrasingContent | undefined) =>
201 node === undefined ||
202 node.type === "break" ||
203 (node.type === "text" && /\n[ \t]*$/.test(node.value));
204const startsLine = (node: PhrasingContent | undefined) =>
205 node === undefined ||
206 node.type === "break" ||
207 (node.type === "text" && /^[ \t]*\n/.test(node.value));
208
209function breakLinesAroundImages(paragraph: Paragraph) {
210 const children = paragraph.children;
211 const ownsLine = (index: number) =>
212 isImageNode(children[index]) &&
213 endsLine(children[index - 1]) &&
214 startsLine(children[index + 1]);
215 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
216 if (child.type !== "text") return [child];
217 const afterImage = ownsLine(index - 1);
218 const beforeImage = ownsLine(index + 1);
219 if (!afterImage && !beforeImage) return [child];
220 const parts: PhrasingContent[] = [];
221 let value = child.value;
222 if (afterImage) {
223 value = value.replace(/^[ \t]*\n/, "");
224 parts.push({ type: "break" });
225 }
226 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
227 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
228 if (value) parts.push({ type: "text", value });
229 if (breakAfter) parts.push({ type: "break" });
230 return parts;
231 });
232}
233
234/**
235 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
236 * joins those lines into one paragraph, which puts the image inline beside its label. An
237 * image alone on its source line keeps that line; prose and inline badges still wrap.
238 */
239function remarkBreakAroundImageLines() {
240 return (tree: Root) => {
241 const visit = (node: Root | RootContent) => {
242 if (node.type === "paragraph") breakLinesAroundImages(node);
243 else if ("children" in node) node.children.forEach(visit);
244 };
245 visit(tree);
246 };
247}
248
249type MarkdownAstNode = {
250 type?: string;
251 meta?: unknown;
252 url?: string;
253 data?: {
254 hProperties?: Record<string, unknown>;
255 };
256 children?: MarkdownAstNode[];
257};
258
259function remarkPreserveCodeMeta() {
260 return (tree: MarkdownAstNode) => {
261 const visit = (node: MarkdownAstNode) => {
262 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
263 node.data = {
264 ...node.data,
265 hProperties: {
266 ...node.data?.hProperties,
267 dataCodeMeta: node.meta.trim(),
268 },
269 };
270 }
271 node.children?.forEach(visit);
272 };
273
274 visit(tree);
275 };
276}
277
278function remarkNormalizeLinksAndTagInlineCode() {
279 return (tree: MarkdownAstNode) => {
280 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
281 if (
282 (node.type === "link" || node.type === "definition") &&
283 typeof node.url === "string" &&
284 /^[A-Za-z]:[\\/]/.test(node.url)
285 ) {
286 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
287 }
288 if (node.type === "inlineCode" && !insideLink) {
289 node.data = {
290 ...node.data,
291 hProperties: {
292 ...node.data?.hProperties,
293 dataInlineCode: "",
294 },
295 };
296 }
297 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
298 node.children?.forEach((child) => visit(child, childInsideLink));
299 };
300
301 visit(tree, false);
302 };
303}
304
305interface DestinationCompileContext {
306 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
307 resume(): string;
308 sliceSerialize(token: unknown): string;
309}
310
311function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
312 const decoded = this.resume();
313 const authored = this.sliceSerialize(token);
314 const node = this.stack.at(-1);
315 // Character references still need decoding, so those destinations keep the parsed URL.
316 if (node)
317 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
318}
319
320const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
321
322interface EscapeCompileContext {
323 readonly stack: ReadonlyArray<{
324 readonly type: string;
325 children?: Array<{ type: string; value?: string }>;
326 }>;
327}
328
329function keepWindowsPathEscape(this: EscapeCompileContext) {
330 const text = this.stack.at(-1)?.children?.at(-1);
331 if (text?.type !== "text" || text.value === undefined) return;
332 const before = text.value.slice(0, -1);
333 if (UNFINISHED_DRIVE_PATH.test(before)) text.value = `${before}\\${text.value.slice(-1)}`;
334}
335
336/**
337 * CommonMark treats backslashes as escapes; preserve them as separators in Windows destinations
338 * and drive-path prose. Prose paths end at whitespace so later escapes still work.
339 */
340function remarkKeepWindowsPaths(this: Processor) {
341 const data = this.data();
342 (data.fromMarkdownExtensions ??= []).push({
343 exit: {
344 resourceDestinationString: keepWindowsPathDestination,
345 definitionDestinationString: keepWindowsPathDestination,
346 characterEscape: keepWindowsPathEscape,
347 },
348 });
349}
350
351export function shouldPreserveAssistantLineBreaks(text: string): boolean {
352 return /^★ Insight(?:\s|─)/mu.test(text);
353}