Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownPipeline.ts

295 lines9.7 KB

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 );
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;
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 });
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 };
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 };
129​
130const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
131 ...defaultSchema,
132 attributes: {
133 ...defaultSchema.attributes,
134 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
135 code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
136 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
137 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
138 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
139 img: [
140 ...(defaultSchema.attributes?.img ?? []),
141 "dataLocalSrc",
142 "dataMarkdownTitle",
143 "dataStandalone",
144 ],
145 },
146 protocols: {
147 ...defaultSchema.protocols,
148 href: [
149 ...(defaultSchema.protocols?.href ?? []),
150 "file",
151 "t3-citation",
152 "t3-context",
153 THREAD_LINK_PROTOCOL,
154 ],
155 src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
156 },
157} satisfies Parameters<typeof rehypeSanitize>[0];
158​
159export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
160 remarkGfm,
161 remarkKeepWindowsPaths,
162 remarkGithubAlerts,
163 remarkNormalizeListItemIndentation,
164 remarkCodexDirectives,
165 remarkPreserveCodeMeta,
166 remarkNormalizeLinksAndTagInlineCode,
167];
168​
169export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
170 remarkGfm,
171 remarkKeepWindowsPaths,
172 remarkGithubAlerts,
173 remarkNormalizeListItemIndentation,
174 remarkCodexDirectives,
175 remarkBreaks,
176 remarkPreserveCodeMeta,
177 remarkNormalizeLinksAndTagInlineCode,
178];
179​
180export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
181 rehypePreserveBareAnchorPlaceholders,
182 rehypeRaw,
183 rehypePreserveImageSourceMeta,
184 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
185];
186​
187type MarkdownAstNode = {
188 type?: string;
189 meta?: unknown;
190 url?: string;
191 data?: {
192 hProperties?: Record<string, unknown>;
193 };
194 children?: MarkdownAstNode[];
195};
196​
197function remarkPreserveCodeMeta() {
198 return (tree: MarkdownAstNode) => {
199 const visit = (node: MarkdownAstNode) => {
200 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
201 node.data = {
202 ...node.data,
203 hProperties: {
204 ...node.data?.hProperties,
205 dataCodeMeta: node.meta.trim(),
206 },
207 };
208 }
209 node.children?.forEach(visit);
210 };
211​
212 visit(tree);
213 };
215​
216function remarkNormalizeLinksAndTagInlineCode() {
217 return (tree: MarkdownAstNode) => {
218 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
219 if (
220 (node.type === "link" || node.type === "definition") &&
221 typeof node.url === "string" &&
222 /^[A-Za-z]:[\\/]/.test(node.url)
223 ) {
224 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
225 }
226 if (node.type === "inlineCode" && !insideLink) {
227 node.data = {
228 ...node.data,
229 hProperties: {
230 ...node.data?.hProperties,
231 dataInlineCode: "",
232 },
233 };
234 }
235 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
236 node.children?.forEach((child) => visit(child, childInsideLink));
237 };
238​
239 visit(tree, false);
240 };
242​
243interface DestinationCompileContext {
244 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
245 resume(): string;
246 sliceSerialize(token: unknown): string;
248​
249function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
250 const decoded = this.resume();
251 const authored = this.sliceSerialize(token);
252 const node = this.stack.at(-1);
253 // Character references still need decoding, so those destinations keep the parsed URL.
254 if (node)
255 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
257​
258// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
259const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
260​
261interface EscapeCompileContext {
262 readonly stack: ReadonlyArray<{
263 readonly type: string;
264 children?: Array<{ type: string; value?: string }>;
265 }>;
267​
268function keepWindowsPathEscape(this: EscapeCompileContext) {
269 const text = this.stack.at(-1)?.children?.at(-1);
270 if (text?.type !== "text" || text.value === undefined) return;
271 const before = text.value.slice(0, -1);
272 if (UNFINISHED_DRIVE_PATH.test(before)) text.value = `${before}\\${text.value.slice(-1)}`;
274​
275/**
276 * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape. Every backslash in a
277 * Windows path is a separator, so link, image, and definition destinations that are
278 * Windows paths keep the text as written, and so do escapes inside drive paths in prose.
279 * Prose paths end at whitespace: past that, nothing tells a path from a sentence, and
280 * `C:\x and \*this\*` must still read `*this*`.
281 */
282export function remarkKeepWindowsPaths(this: Processor) {
283 const data = this.data();
284 (data.fromMarkdownExtensions ??= []).push({
285 exit: {
286 resourceDestinationString: keepWindowsPathDestination,
287 definitionDestinationString: keepWindowsPathDestination,
288 characterEscape: keepWindowsPathEscape,
289 },
290 });
292​
293export function shouldPreserveAssistantLineBreaks(text: string): boolean {
294 return /^★ Insight(?:\s|─)/mu.test(text);