Open History to see the last commit
1import type { Processor } from "unified";
2import { isWindowsAbsolutePath } from "./path.ts";
3import type { PluggableList } from "unified";
4import rehypeRaw from "rehype-raw";
5import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
6import remarkBreaks from "remark-breaks";
7import remarkGfm from "remark-gfm";
8import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
9import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
10import {
11 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
12 remarkCodexDirectives,
13} from "./codexMarkdownDirectives.ts";
14import { isWindowsDrivePathHref } from "./markdownLinks.ts";
15import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
16
17type MarkdownImageHastNode = {
18 type?: string;
19 value?: string;
20 tagName?: string;
21 properties?: Record<string, unknown>;
22 children?: MarkdownImageHastNode[];
23};
24
25function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
26 return (node.children ?? []).filter(
27 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
28 );
29}
30
31const STANDALONE_IMAGE_BLOCKS = new Set([
32 "p",
33 "div",
34 "li",
35 "td",
36 "th",
37 "figure",
38 "center",
39 "blockquote",
40]);
41
42function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
43 const children = meaningfulHastChildren(node);
44 if (children.length !== 1) return undefined;
45 const only = children[0];
46 if (only?.type !== "element") return undefined;
47 if (only.tagName === "img") return only;
48 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
49 ? soleImageDescendant(only)
50 : undefined;
51}
52
53function markStandaloneImages(node: MarkdownImageHastNode) {
54 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
55 const image = soleImageDescendant(node);
56 if (image) image.properties = { ...image.properties, dataStandalone: true };
57 }
58 node.children?.forEach((child) => {
59 if (child.type === "element") markStandaloneImages(child);
60 });
61}
62
63function rehypePreserveBareAnchorPlaceholders() {
64 return (tree: MarkdownImageHastNode) => {
65 const anchors: Array<MarkdownImageHastNode | null> = [];
66 let rawTextTag: string | undefined;
67 const visit = (node: MarkdownImageHastNode) => {
68 if (node.type === "raw" && typeof node.value === "string") {
69 // Raw blocks can contain several tags. Consume whole tags, quoted attributes,
70 // and comments so text resembling a closing anchor cannot pair 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 remarkPreserveCodeMeta,
171 remarkNormalizeLinksAndTagInlineCode,
172];
173
174export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
175 remarkGfm,
176 remarkKeepWindowsPaths,
177 remarkGithubAlerts,
178 remarkNormalizeListItemIndentation,
179 remarkCodexDirectives,
180 remarkBreaks,
181 remarkPreserveCodeMeta,
182 remarkNormalizeLinksAndTagInlineCode,
183];
184
185export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
186 rehypePreserveBareAnchorPlaceholders,
187 rehypeRaw,
188 rehypePreserveImageSourceMeta,
189 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
190];
191
192type MarkdownAstNode = {
193 type?: string;
194 meta?: unknown;
195 url?: string;
196 data?: {
197 hProperties?: Record<string, unknown>;
198 };
199 children?: MarkdownAstNode[];
200};
201
202function remarkPreserveCodeMeta() {
203 return (tree: MarkdownAstNode) => {
204 const visit = (node: MarkdownAstNode) => {
205 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
206 node.data = {
207 ...node.data,
208 hProperties: {
209 ...node.data?.hProperties,
210 dataCodeMeta: node.meta.trim(),
211 },
212 };
213 }
214 node.children?.forEach(visit);
215 };
216
217 visit(tree);
218 };
219}
220
221function remarkNormalizeLinksAndTagInlineCode() {
222 return (tree: MarkdownAstNode) => {
223 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
224 if (
225 (node.type === "link" || node.type === "definition") &&
226 typeof node.url === "string" &&
227 /^[A-Za-z]:[\\/]/.test(node.url)
228 ) {
229 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
230 }
231 if (node.type === "inlineCode" && !insideLink) {
232 node.data = {
233 ...node.data,
234 hProperties: {
235 ...node.data?.hProperties,
236 dataInlineCode: "",
237 },
238 };
239 }
240 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
241 node.children?.forEach((child) => visit(child, childInsideLink));
242 };
243
244 visit(tree, false);
245 };
246}
247
248interface DestinationCompileContext {
249 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
250 resume(): string;
251 sliceSerialize(token: unknown): string;
252}
253
254function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
255 const decoded = this.resume();
256 const authored = this.sliceSerialize(token);
257 const node = this.stack.at(-1);
258 // Character references still need decoding, so those destinations keep the parsed URL.
259 if (node)
260 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
261}
262
263// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
264const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
265
266interface EscapeCompileContext {
267 readonly stack: ReadonlyArray<{
268 readonly type: string;
269 children?: Array<{ type: string; value?: string }>;
270 }>;
271}
272
273function keepWindowsPathEscape(this: EscapeCompileContext) {
274 const text = this.stack.at(-1)?.children?.at(-1);
275 if (text?.type !== "text" || text.value === undefined) return;
276 const before = text.value.slice(0, -1);
277 if (UNFINISHED_DRIVE_PATH.test(before)) text.value = `${before}\\${text.value.slice(-1)}`;
278}
279
280/**
281 * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape. Every backslash in a
282 * Windows path is a separator, so link, image, and definition destinations that are
283 * Windows paths keep the text as written, and so do escapes inside drive paths in prose.
284 * Prose paths end at whitespace: past that, nothing tells a path from a sentence, and
285 * `C:\x and \*this\*` must still read `*this*`.
286 */
287function remarkKeepWindowsPaths(this: Processor) {
288 const data = this.data();
289 (data.fromMarkdownExtensions ??= []).push({
290 exit: {
291 resourceDestinationString: keepWindowsPathDestination,
292 definitionDestinationString: keepWindowsPathDestination,
293 characterEscape: keepWindowsPathEscape,
294 },
295 });
296}
297
298export function shouldPreserveAssistantLineBreaks(text: string): boolean {
299 return /^★ Insight(?:\s|─)/mu.test(text);
300}