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"];
174const NORMALIZED_HREF_SCHEMES = new Set([...(defaultSchema.protocols?.href ?? []), "file"]);
175
176// The sanitizer compares schemes case-sensitively, so lowercase accepted link schemes first.
177function normalizeHrefScheme(href: string): string {
178 return href.replace(/^([a-z][a-z0-9+.-]*):/i, (match, scheme: string) => {
179 const lower = scheme.toLowerCase();
180 return NORMALIZED_HREF_SCHEMES.has(lower) ? `${lower}:` : match;
181 });
182}
183
184function normalizeLocalFileHref(href: string): string {
185 if (/^sandbox:/i.test(href)) {
186 return parseMarkdownSandboxFileLink(href) ? href.replace(/^sandbox:/i, "sandbox:") : "";
187 }
188 try {
189 const url = new URL(href);
190 return isLocalEditorFileUrl(url) ? url.href : href;
191 } catch {
192 // Not an absolute URL; the sanitizer decides.
193 return href;
194 }
195}
196
197export function rehypeNormalizeLocalFileLinks() {
198 return (tree: MarkdownImageHastNode) => {
199 const visit = (node: MarkdownImageHastNode) => {
200 const href = node.properties?.href;
201 if (node.type === "element" && node.tagName === "a" && typeof href === "string") {
202 const normalized = normalizeLocalFileHref(normalizeHrefScheme(href));
203 if (normalized !== href) node.properties = { ...node.properties, href: normalized };
204 }
205 node.children?.forEach(visit);
206 };
207
208 visit(tree);
209 };
210}
211
212export const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
213 ...defaultSchema,
214 attributes: {
215 ...defaultSchema.attributes,
216 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
217 // Fence languages plus the two math classes the web chat's math plugin emits.
218 code: [
219 ["className", /^language-./, "math-inline", "math-display"],
220 "dataCodeMeta",
221 "dataInlineCode",
222 ],
223 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
224 // Spaces typed at the start of a user's line (keepLeadingWhitespace).
225 span: [...(defaultSchema.attributes?.span ?? []), "dataLeadingWhitespace"],
226 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
227 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
228 img: [
229 ...(defaultSchema.attributes?.img ?? []),
230 "dataDarkSrc",
231 "dataLightSrc",
232 "dataLocalSrc",
233 "dataMarkdownTitle",
234 "dataStandalone",
235 ],
236 },
237 protocols: {
238 ...defaultSchema.protocols,
239 href: [
240 ...(defaultSchema.protocols?.href ?? []),
241 "file",
242 "sandbox",
243 "t3-citation",
244 "t3-context",
245 THREAD_LINK_PROTOCOL,
246 // Scheme only: the renderer's URL transform checks the rest of the link shape.
247 ...LOCAL_FILE_LINK_SCHEMES,
248 ],
249 src: IMAGE_SRC_PROTOCOLS,
250 dataDarkSrc: IMAGE_SRC_PROTOCOLS,
251 dataLightSrc: IMAGE_SRC_PROTOCOLS,
252 },
253} satisfies Schema;
254
255/** Sanitizes one tree with the chat's schema, as the last rehype plugin does. */
256export const sanitizeChatHast = (tree: Root): Root =>
257 sanitize(tree, CHAT_MARKDOWN_SANITIZE_SCHEMA) as Root;
258
259export type ChatMarkdownImageProperties = {
260 readonly src?: unknown;
261 readonly dataLocalSrc?: unknown;
262 readonly dataDarkSrc?: unknown;
263 readonly dataLightSrc?: unknown;
264};
265
266/** Keep the authored path for file links and normalize Windows separators for classification. */
267export function chatMarkdownImageSource(
268 properties?: ChatMarkdownImageProperties,
269 theme?: "dark" | "light",
270) {
271 const themeSrc =
272 theme === undefined
273 ? undefined
274 : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
275 const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc;
276 const source =
277 typeof themeSrc === "string"
278 ? themeSrc
279 : typeof localSrc === "string"
280 ? localSrc
281 : properties?.src;
282 if (typeof source !== "string") return null;
283 const authoredSrc = normalizeMarkdownLinkDestination(source);
284 return {
285 authoredSrc,
286 classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc,
287 };
288}