Open History to see the last commit
1import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts";
2import type { Root } from "hast";
3import { defaultSchema, sanitize, type Schema } from "hast-util-sanitize";
4
5import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES } from "./codexArtifactTemplates.ts";
6import {
7 isWindowsDrivePathHref,
8 normalizeMarkdownLinkDestination,
9 parseMarkdownSandboxFileLink,
10} from "./markdownLinks.ts";
11import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
12
13type MarkdownImageHastNode = {
14 type?: string;
15 value?: string;
16 tagName?: string;
17 properties?: Record<string, unknown>;
18 children?: MarkdownImageHastNode[];
19};
20
21function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
22 return (node.children ?? []).filter(
23 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
24 );
25}
26
27const STANDALONE_IMAGE_BLOCKS = new Set([
28 "p",
29 "div",
30 "li",
31 "td",
32 "th",
33 "figure",
34 "center",
35 "blockquote",
36]);
37
38function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
39 const children = meaningfulHastChildren(node);
40 if (children.length !== 1) return undefined;
41 const only = children[0];
42 if (only?.type !== "element") return undefined;
43 if (only.tagName === "img") return only;
44 return only.tagName === "a" ||
45 only.tagName === "strong" ||
46 only.tagName === "em" ||
47 only.tagName === "picture"
48 ? soleImageDescendant(only)
49 : undefined;
50}
51
52const BLOCK_ELEMENTS = new Set([
53 ...STANDALONE_IMAGE_BLOCKS,
54 "address",
55 "article",
56 "aside",
57 "dd",
58 "details",
59 "dl",
60 "dt",
61 "figcaption",
62 "footer",
63 "h1",
64 "h2",
65 "h3",
66 "h4",
67 "h5",
68 "h6",
69 "header",
70 "hr",
71 "main",
72 "nav",
73 "ol",
74 "pre",
75 "section",
76 "summary",
77 "table",
78 "ul",
79]);
80
81const isBlockOrEdge = (node: MarkdownImageHastNode | undefined) =>
82 !node || (node.type === "element" && BLOCK_ELEMENTS.has(node.tagName ?? ""));
83
84// A raw-HTML image block between other blocks sits directly under the root, with no paragraph of
85// its own; it is standalone when nothing inline shares its line.
86function markRootImageBlocks(root: MarkdownImageHastNode) {
87 const children = meaningfulHastChildren(root).filter((child) => child.type !== "comment");
88 children.forEach((child, index) => {
89 if (isBlockOrEdge(child)) return;
90 const image = soleImageDescendant({ children: [child] });
91 if (image && isBlockOrEdge(children[index - 1]) && isBlockOrEdge(children[index + 1])) {
92 image.properties = { ...image.properties, dataStandalone: true };
93 }
94 });
95}
96
97function markStandaloneImages(node: MarkdownImageHastNode) {
98 if (node.type === "root") markRootImageBlocks(node);
99 else if (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName)) {
100 const image = soleImageDescendant(node);
101 if (image) image.properties = { ...image.properties, dataStandalone: true };
102 }
103 node.children?.forEach((child) => {
104 if (child.type === "element") markStandaloneImages(child);
105 });
106}
107
108const COLOR_SCHEME_MEDIA =
109 /^[\t\n\f\r ]*\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)[\t\n\f\r ]*$/i;
110const FIRST_SRCSET_URL = /^[\t\n\f\r ]*([^\t\n\f\r ]+)/;
111
112function normalizeUrlScheme(url: string): string {
113 return url.replace(/^(?:https?|file):/i, (scheme) => scheme.toLowerCase());
114}
115
116/**
117 * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
118 * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
119 * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
120 */
121function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
122 if (!picture.children) return;
123 const image = picture.children.find((child) => child.tagName === "img");
124 for (const source of picture.children) {
125 if (source.tagName !== "source" || !image) continue;
126 const media = source.properties?.media;
127 const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
128 const srcSet = source.properties?.srcSet;
129 const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
130 // HTML srcset splits URLs on ASCII whitespace only, so U+00A0 in filenames stays intact.
131 const url =
132 typeof candidate === "string"
133 ? (FIRST_SRCSET_URL.exec(candidate)?.[1]?.replace(/,+$/, "") ?? "")
134 : "";
135 const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
136 // As in a browser, the first source that matches a scheme is the one shown.
137 if (scheme && url && image.properties?.[key] === undefined) {
138 // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
139 const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
140 image.properties = { ...image.properties, [key]: value };
141 }
142 }
143 picture.children = picture.children.filter((child) => child.tagName !== "source");
144}
145
146export function rehypePreserveImageSourceMeta() {
147 return (tree: MarkdownImageHastNode) => {
148 const visit = (node: MarkdownImageHastNode) => {
149 const src = node.properties?.src;
150 const title = node.properties?.title;
151 if (node.type === "element" && node.tagName === "picture") {
152 moveColorSchemeSourcesToImage(node);
153 }
154 if (node.type === "element" && node.tagName === "img") {
155 node.properties = {
156 ...node.properties,
157 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
158 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
159 };
160 for (const key of ["src", "dataDarkSrc", "dataLightSrc"]) {
161 const value = node.properties[key];
162 if (typeof value === "string") node.properties[key] = normalizeUrlScheme(value);
163 }
164 }
165 node.children?.forEach(visit);
166 };
167
168 visit(tree);
169 markStandaloneImages(tree);
170 };
171}
172
173const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
174
175// The sanitizer compares schemes case-sensitively, so lowercase accepted file link schemes first.
176function normalizeLocalFileHref(href: string): string {
177 if (/^sandbox:/i.test(href)) {
178 return parseMarkdownSandboxFileLink(href) ? href.replace(/^sandbox:/i, "sandbox:") : "";
179 }
180 try {
181 const url = new URL(href);
182 return isLocalEditorFileUrl(url) ? url.href : href;
183 } catch {
184 // Not an absolute URL; the sanitizer decides.
185 return href;
186 }
187}
188
189export function rehypeNormalizeLocalFileLinks() {
190 return (tree: MarkdownImageHastNode) => {
191 const visit = (node: MarkdownImageHastNode) => {
192 const href = node.properties?.href;
193 if (node.type === "element" && node.tagName === "a" && typeof href === "string") {
194 const normalized = normalizeLocalFileHref(normalizeUrlScheme(href));
195 if (normalized !== href) node.properties = { ...node.properties, href: normalized };
196 }
197 node.children?.forEach(visit);
198 };
199
200 visit(tree);
201 };
202}
203
204export const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
205 ...defaultSchema,
206 attributes: {
207 ...defaultSchema.attributes,
208 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
209 // Fence languages plus the two math classes the web chat's math plugin emits.
210 code: [
211 ["className", /^language-./, "math-inline", "math-display"],
212 "dataCodeMeta",
213 "dataInlineCode",
214 ],
215 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
216 // Spaces typed at the start of a user's line (keepLeadingWhitespace).
217 span: [...(defaultSchema.attributes?.span ?? []), "dataLeadingWhitespace"],
218 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
219 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
220 img: [
221 ...(defaultSchema.attributes?.img ?? []),
222 "dataDarkSrc",
223 "dataLightSrc",
224 "dataLocalSrc",
225 "dataMarkdownTitle",
226 "dataStandalone",
227 ],
228 },
229 protocols: {
230 ...defaultSchema.protocols,
231 href: [
232 ...(defaultSchema.protocols?.href ?? []),
233 "file",
234 "sandbox",
235 "t3-citation",
236 "t3-context",
237 THREAD_LINK_PROTOCOL,
238 // Scheme only: the renderer's URL transform checks the rest of the link shape.
239 ...LOCAL_FILE_LINK_SCHEMES,
240 ],
241 src: IMAGE_SRC_PROTOCOLS,
242 dataDarkSrc: IMAGE_SRC_PROTOCOLS,
243 dataLightSrc: IMAGE_SRC_PROTOCOLS,
244 },
245} satisfies Schema;
246
247/** Sanitizes one tree with the chat's schema, as the last rehype plugin does. */
248export const sanitizeChatHast = (tree: Root): Root =>
249 sanitize(tree, CHAT_MARKDOWN_SANITIZE_SCHEMA) as Root;
250
251export type ChatMarkdownImageProperties = {
252 readonly src?: unknown;
253 readonly dataLocalSrc?: unknown;
254 readonly dataDarkSrc?: unknown;
255 readonly dataLightSrc?: unknown;
256};
257
258/** Keep the authored path for file links and normalize Windows separators for classification. */
259export function chatMarkdownImageSource(
260 properties?: ChatMarkdownImageProperties,
261 theme?: "dark" | "light",
262) {
263 const themeSrc =
264 theme === undefined
265 ? undefined
266 : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
267 const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc;
268 const source =
269 typeof themeSrc === "string"
270 ? themeSrc
271 : typeof localSrc === "string"
272 ? localSrc
273 : properties?.src;
274 if (typeof source !== "string") return null;
275 const authoredSrc = normalizeMarkdownLinkDestination(source);
276 return {
277 authoredSrc,
278 classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc,
279 };
280}